diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000000..2a4cd2cb93 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,3 @@ +# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI +# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET). +nextest-version = "0.9.150" diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index bb3989d308..2d1213a4e8 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,27 @@ jobs: lint: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + + windows-install-policy: + timeout-minutes: 10 + name: Windows installation policy (no app build) + runs-on: windows-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install the pinned packaging toolchain + shell: pwsh + run: | + $tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix' + dotnet tool install --tool-path $tools wix --version 5.0.2 + if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' } + $tools >> $env:GITHUB_PATH + $policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json + foreach ($extension in @($policy.extensions)) { + & (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2" + if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." } + } + - name: Build and check non-executable installer fixtures + shell: pwsh + run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 168408d87e..e0c09905d1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,7 @@ on: permissions: contents: write + packages: write concurrency: group: release-${{ github.ref }} diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 2f9b1416d5..3d5312b143 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -24,3 +24,5 @@ jobs: with: app-name: gridcraft app-dir: GridCraft + install-relative-path: Programs/ArtCraft/GridCraft + install-scope: perUser diff --git a/AGENTS.md b/AGENTS.md index 289cb12d08..e4fcf55709 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,8 +2,6 @@ GridCraft is a clean-room, open-source, Rust-native spreadsheet targeting Microsoft Excel parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../designcraft` (InDesign-class, the closest reference), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../effectcraft` (After Effects). -Standards and learnings shared across the crafting apps live in `../../craftrules` (checked out next to the craft apps, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code. - ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/excel/*.md` (`observed-ui.md` holds measured observations of the running app). 2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. @@ -20,10 +18,10 @@ Standards and learnings shared across the crafting apps live in `../../craftrule - The ArtCraft brand files in `docs/brand/` are ArtCraft trademarks under `docs/brand/LICENSE-brand.txt`, the one exception. ## Never crash -People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. -- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references). +- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): validate indexes and ranges before access, use checked access when validity is not established, use checked/saturating arithmetic, and cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references). - **Bound recursion** (formula nesting, dependency chains, names referring to names). - **Last-resort guard:** `Session::execute` catches escaped panics and restores the workbook. It's a safety net, not a licence. - **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/it/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`). @@ -31,8 +29,8 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr ## Non-negotiables - **Clean-room.** Microsoft Excel is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic workbooks, take screenshots (by window id) stored only under `plan/excel/screenshots/`. Never read, disassemble or copy anything inside the Office bundle, never commit files produced by Excel, never copy GPL/AGPL/LGPL code (LibreOffice, Gnumeric…). Function behaviour comes from public documentation and observation. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. Standard: craftrules `standards/fonts.md`. -- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified (craftrules `standards/test-corpora.md`). Never commit large binary fixtures; build test workbooks in code. +- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. +- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified. Never commit large binary fixtures; build test workbooks in code. - **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, ribbon path, shortcut, params doc, `enabled`, `run`) + tests. Ids follow Excel's ribbon (`home.bold`, `insert.chart`, `data.sortAscending`) plus primitives (`cell.set`, `selection.set`, `range.setValues`). UI-only commands live in `crates/ui-egui`. The control channel, CLI and MCP reach all of them. - **Programmatic calls never open dialogs**: a command with empty params runs with defaults or returns an error; only menu-style invocation opens a dialog (`UiRequest::Dialog`). - **Layering** is enforced by `cargo xtask layers`: `core`/`numfmt` (L0) → `formula`/`functions` (L1) → `model`/`calc`/`xlsx` (L2) → `chart` (L3) → `engine` (L5) → `ui-egui`/`mcp` (L6) → `apps/*` (L7). Nothing below L6 depends on egui/eframe/winit/rfd. **The UI crate is swappable.** @@ -51,7 +49,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done. ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules `standards/progress-docs.md` and points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`. +`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`. ## Contributor credits (About window) @@ -62,11 +60,13 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a1e4d8fbcf..2a4b5c96e4 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -12,15 +12,15 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `epaint_default_fonts::HACK_REGULAR` (dependency font input) | Source Foundry Authors (Hack; DejaVu and Bitstream Vera foundations) | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Hack](https://github.com/source-foundry/Hack) | MIT + Bitstream Vera License (full upstream texts in `NOTICE`) | Hack-Regular.ttf is egui's bundled monospace face and GridCraft's last-resort symbol fallback. Dependency asset unmodified here, no font file copied into this repository. | | `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | The Noto Project Authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Noto Emoji](https://fonts.google.com/noto/specimen/Noto+Emoji) | SIL Open Font License 1.1 (full upstream text in `NOTICE`) | NotoEmoji-Regular.ttf is enabled by egui's `monochrome_emoji_fonts` feature and used as the monochrome emoji fallback. Dependency asset unmodified here, no font file copied into this repository. | | `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Canonical Ltd. and the Ubuntu Font Family authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Ubuntu font](https://design.ubuntu.com/font) | Ubuntu Font Licence 1.0 (full upstream text in `NOTICE`) | Ubuntu-Light.ttf is egui's default proportional face. Dependency asset unmodified here, no font file copied into this repository. | -| `docs/brand/artcraft-logo.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-logo.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-mark.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-mark.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark | -| `docs/brand/LICENSE-brand.txt` | (licence text) | craftrules | — | | +| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-mark.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark | +| `docs/brand/LICENSE-brand.txt` | (licence text) | project | — | | | `assets/app-icon/gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | PLACEHOLDER app icon (ledger page); replaced by the owner's creature art later | | `packaging/macos/dmg/background.svg` | @XusBadia | original (hand-written SVG, derived from the GridCraft app icon `assets/app-icon/gridcraft.svg`, referenced via ``, not copied; text is outlined glyph paths; `packaging/macos/dmg/generate.py` renders it to `background.tiff`) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | GridCraft macOS DMG window background for the Finder window; added 2026-10-08 | | `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") | @@ -46,3 +46,5 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `docs/images/pivot.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | | `docs/images/format-chart.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | | `docs/images/page-break.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | +| Core 14 AFM metric numbers in `crates/pdf/src/symbol.rs` (Symbol: character codes and advance widths) and `crates/pdf/src/metrics.rs` (Helvetica, Times and Courier advance widths); no font file | Adobe Systems Incorporated | Adobe's Core 14 AFM font metrics files (`Symbol.afm` 001.008 and the Helvetica, Times and Courier AFMs) | Adobe's Core 14 metrics notice: the files may be used, copied and distributed for any purpose and without charge, provided the notice is kept (quoted in `crates/pdf/src/metrics.rs`) | Numbers only, typed in from the public metrics. PDF export embeds no font: Symbol and the Times faces are base-14 fonts every PDF reader supplies, and text outside WinAnsiEncoding is set in a predefined, non-embedded Adobe-GB1 CID font | +| Unicode values of the Symbol encoding in `crates/pdf/src/symbol.rs` (the code-to-character map; numbers only, no file copied) | Unicode, Inc. | `symbol.txt`, "Adobe Symbol Encoding to Unicode", table version 1.0 (2011-07-12), at unicode.org/Public/MAPPINGS/VENDORS/ADOBE/ | Unicode, Inc.'s notice in the file: "Unicode, Inc. hereby grants the right to freely use the information supplied in this file in the creation of products supporting the Unicode Standard, and to make copies of this file in any form for internal or external distribution as long as this notice remains attached." The file is provided as-is, without warranties | Separate from Adobe's Core 14 notice (previous row), which covers the character codes and widths; the Unicode values come from this table | diff --git a/CLAUDE.md b/CLAUDE.md index 8bf527c54e..3297f122ad 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,8 +2,6 @@ GridCraft is a clean-room, open-source, Rust-native spreadsheet targeting Microsoft Excel parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../designcraft` (InDesign-class, the closest reference), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../effectcraft` (After Effects). -Standards and learnings shared across the crafting apps live in `../../craftrules` (checked out next to the craft apps, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code. - ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/excel/*.md` (`observed-ui.md` holds measured observations of the running app). 2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. @@ -20,19 +18,19 @@ Standards and learnings shared across the crafting apps live in `../../craftrule - The ArtCraft brand files in `docs/brand/` are ArtCraft trademarks under `docs/brand/LICENSE-brand.txt`, the one exception. ## Never crash -People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. - **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references). - **Bound recursion** (formula nesting, dependency chains, names referring to names). - **Last-resort guard:** `Session::execute` catches escaped panics and restores the workbook. It's a safety net, not a licence. - **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/it/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`). -- Crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. +- Production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. ## Non-negotiables - **Clean-room.** Microsoft Excel is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic workbooks, take screenshots (by window id) stored only under `plan/excel/screenshots/`. Never read, disassemble or copy anything inside the Office bundle, never commit files produced by Excel, never copy GPL/AGPL/LGPL code (LibreOffice, Gnumeric…). Function behaviour comes from public documentation and observation. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. Standard: craftrules `standards/fonts.md`. -- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified (craftrules `standards/test-corpora.md`). Never commit large binary fixtures; build test workbooks in code. +- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. +- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified. Never commit large binary fixtures; build test workbooks in code. - **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, ribbon path, shortcut, params doc, `enabled`, `run`) + tests. Ids follow Excel's ribbon (`home.bold`, `insert.chart`, `data.sortAscending`) plus primitives (`cell.set`, `selection.set`, `range.setValues`). UI-only commands live in `crates/ui-egui`. The control channel, CLI and MCP reach all of them. - **Programmatic calls never open dialogs**: a command with empty params runs with defaults or returns an error; only menu-style invocation opens a dialog (`UiRequest::Dialog`). - **Layering** is enforced by `cargo xtask layers`: `core`/`numfmt` (L0) → `formula`/`functions` (L1) → `model`/`calc`/`xlsx` (L2) → `chart` (L3) → `engine` (L5) → `ui-egui`/`mcp` (L6) → `apps/*` (L7). Nothing below L6 depends on egui/eframe/winit/rfd. **The UI crate is swappable.** @@ -50,4 +48,9 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done. ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules `standards/progress-docs.md` and points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`. +`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/Cargo.lock b/Cargo.lock index 53b2326da1..20dcf28abc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,7 +20,7 @@ dependencies = [ "accesskit", "accesskit_consumer", "atspi-common", - "phf", + "phf 0.14.0", "serde", "zvariant", ] @@ -220,11 +220,17 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.8" @@ -468,15 +474,30 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" @@ -889,12 +910,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "fixed_decimal", "icu_decimal", @@ -917,9 +938,10 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "craft-winprint-gdi", + "log", "miniz_oxide 0.9.1", "roxmltree", "tempfile", @@ -930,7 +952,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -950,13 +972,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", @@ -975,7 +998,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "egui", "objc2 0.6.5", @@ -1455,7 +1478,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1493,6 +1516,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fancy-regex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -1935,7 +1969,7 @@ dependencies = [ [[package]] name = "gridcraft" -version = "0.12.1" +version = "0.16.0" dependencies = [ "arboard", "chrono", @@ -1962,7 +1996,7 @@ dependencies = [ [[package]] name = "gridcraft-calc" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-core", "gridcraft-formula", @@ -1974,7 +2008,7 @@ dependencies = [ [[package]] name = "gridcraft-chart" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-calc", "gridcraft-core", @@ -1985,7 +2019,7 @@ dependencies = [ [[package]] name = "gridcraft-cli" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-engine", "gridcraft-mcp", @@ -1997,7 +2031,7 @@ dependencies = [ [[package]] name = "gridcraft-core" -version = "0.12.1" +version = "0.16.0" dependencies = [ "chrono", "js-sys", @@ -2008,13 +2042,14 @@ dependencies = [ [[package]] name = "gridcraft-engine" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-calc", "gridcraft-chart", "gridcraft-core", "gridcraft-formula", "gridcraft-functions", + "gridcraft-math", "gridcraft-model", "gridcraft-numfmt", "gridcraft-pdf", @@ -2024,12 +2059,13 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "web-time", "zip 3.0.0", ] [[package]] name = "gridcraft-formula" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-core", "serde", @@ -2038,15 +2074,25 @@ dependencies = [ [[package]] name = "gridcraft-functions" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-core", "regex", ] +[[package]] +name = "gridcraft-math" +version = "0.16.0" +dependencies = [ + "ratex-font", + "ratex-layout", + "ratex-parser", + "ratex-types", +] + [[package]] name = "gridcraft-mcp" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-engine", "log", @@ -2055,10 +2101,11 @@ dependencies = [ [[package]] name = "gridcraft-model" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-core", "gridcraft-formula", + "gridcraft-math", "serde", "serde_json", "sha2 0.11.1", @@ -2067,18 +2114,18 @@ dependencies = [ [[package]] name = "gridcraft-numfmt" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-core", ] [[package]] name = "gridcraft-pdf" -version = "0.12.1" +version = "0.16.0" [[package]] name = "gridcraft-ui-egui" -version = "0.12.1" +version = "0.16.0" dependencies = [ "craft-ui", "craft-update", @@ -2097,12 +2144,13 @@ dependencies = [ "sys-locale", "toml", "web-sys", + "web-time", "zbus", ] [[package]] name = "gridcraft-web" -version = "0.12.1" +version = "0.16.0" dependencies = [ "eframe", "egui", @@ -2119,11 +2167,13 @@ dependencies = [ [[package]] name = "gridcraft-xlsx" -version = "0.12.1" +version = "0.16.0" dependencies = [ "aes", "gridcraft-core", "gridcraft-formula", + "gridcraft-functions", + "gridcraft-math", "gridcraft-model", "quick-xml 0.41.0", "sha1 0.11.0", @@ -2962,7 +3012,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -3457,7 +3507,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3538,17 +3588,37 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.14.0", + "phf_shared 0.14.0", "serde", ] +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.8", +] + [[package]] name = "phf_generator" version = "0.14.0" @@ -3556,7 +3626,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -3565,13 +3648,22 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.14.0" @@ -3847,7 +3939,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash 2.1.3", @@ -3871,7 +3963,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3895,6 +3987,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.10.3" @@ -3933,6 +4034,66 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +[[package]] +name = "ratex-font" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7b73531dabe934a3e725ed5c90d18dacf43778b7a208381390943a9a8c24db" +dependencies = [ + "phf 0.11.3", + "ratex-types", +] + +[[package]] +name = "ratex-layout" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1792738e2e36683cd20de742296a5233759565efc8cd03831064a0ccfb1fe0f7" +dependencies = [ + "ratex-font", + "ratex-parser", + "ratex-types", + "serde_json", +] + +[[package]] +name = "ratex-lexer" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f704add86d7bf4c4ecc7767f45ab38a44f1bbfa4b49725b2ae53c32e83b8a61e" +dependencies = [ + "ratex-types", + "serde", + "thiserror 1.0.69", +] + +[[package]] +name = "ratex-parser" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "079ec2e7ac6bc76137a6de093a173d1f901139a51318589ab9ce17139c21a6f0" +dependencies = [ + "fancy-regex", + "ratex-font", + "ratex-lexer", + "ratex-types", + "regex", + "regex-lite", + "serde", + "serde_json", + "thiserror 1.0.69", + "unicode-normalization", +] + +[[package]] +name = "ratex-types" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cf0be3d050525f0f7d37af55a443d7648c222ccc617639950e3de1f8e6f9900" +dependencies = [ + "serde", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4032,6 +4193,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -4181,7 +4348,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4240,7 +4407,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4309,6 +4476,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "log", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -4612,7 +4790,7 @@ dependencies = [ "const-oid", "der", "hex", - "rand", + "rand 0.10.3", "reqwest", "rustls-pki-types", "rustls-webpki", @@ -4841,6 +5019,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + [[package]] name = "strum" version = "0.28.0" @@ -4974,7 +5158,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5070,6 +5254,31 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -5341,6 +5550,15 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -5781,8 +5999,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.10.0", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -5854,7 +6072,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", @@ -5933,7 +6151,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.59.0", ] [[package]] @@ -6180,6 +6398,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", + "sctk-adwaita", "smithay-client-toolkit 0.19.2", "smol_str", "tracing", @@ -6399,7 +6618,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.12.1" +version = "0.16.0" dependencies = [ "gridcraft-engine", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index e23c106e6e..594b29273d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"] [workspace.package] -version = "0.12.1" +version = "0.16.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -24,9 +24,11 @@ gridcraft-engine = { path = "crates/engine" } gridcraft-ui-egui = { path = "crates/ui-egui" } gridcraft-mcp = { path = "crates/mcp" } gridcraft-pdf = { path = "crates/pdf" } +gridcraft-math = { path = "crates/math" } # Every craft-libs crate (craft-update and craft-window here, craft-ui in ui-egui, craft-print in # the app) comes from one storytold/craft-libs revision. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7", version = "=0.1.0", features = ["egui"] } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.1.0", features = ["egui"] } # foundation thiserror = "2" @@ -34,7 +36,8 @@ serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). -chrono = { version = "0.4.45", default-features = false, features = ["std"] } +chrono = { version = "0.4.45", default-features = false, features = ["std", "clock"] } +web-time = "1.1.0" rayon = "1" regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] } quick-xml = "0.41" @@ -45,6 +48,13 @@ aes = { version = "0.9", default-features = false } 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 +# young (0.1.x), and the gate recorded in docs/decisions.md vetted this release. +ratex-parser = "=0.1.14" +ratex-layout = "=0.1.14" +ratex-types = "=0.1.14" +ratex-font = "=0.1.14" + # ui egui = "0.37" egui_extras = { version = "0.37", default-features = false } @@ -61,16 +71,17 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" # One native window per workbook: the window list, Window menu titles and the immediate-viewport # driver. Same craft-libs revision as craft-update above. -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7", default-features = false, features = ["egui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", default-features = false, features = ["egui"] } [workspace.lints.rust] unsafe_code = "forbid" [workspace.lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" -too_many_arguments = "allow" -type_complexity = "allow" [profile.dev.package."*"] opt-level = 2 diff --git a/NOTICE b/NOTICE index 78c72b9ace..d859d99d3a 100644 --- a/NOTICE +++ b/NOTICE @@ -274,3 +274,34 @@ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Linux Wayland window decorations +------------------------------- +sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, +commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux +for vector window controls. Its title-font features are disabled: no Cantarell +font is embedded by this dependency and no font file is added to this repo. + +sctk-adwaita's MIT licence: + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d9dc5eb363..f2d9a930e4 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,15 @@ stand on its own. | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | -| | **GridCraft** | **Spreadsheets and data · you are here** | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce78..3d65350f09 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-02 · **Change:** minor (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) · **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. @@ -22,7 +22,7 @@ This page is the summary. The detail is in: | Number | Value | Kind | |---|---|---| | 2026-10-14 | Editing a cell with text that would read back as a number, boolean, date or formula (entered with a leading apostrophe) shows the apostrophe in the editor and formula bar, so Enter unchanged keeps it text (#1362) | -| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 274 / 290 (94.5%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) | +| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 277 / 292 (94.9%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) | | **Ready for real work** | **~50%** | estimated from written weights (51.6); [target-app-parity.md](docs/target-app-parity.md) | | **Mainstream practitioner** | **~50%** | estimated: typical analyst/finance user, weekly features, × 0.90 interaction × 0.92 stability × 0.88 file exchange; [method](docs/target-app-parity.md#mainstream-practitioner) | | **Essentials user** | **~63%** | estimated: core features only, × 0.92 launch/stability × 0.95 clarity × 0.90 opening sent files; [method](docs/target-app-parity.md#essentials-user) | @@ -86,7 +86,7 @@ collaboration, mobile, AI). | Get & Transform, external data, data model | ~15% | ~10% | 60–100 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) | | Insert objects (pictures, shapes, ink, SmartArt, equations) | ~55% | ~45% | 25–40 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) | | Review, comments, protection, collaboration | ~55% | ~40% | 35–55 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) | -| Automation (recorded scripts; no VBA) | ~30% | ~20% | 12–20 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) | +| Automation (recorded scripts; typed macros with a recorder, a Macros dialog and a step editor; no VBA) | ~30% | ~20% | 12–20 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) | ## Languages @@ -135,7 +135,20 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors | +| 2026-11-02 | Python mode in the formula bar: Ctrl+Alt+Shift+P, `=PY` then Tab, or editing a Python cell edits its code in the formula bar, with Enter for a new line, Tab to indent and Ctrl+Enter to commit through `python.set`. The code still doesn't run | +| 2026-11-02 | Python cells as data: `python.set` stores code in a cell, Python cells copy, move, fill and undo like formulas, and `.xlsx` reads and writes Python cells as [MS-XLSX] specifies (`_xlfn._xlws.PY(index,0 or 1)`, the code in the workbook's Python part) with cached values and spills, so such workbooks open with their results; nothing runs Python (new code shows `#BLOCKED!`), and opening a file limits code size, result size and spill ranges | +| 2026-11-02 | Equations: Insert › Equation (a split button with a gallery of examples) and an editor with quick-insert buttons, the error underlined at its position and a live preview; `insert.equation` and `equation.edit`; LaTeX laid out by RaTeX inside the new `gridcraft-math` crate, capped and panic-guarded, and cached on the shape so that painting never runs the layout engine; xlsx writes Office Math with a plain-text fallback and the source in `descr`, and reads Office Math back into LaTeX; PDF prints equations with the standard Symbol font and `[?]` for anything else | +| 2026-11-02 | Solver writes a Sensitivity report: Simplex LP shadow prices, reduced costs and allowable ranges from the final tableau; GRG Nonlinear reduced gradients and Lagrange multipliers from difference gradients, at a Karush-Kuhn-Tucker point only; Solver Results offers it where it applies (no score change) | +| 2026-11-02 | Floating objects: charts, pictures, shapes and slicers share one selection with a frame of eight resize handles (each moves only its own edges, also on right-to-left sheets); Delete or Backspace deletes the selected object and Escape drops the selection; slicers follow row and column edits and sorts like the other objects; chart series follow cut-moves and sheet renames and deletes; a copied sheet gives its objects fresh ids; `ui.inspect` reports `selectedObject` and `ui.object.select` selects any object (#190, #213) | +| 2026-11-01 | Chart data tables are available from Chart Design › Add Chart Element and Format Chart Area. Tables follow live source values and number formats, keep blank cells blank, offer legend keys and border settings, and survive XLSX save/reopen; the shared renderer includes them in print and PDF. Readiness estimates unchanged. | +| 2026-11-01 | XLSX keeps the first visible workbook window's active sheet and display settings together, falling back to the first view when all are hidden. Tab ratios are normalized to 0–1000 on import and export; invalid numeric text uses 600. Synthetic round trips cover isolated attributes, missing views, and active tabs after sheet deletion/reordering; firstSheet remains separate #2264 work (#3057). | +| 2026-10-31 | Esc in File › Info, Print or Options first leaves the text field; the next Esc returns to the sheet (#3035) | +| 2026-10-31 | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) | +| 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-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`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | | 2026-10-24 | Ctrl+Shift+U (Control+Shift+U on a Mac) expands and collapses the formula bar, on the grid and while editing (`view.expandFormulaBar`); on Windows and Linux it used to underline | @@ -166,6 +179,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 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 | 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 | `.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 | | 2026-10-14 | Recalculation: when two arrays of one recalculation want the same empty cells, the formulas that read the one laid out second (at its anchor or over the cells it would have spilled into) read `#SPILL!` and empty cells instead of its values | @@ -179,6 +193,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-13 | XLSX: `[Content_Types].xml`, `_rels/.rels`, the workbook rels and `xl/workbook.xml` are the first zip entries (document properties last), so libmagic and PHP `finfo` detect the file type even with large properties (#1090) | | 2026-10-13 | Conditional formatting: a rule gathers range statistics only when it reads them (top/bottom, above average, duplicates, scales, bars, icons) and borrows them instead of copying them per cell, so the per-frame lookup of an expression or cell-value rule no longer visits its whole range (#1098, part 1) | | 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-21 | Macro engine ([macros.md](docs/macros.md)): typed, declarative macros saved in the workbook (a JSON field; hidden names in xlsx); declared inputs checked with messages that name the cells; tokens (`Input.col(2)`, `Row`, `Output`, `Name:Total`, `{{…}}` in formulas); one undo step with full rollback; a footprint dry run with ask, fail, overwrite, shift down or shift right; a policy that keeps macros away from files and the app, with approval for macros in opened files; Repeat, If and Stop steps; a debugger; a relative recorder; `macro.*` commands beside the unchanged Automate scripts | | 2026-10-12 | Security: the `--control` server requires an auth token (random, kept in a 0600 file or chosen with `GRIDCRAFT_CONTROL_TOKEN`) on each connection's first line and closes bad connections (#777) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | @@ -231,7 +246,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-11 | PivotCharts (`insert.pivotChart`): charts bound to a PivotTable's report, following refreshes and layout changes (#311) | | 2026-10-11 | FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.ETS.STAT: AAA exponential smoothing forecasts (#314) | | 2026-10-11 | File tab Backstage view (Home, New, Open, Info, Save As, Print preview, Export, Options) and `file.options` (#174) | -| 2026-10-10 | Ribbon translated into Japanese, Chinese, Korean, Brazilian Portuguese and Russian with system-language default (#31, #104, #82); CJK/Thai/Hebrew font fallback (#38); clear messages for encrypted and `.xls` files (#17); smooth line charts (#62). Progress docs restructured to the craftrules standard; full re-measure (this page). Initial ribbon key tips (#43), in-place text box editing (#84), copy as HTML table (#36). ODS and XLSB data import (#100, #101); recalc linear in the number of range formulas (#66); RISC-V Linux build; Flatpak repository on Pages; web cell-commit trap fixed | +| 2026-10-10 | Ribbon translated into Japanese, Chinese, Korean, Brazilian Portuguese and Russian with system-language default (#31, #104, #82); CJK/Thai/Hebrew font fallback (#38); clear messages for encrypted and `.xls` files (#17); smooth line charts (#62). Progress docs restructured; full re-measure (this page). Initial ribbon key tips (#43), in-place text box editing (#84), copy as HTML table (#36). ODS and XLSB data import (#100, #101); recalc linear in the number of range formulas (#66); RISC-V Linux build; Flatpak repository on Pages; web cell-commit trap fixed | | 2026-10-09 | Community fixes: spill range operator `A1#`, sheet-scoped names, protection refuses locked-cell edits, Insert/Delete Cells adjust references, `DATE(1900,2,29)`, SUMIF sizing, `ROUND` at 15 digits, `_xlpm.` LAMBDA parameters in XLSX, vertical scrollbar, system appearance, border previews; v0.4.0 | | 2026-10-08 | v0.2.0 and v0.3.0 releases; Flatpak, AppImage zsync, branded DMG; desktop log file; DirectX 12 default on Windows | | 2026-10-07 | About window with contributor and model credits; macOS release runner | @@ -242,7 +257,20 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Progress log: RefEdit reference boxes in dialogs | +| 2026-11-02 | minor | Progress log: Python mode in the formula bar | +| 2026-11-02 | minor | Progress log: Python cells as data | +| 2026-11-02 | minor | Progress log: equations (Insert › Equation, the editor, gridcraft-math) | +| 2026-11-02 | minor | What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear (no score change) | +| 2026-11-02 | minor | Progress log: one selection and eight resize handles for every floating object | +| 2026-11-01 | minor | Chart data tables are available from Chart Design › Add Chart Element and Format Chart Area. Tables follow live source values and number formats, keep blank cells blank, offer legend keys and border settings, and survive XLSX save/reopen; the shared renderer includes them in print and PDF. Readiness estimates unchanged. | +| 2026-11-01 | trivial | Workbook views: selected window settings stay together, tab ratios are bounded, and regressions cover isolated settings and sheet edits; readiness estimates unchanged (#3057) | +| 2026-10-31 | minor | File-page text fields keep the view open when Esc cancels an edit (#3035) | +| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories | +| 2026-10-31 | minor | Progress log: Function Library | | 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-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) | @@ -258,6 +286,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook | | 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) | | 2026-10-16 | minor | Progress log: interface fonts held once instead of twice | +| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting | | 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 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row | @@ -292,5 +321,5 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% per audience; full number unchanged (additive weighted sum) | | 2026-10-10 | minor | Added Mainstream practitioner (~50%) and Essentials user (~63%); languages updated for the 10-10 merges (ribbon in ja, zh, ko, pt-BR, ru); localization 5%→10%; full number re-checked (51.6, unchanged) | | 2026-10-10 | minor | Checked against the alpha gate (six core workflows pass): stays alpha | -| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; restructured to the progress-docs standard; detail moved to `docs/` | +| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; progress docs restructured; detail moved to `docs/` | | 2026-10-07 | major | First estimates: catalog 89%, functions ~93%, depth ~65%, ~35 h to alpha, ~215 h to full parity | diff --git a/apps/gridcraft-cli/src/check.rs b/apps/gridcraft-cli/src/check.rs index bbd3103d8a..5fc37b14ce 100644 --- a/apps/gridcraft-cli/src/check.rs +++ b/apps/gridcraft-cli/src/check.rs @@ -26,22 +26,31 @@ use serde_json::{Value as Json, json}; use super::{Args, USAGE, number_text, pretty}; +mod calc; +mod fidelity; +mod package; +mod report; + +pub use calc::oracle; +#[cfg(test)] +use calc::volatile_names; +#[cfg(test)] +use calc::{bool_cached_as_number, values_match}; +#[cfg(test)] +use fidelity::diff_workbooks; +pub use fidelity::round_trip; +use package::full_calc_on_load; +#[cfg(test)] +use package::validate_package; +use report::print_human; +pub use report::report_json; + /// Version tag of the `--json` output; bumped when a field changes meaning or disappears. pub const SCHEMA: &str = "gridcraft-check/1"; - -/// Functions whose result depends on the clock, a random generator or the environment. -const VOLATILE: [&str; 6] = ["RAND", "RANDARRAY", "RANDBETWEEN", "NOW", "TODAY", "INFO"]; /// Directory recursion limit (symlink loops end here). const MAX_DEPTH: usize = 32; /// Most files collected from the inputs. const MAX_FILES: usize = 100_000; -/// Largest package part read while validating a written package. -const MAX_XML_PART: u64 = 64 * 1024 * 1024; -/// Most zip entries looked at while validating a written package. -const MAX_ENTRIES: usize = 200_000; -/// Relationship kinds (lower case) whose absence after a save isn't a loss: the calculation chain is -/// a cache Excel rebuilds, and GridCraft never writes it. -const REBUILT_KINDS: [&str; 1] = ["calcchain"]; #[derive(Clone, Copy, Debug)] pub struct Options { @@ -357,1452 +366,5 @@ fn check_inner(path: &str, bytes: &[u8], opts: &Options) -> FileReport { report } -// ---------------------------------------------------------------- calc oracle - -fn functions_of(e: &Expr) -> Vec { - let mut set = BTreeSet::new(); - e.walk(&mut |x| { - if let Expr::Call(n, _) = x { - set.insert(n.clone()); - } - }); - set.into_iter().collect() -} - -fn is_volatile(e: &Expr, volatile_names: &HashSet) -> bool { - let mut v = false; - e.walk(&mut |x| match x { - Expr::Call(n, args) => { - let filename = n == "CELL" && matches!(args.first(), Some(Expr::Text(t)) if t.eq_ignore_ascii_case("filename")); - if filename || VOLATILE.contains(&n.as_str()) { - v = true; - } - } - Expr::Name(n) if volatile_names.contains(&n.to_ascii_uppercase()) => v = true, - _ => {} - }); - v -} - -/// Upper-cased defined names whose formula is volatile, directly or through other names. -fn volatile_names(wb: &Workbook) -> HashSet { - let parsed: Vec<(String, Option)> = - wb.names.iter().map(|n| (n.name.to_ascii_uppercase(), gridcraft_engine::formula::parse(&n.formula).ok())).collect(); - let mut set = HashSet::new(); - // Each round adds at least one name or stops, so `len + 1` rounds reach the fixed point. - for _ in 0..=parsed.len() { - let before = set.len(); - for (name, e) in &parsed { - if !set.contains(name) && e.as_ref().is_some_and(|e| is_volatile(e, &set)) { - set.insert(name.clone()); - } - } - if set.len() == before { - break; - } - } - set -} - -/// The formula as the formula bar shows it. -fn formula_text(cell: &Cell) -> String { - cell.bar_text() -} - -fn cell_name(wb: &Workbook, (sheet, c): Key) -> String { - let name = wb.sheet(sheet).map(|s| s.name.as_str()).unwrap_or("?"); - format!("{}!{}", quote_sheet(name), c.a1()) -} - -/// Whether the producer cached GridCraft's logical result as the number 1 or 0. Excel types a -/// logical result `t="b"`; a writer that leaves the type out (`TRUE()1`, as -/// Business Central's "Open in Excel" exports do) stores the same value, read back as a number. -pub fn bool_cached_as_number(expected: &Value, actual: &Value) -> bool { - matches!((expected, actual), (Value::Number(n), Value::Bool(b)) if *n == if *b { 1.0 } else { 0.0 }) -} - -/// Whether GridCraft's `actual` agrees with the producer's `expected`. -pub fn values_match(expected: &Value, actual: &Value, tolerance: f64) -> bool { - match (expected, actual) { - (Value::Number(a), Value::Number(b)) => (a - b).abs() <= tolerance * a.abs().max(b.abs()).max(1.0), - (Value::Text(a), Value::Text(b)) => a == b, - (Value::Bool(a), Value::Bool(b)) => a == b, - (Value::Error(a), Value::Error(b)) => a == b, - _ => false, - } -} - -fn type_name(v: &Value) -> &'static str { - match v { - Value::Empty => "blank", - Value::Number(_) => "number", - Value::Text(_) => "text", - Value::Bool(_) => "bool", - Value::Error(e) => e.as_str(), - Value::Array(_) => "array", - } -} - -fn mismatch_kind(expected: &Value, actual: &Value) -> &'static str { - match (expected, actual) { - (_, Value::Empty) => "blank", - (Value::Number(_), Value::Number(_)) => "numeric", - (Value::Text(_), Value::Text(_)) => "text", - (Value::Bool(_), Value::Bool(_)) => "bool", - (Value::Error(_), _) | (_, Value::Error(_)) => "error", - _ => "type", - } -} - -/// Mismatched cells indexed by (sheet, column) → rows, for precedent-area queries. -struct MismatchIndex { - cols: HashMap<(usize, u32), BTreeSet>, - /// Columns with mismatches per sheet (for very wide areas). - sheet_cols: HashMap>, -} - -impl MismatchIndex { - fn new(keys: &[Key]) -> MismatchIndex { - let mut cols: HashMap<(usize, u32), BTreeSet> = HashMap::new(); - let mut sheet_cols: HashMap> = HashMap::new(); - for &(s, c) in keys { - cols.entry((s, c.col)).or_default().insert(c.row); - sheet_cols.entry(s).or_default().insert(c.col); - } - MismatchIndex { cols, sheet_cols } - } - /// Whether a mismatched cell other than `own` lies in the area. - fn any_in(&self, sheet: usize, r0: u32, r1: u32, c0: u32, c1: u32, own: Key) -> bool { - let Some(cols) = self.sheet_cols.get(&sheet) else { return false }; - cols.range(c0..=c1) - .any(|&col| self.cols.get(&(sheet, col)).is_some_and(|rows| rows.range(r0..=r1).any(|&row| (sheet, CellRef::new(row, col)) != own))) - } -} - -/// Compares every formula cell of `cached` (as the producer saved it) with `fresh` (recalculated -/// by GridCraft). Without `trust_cache` nothing is compared (see [`CalcReport::stale_cache`]). -pub fn oracle(cached: &Workbook, fresh: &Workbook, calc: &Calc, trust_cache: bool, opts: &Options) -> CalcReport { - let mut r = CalcReport { stale_cache: !trust_cache, ..Default::default() }; - let vnames = volatile_names(cached); - let mut volatile: HashSet = HashSet::new(); - for (si, sh) in cached.sheets.iter().enumerate() { - for (c, cell) in sh.cells.iter() { - if let Some(f) = &cell.formula { - r.formula_cells += 1; - if f.expr_arc().is_some_and(|e| is_volatile(&e, &vnames)) { - volatile.insert((si, c)); - } - } - } - } - // Everything downstream of a volatile formula is volatile too; each key is pushed once. - let mut stack: Vec = volatile.iter().copied().collect(); - let mut deps = Vec::new(); - while let Some((s, c)) = stack.pop() { - deps.clear(); - calc.graph.dependents(s, c, &mut deps); - if let Some(range) = fresh.sheet(s).and_then(|sh| sh.spill_ranges.get(&c)) { - calc.graph.dependents_of_range(s, *range, &mut deps); - } - for k in deps.drain(..) { - if volatile.insert(k) { - stack.push(k); - } - } - } - - let mut bad: Vec<(Key, Vec)> = Vec::new(); - for (si, sh) in cached.sheets.iter().enumerate() { - for (c, cell) in sh.cells.iter() { - let Some(f) = &cell.formula else { continue }; - if volatile.contains(&(si, c)) { - r.volatile += 1; - continue; - } - if cell.value.is_empty() || !trust_cache { - r.no_oracle += 1; - continue; - } - r.checked += 1; - let actual = fresh.sheet(si).and_then(|s| s.cell(c)).map(|x| x.value.scalar()).unwrap_or_default(); - let funcs = match f.expr_arc() { - Some(e) => { - let names = functions_of(&e); - if names.is_empty() { vec!["(no function)".to_string()] } else { names } - } - None => vec!["(unparsed)".to_string()], - }; - let bool_as_number = bool_cached_as_number(&cell.value, &actual); - let ok = bool_as_number || values_match(&cell.value, &actual, opts.tolerance); - if bool_as_number { - r.bool_as_number += 1; - } - for n in &funcs { - let st = r.functions.entry(n.clone()).or_default(); - st.checked += 1; - if !ok { - st.mismatched += 1; - } - } - if ok { - r.matched += 1; - } else { - r.mismatched += 1; - *r.signatures.entry(format!("{} → {}", type_name(&cell.value), type_name(&actual))).or_default() += 1; - bad.push(((si, c), funcs)); - } - } - } - - // A mismatch is primary when none of its precedent cells mismatch. - let keys: Vec = bad.iter().map(|(k, _)| *k).collect(); - let index = MismatchIndex::new(&keys); - let mut listed: Vec<(bool, Key, Vec)> = Vec::with_capacity(bad.len()); - for (k, funcs) in bad { - let upstream = calc - .graph - .precedents_of(k) - .iter() - .any(|a| index.any_in(a.sheet, a.range.start.row, a.range.end.row, a.range.start.col, a.range.end.col, k)); - if !upstream { - for n in &funcs { - r.functions.entry(n.clone()).or_default().primary += 1; - } - } - listed.push((!upstream, k, funcs)); - } - // Primary mismatches first, each group in sheet then row-major order (already sorted). - listed.sort_by_key(|(primary, _, _)| !*primary); - for (primary, k, functions) in listed.into_iter().take(opts.max_report) { - let cell = cached.sheet(k.0).and_then(|s| s.cell(k.1)); - let expected = cell.map(|c| c.value.clone()).unwrap_or_default(); - let actual = fresh.sheet(k.0).and_then(|s| s.cell(k.1)).map(|x| x.value.scalar()).unwrap_or_default(); - r.mismatches.push(Mismatch { - cell: cell_name(cached, k), - formula: cell.map(formula_text).unwrap_or_default(), - kind: mismatch_kind(&expected, &actual), - expected, - actual, - functions, - primary, - }); - } - r -} - -// ---------------------------------------------------------------- round trip - -/// Writes `wb` with GridCraft's XLSX writer, validates the package against itself and against -/// `source` (the file `wb` was read from), reads it back and compares. -pub fn round_trip(wb: &Workbook, source: &[u8], opts: &Options) -> RoundTrip { - let bytes = match gridcraft_engine::io::save_bytes(wb, "roundtrip.xlsx") { - Ok(b) => b, - Err(e) => return RoundTrip { error: Some(format!("write failed: {e}")), categories: vec![] }, - }; - let mut package = Diffs::new("package", opts.max_report); - match validate_package(&bytes) { - Ok(issues) => issues.into_iter().for_each(|i| package.push(|| i)), - Err(e) => package.push(|| e), - } - if let (Ok(before), Ok(after)) = (relationship_kinds(source), relationship_kinds(&bytes)) { - for (key, kind) in &before { - if !after.contains_key(key) && !REBUILT_KINDS.contains(&key.as_str()) { - package.push(|| format!("lost relationship {kind}")); - } - } - } - let back = match gridcraft_engine::io::open_bytes("roundtrip.xlsx", &bytes) { - Ok((b, _)) => b, - Err(e) => return RoundTrip { error: Some(format!("reading the written file failed: {e}")), categories: vec![package.done()] }, - }; - let mut categories = diff_workbooks(wb, &back, opts); - categories.push(package.done()); - RoundTrip { error: None, categories } -} - -fn value_show(v: &Value) -> String { - match v { - Value::Empty => "(blank)".to_string(), - Value::Text(t) => serde_json::to_string(t.as_ref()).unwrap_or_default(), - Value::Number(n) => number_text(*n), - Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(), - Value::Error(e) => e.as_str().to_string(), - Value::Array(_) => v.scalar().display(), - } -} - -fn opt_formula(c: Option<&Cell>) -> String { - c.filter(|c| c.formula.is_some()).map(formula_text).unwrap_or_default() -} - -/// Per-sheet comparison of two lists, reporting what one side has and the other lacks. -fn diff_sets(d: &mut Diffs, sheet: &str, a: &BTreeSet, b: &BTreeSet) { - for x in a.difference(b) { - d.push(|| format!("{sheet}: lost {x}")); - } - for x in b.difference(a) { - d.push(|| format!("{sheet}: gained {x}")); - } -} - -/// A sheet's conditional-format rules in precedence order, as comparable text. The priority number -/// itself is left out, so renumbering without changing the order isn't a difference. -fn cond_format_list(s: &Sheet) -> Vec { - let mut cfs: Vec<_> = s.cond_formats.iter().collect(); - cfs.sort_by_key(|c| c.priority); - cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect() -} - -fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) { - if a != b { - d.push(|| format!("{sheet}: {a} → {b}")); - } -} - -/// A value as the file format can hold it: `#SPILL!`/`#CALC!` are cached as `#VALUE!` and an -/// unresolved circular reference as 0 (what Excel writes), so those aren't round-trip losses. -fn as_cached(v: Value) -> Value { - match v { - Value::Error(CellError::Spill | CellError::Calc) => Value::Error(CellError::Value), - Value::Error(CellError::Circ) => Value::Number(0.0), - v => v, - } -} - -fn num_fmt<'a>(wb: &'a Workbook, c: Option<&Cell>) -> &'a str { - wb.styles.get(c.map(|c| c.style).unwrap_or_default()).num_fmt.as_str() -} - -/// Feature-by-feature comparison of a workbook (`a`) with what reading it back gave (`b`). Sheets -/// are paired by position. -pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec { - let m = opts.max_report; - let mut sheets = Diffs::new("sheets", m); - let (an, bn): (Vec<&str>, Vec<&str>) = (a.sheets.iter().map(|s| s.name.as_str()).collect(), b.sheets.iter().map(|s| s.name.as_str()).collect()); - if an != bn { - sheets.push(|| format!("{an:?} → {bn:?}")); - } - let mut values = Diffs::new("values", m); - let mut formulas = Diffs::new("formulas", m); - let mut num_fmts = Diffs::new("numFmts", m); - let mut merges = Diffs::new("merges", m); - let mut tables = Diffs::new("tables", m); - let mut cond_formats = Diffs::new("condFormats", m); - let mut validations = Diffs::new("validations", m); - let mut charts = Diffs::new("charts", m); - let mut comments = Diffs::new("comments", m); - let mut hyperlinks = Diffs::new("hyperlinks", m); - let mut pivots = Diffs::new("pivots", m); - for (sa, sb) in a.sheets.iter().zip(b.sheets.iter()) { - let name = quote_sheet(&sa.name); - let mut cell = |c: CellRef, ca: Option<&Cell>, cb: Option<&Cell>| { - let cached = |x: Option<&Cell>| as_cached(x.map(|x| x.value.scalar()).unwrap_or_default()); - let (va, vb) = (cached(ca), cached(cb)); - if va != vb { - values.push(|| format!("{name}!{}: {} → {}", c.a1(), value_show(&va), value_show(&vb))); - } - let (fa, fb) = (opt_formula(ca), opt_formula(cb)); - if fa != fb { - formulas.push(|| format!("{name}!{}: {fa} → {fb}", c.a1())); - } - let (na, nb) = (num_fmt(a, ca), num_fmt(b, cb)); - if na != nb { - num_fmts.push(|| format!("{name}!{}: {na} → {nb}", c.a1())); - } - }; - for (c, ca) in sa.cells.iter() { - cell(c, Some(ca), sb.cell(c)); - } - for (c, cb) in sb.cells.iter() { - if sa.cell(c).is_none() { - cell(c, None, Some(cb)); - } - } - let set = |f: &dyn Fn(&Sheet) -> Vec, s: &Sheet| f(s).into_iter().collect::>(); - let merge_list = |s: &Sheet| -> Vec { s.merges.iter().map(|r| r.a1()).collect() }; - diff_sets(&mut merges, &name, &set(&merge_list, sa), &set(&merge_list, sb)); - let table_list = |s: &Sheet| -> Vec { - s.tables - .iter() - .map(|t| format!("{} {} [{}]", t.name, t.range.a1(), t.columns.iter().map(|c| c.name.as_str()).collect::>().join(", "))) - .collect() - }; - diff_sets(&mut tables, &name, &set(&table_list, sa), &set(&table_list, sb)); - let (cfa, cfb) = (cond_format_list(sa), cond_format_list(sb)); - if cfa.len() != cfb.len() { - cond_formats.push(|| format!("{name}: {} → {}", cfa.len(), cfb.len())); - } else if let Some((x, y)) = cfa.iter().zip(&cfb).find(|(x, y)| x != y) { - cond_formats.push(|| format!("{name}: {x} → {y}")); - } - diff_count(&mut validations, &name, sa.validations.len(), sb.validations.len()); - let chart_list = |s: &Sheet| s.charts.iter().map(|c| format!("{:?} ({} series)", c.kind, c.series.len())).collect::>(); - let (ca, cb) = (chart_list(sa), chart_list(sb)); - if ca != cb { - charts.push(|| format!("{name}: {ca:?} → {cb:?}")); - } - diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len()); - diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len()); - diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len()); - } - let mut names = Diffs::new("names", m); - let name_list = |wb: &Workbook| -> BTreeSet { - wb.names - .iter() - .map(|n| { - let scope = n.scope.map(|i| format!("{}!", quote_sheet(wb.sheet(i).map(|s| s.name.as_str()).unwrap_or("?")))).unwrap_or_default(); - format!("{scope}{}={}", n.name, n.formula) - }) - .collect() - }; - diff_sets(&mut names, "workbook", &name_list(a), &name_list(b)); - vec![ - sheets.done(), - values.done(), - formulas.done(), - num_fmts.done(), - merges.done(), - names.done(), - tables.done(), - cond_formats.done(), - validations.done(), - charts.done(), - comments.done(), - hyperlinks.done(), - pivots.done(), - ] -} - -// ---------------------------------------------------------------- package validation - -fn local_name(name: &[u8]) -> &[u8] { - match name.iter().rposition(|&b| b == b':') { - Some(i) => name.get(i + 1..).unwrap_or(name), - None => name, - } -} - -/// `(element local name, attributes)` for every start/empty element of an XML part. -fn xml_elements(xml: &[u8]) -> Result)>, String> { - use quick_xml::events::Event; - let mut reader = quick_xml::Reader::from_reader(xml); - let mut buf = Vec::new(); - let mut out = Vec::new(); - loop { - match reader.read_event_into(&mut buf) { - Ok(Event::Start(e)) | Ok(Event::Empty(e)) => { - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| { - let v = match a.normalized_value(quick_xml::XmlVersion::Explicit1_0) { - Ok(v) => v.into_owned(), - Err(_) => String::from_utf8_lossy(&a.value).into_owned(), - }; - (String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v) - }) - .collect(); - out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs)); - } - Ok(Event::Eof) => break, - Ok(_) => {} - Err(e) => return Err(format!("invalid XML: {e}")), - } - buf.clear(); - } - Ok(out) -} - -fn attr<'a>(attrs: &'a [(String, String)], k: &str) -> Option<&'a str> { - attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) -} - -/// Lower-cased part name without a leading slash: OPC part names compare case-insensitively. -fn part_key(name: &str) -> String { - name.trim_start_matches('/').to_ascii_lowercase() -} - -/// `%XX` escapes in a relationship target. -fn percent_decode(s: &str) -> String { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while let Some(&c) = b.get(i) { - let hex = |j: usize| b.get(j).and_then(|h| (*h as char).to_digit(16)); - match (c, hex(i + 1), hex(i + 2)) { - (b'%', Some(h), Some(l)) => { - out.push((h * 16 + l) as u8); - i += 3; - } - _ => { - out.push(c); - i += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() -} - -/// Resolves a relationship target against the source part's directory. -fn resolve_target(source_dir: &str, target: &str) -> String { - let target = percent_decode(target.split('#').next().unwrap_or(target)); - let joined = match target.strip_prefix('/') { - Some(abs) => abs.to_string(), - None if source_dir.is_empty() => target, - None => format!("{source_dir}/{target}"), - }; - let mut parts: Vec<&str> = Vec::new(); - for seg in joined.split('/') { - match seg { - "" | "." => {} - ".." => { - parts.pop(); - } - s => parts.push(s), - } - } - parts.join("/") -} - -type Zip<'a> = zip::ZipArchive>; - -fn zip_names(zip: &mut Zip<'_>) -> Vec { - (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() -} - -fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result, 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) -} - -/// Whether the producer flagged its cached results as stale with ``: -/// libraries that don't calculate write it, and store 0 or nothing as every formula's value. -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 mut workbook = "xl/workbook.xml".to_string(); - 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() - .find(|(e, a)| e == "Relationship" && attr(a, "Type").is_some_and(|t| t.ends_with("/officeDocument"))) - .and_then(|(_, a)| attr(a, "Target")) - { - workbook = resolve_target("", target); - } - 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() - .flatten() - .any(|(e, a)| e == "calcPr" && attr(&a, "fullCalcOnLoad").is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))) -} - -/// Problems Excel would repair in a written package: parts without a content type, content-type -/// overrides for missing parts, relationship files for missing parts, duplicate relationship ids -/// and internal relationships pointing at missing parts. `Err` when the package can't be read. -pub fn validate_package(bytes: &[u8]) -> Result, 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 = 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 (mut defaults, mut overrides) = (HashSet::new(), HashSet::new()); - match ct_name { - None => issues.push("no [Content_Types].xml".to_string()), - 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") { - defaults.insert(x.to_ascii_lowercase()); - } - } - "Override" => { - if let Some(p) = attr(&attrs, "PartName") { - overrides.insert(part_key(p)); - } - } - _ => {} - } - } - } - } - 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; - } - let ext = key.rsplit('/').next().and_then(|f| f.rsplit_once('.')).map(|(_, e)| e.to_string()); - if !overrides.contains(&key) && !ext.is_some_and(|e| defaults.contains(&e)) { - issues.push(format!("part {n} has no content type")); - } - } - let mut missing_overrides: Vec<&String> = overrides.iter().filter(|p| !parts.contains(*p)).collect(); - missing_overrides.sort(); - for p in missing_overrides { - issues.push(format!("content type override for missing part /{p}")); - } - 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. - let (dir, file) = match rels_file.rsplit_once('/') { - Some((d, f)) => (d, f), - None => continue, - }; - let Some(src_dir) = dir.strip_suffix("_rels").map(|d| d.trim_end_matches('/')) else { continue }; - let source = if src_dir.is_empty() { file.to_string() } else { format!("{src_dir}/{file}") }; - if !source.is_empty() && !parts.contains(&source) { - issues.push(format!("{n} describes missing part {source}")); - } - let mut ids = HashSet::new(); - for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? { - if el != "Relationship" { - continue; - } - let id = attr(&attrs, "Id").unwrap_or(""); - if !ids.insert(id.to_string()) { - issues.push(format!("{n}: duplicate relationship id {id}")); - } - if attr(&attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External")) { - continue; - } - let target = attr(&attrs, "Target").unwrap_or(""); - let resolved = resolve_target(src_dir, target); - if !parts.contains(&resolved.to_ascii_lowercase()) { - let kind = attr(&attrs, "Type").and_then(|t| t.rsplit('/').next()).unwrap_or("?"); - issues.push(format!("{n}: {id} ({kind}) targets missing part {resolved}")); - } - } - } - Ok(issues) -} - -/// Every relationship kind (last segment of the type, the same in the transitional and strict -/// namespaces) in the package's relationship parts, keyed in lower case. Relationships that carry -/// nothing are left out, as a save may rightly drop them: a link to a place in the workbook -/// (`#Sheet1!A1`, written as a cell's `location`) and a target part with nothing in it. -fn relationship_kinds(bytes: &[u8]) -> Result, 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 = 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 (finding: repeated decompression). - let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new(); - let mut budget: u64 = 512 * 1024 * 1024; - let mut kinds = BTreeMap::new(); - 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 Ok(els) = read_zip_part(&mut zip, n).and_then(|xml| xml_elements(&xml)) else { continue }; - for (_, attrs) in els.iter().filter(|(el, _)| el == "Relationship") { - let Some(kind) = attr(attrs, "Type").and_then(|t| t.rsplit('/').next()) else { continue }; - let target = attr(attrs, "Target").unwrap_or(""); - if kind.eq_ignore_ascii_case("hyperlink") && target.starts_with('#') { - continue; - } - let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External")); - if !external - && 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; - } - kinds.entry(kind.to_ascii_lowercase()).or_insert_with(|| kind.to_string()); - } - } - Ok(kinds) -} - -/// The directory of the part a rels part describes: `xl` for `xl/_rels/workbook.xml.rels`, the -/// empty string for the package's `_rels/.rels`. -fn rels_source_dir(key: &str) -> Option { - let (dir, _) = key.strip_suffix(".rels")?.rsplit_once('/')?; - Some(dir.strip_suffix("_rels")?.trim_end_matches('/').to_string()) -} - -/// Whether a part has content: an element under its root, or for comments (whose authors list -/// 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<'_>, 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"), - _ => None, - }; - let marker = match wanted { - Some(b"comment") => "comment", - Some(_) => "shape", - None => "any", - }; - if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) { - return *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<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool { - use quick_xml::events::Event; - let Ok(f) = zip.by_name(name) else { return true }; - if *budget == 0 { - return true; - } - let take = f.size().min(MAX_XML_PART).min(*budget); - *budget -= take; - let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(f.take(take))); - let wanted: Option<&'static [u8]> = match marker { - "comment" => Some(b"comment"), - "shape" => Some(b"shape"), - _ => None, - }; - let mut buf = Vec::new(); - let mut in_root = false; - loop { - match reader.read_event_into(&mut buf) { - Ok(Event::Start(e)) | Ok(Event::Empty(e)) => { - let found = match wanted { - Some(w) => local_name(e.name().as_ref()) == w, - None => in_root, - }; - if found { - return true; - } - in_root = true; - } - Ok(Event::Eof) => return false, - Ok(_) => {} - Err(_) => return true, - } - buf.clear(); - } -} - -// ---------------------------------------------------------------- output - -#[derive(Default)] -struct Totals { - files: usize, - opened: usize, - failed: usize, - formula_cells: usize, - checked: usize, - matched: usize, - mismatched: usize, - no_oracle: usize, - volatile: usize, - bool_as_number: usize, - round_trip_failed: usize, - round_trip_differing: usize, - categories: BTreeMap<&'static str, usize>, - functions: BTreeMap, - signatures: BTreeMap, -} - -fn totals(reports: &[FileReport]) -> Totals { - let mut t = Totals { files: reports.len(), ..Default::default() }; - for r in reports { - if r.error.is_some() { - t.failed += 1; - continue; - } - t.opened += 1; - t.formula_cells += r.calc.formula_cells; - t.checked += r.calc.checked; - t.matched += r.calc.matched; - t.mismatched += r.calc.mismatched; - t.no_oracle += r.calc.no_oracle; - t.volatile += r.calc.volatile; - t.bool_as_number += r.calc.bool_as_number; - if r.round_trip.error.is_some() { - t.round_trip_failed += 1; - } - if !r.round_trip.is_clean() { - t.round_trip_differing += 1; - } - for c in r.round_trip.differing() { - *t.categories.entry(c).or_default() += 1; - } - for (n, s) in &r.calc.functions { - t.functions.entry(n.clone()).or_default().add(s); - } - for (sig, n) in &r.calc.signatures { - *t.signatures.entry(sig.clone()).or_default() += n; - } - } - t -} - -/// Functions with mismatches, worst first: most primary mismatches, then most mismatches. -fn ranked(functions: &BTreeMap) -> Vec<(&String, &FnStat)> { - let mut v: Vec<(&String, &FnStat)> = functions.iter().filter(|(_, s)| s.mismatched > 0).collect(); - v.sort_by(|a, b| b.1.primary.cmp(&a.1.primary).then(b.1.mismatched.cmp(&a.1.mismatched)).then(a.0.cmp(b.0))); - v -} - -fn functions_json(functions: &BTreeMap) -> Json { - let mut v: Vec<(&String, &FnStat)> = functions.iter().collect(); - v.sort_by(|a, b| b.1.primary.cmp(&a.1.primary).then(b.1.mismatched.cmp(&a.1.mismatched)).then(a.0.cmp(b.0))); - Json::Array(v.into_iter().map(|(n, s)| json!({"name": n, "checked": s.checked, "mismatched": s.mismatched, "primary": s.primary})).collect()) -} - -pub fn report_json(reports: &[FileReport], opts: &Options) -> Json { - let files: Vec = reports - .iter() - .map(|r| { - let c = &r.calc; - let mismatches: Vec = c - .mismatches - .iter() - .map(|m| { - json!({ - "cell": m.cell, "formula": m.formula, "expected": value_json(&m.expected), "actual": value_json(&m.actual), - "kind": m.kind, "functions": m.functions, "primary": m.primary, - }) - }) - .collect(); - let categories: serde_json::Map = r - .round_trip - .categories - .iter() - .map(|cat| (cat.name.to_string(), json!({"equal": cat.diffs == 0, "diffs": cat.diffs, "examples": cat.examples}))) - .collect(); - json!({ - "path": r.path, - "opened": r.error.is_none(), - "error": r.error, - "warnings": r.warnings, - "calc": { - "formulaCells": c.formula_cells, "checked": c.checked, "matched": c.matched, "mismatched": c.mismatched, - "noOracle": c.no_oracle, "staleCache": c.stale_cache, "volatile": c.volatile, "boolAsNumber": c.bool_as_number, - "mismatches": mismatches, "functions": functions_json(&c.functions), - "signatures": c.signatures, - }, - "roundTrip": {"error": r.round_trip.error, "differing": r.round_trip.differing(), "categories": categories}, - }) - }) - .collect(); - let t = totals(reports); - json!({ - "schema": SCHEMA, - "tolerance": opts.tolerance, - "files": files, - "totals": { - "files": t.files, "opened": t.opened, "failedToOpen": t.failed, "formulaCells": t.formula_cells, "checked": t.checked, - "matched": t.matched, "mismatched": t.mismatched, "noOracle": t.no_oracle, "volatile": t.volatile, "boolAsNumber": t.bool_as_number, - "roundTripFailed": t.round_trip_failed, "roundTripDiffering": t.round_trip_differing, "categoriesDiffering": t.categories, - }, - "functions": functions_json(&t.functions), - "signatures": t.signatures, - }) -} - -/// One report line: line breaks and tabs shown escaped so that they stay visible as differences. -fn one_line(s: &str) -> String { - s.replace('\n', "\\n").replace('\r', "\\r").replace('\t', "\\t") -} - -/// `…tail` of a long label. -fn fit(s: &str, w: usize) -> String { - let n = s.chars().count(); - if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::()) } -} - -fn print_human(reports: &[FileReport], opts: &Options) { - for r in reports { - outln!("== {}", r.path); - if let Some(e) = &r.error { - outln!(" can't open: {e}"); - continue; - } - let c = &r.calc; - outln!( - " formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile", - c.formula_cells, - c.checked, - c.matched, - c.mismatched, - c.no_oracle, - c.volatile - ); - if c.stale_cache { - outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)"); - } - if c.bool_as_number > 0 { - outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number); - } - for m in &c.mismatches { - let tag = if m.primary { "mismatch" } else { " (downstream)" }; - outln!( - " {tag} {} {} expected {} got {} [{}]", - m.cell, - one_line(&m.formula), - value_show(&m.expected), - value_show(&m.actual), - m.functions.join(" ") - ); - } - if c.mismatched > c.mismatches.len() { - outln!(" … {} more mismatches", c.mismatched - c.mismatches.len()); - } - let rt = &r.round_trip; - if let Some(e) = &rt.error { - outln!(" round trip: {e}"); - } - let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect(); - if differing.is_empty() && rt.error.is_none() { - outln!(" round trip: all equal"); - } - for cat in differing { - outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs); - for e in &cat.examples { - outln!(" {}", one_line(e)); - } - if cat.diffs > cat.examples.len() { - outln!(" … {} more", cat.diffs - cat.examples.len()); - } - } - } - outln!(""); - let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50); - outln!( - "{:8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip", - "file", - "formulas", - "checked", - "matched", - "mismatch", - "no-oracle", - "volatile" - ); - for r in reports { - let label = fit(&r.path, w); - if let Some(e) = &r.error { - outln!("{label: "FAILED".to_string(), - (None, d) if d.is_empty() => "ok".to_string(), - (None, d) => d.join(","), - }; - outln!( - "{label:8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}", - c.formula_cells, - c.checked, - c.matched, - c.mismatched, - c.no_oracle, - c.volatile - ); - } - let t = totals(reports); - let top = ranked(&t.functions); - if !top.is_empty() { - outln!(""); - outln!("top mismatching functions (primary = no mismatching precedent):"); - outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked"); - for (n, s) in top.iter().take(opts.max_report.max(1)) { - outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked); - } - } - let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect(); - sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); - if !sigs.is_empty() { - outln!(""); - outln!("mismatch signatures (expected → GridCraft):"); - for (sig, n) in sigs.iter().take(opts.max_report.max(1)) { - outln!(" {n:>8} {sig}"); - } - } - outln!(""); - outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed); - outln!( - "formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)", - t.formula_cells, - t.checked, - t.matched, - t.mismatched, - t.no_oracle, - t.volatile - ); - if t.bool_as_number > 0 { - outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number); - } - let cats: Vec = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect(); - outln!( - "round trip: {} of {} files differ{}{}", - t.round_trip_differing, - t.opened, - if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() }, - if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) } - ); -} - #[cfg(test)] -mod tests { - #![allow(clippy::unwrap_used)] - use std::io::Write as _; - use std::sync::Arc; - - use gridcraft_engine::model::Formula; - - use super::*; - - #[test] - fn discovery_reports_a_directory_read_error() { - let path = std::env::temp_dir().join(format!("gridcraft-check-not-a-directory-{}", std::process::id())); - std::fs::write(&path, "not a directory").unwrap(); - let mut discovery = Discovery::default(); - let mut seen = std::collections::HashSet::new(); - assert!(walk(&path, 0, &mut discovery, &mut seen)); - assert!(discovery.files.is_empty()); - assert_eq!(discovery.failures.len(), 1); - assert_eq!(discovery.failures[0].path, path.to_string_lossy()); - assert!(discovery.failures[0].error.as_ref().unwrap().contains("cannot read directory")); - let _ = std::fs::remove_file(path); - } - - #[test] - fn discovery_reports_omissions_only_after_the_file_limit() { - let mut discovery = Discovery { files: vec![PathBuf::from("book.xlsx"); MAX_FILES - 1], ..Default::default() }; - assert!(discovery.add_file(PathBuf::from("last.xlsx"))); - assert!(discovery.failures.is_empty()); - assert!(!discovery.add_file(PathBuf::from("omitted.xlsx"))); - assert_eq!(discovery.files.len(), MAX_FILES); - assert_eq!(discovery.failures[0].path, "omitted.xlsx"); - assert!(discovery.failures[0].error.as_ref().unwrap().contains("file limit")); - } - - fn at(a1: &str) -> CellRef { - CellRef::parse(a1).unwrap() - } - - /// A workbook whose cells are `(A1, input, cached value)`: an input starting with `=` is a - /// formula with that cached value, anything else a constant. - fn book(cells: &[(&str, &str, Value)]) -> Workbook { - let mut wb = Workbook::new(); - let sh = wb.sheet_mut(0).unwrap(); - for (a1, input, cached) in cells { - let cell = if input.starts_with('=') { - Cell { value: cached.clone(), formula: Some(Arc::new(Formula::new(input))), ..Default::default() } - } else { - Cell::value(cached.clone()) - }; - sh.set_cell(at(a1), cell); - } - wb - } - - fn check(wb: &Workbook, opts: &Options) -> FileReport { - let bytes = gridcraft_engine::io::save_bytes(wb, "t.xlsx").unwrap(); - check_bytes("t.xlsx", &bytes, opts) - } - - fn n(x: f64) -> Value { - Value::number(x) - } - - #[test] - fn matching_cached_values_pass() { - let wb = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0)), ("C1", "=A1&\"x\"", Value::text("2x")), ("D1", "=A1>1", Value::Bool(true))]); - let r = check(&wb, &Options::default()); - assert_eq!(r.error, None); - assert_eq!((r.calc.formula_cells, r.calc.checked, r.calc.matched, r.calc.mismatched), (3, 3, 3, 0)); - assert!(r.is_clean(), "{r:?}"); - } - - #[test] - fn wrong_cached_value_is_a_mismatch_and_ranks_its_function() { - // Excel "said" SUM gives 7; GridCraft computes 6. C1 reads B1 and is consistent with - // Excel's 7, so it mismatches too, but only as a downstream effect. - let wb = book(&[("A1", "2", n(2.0)), ("A2", "4", n(4.0)), ("B1", "=SUM(A1:A2)", n(7.0)), ("C1", "=B1+1", n(8.0))]); - let r = check(&wb, &Options::default()); - assert_eq!((r.calc.checked, r.calc.mismatched), (2, 2)); - let first = &r.calc.mismatches[0]; - assert_eq!(first.cell, "Sheet1!B1"); - assert_eq!(first.formula, "=SUM(A1:A2)"); - assert_eq!((first.expected.clone(), first.actual.clone(), first.kind, first.primary), (n(7.0), n(6.0), "numeric", true)); - assert!(!r.calc.mismatches[1].primary); - assert_eq!(r.calc.functions["SUM"], FnStat { checked: 1, mismatched: 1, primary: 1 }); - assert_eq!(r.calc.functions["(no function)"], FnStat { checked: 1, mismatched: 1, primary: 0 }); - assert!(!r.is_clean()); - } - - #[test] - fn errors_compare_by_kind() { - let wb = book(&[("A1", "=1/0", Value::Error(CellError::Div0)), ("A2", "=1/0", Value::Error(CellError::NA)), ("A3", "=1/0", n(0.0))]); - let r = check(&wb, &Options::default()); - assert_eq!((r.calc.matched, r.calc.mismatched), (1, 2)); - assert!(r.calc.mismatches.iter().all(|m| m.kind == "error")); - assert_eq!(r.calc.signatures.get("#N/A → #DIV/0!"), Some(&1)); - assert_eq!(r.calc.signatures.get("number → #DIV/0!"), Some(&1)); - assert!(values_match(&Value::Error(CellError::NA), &Value::Error(CellError::NA), 0.0)); - assert!(!values_match(&Value::Error(CellError::NA), &Value::Error(CellError::Value), 0.0)); - } - - #[test] - fn numbers_compare_within_tolerance() { - assert!(values_match(&n(3.0000000001), &n(3.0), 1e-9)); - assert!(!values_match(&n(3.0000000001), &n(3.0), 1e-12)); - // Absolute near zero. - assert!(values_match(&n(1e-12), &n(0.0), 1e-9)); - assert!(values_match(&n(1e12 + 1.0), &n(1e12), 1e-9)); - assert!(!values_match(&n(0.0), &Value::Empty, 1.0)); - assert!(!values_match(&Value::text("1"), &n(1.0), 1.0)); - assert!(values_match(&Value::text("a"), &Value::text("a"), 0.0)); - assert!(!values_match(&Value::text("a"), &Value::text("A"), 0.0)); - assert!(!values_match(&Value::Bool(true), &n(1.0), 1.0)); - let wb = book(&[("A1", "=1+2", n(3.0000000001))]); - assert_eq!(check(&wb, &Options::default()).calc.matched, 1); - assert_eq!(check(&wb, &Options { tolerance: 1e-12, ..Default::default() }).calc.mismatched, 1); - } - - /// Business Central writes TRUE and FALSE as `TRUE()1`, without `t="b"`: - /// the cache holds the right value under a number type, so it matches and is counted apart. - #[test] - fn booleans_cached_as_numbers_match_and_are_counted_apart() { - let wb = book(&[ - ("A1", "=TRUE()", n(1.0)), - ("B1", "=FALSE()", n(0.0)), - ("C1", "=TRUE()", Value::Bool(true)), - ("D1", "=1=1", n(0.0)), - ("E1", "=TRUE()+0", n(1.0)), - ]); - let r = check(&wb, &Options::default()); - assert_eq!((r.calc.checked, r.calc.matched, r.calc.mismatched), (5, 4, 1)); - // A cached 0 for TRUE is still a mismatch, and a number result is compared as a number. - assert_eq!(r.calc.mismatches[0].cell, "Sheet1!D1"); - assert_eq!(r.calc.signatures.get("number → bool"), Some(&1)); - assert_eq!(r.calc.bool_as_number, 2); - let v = report_json(std::slice::from_ref(&r), &Options::default()); - assert_eq!((v["files"][0]["calc"]["boolAsNumber"].clone(), v["totals"]["boolAsNumber"].clone()), (json!(2), json!(2))); - assert!(bool_cached_as_number(&n(1.0), &Value::Bool(true))); - assert!(!bool_cached_as_number(&n(1.0), &Value::Bool(false))); - assert!(!bool_cached_as_number(&n(2.0), &Value::Bool(true))); - assert!(!bool_cached_as_number(&Value::Bool(true), &n(1.0))); - } - - #[test] - fn missing_cached_values_and_volatile_formulas_are_skipped() { - let wb = - book(&[("A1", "=1+1", Value::Empty), ("B1", "=NOW()", n(1.0)), ("B2", "=B1+1", n(2.0)), ("B3", "=CELL(\"filename\")", Value::text("x"))]); - let r = check(&wb, &Options::default()); - assert_eq!((r.calc.formula_cells, r.calc.checked, r.calc.no_oracle, r.calc.volatile), (4, 0, 1, 3)); - } - - #[test] - fn full_calc_on_load_means_no_oracle() { - // A formula without a cached value makes GridCraft's writer flag the file - // `fullCalcOnLoad`, like libraries that store 0 for every formula: B1's wrong "cached" - // value must not count as a mismatch then. - let wb = book(&[("A1", "=1+1", Value::Empty), ("B1", "=2+2", n(0.0))]); - let bytes = gridcraft_engine::io::save_bytes(&wb, "t.xlsx").unwrap(); - assert!(full_calc_on_load(&bytes)); - let r = check_bytes("t.xlsx", &bytes, &Options::default()); - assert!(r.calc.stale_cache); - assert_eq!((r.calc.checked, r.calc.no_oracle, r.calc.mismatched), (0, 2, 0)); - let fresh = gridcraft_engine::io::save_bytes(&book(&[("B1", "=2+2", n(0.0))]), "t.xlsx").unwrap(); - assert!(!full_calc_on_load(&fresh)); - assert!(!full_calc_on_load(b"not a zip")); - } - - #[test] - fn volatile_names_propagate() { - let mut wb = book(&[("A1", "=Stamp+1", n(1.0))]); - wb.names.push(gridcraft_engine::model::DefinedName { - name: "Stamp".into(), - scope: None, - formula: "TODAY()".into(), - comment: String::new(), - hidden: false, - }); - assert!(volatile_names(&wb).contains("STAMP")); - assert_eq!(check(&wb, &Options::default()).calc.volatile, 1); - } - - #[test] - fn round_trip_of_a_simple_book_is_clean() { - let mut wb = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0)), ("A2", "x", Value::text("x"))]); - wb.sheet_mut(0).unwrap().merges.push(gridcraft_engine::core::RangeRef::parse("C1:D2").unwrap()); - let source = gridcraft_engine::io::save_bytes(&wb, "t.xlsx").unwrap(); - let rt = round_trip(&wb, &source, &Options::default()); - assert_eq!(rt.error, None); - assert!(rt.is_clean(), "{rt:?}"); - assert!(rt.categories.iter().any(|c| c.name == "package")); - } - - #[test] - fn diff_detects_lost_features() { - let mut a = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0))]); - a.sheet_mut(0).unwrap().merges.push(gridcraft_engine::core::RangeRef::parse("C1:D2").unwrap()); - let mut b = a.clone(); - let sh = b.sheet_mut(0).unwrap(); - sh.merges.clear(); - sh.set_cell(at("A1"), Cell::value(n(3.0))); - sh.set_cell(at("B1"), Cell::value(n(6.0))); - b.sheets.push(Arc::new(Sheet::new("Extra"))); - let cats = diff_workbooks(&a, &b, &Options { max_report: 1, ..Default::default() }); - let get = |name: &str| cats.iter().find(|c| c.name == name).unwrap(); - assert_eq!(get("values").diffs, 1); - assert_eq!(get("values").examples, ["Sheet1!A1: 2 → 3"]); - assert_eq!(get("formulas").examples, ["Sheet1!B1: =A1*3 → "]); - assert_eq!(get("merges").examples, ["Sheet1: lost C1:D2"]); - assert_eq!(get("sheets").diffs, 1); - assert_eq!(get("tables").diffs, 0); - } - - #[test] - fn diff_detects_changed_cond_format_rule() { - use gridcraft_engine::model::{CfRule, CfValueKind, Color, CondFormat}; - let bar = |gradient: bool, priority: u32| CondFormat { - ranges: vec![gridcraft_engine::core::RangeRef::parse("A1").unwrap()], - rule: CfRule::DataBar { min: CfValueKind::Min, max: CfValueKind::Max, color: Color::Rgb(0x638EC6), gradient, show_value: true }, - priority, - stop_if_true: false, - }; - let with = |cf: CondFormat| { - let mut wb = book(&[("A1", "2", n(2.0))]); - wb.sheet_mut(0).unwrap().cond_formats.push(cf); - wb - }; - let diffs = - |a: &Workbook, b: &Workbook| diff_workbooks(a, b, &Options::default()).into_iter().find(|c| c.name == "condFormats").unwrap().diffs; - assert_eq!(diffs(&with(bar(false, 1)), &with(bar(true, 1))), 1); - assert_eq!(diffs(&with(bar(true, 1)), &with(bar(true, 1))), 0); - assert_eq!(diffs(&with(bar(true, 1)), &with(bar(true, 5))), 0); - } - - fn zip_of(parts: &[(&str, &str)]) -> Vec { - let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); - for (name, body) in parts { - z.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); - z.write_all(body.as_bytes()).unwrap(); - } - z.finish().unwrap().into_inner() - } - - #[test] - fn package_validation_finds_what_excel_would_repair() { - let bytes = zip_of(&[ - ( - "[Content_Types].xml", - r#""#, - ), - ("_rels/.rels", r#""#), - ("xl/workbook.xml", ""), - ("xl/styles.xml", ""), - ( - "xl/_rels/workbook.xml.rels", - r#""#, - ), - ]); - let issues = validate_package(&bytes).unwrap(); - assert_eq!( - issues, - [ - "part xl/styles.xml has no content type", - "content type override for missing part /xl/gone.xml", - "xl/_rels/workbook.xml.rels: rId2 (worksheet) targets missing part xl/worksheets/sheet1.xml", - "xl/_rels/workbook.xml.rels: duplicate relationship id rId2", - ] - ); - assert!(validate_package(b"not a zip").is_err()); - let own = gridcraft_engine::io::save_bytes(&book(&[("A1", "=1", n(1.0))]), "t.xlsx").unwrap(); - assert_eq!(validate_package(&own).unwrap(), Vec::::new()); - } - - const WB_RELS: &str = "xl/_rels/workbook.xml.rels"; - const SHEET_RELS: &str = "xl/worksheets/_rels/sheet1.xml.rels"; - const MADE_UP: &str = r#""#; - /// Not empty: an empty part isn't a loss. - const MADE_UP_PART: (&str, &str) = ("xl/madeUp.xml", ""); - - /// `bytes` with relationships added to rels parts (created when missing) and `parts` added. - fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec { - let mut src = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); - let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); - 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().to_string(); - let mut body = String::new(); - f.read_to_string(&mut body).unwrap(); - if let Some(at) = pending.iter().position(|(r, _)| *r == name) { - body = body.replace("", &format!("{}", pending.remove(at).1)); - } - out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); - out.write_all(body.as_bytes()).unwrap(); - } - let created = pending.iter().map(|(r, extra)| { - (*r, format!(r#"{extra}"#)) - }); - for (name, body) in created.collect::>().iter().map(|(n, b)| (*n, b.as_str())).chain(parts.iter().copied()) { - out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); - out.write_all(body.as_bytes()).unwrap(); - } - out.finish().unwrap().into_inner() - } - - /// The `package` examples of checking `source`. - fn package_of(source: &[u8]) -> Vec { - let r = check_bytes("t.xlsx", source, &Options::default()); - r.round_trip.categories.iter().find(|c| c.name == "package").unwrap().examples.clone() - } - - fn plain() -> Vec { - gridcraft_engine::io::save_bytes(&book(&[("A1", "1", n(1.0))]), "t.xlsx").unwrap() - } - - #[test] - fn package_reports_relationship_kinds_the_output_lost() { - // A kind GridCraft doesn't know is dropped on save; a calculation chain is never written - // (Excel rebuilds it), so its absence isn't a loss. - let calc_chain = r#""#; - let source = with_rels(&plain(), &[(WB_RELS, &format!("{MADE_UP}{calc_chain}"))], &[MADE_UP_PART, ("xl/calcChain.xml", "")]); - assert_eq!(package_of(&source), ["lost relationship madeUp"]); - assert!(check_bytes("t.xlsx", &plain(), &Options::default()).round_trip.is_clean()); - } - - // In the three tests below the made-up kind stays lost, so the comparison is known to run. - - #[test] - fn an_internal_link_written_as_a_relationship_is_not_a_loss() { - // openpyxl writes `#Sheet1!B2` as an external relationship; GridCraft writes `location`. - let link = r##""##; - let source = with_rels(&plain(), &[(WB_RELS, MADE_UP), (SHEET_RELS, link)], &[MADE_UP_PART]); - assert_eq!(package_of(&source), ["lost relationship madeUp"]); - } - - #[test] - fn comments_without_a_comment_are_not_a_loss() { - let rels = r#""#; - let comments = r#"A"#; - let vml = r#""#; - let source = with_rels( - &plain(), - &[(WB_RELS, MADE_UP), (SHEET_RELS, rels)], - &[MADE_UP_PART, ("xl/comments1.xml", comments), ("xl/drawings/vmlDrawing1.vml", vml)], - ); - assert_eq!(package_of(&source), ["lost relationship madeUp"]); - } - - #[test] - fn empty_drawings_and_person_lists_are_not_a_loss() { - let drawing = r#""#; - let person = - r#""#; - let source = with_rels( - &plain(), - &[(WB_RELS, &format!("{MADE_UP}{person}")), (SHEET_RELS, drawing)], - &[ - MADE_UP_PART, - ("xl/drawings/drawing1.xml", r#""#), - ("xl/persons/person.xml", r#""#), - ], - ); - assert_eq!(package_of(&source), ["lost relationship madeUp"]); - } - - #[test] - fn json_lists_warning_messages() { - let with = FileReport { path: "a.ods".into(), warnings: vec!["ODS data-only import".into()], ..Default::default() }; - let without = FileReport { path: "b.xlsx".into(), ..Default::default() }; - let v = report_json(&[with, without], &Options::default()); - assert_eq!(v["files"][0]["warnings"], json!(["ODS data-only import"])); - assert_eq!(v["files"][1]["warnings"], json!([])); - } - - #[test] - fn unopenable_files_are_reported() { - let r = check_bytes("broken.xlsx", b"PK\x03\x04 not really", &Options::default()); - assert!(r.error.is_some()); - assert!(!r.is_clean()); - } - - #[test] - fn json_schema_keys() { - let wb = book(&[("A1", "=1+1", n(3.0))]); - let reports = vec![check(&wb, &Options::default()), check_bytes("bad.xlsx", b"", &Options::default())]; - let v = report_json(&reports, &Options::default()); - let keys = |v: &Json| v.as_object().unwrap().keys().cloned().collect::>(); - let set = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::>(); - assert_eq!(keys(&v), set(&["schema", "tolerance", "files", "totals", "functions", "signatures"])); - assert_eq!(v["schema"], SCHEMA); - let f = &v["files"][0]; - assert_eq!(keys(f), set(&["path", "opened", "error", "warnings", "calc", "roundTrip"])); - assert_eq!( - keys(&f["calc"]), - set(&[ - "formulaCells", - "checked", - "matched", - "mismatched", - "noOracle", - "staleCache", - "volatile", - "boolAsNumber", - "mismatches", - "functions", - "signatures" - ]) - ); - assert_eq!(f["calc"]["signatures"], json!({"number → number": 1})); - assert_eq!(keys(&f["calc"]["mismatches"][0]), set(&["cell", "formula", "expected", "actual", "kind", "functions", "primary"])); - assert_eq!(f["calc"]["mismatches"][0]["expected"], json!(3.0)); - assert_eq!(keys(&f["roundTrip"]), set(&["error", "differing", "categories"])); - assert_eq!( - keys(&f["roundTrip"]["categories"]), - set(&[ - "sheets", - "values", - "formulas", - "numFmts", - "merges", - "names", - "tables", - "condFormats", - "validations", - "charts", - "comments", - "hyperlinks", - "pivots", - "package" - ]) - ); - assert_eq!(keys(&f["roundTrip"]["categories"]["values"]), set(&["equal", "diffs", "examples"])); - assert_eq!(v["files"][1]["opened"], json!(false)); - assert_eq!( - keys(&v["totals"]), - set(&[ - "files", - "opened", - "failedToOpen", - "formulaCells", - "checked", - "matched", - "mismatched", - "noOracle", - "volatile", - "boolAsNumber", - "roundTripFailed", - "roundTripDiffering", - "categoriesDiffering" - ]) - ); - assert_eq!(keys(&v["functions"][0]), set(&["name", "checked", "mismatched", "primary"])); - } -} +mod tests; diff --git a/apps/gridcraft-cli/src/check/calc.rs b/apps/gridcraft-cli/src/check/calc.rs new file mode 100644 index 0000000000..8ce3780710 --- /dev/null +++ b/apps/gridcraft-cli/src/check/calc.rs @@ -0,0 +1,258 @@ +use super::*; + +/// Functions whose result depends on the clock, a random generator or the environment. +const VOLATILE: [&str; 6] = ["RAND", "RANDARRAY", "RANDBETWEEN", "NOW", "TODAY", "INFO"]; + +// ---------------------------------------------------------------- calc oracle + +fn functions_of(e: &Expr) -> Vec { + let mut set = BTreeSet::new(); + e.walk(&mut |x| { + if let Expr::Call(n, _) = x { + set.insert(n.clone()); + } + }); + set.into_iter().collect() +} + +fn is_volatile(e: &Expr, volatile_names: &HashSet) -> bool { + let mut v = false; + e.walk(&mut |x| match x { + Expr::Call(n, args) => { + let filename = n == "CELL" && matches!(args.first(), Some(Expr::Text(t)) if t.eq_ignore_ascii_case("filename")); + if filename || VOLATILE.contains(&n.as_str()) { + v = true; + } + } + Expr::Name(n) if volatile_names.contains(&n.to_ascii_uppercase()) => v = true, + _ => {} + }); + v +} + +/// Upper-cased defined names whose formula is volatile, directly or through other names. +/// +/// Volatility flows backwards along name references: each name is parsed and walked once, and a +/// worklist carries volatility from a name to the names that use it. Rescanning every name until +/// nothing changes was quadratic: a file listing its names so that each pass marked only one more +/// did one full pass per name. +pub(super) fn volatile_names(wb: &Workbook) -> HashSet { + let mut set = HashSet::new(); + // Upper-cased name -> the names whose formulas refer to it. + let mut users: HashMap> = HashMap::new(); + let mut queue = Vec::new(); + let none = HashSet::new(); + for n in &wb.names { + let name = n.name.to_ascii_uppercase(); + let Ok(e) = gridcraft_engine::formula::parse(&n.formula) else { continue }; + if is_volatile(&e, &none) { + if set.insert(name.clone()) { + queue.push(name.clone()); + } + continue; + } + let mut used = BTreeSet::new(); + e.walk(&mut |x| { + if let Expr::Name(r) = x { + used.insert(r.to_ascii_uppercase()); + } + }); + for r in used { + users.entry(r).or_default().push(name.clone()); + } + } + while let Some(v) = queue.pop() { + for user in users.remove(&v).unwrap_or_default() { + if set.insert(user.clone()) { + queue.push(user); + } + } + } + set +} + +/// The formula as the formula bar shows it. +pub(super) fn formula_text(cell: &Cell) -> String { + cell.bar_text() +} + +fn cell_name(wb: &Workbook, (sheet, c): Key) -> String { + let name = wb.sheet(sheet).map(|s| s.name.as_str()).unwrap_or("?"); + format!("{}!{}", quote_sheet(name), c.a1()) +} + +/// Whether the producer cached GridCraft's logical result as the number 1 or 0. Excel types a +/// logical result `t="b"`; a writer that leaves the type out (`TRUE()1`, as +/// Business Central's "Open in Excel" exports do) stores the same value, read back as a number. +pub fn bool_cached_as_number(expected: &Value, actual: &Value) -> bool { + matches!((expected, actual), (Value::Number(n), Value::Bool(b)) if *n == if *b { 1.0 } else { 0.0 }) +} + +/// Whether GridCraft's `actual` agrees with the producer's `expected`. +pub fn values_match(expected: &Value, actual: &Value, tolerance: f64) -> bool { + match (expected, actual) { + (Value::Number(a), Value::Number(b)) => (a - b).abs() <= tolerance * a.abs().max(b.abs()).max(1.0), + (Value::Text(a), Value::Text(b)) => a == b, + (Value::Bool(a), Value::Bool(b)) => a == b, + (Value::Error(a), Value::Error(b)) => a == b, + _ => false, + } +} + +fn type_name(v: &Value) -> &'static str { + match v { + Value::Empty => "blank", + Value::Number(_) => "number", + Value::Text(_) => "text", + Value::Bool(_) => "bool", + Value::Error(e) => e.as_str(), + Value::Array(_) => "array", + } +} + +fn mismatch_kind(expected: &Value, actual: &Value) -> &'static str { + match (expected, actual) { + (_, Value::Empty) => "blank", + (Value::Number(_), Value::Number(_)) => "numeric", + (Value::Text(_), Value::Text(_)) => "text", + (Value::Bool(_), Value::Bool(_)) => "bool", + (Value::Error(_), _) | (_, Value::Error(_)) => "error", + _ => "type", + } +} + +/// Mismatched cells indexed by (sheet, column) → rows, for precedent-area queries. +struct MismatchIndex { + cols: HashMap<(usize, u32), BTreeSet>, + /// Columns with mismatches per sheet (for very wide areas). + sheet_cols: HashMap>, +} + +impl MismatchIndex { + fn new(keys: &[Key]) -> MismatchIndex { + let mut cols: HashMap<(usize, u32), BTreeSet> = HashMap::new(); + let mut sheet_cols: HashMap> = HashMap::new(); + for &(s, c) in keys { + cols.entry((s, c.col)).or_default().insert(c.row); + sheet_cols.entry(s).or_default().insert(c.col); + } + MismatchIndex { cols, sheet_cols } + } + /// Whether a mismatched cell other than `own` lies in the area. + fn any_in(&self, sheet: usize, r0: u32, r1: u32, c0: u32, c1: u32, own: Key) -> bool { + let Some(cols) = self.sheet_cols.get(&sheet) else { return false }; + cols.range(c0..=c1) + .any(|&col| self.cols.get(&(sheet, col)).is_some_and(|rows| rows.range(r0..=r1).any(|&row| (sheet, CellRef::new(row, col)) != own))) + } +} + +/// Compares every formula cell of `cached` (as the producer saved it) with `fresh` (recalculated +/// by GridCraft). Without `trust_cache` nothing is compared (see [`CalcReport::stale_cache`]). +pub fn oracle(cached: &Workbook, fresh: &Workbook, calc: &Calc, trust_cache: bool, opts: &Options) -> CalcReport { + let mut r = CalcReport { stale_cache: !trust_cache, ..Default::default() }; + let vnames = volatile_names(cached); + let mut volatile: HashSet = HashSet::new(); + for (si, sh) in cached.sheets.iter().enumerate() { + for (c, cell) in sh.cells.iter() { + if let Some(f) = &cell.formula { + r.formula_cells += 1; + if f.expr_arc().is_some_and(|e| is_volatile(&e, &vnames)) { + volatile.insert((si, c)); + } + } + } + } + // Everything downstream of a volatile formula is volatile too; each key is pushed once. + let mut stack: Vec = volatile.iter().copied().collect(); + let mut deps = Vec::new(); + while let Some((s, c)) = stack.pop() { + deps.clear(); + calc.graph.dependents(s, c, &mut deps); + if let Some(range) = fresh.sheet(s).and_then(|sh| sh.spill_ranges.get(&c)) { + calc.graph.dependents_of_range(s, *range, &mut deps); + } + for k in deps.drain(..) { + if volatile.insert(k) { + stack.push(k); + } + } + } + + let mut bad: Vec<(Key, Vec)> = Vec::new(); + for (si, sh) in cached.sheets.iter().enumerate() { + for (c, cell) in sh.cells.iter() { + let Some(f) = &cell.formula else { continue }; + if volatile.contains(&(si, c)) { + r.volatile += 1; + continue; + } + if cell.value.is_empty() || !trust_cache { + r.no_oracle += 1; + continue; + } + r.checked += 1; + let actual = fresh.sheet(si).and_then(|s| s.cell(c)).map(|x| x.value.scalar()).unwrap_or_default(); + let funcs = match f.expr_arc() { + Some(e) => { + let names = functions_of(&e); + if names.is_empty() { vec!["(no function)".to_string()] } else { names } + } + None => vec!["(unparsed)".to_string()], + }; + let bool_as_number = bool_cached_as_number(&cell.value, &actual); + let ok = bool_as_number || values_match(&cell.value, &actual, opts.tolerance); + if bool_as_number { + r.bool_as_number += 1; + } + for n in &funcs { + let st = r.functions.entry(n.clone()).or_default(); + st.checked += 1; + if !ok { + st.mismatched += 1; + } + } + if ok { + r.matched += 1; + } else { + r.mismatched += 1; + *r.signatures.entry(format!("{} → {}", type_name(&cell.value), type_name(&actual))).or_default() += 1; + bad.push(((si, c), funcs)); + } + } + } + + // A mismatch is primary when none of its precedent cells mismatch. + let keys: Vec = bad.iter().map(|(k, _)| *k).collect(); + let index = MismatchIndex::new(&keys); + let mut listed: Vec<(bool, Key, Vec)> = Vec::with_capacity(bad.len()); + for (k, funcs) in bad { + let upstream = calc + .graph + .precedents_of(k) + .iter() + .any(|a| index.any_in(a.sheet, a.range.start.row, a.range.end.row, a.range.start.col, a.range.end.col, k)); + if !upstream { + for n in &funcs { + r.functions.entry(n.clone()).or_default().primary += 1; + } + } + listed.push((!upstream, k, funcs)); + } + // Primary mismatches first, each group in sheet then row-major order (already sorted). + listed.sort_by_key(|(primary, _, _)| !*primary); + for (primary, k, functions) in listed.into_iter().take(opts.max_report) { + let cell = cached.sheet(k.0).and_then(|s| s.cell(k.1)); + let expected = cell.map(|c| c.value.clone()).unwrap_or_default(); + let actual = fresh.sheet(k.0).and_then(|s| s.cell(k.1)).map(|x| x.value.scalar()).unwrap_or_default(); + r.mismatches.push(Mismatch { + cell: cell_name(cached, k), + formula: cell.map(formula_text).unwrap_or_default(), + kind: mismatch_kind(&expected, &actual), + expected, + actual, + functions, + primary, + }); + } + r +} diff --git a/apps/gridcraft-cli/src/check/fidelity.rs b/apps/gridcraft-cli/src/check/fidelity.rs new file mode 100644 index 0000000000..d8def2747e --- /dev/null +++ b/apps/gridcraft-cli/src/check/fidelity.rs @@ -0,0 +1,185 @@ +use super::calc::formula_text; +use super::package::{REBUILT_KINDS, relationship_kinds, validate_package}; +use super::{BTreeSet, Category, Cell, CellError, CellRef, Diffs, Options, RoundTrip, Sheet, Value, Workbook, number_text, quote_sheet}; + +// ---------------------------------------------------------------- round trip + +/// Writes `wb` with GridCraft's XLSX writer, validates the package against itself and against +/// `source` (the file `wb` was read from), reads it back and compares. +pub fn round_trip(wb: &Workbook, source: &[u8], opts: &Options) -> RoundTrip { + let bytes = match gridcraft_engine::io::save_bytes(wb, "roundtrip.xlsx") { + Ok(b) => b, + Err(e) => return RoundTrip { error: Some(format!("write failed: {e}")), categories: vec![] }, + }; + let mut package = Diffs::new("package", opts.max_report); + match validate_package(&bytes) { + Ok(issues) => issues.into_iter().for_each(|i| package.push(|| i)), + Err(e) => package.push(|| e), + } + if let (Ok(before), Ok(after)) = (relationship_kinds(source), relationship_kinds(&bytes)) { + for (key, kind) in &before { + if !after.contains_key(key) && !REBUILT_KINDS.contains(&key.as_str()) { + package.push(|| format!("lost relationship {kind}")); + } + } + } + let back = match gridcraft_engine::io::open_bytes("roundtrip.xlsx", &bytes) { + Ok((b, _)) => b, + Err(e) => return RoundTrip { error: Some(format!("reading the written file failed: {e}")), categories: vec![package.done()] }, + }; + let mut categories = diff_workbooks(wb, &back, opts); + categories.push(package.done()); + RoundTrip { error: None, categories } +} + +pub(super) fn value_show(v: &Value) -> String { + match v { + Value::Empty => "(blank)".to_string(), + Value::Text(t) => serde_json::to_string(t.as_ref()).unwrap_or_default(), + Value::Number(n) => number_text(*n), + Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(), + Value::Error(e) => e.as_str().to_string(), + Value::Array(_) => v.scalar().display(), + } +} + +fn opt_formula(c: Option<&Cell>) -> String { + c.filter(|c| c.formula.is_some()).map(formula_text).unwrap_or_default() +} + +/// Per-sheet comparison of two lists, reporting what one side has and the other lacks. +fn diff_sets(d: &mut Diffs, sheet: &str, a: &BTreeSet, b: &BTreeSet) { + for x in a.difference(b) { + d.push(|| format!("{sheet}: lost {x}")); + } + for x in b.difference(a) { + d.push(|| format!("{sheet}: gained {x}")); + } +} + +/// A sheet's conditional-format rules in precedence order, as comparable text. The priority number +/// itself is left out, so renumbering without changing the order isn't a difference. +fn cond_format_list(s: &Sheet) -> Vec { + let mut cfs: Vec<_> = s.cond_formats.iter().collect(); + cfs.sort_by_key(|c| c.priority); + cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect() +} + +fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) { + if a != b { + d.push(|| format!("{sheet}: {a} → {b}")); + } +} + +/// A value as the file format can hold it: `#SPILL!`/`#CALC!` are cached as `#VALUE!` and an +/// unresolved circular reference as 0 (what Excel writes), so those aren't round-trip losses. +fn as_cached(v: Value) -> Value { + match v { + Value::Error(CellError::Spill | CellError::Calc) => Value::Error(CellError::Value), + Value::Error(CellError::Circ) => Value::Number(0.0), + v => v, + } +} + +fn num_fmt<'a>(wb: &'a Workbook, c: Option<&Cell>) -> &'a str { + wb.styles.get(c.map(|c| c.style).unwrap_or_default()).num_fmt.as_str() +} + +/// Feature-by-feature comparison of a workbook (`a`) with what reading it back gave (`b`). Sheets +/// are paired by position. +pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec { + let m = opts.max_report; + let mut sheets = Diffs::new("sheets", m); + let (an, bn): (Vec<&str>, Vec<&str>) = (a.sheets.iter().map(|s| s.name.as_str()).collect(), b.sheets.iter().map(|s| s.name.as_str()).collect()); + if an != bn { + sheets.push(|| format!("{an:?} → {bn:?}")); + } + let mut values = Diffs::new("values", m); + let mut formulas = Diffs::new("formulas", m); + let mut num_fmts = Diffs::new("numFmts", m); + let mut merges = Diffs::new("merges", m); + let mut tables = Diffs::new("tables", m); + let mut cond_formats = Diffs::new("condFormats", m); + let mut validations = Diffs::new("validations", m); + let mut charts = Diffs::new("charts", m); + let mut comments = Diffs::new("comments", m); + let mut hyperlinks = Diffs::new("hyperlinks", m); + let mut pivots = Diffs::new("pivots", m); + for (sa, sb) in a.sheets.iter().zip(b.sheets.iter()) { + let name = quote_sheet(&sa.name); + let mut cell = |c: CellRef, ca: Option<&Cell>, cb: Option<&Cell>| { + let cached = |x: Option<&Cell>| as_cached(x.map(|x| x.value.scalar()).unwrap_or_default()); + let (va, vb) = (cached(ca), cached(cb)); + if va != vb { + values.push(|| format!("{name}!{}: {} → {}", c.a1(), value_show(&va), value_show(&vb))); + } + let (fa, fb) = (opt_formula(ca), opt_formula(cb)); + if fa != fb { + formulas.push(|| format!("{name}!{}: {fa} → {fb}", c.a1())); + } + let (na, nb) = (num_fmt(a, ca), num_fmt(b, cb)); + if na != nb { + num_fmts.push(|| format!("{name}!{}: {na} → {nb}", c.a1())); + } + }; + for (c, ca) in sa.cells.iter() { + cell(c, Some(ca), sb.cell(c)); + } + for (c, cb) in sb.cells.iter() { + if sa.cell(c).is_none() { + cell(c, None, Some(cb)); + } + } + let set = |f: &dyn Fn(&Sheet) -> Vec, s: &Sheet| f(s).into_iter().collect::>(); + let merge_list = |s: &Sheet| -> Vec { s.merges.iter().map(|r| r.a1()).collect() }; + diff_sets(&mut merges, &name, &set(&merge_list, sa), &set(&merge_list, sb)); + let table_list = |s: &Sheet| -> Vec { + s.tables + .iter() + .map(|t| format!("{} {} [{}]", t.name, t.range.a1(), t.columns.iter().map(|c| c.name.as_str()).collect::>().join(", "))) + .collect() + }; + diff_sets(&mut tables, &name, &set(&table_list, sa), &set(&table_list, sb)); + let (cfa, cfb) = (cond_format_list(sa), cond_format_list(sb)); + if cfa.len() != cfb.len() { + cond_formats.push(|| format!("{name}: {} → {}", cfa.len(), cfb.len())); + } else if let Some((x, y)) = cfa.iter().zip(&cfb).find(|(x, y)| x != y) { + cond_formats.push(|| format!("{name}: {x} → {y}")); + } + diff_count(&mut validations, &name, sa.validations.len(), sb.validations.len()); + let chart_list = |s: &Sheet| s.charts.iter().map(|c| format!("{:?} ({} series)", c.kind, c.series.len())).collect::>(); + let (ca, cb) = (chart_list(sa), chart_list(sb)); + if ca != cb { + charts.push(|| format!("{name}: {ca:?} → {cb:?}")); + } + diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len()); + diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len()); + diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len()); + } + let mut names = Diffs::new("names", m); + let name_list = |wb: &Workbook| -> BTreeSet { + wb.names + .iter() + .map(|n| { + let scope = n.scope.map(|i| format!("{}!", quote_sheet(wb.sheet(i).map(|s| s.name.as_str()).unwrap_or("?")))).unwrap_or_default(); + format!("{scope}{}={}", n.name, n.formula) + }) + .collect() + }; + diff_sets(&mut names, "workbook", &name_list(a), &name_list(b)); + vec![ + sheets.done(), + values.done(), + formulas.done(), + num_fmts.done(), + merges.done(), + names.done(), + tables.done(), + cond_formats.done(), + validations.done(), + charts.done(), + comments.done(), + hyperlinks.done(), + pivots.done(), + ] +} diff --git a/apps/gridcraft-cli/src/check/package.rs b/apps/gridcraft-cli/src/check/package.rs new file mode 100644 index 0000000000..6b97fa4951 --- /dev/null +++ b/apps/gridcraft-cli/src/check/package.rs @@ -0,0 +1,331 @@ +use super::*; + +/// Largest package part read while validating a written package. +const MAX_XML_PART: u64 = 64 * 1024 * 1024; + +/// Most zip entries looked at while validating a written package. +const MAX_ENTRIES: usize = 200_000; + +/// Relationship kinds (lower case) whose absence after a save isn't a loss: the calculation chain is +/// a cache Excel rebuilds, and GridCraft never writes it. +pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"]; + +// ---------------------------------------------------------------- package validation + +fn local_name(name: &[u8]) -> &[u8] { + match name.iter().rposition(|&b| b == b':') { + Some(i) => name.get(i + 1..).unwrap_or(name), + None => name, + } +} + +/// `(element local name, attributes)` for every start/empty element of an XML part. +type XmlElement = (String, Vec<(String, String)>); + +fn xml_elements(xml: &[u8]) -> Result, String> { + use quick_xml::events::Event; + let mut reader = quick_xml::Reader::from_reader(xml); + let mut buf = Vec::new(); + let mut out = Vec::new(); + loop { + match reader.read_event_into(&mut buf) { + Ok(Event::Start(e)) | Ok(Event::Empty(e)) => { + let attrs = e + .attributes() + .with_checks(false) + .flatten() + .map(|a| { + let v = match a.normalized_value(quick_xml::XmlVersion::Explicit1_0) { + Ok(v) => v.into_owned(), + Err(_) => String::from_utf8_lossy(&a.value).into_owned(), + }; + (String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v) + }) + .collect(); + out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs)); + } + Ok(Event::Eof) => break, + Ok(_) => {} + Err(e) => return Err(format!("invalid XML: {e}")), + } + buf.clear(); + } + Ok(out) +} + +fn attr<'a>(attrs: &'a [(String, String)], k: &str) -> Option<&'a str> { + attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) +} + +/// Lower-cased part name without a leading slash: OPC part names compare case-insensitively. +fn part_key(name: &str) -> String { + name.trim_start_matches('/').to_ascii_lowercase() +} + +/// `%XX` escapes in a relationship target. +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while let Some(&c) = b.get(i) { + let hex = |j: usize| b.get(j).and_then(|h| (*h as char).to_digit(16)); + match (c, hex(i + 1), hex(i + 2)) { + (b'%', Some(h), Some(l)) => { + out.push((h * 16 + l) as u8); + i += 3; + } + _ => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Resolves a relationship target against the source part's directory. +fn resolve_target(source_dir: &str, target: &str) -> String { + let target = percent_decode(target.split('#').next().unwrap_or(target)); + let joined = match target.strip_prefix('/') { + Some(abs) => abs.to_string(), + None if source_dir.is_empty() => target, + None => format!("{source_dir}/{target}"), + }; + let mut parts: Vec<&str> = Vec::new(); + for seg in joined.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +type Zip<'a> = zip::ZipArchive>; + +fn zip_names(zip: &mut Zip<'_>) -> Vec { + (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() +} + +fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result, 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) +} + +/// Whether the producer flagged its cached results as stale with ``: +/// libraries that don't calculate write it, and store 0 or nothing as every formula's value. +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 mut workbook = "xl/workbook.xml".to_string(); + 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() + .find(|(e, a)| e == "Relationship" && attr(a, "Type").is_some_and(|t| t.ends_with("/officeDocument"))) + .and_then(|(_, a)| attr(a, "Target")) + { + workbook = resolve_target("", target); + } + 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() + .flatten() + .any(|(e, a)| e == "calcPr" && attr(&a, "fullCalcOnLoad").is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))) +} + +/// Problems Excel would repair in a written package: parts without a content type, content-type +/// overrides for missing parts, relationship files for missing parts, duplicate relationship ids +/// and internal relationships pointing at missing parts. `Err` when the package can't be read. +pub fn validate_package(bytes: &[u8]) -> Result, 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 = 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 (mut defaults, mut overrides) = (HashSet::new(), HashSet::new()); + match ct_name { + None => issues.push("no [Content_Types].xml".to_string()), + 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") { + defaults.insert(x.to_ascii_lowercase()); + } + } + "Override" => { + if let Some(p) = attr(&attrs, "PartName") { + overrides.insert(part_key(p)); + } + } + _ => {} + } + } + } + } + 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; + } + let ext = key.rsplit('/').next().and_then(|f| f.rsplit_once('.')).map(|(_, e)| e.to_string()); + if !overrides.contains(&key) && !ext.is_some_and(|e| defaults.contains(&e)) { + issues.push(format!("part {n} has no content type")); + } + } + let mut missing_overrides: Vec<&String> = overrides.iter().filter(|p| !parts.contains(*p)).collect(); + missing_overrides.sort(); + for p in missing_overrides { + issues.push(format!("content type override for missing part /{p}")); + } + 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. + let (dir, file) = match rels_file.rsplit_once('/') { + Some((d, f)) => (d, f), + None => continue, + }; + let Some(src_dir) = dir.strip_suffix("_rels").map(|d| d.trim_end_matches('/')) else { continue }; + let source = if src_dir.is_empty() { file.to_string() } else { format!("{src_dir}/{file}") }; + if !source.is_empty() && !parts.contains(&source) { + issues.push(format!("{n} describes missing part {source}")); + } + let mut ids = HashSet::new(); + for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? { + if el != "Relationship" { + continue; + } + let id = attr(&attrs, "Id").unwrap_or(""); + if !ids.insert(id.to_string()) { + issues.push(format!("{n}: duplicate relationship id {id}")); + } + if attr(&attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External")) { + continue; + } + let target = attr(&attrs, "Target").unwrap_or(""); + let resolved = resolve_target(src_dir, target); + if !parts.contains(&resolved.to_ascii_lowercase()) { + let kind = attr(&attrs, "Type").and_then(|t| t.rsplit('/').next()).unwrap_or("?"); + issues.push(format!("{n}: {id} ({kind}) targets missing part {resolved}")); + } + } + } + Ok(issues) +} + +/// Every relationship kind (last segment of the type, the same in the transitional and strict +/// namespaces) in the package's relationship parts, keyed in lower case. Relationships that carry +/// nothing are left out, as a save may rightly drop them: a link to a place in the workbook +/// (`#Sheet1!A1`, written as a cell's `location`) and a target part with nothing in it. +pub(super) fn relationship_kinds(bytes: &[u8]) -> Result, 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 = 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 (finding: repeated decompression). + let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new(); + let mut budget: u64 = 512 * 1024 * 1024; + let mut kinds = BTreeMap::new(); + 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 Ok(els) = read_zip_part(&mut zip, n).and_then(|xml| xml_elements(&xml)) else { continue }; + for (_, attrs) in els.iter().filter(|(el, _)| el == "Relationship") { + let Some(kind) = attr(attrs, "Type").and_then(|t| t.rsplit('/').next()) else { continue }; + let target = attr(attrs, "Target").unwrap_or(""); + if kind.eq_ignore_ascii_case("hyperlink") && target.starts_with('#') { + continue; + } + let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External")); + if !external + && 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; + } + kinds.entry(kind.to_ascii_lowercase()).or_insert_with(|| kind.to_string()); + } + } + Ok(kinds) +} + +/// The directory of the part a rels part describes: `xl` for `xl/_rels/workbook.xml.rels`, the +/// empty string for the package's `_rels/.rels`. +fn rels_source_dir(key: &str) -> Option { + let (dir, _) = key.strip_suffix(".rels")?.rsplit_once('/')?; + Some(dir.strip_suffix("_rels")?.trim_end_matches('/').to_string()) +} + +/// Whether a part has content: an element under its root, or for comments (whose authors list +/// 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<'_>, 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"), + _ => None, + }; + let marker = match wanted { + Some(b"comment") => "comment", + Some(_) => "shape", + None => "any", + }; + if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) { + return *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<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool { + use quick_xml::events::Event; + let Ok(f) = zip.by_name(name) else { return true }; + if *budget == 0 { + return true; + } + let take = f.size().min(MAX_XML_PART).min(*budget); + *budget -= take; + let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(f.take(take))); + let wanted: Option<&'static [u8]> = match marker { + "comment" => Some(b"comment"), + "shape" => Some(b"shape"), + _ => None, + }; + let mut buf = Vec::new(); + let mut in_root = false; + loop { + match reader.read_event_into(&mut buf) { + Ok(Event::Start(e)) | Ok(Event::Empty(e)) => { + let found = match wanted { + Some(w) => local_name(e.name().as_ref()) == w, + None => in_root, + }; + if found { + return true; + } + in_root = true; + } + Ok(Event::Eof) => return false, + Ok(_) => {} + Err(_) => return true, + } + buf.clear(); + } +} diff --git a/apps/gridcraft-cli/src/check/report.rs b/apps/gridcraft-cli/src/check/report.rs new file mode 100644 index 0000000000..6c0d6b36da --- /dev/null +++ b/apps/gridcraft-cli/src/check/report.rs @@ -0,0 +1,280 @@ +use super::fidelity::value_show; +use super::*; + +// ---------------------------------------------------------------- output + +#[derive(Default)] +struct Totals { + files: usize, + opened: usize, + failed: usize, + formula_cells: usize, + checked: usize, + matched: usize, + mismatched: usize, + no_oracle: usize, + volatile: usize, + bool_as_number: usize, + round_trip_failed: usize, + round_trip_differing: usize, + categories: BTreeMap<&'static str, usize>, + functions: BTreeMap, + signatures: BTreeMap, +} + +fn totals(reports: &[FileReport]) -> Totals { + let mut t = Totals { files: reports.len(), ..Default::default() }; + for r in reports { + if r.error.is_some() { + t.failed += 1; + continue; + } + t.opened += 1; + t.formula_cells += r.calc.formula_cells; + t.checked += r.calc.checked; + t.matched += r.calc.matched; + t.mismatched += r.calc.mismatched; + t.no_oracle += r.calc.no_oracle; + t.volatile += r.calc.volatile; + t.bool_as_number += r.calc.bool_as_number; + if r.round_trip.error.is_some() { + t.round_trip_failed += 1; + } + if !r.round_trip.is_clean() { + t.round_trip_differing += 1; + } + for c in r.round_trip.differing() { + *t.categories.entry(c).or_default() += 1; + } + for (n, s) in &r.calc.functions { + t.functions.entry(n.clone()).or_default().add(s); + } + for (sig, n) in &r.calc.signatures { + *t.signatures.entry(sig.clone()).or_default() += n; + } + } + t +} + +/// Functions with mismatches, worst first: most primary mismatches, then most mismatches. +fn ranked(functions: &BTreeMap) -> Vec<(&String, &FnStat)> { + let mut v: Vec<(&String, &FnStat)> = functions.iter().filter(|(_, s)| s.mismatched > 0).collect(); + v.sort_by(|a, b| b.1.primary.cmp(&a.1.primary).then(b.1.mismatched.cmp(&a.1.mismatched)).then(a.0.cmp(b.0))); + v +} + +fn functions_json(functions: &BTreeMap) -> Json { + let mut v: Vec<(&String, &FnStat)> = functions.iter().collect(); + v.sort_by(|a, b| b.1.primary.cmp(&a.1.primary).then(b.1.mismatched.cmp(&a.1.mismatched)).then(a.0.cmp(b.0))); + Json::Array(v.into_iter().map(|(n, s)| json!({"name": n, "checked": s.checked, "mismatched": s.mismatched, "primary": s.primary})).collect()) +} + +pub fn report_json(reports: &[FileReport], opts: &Options) -> Json { + let files: Vec = reports + .iter() + .map(|r| { + let c = &r.calc; + let mismatches: Vec = c + .mismatches + .iter() + .map(|m| { + json!({ + "cell": m.cell, "formula": m.formula, "expected": value_json(&m.expected), "actual": value_json(&m.actual), + "kind": m.kind, "functions": m.functions, "primary": m.primary, + }) + }) + .collect(); + let categories: serde_json::Map = r + .round_trip + .categories + .iter() + .map(|cat| (cat.name.to_string(), json!({"equal": cat.diffs == 0, "diffs": cat.diffs, "examples": cat.examples}))) + .collect(); + json!({ + "path": r.path, + "opened": r.error.is_none(), + "error": r.error, + "warnings": r.warnings, + "calc": { + "formulaCells": c.formula_cells, "checked": c.checked, "matched": c.matched, "mismatched": c.mismatched, + "noOracle": c.no_oracle, "staleCache": c.stale_cache, "volatile": c.volatile, "boolAsNumber": c.bool_as_number, + "mismatches": mismatches, "functions": functions_json(&c.functions), + "signatures": c.signatures, + }, + "roundTrip": {"error": r.round_trip.error, "differing": r.round_trip.differing(), "categories": categories}, + }) + }) + .collect(); + let t = totals(reports); + json!({ + "schema": SCHEMA, + "tolerance": opts.tolerance, + "files": files, + "totals": { + "files": t.files, "opened": t.opened, "failedToOpen": t.failed, "formulaCells": t.formula_cells, "checked": t.checked, + "matched": t.matched, "mismatched": t.mismatched, "noOracle": t.no_oracle, "volatile": t.volatile, "boolAsNumber": t.bool_as_number, + "roundTripFailed": t.round_trip_failed, "roundTripDiffering": t.round_trip_differing, "categoriesDiffering": t.categories, + }, + "functions": functions_json(&t.functions), + "signatures": t.signatures, + }) +} + +/// One report line: line breaks and tabs shown escaped so that they stay visible as differences. +fn one_line(s: &str) -> String { + s.replace('\n', "\\n").replace('\r', "\\r").replace('\t', "\\t") +} + +/// `…tail` of a long label. +fn fit(s: &str, w: usize) -> String { + let n = s.chars().count(); + if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::()) } +} + +fn print_file_reports(reports: &[FileReport]) { + for r in reports { + outln!("== {}", r.path); + if let Some(e) = &r.error { + outln!(" can't open: {e}"); + continue; + } + let c = &r.calc; + outln!( + " formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile", + c.formula_cells, + c.checked, + c.matched, + c.mismatched, + c.no_oracle, + c.volatile + ); + if c.stale_cache { + outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)"); + } + if c.bool_as_number > 0 { + outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number); + } + for m in &c.mismatches { + let tag = if m.primary { "mismatch" } else { " (downstream)" }; + outln!( + " {tag} {} {} expected {} got {} [{}]", + m.cell, + one_line(&m.formula), + value_show(&m.expected), + value_show(&m.actual), + m.functions.join(" ") + ); + } + if c.mismatched > c.mismatches.len() { + outln!(" … {} more mismatches", c.mismatched - c.mismatches.len()); + } + let rt = &r.round_trip; + if let Some(e) = &rt.error { + outln!(" round trip: {e}"); + } + let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect(); + if differing.is_empty() && rt.error.is_none() { + outln!(" round trip: all equal"); + } + for cat in differing { + outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs); + for e in &cat.examples { + outln!(" {}", one_line(e)); + } + if cat.diffs > cat.examples.len() { + outln!(" … {} more", cat.diffs - cat.examples.len()); + } + } + } +} + +fn print_file_table(reports: &[FileReport]) { + let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50); + outln!( + "{:8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip", + "file", + "formulas", + "checked", + "matched", + "mismatch", + "no-oracle", + "volatile" + ); + for r in reports { + let label = fit(&r.path, w); + if let Some(e) = &r.error { + outln!("{label: "FAILED".to_string(), + (None, d) if d.is_empty() => "ok".to_string(), + (None, d) => d.join(","), + }; + outln!( + "{label:8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}", + c.formula_cells, + c.checked, + c.matched, + c.mismatched, + c.no_oracle, + c.volatile + ); + } +} + +fn print_rankings(t: &Totals, opts: &Options) { + let top = ranked(&t.functions); + if !top.is_empty() { + outln!(""); + outln!("top mismatching functions (primary = no mismatching precedent):"); + outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked"); + for (n, s) in top.iter().take(opts.max_report.max(1)) { + outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked); + } + } + let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect(); + sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0))); + if !sigs.is_empty() { + outln!(""); + outln!("mismatch signatures (expected → GridCraft):"); + for (sig, n) in sigs.iter().take(opts.max_report.max(1)) { + outln!(" {n:>8} {sig}"); + } + } +} + +fn print_totals(t: &Totals) { + outln!(""); + outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed); + outln!( + "formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)", + t.formula_cells, + t.checked, + t.matched, + t.mismatched, + t.no_oracle, + t.volatile + ); + if t.bool_as_number > 0 { + outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number); + } + let cats: Vec = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect(); + outln!( + "round trip: {} of {} files differ{}{}", + t.round_trip_differing, + t.opened, + if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() }, + if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) } + ); +} + +pub(super) fn print_human(reports: &[FileReport], opts: &Options) { + print_file_reports(reports); + outln!(""); + print_file_table(reports); + let t = totals(reports); + print_rankings(&t, opts); + print_totals(&t); +} diff --git a/apps/gridcraft-cli/src/check/tests.rs b/apps/gridcraft-cli/src/check/tests.rs new file mode 100644 index 0000000000..57baa21986 --- /dev/null +++ b/apps/gridcraft-cli/src/check/tests.rs @@ -0,0 +1,472 @@ +#![allow(clippy::unwrap_used)] +use std::io::Write as _; +use std::sync::Arc; + +use gridcraft_engine::model::Formula; + +use super::*; + +#[test] +fn discovery_reports_a_directory_read_error() { + let path = std::env::temp_dir().join(format!("gridcraft-check-not-a-directory-{}", std::process::id())); + std::fs::write(&path, "not a directory").unwrap(); + let mut discovery = Discovery::default(); + let mut seen = std::collections::HashSet::new(); + assert!(walk(&path, 0, &mut discovery, &mut seen)); + assert!(discovery.files.is_empty()); + assert_eq!(discovery.failures.len(), 1); + assert_eq!(discovery.failures[0].path, path.to_string_lossy()); + assert!(discovery.failures[0].error.as_ref().unwrap().contains("cannot read directory")); + let _ = std::fs::remove_file(path); +} + +#[test] +fn discovery_reports_omissions_only_after_the_file_limit() { + let mut discovery = Discovery { files: vec![PathBuf::from("book.xlsx"); MAX_FILES - 1], ..Default::default() }; + assert!(discovery.add_file(PathBuf::from("last.xlsx"))); + assert!(discovery.failures.is_empty()); + assert!(!discovery.add_file(PathBuf::from("omitted.xlsx"))); + assert_eq!(discovery.files.len(), MAX_FILES); + assert_eq!(discovery.failures[0].path, "omitted.xlsx"); + assert!(discovery.failures[0].error.as_ref().unwrap().contains("file limit")); +} + +fn at(a1: &str) -> CellRef { + CellRef::parse(a1).unwrap() +} + +/// A workbook whose cells are `(A1, input, cached value)`: an input starting with `=` is a +/// formula with that cached value, anything else a constant. +fn book(cells: &[(&str, &str, Value)]) -> Workbook { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + for (a1, input, cached) in cells { + let cell = if input.starts_with('=') { + Cell { value: cached.clone(), formula: Some(Arc::new(Formula::new(input))), ..Default::default() } + } else { + Cell::value(cached.clone()) + }; + sh.set_cell(at(a1), cell); + } + wb +} + +fn check(wb: &Workbook, opts: &Options) -> FileReport { + let bytes = gridcraft_engine::io::save_bytes(wb, "t.xlsx").unwrap(); + check_bytes("t.xlsx", &bytes, opts) +} + +fn n(x: f64) -> Value { + Value::number(x) +} + +#[test] +fn matching_cached_values_pass() { + let wb = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0)), ("C1", "=A1&\"x\"", Value::text("2x")), ("D1", "=A1>1", Value::Bool(true))]); + let r = check(&wb, &Options::default()); + assert_eq!(r.error, None); + assert_eq!((r.calc.formula_cells, r.calc.checked, r.calc.matched, r.calc.mismatched), (3, 3, 3, 0)); + assert!(r.is_clean(), "{r:?}"); +} + +#[test] +fn wrong_cached_value_is_a_mismatch_and_ranks_its_function() { + // Excel "said" SUM gives 7; GridCraft computes 6. C1 reads B1 and is consistent with + // Excel's 7, so it mismatches too, but only as a downstream effect. + let wb = book(&[("A1", "2", n(2.0)), ("A2", "4", n(4.0)), ("B1", "=SUM(A1:A2)", n(7.0)), ("C1", "=B1+1", n(8.0))]); + let r = check(&wb, &Options::default()); + assert_eq!((r.calc.checked, r.calc.mismatched), (2, 2)); + let first = &r.calc.mismatches[0]; + assert_eq!(first.cell, "Sheet1!B1"); + assert_eq!(first.formula, "=SUM(A1:A2)"); + assert_eq!((first.expected.clone(), first.actual.clone(), first.kind, first.primary), (n(7.0), n(6.0), "numeric", true)); + assert!(!r.calc.mismatches[1].primary); + assert_eq!(r.calc.functions["SUM"], FnStat { checked: 1, mismatched: 1, primary: 1 }); + assert_eq!(r.calc.functions["(no function)"], FnStat { checked: 1, mismatched: 1, primary: 0 }); + assert!(!r.is_clean()); +} + +#[test] +fn errors_compare_by_kind() { + let wb = book(&[("A1", "=1/0", Value::Error(CellError::Div0)), ("A2", "=1/0", Value::Error(CellError::NA)), ("A3", "=1/0", n(0.0))]); + let r = check(&wb, &Options::default()); + assert_eq!((r.calc.matched, r.calc.mismatched), (1, 2)); + assert!(r.calc.mismatches.iter().all(|m| m.kind == "error")); + assert_eq!(r.calc.signatures.get("#N/A → #DIV/0!"), Some(&1)); + assert_eq!(r.calc.signatures.get("number → #DIV/0!"), Some(&1)); + assert!(values_match(&Value::Error(CellError::NA), &Value::Error(CellError::NA), 0.0)); + assert!(!values_match(&Value::Error(CellError::NA), &Value::Error(CellError::Value), 0.0)); +} + +#[test] +fn numbers_compare_within_tolerance() { + assert!(values_match(&n(3.0000000001), &n(3.0), 1e-9)); + assert!(!values_match(&n(3.0000000001), &n(3.0), 1e-12)); + // Absolute near zero. + assert!(values_match(&n(1e-12), &n(0.0), 1e-9)); + assert!(values_match(&n(1e12 + 1.0), &n(1e12), 1e-9)); + assert!(!values_match(&n(0.0), &Value::Empty, 1.0)); + assert!(!values_match(&Value::text("1"), &n(1.0), 1.0)); + assert!(values_match(&Value::text("a"), &Value::text("a"), 0.0)); + assert!(!values_match(&Value::text("a"), &Value::text("A"), 0.0)); + assert!(!values_match(&Value::Bool(true), &n(1.0), 1.0)); + let wb = book(&[("A1", "=1+2", n(3.0000000001))]); + assert_eq!(check(&wb, &Options::default()).calc.matched, 1); + assert_eq!(check(&wb, &Options { tolerance: 1e-12, ..Default::default() }).calc.mismatched, 1); +} + +/// Business Central writes TRUE and FALSE as `TRUE()1`, without `t="b"`: +/// the cache holds the right value under a number type, so it matches and is counted apart. +#[test] +fn booleans_cached_as_numbers_match_and_are_counted_apart() { + let wb = book(&[ + ("A1", "=TRUE()", n(1.0)), + ("B1", "=FALSE()", n(0.0)), + ("C1", "=TRUE()", Value::Bool(true)), + ("D1", "=1=1", n(0.0)), + ("E1", "=TRUE()+0", n(1.0)), + ]); + let r = check(&wb, &Options::default()); + assert_eq!((r.calc.checked, r.calc.matched, r.calc.mismatched), (5, 4, 1)); + // A cached 0 for TRUE is still a mismatch, and a number result is compared as a number. + assert_eq!(r.calc.mismatches[0].cell, "Sheet1!D1"); + assert_eq!(r.calc.signatures.get("number → bool"), Some(&1)); + assert_eq!(r.calc.bool_as_number, 2); + let v = report_json(std::slice::from_ref(&r), &Options::default()); + assert_eq!((v["files"][0]["calc"]["boolAsNumber"].clone(), v["totals"]["boolAsNumber"].clone()), (json!(2), json!(2))); + assert!(bool_cached_as_number(&n(1.0), &Value::Bool(true))); + assert!(!bool_cached_as_number(&n(1.0), &Value::Bool(false))); + assert!(!bool_cached_as_number(&n(2.0), &Value::Bool(true))); + assert!(!bool_cached_as_number(&Value::Bool(true), &n(1.0))); +} + +#[test] +fn missing_cached_values_and_volatile_formulas_are_skipped() { + let wb = + book(&[("A1", "=1+1", Value::Empty), ("B1", "=NOW()", n(1.0)), ("B2", "=B1+1", n(2.0)), ("B3", "=CELL(\"filename\")", Value::text("x"))]); + let r = check(&wb, &Options::default()); + assert_eq!((r.calc.formula_cells, r.calc.checked, r.calc.no_oracle, r.calc.volatile), (4, 0, 1, 3)); +} + +#[test] +fn full_calc_on_load_means_no_oracle() { + // A formula without a cached value makes GridCraft's writer flag the file + // `fullCalcOnLoad`, like libraries that store 0 for every formula: B1's wrong "cached" + // value must not count as a mismatch then. + let wb = book(&[("A1", "=1+1", Value::Empty), ("B1", "=2+2", n(0.0))]); + let bytes = gridcraft_engine::io::save_bytes(&wb, "t.xlsx").unwrap(); + assert!(full_calc_on_load(&bytes)); + let r = check_bytes("t.xlsx", &bytes, &Options::default()); + assert!(r.calc.stale_cache); + assert_eq!((r.calc.checked, r.calc.no_oracle, r.calc.mismatched), (0, 2, 0)); + let fresh = gridcraft_engine::io::save_bytes(&book(&[("B1", "=2+2", n(0.0))]), "t.xlsx").unwrap(); + assert!(!full_calc_on_load(&fresh)); + assert!(!full_calc_on_load(b"not a zip")); +} + +#[test] +fn volatile_names_propagate() { + let mut wb = book(&[("A1", "=Stamp+1", n(1.0))]); + wb.names.push(gridcraft_engine::model::DefinedName { + name: "Stamp".into(), + scope: None, + formula: "TODAY()".into(), + comment: String::new(), + hidden: false, + }); + assert!(volatile_names(&wb).contains("STAMP")); + assert_eq!(check(&wb, &Options::default()).calc.volatile, 1); +} + +#[test] +fn volatile_names_propagate_through_a_long_chain_in_one_walk() { + // Chain0 uses Chain1, Chain1 uses Chain2, ... and only the last is volatile: listed in this order, a rescan + // until nothing changes marked one name per pass (quadratic). Every name in the chain is + // volatile; a name off the chain is not. + const LEN: usize = 5_000; + let mut wb = book(&[("A1", "=1", n(1.0))]); + let name = + |name: String, formula: String| gridcraft_engine::model::DefinedName { name, scope: None, formula, comment: String::new(), hidden: false }; + for i in 0..LEN { + let formula = if i + 1 == LEN { "NOW()".to_string() } else { format!("Chain{}+1", i + 1) }; + wb.names.push(name(format!("Chain{i}"), formula)); + } + wb.names.push(name("Plain".into(), "Chain0*0+Other".into())); + wb.names.push(name("Other".into(), "1".into())); + let set = volatile_names(&wb); + assert!((0..LEN).all(|i| set.contains(&format!("CHAIN{i}")))); + assert!(set.contains("PLAIN")); + assert!(!set.contains("OTHER")); + assert_eq!(set.len(), LEN + 1); +} + +#[test] +fn round_trip_of_a_simple_book_is_clean() { + let mut wb = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0)), ("A2", "x", Value::text("x"))]); + wb.sheet_mut(0).unwrap().merges.push(gridcraft_engine::core::RangeRef::parse("C1:D2").unwrap()); + let source = gridcraft_engine::io::save_bytes(&wb, "t.xlsx").unwrap(); + let rt = round_trip(&wb, &source, &Options::default()); + assert_eq!(rt.error, None); + assert!(rt.is_clean(), "{rt:?}"); + assert!(rt.categories.iter().any(|c| c.name == "package")); +} + +#[test] +fn diff_detects_lost_features() { + let mut a = book(&[("A1", "2", n(2.0)), ("B1", "=A1*3", n(6.0))]); + a.sheet_mut(0).unwrap().merges.push(gridcraft_engine::core::RangeRef::parse("C1:D2").unwrap()); + let mut b = a.clone(); + let sh = b.sheet_mut(0).unwrap(); + sh.merges.clear(); + sh.set_cell(at("A1"), Cell::value(n(3.0))); + sh.set_cell(at("B1"), Cell::value(n(6.0))); + b.sheets.push(Arc::new(Sheet::new("Extra"))); + let cats = diff_workbooks(&a, &b, &Options { max_report: 1, ..Default::default() }); + let get = |name: &str| cats.iter().find(|c| c.name == name).unwrap(); + assert_eq!(get("values").diffs, 1); + assert_eq!(get("values").examples, ["Sheet1!A1: 2 → 3"]); + assert_eq!(get("formulas").examples, ["Sheet1!B1: =A1*3 → "]); + assert_eq!(get("merges").examples, ["Sheet1: lost C1:D2"]); + assert_eq!(get("sheets").diffs, 1); + assert_eq!(get("tables").diffs, 0); +} + +#[test] +fn diff_detects_changed_cond_format_rule() { + use gridcraft_engine::model::{CfRule, CfValueKind, Color, CondFormat}; + let bar = |gradient: bool, priority: u32| CondFormat { + ranges: vec![gridcraft_engine::core::RangeRef::parse("A1").unwrap()], + rule: CfRule::DataBar { min: CfValueKind::Min, max: CfValueKind::Max, color: Color::Rgb(0x638EC6), gradient, show_value: true }, + priority, + stop_if_true: false, + }; + let with = |cf: CondFormat| { + let mut wb = book(&[("A1", "2", n(2.0))]); + wb.sheet_mut(0).unwrap().cond_formats.push(cf); + wb + }; + let diffs = |a: &Workbook, b: &Workbook| diff_workbooks(a, b, &Options::default()).into_iter().find(|c| c.name == "condFormats").unwrap().diffs; + assert_eq!(diffs(&with(bar(false, 1)), &with(bar(true, 1))), 1); + assert_eq!(diffs(&with(bar(true, 1)), &with(bar(true, 1))), 0); + assert_eq!(diffs(&with(bar(true, 1)), &with(bar(true, 5))), 0); +} + +fn zip_of(parts: &[(&str, &str)]) -> Vec { + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + for (name, body) in parts { + z.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + z.write_all(body.as_bytes()).unwrap(); + } + z.finish().unwrap().into_inner() +} + +#[test] +fn package_validation_finds_what_excel_would_repair() { + let bytes = zip_of(&[ + ( + "[Content_Types].xml", + r#""#, + ), + ("_rels/.rels", r#""#), + ("xl/workbook.xml", ""), + ("xl/styles.xml", ""), + ( + "xl/_rels/workbook.xml.rels", + r#""#, + ), + ]); + let issues = validate_package(&bytes).unwrap(); + assert_eq!( + issues, + [ + "part xl/styles.xml has no content type", + "content type override for missing part /xl/gone.xml", + "xl/_rels/workbook.xml.rels: rId2 (worksheet) targets missing part xl/worksheets/sheet1.xml", + "xl/_rels/workbook.xml.rels: duplicate relationship id rId2", + ] + ); + assert!(validate_package(b"not a zip").is_err()); + let own = gridcraft_engine::io::save_bytes(&book(&[("A1", "=1", n(1.0))]), "t.xlsx").unwrap(); + assert_eq!(validate_package(&own).unwrap(), Vec::::new()); +} + +const WB_RELS: &str = "xl/_rels/workbook.xml.rels"; +const SHEET_RELS: &str = "xl/worksheets/_rels/sheet1.xml.rels"; +const MADE_UP: &str = r#""#; +/// Not empty: an empty part isn't a loss. +const MADE_UP_PART: (&str, &str) = ("xl/madeUp.xml", ""); + +/// `bytes` with relationships added to rels parts (created when missing) and `parts` added. +fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec { + let mut src = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); + 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().to_string(); + let mut body = String::new(); + f.read_to_string(&mut body).unwrap(); + if let Some(at) = pending.iter().position(|(r, _)| *r == name) { + body = body.replace("", &format!("{}", pending.remove(at).1)); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(body.as_bytes()).unwrap(); + } + let created = pending.iter().map(|(r, extra)| { + (*r, format!(r#"{extra}"#)) + }); + for (name, body) in created.collect::>().iter().map(|(n, b)| (*n, b.as_str())).chain(parts.iter().copied()) { + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(body.as_bytes()).unwrap(); + } + out.finish().unwrap().into_inner() +} + +/// The `package` examples of checking `source`. +fn package_of(source: &[u8]) -> Vec { + let r = check_bytes("t.xlsx", source, &Options::default()); + r.round_trip.categories.iter().find(|c| c.name == "package").unwrap().examples.clone() +} + +fn plain() -> Vec { + gridcraft_engine::io::save_bytes(&book(&[("A1", "1", n(1.0))]), "t.xlsx").unwrap() +} + +#[test] +fn package_reports_relationship_kinds_the_output_lost() { + // A kind GridCraft doesn't know is dropped on save; a calculation chain is never written + // (Excel rebuilds it), so its absence isn't a loss. + let calc_chain = + r#""#; + let source = with_rels(&plain(), &[(WB_RELS, &format!("{MADE_UP}{calc_chain}"))], &[MADE_UP_PART, ("xl/calcChain.xml", "")]); + assert_eq!(package_of(&source), ["lost relationship madeUp"]); + assert!(check_bytes("t.xlsx", &plain(), &Options::default()).round_trip.is_clean()); +} + +// In the three tests below the made-up kind stays lost, so the comparison is known to run. + +#[test] +fn an_internal_link_written_as_a_relationship_is_not_a_loss() { + // openpyxl writes `#Sheet1!B2` as an external relationship; GridCraft writes `location`. + let link = r##""##; + let source = with_rels(&plain(), &[(WB_RELS, MADE_UP), (SHEET_RELS, link)], &[MADE_UP_PART]); + assert_eq!(package_of(&source), ["lost relationship madeUp"]); +} + +#[test] +fn comments_without_a_comment_are_not_a_loss() { + let rels = r#""#; + let comments = r#"A"#; + let vml = r#""#; + let source = with_rels( + &plain(), + &[(WB_RELS, MADE_UP), (SHEET_RELS, rels)], + &[MADE_UP_PART, ("xl/comments1.xml", comments), ("xl/drawings/vmlDrawing1.vml", vml)], + ); + assert_eq!(package_of(&source), ["lost relationship madeUp"]); +} + +#[test] +fn empty_drawings_and_person_lists_are_not_a_loss() { + let drawing = r#""#; + let person = r#""#; + let source = with_rels( + &plain(), + &[(WB_RELS, &format!("{MADE_UP}{person}")), (SHEET_RELS, drawing)], + &[ + MADE_UP_PART, + ("xl/drawings/drawing1.xml", r#""#), + ("xl/persons/person.xml", r#""#), + ], + ); + assert_eq!(package_of(&source), ["lost relationship madeUp"]); +} + +#[test] +fn json_lists_warning_messages() { + let with = FileReport { path: "a.ods".into(), warnings: vec!["ODS data-only import".into()], ..Default::default() }; + let without = FileReport { path: "b.xlsx".into(), ..Default::default() }; + let v = report_json(&[with, without], &Options::default()); + assert_eq!(v["files"][0]["warnings"], json!(["ODS data-only import"])); + assert_eq!(v["files"][1]["warnings"], json!([])); +} + +#[test] +fn unopenable_files_are_reported() { + let r = check_bytes("broken.xlsx", b"PK\x03\x04 not really", &Options::default()); + assert!(r.error.is_some()); + assert!(!r.is_clean()); +} + +#[test] +fn json_schema_keys() { + let wb = book(&[("A1", "=1+1", n(3.0))]); + let reports = vec![check(&wb, &Options::default()), check_bytes("bad.xlsx", b"", &Options::default())]; + let v = report_json(&reports, &Options::default()); + let keys = |v: &Json| v.as_object().unwrap().keys().cloned().collect::>(); + let set = |k: &[&str]| k.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(keys(&v), set(&["schema", "tolerance", "files", "totals", "functions", "signatures"])); + assert_eq!(v["schema"], SCHEMA); + let f = &v["files"][0]; + assert_eq!(keys(f), set(&["path", "opened", "error", "warnings", "calc", "roundTrip"])); + assert_eq!( + keys(&f["calc"]), + set(&[ + "formulaCells", + "checked", + "matched", + "mismatched", + "noOracle", + "staleCache", + "volatile", + "boolAsNumber", + "mismatches", + "functions", + "signatures" + ]) + ); + assert_eq!(f["calc"]["signatures"], json!({"number → number": 1})); + assert_eq!(keys(&f["calc"]["mismatches"][0]), set(&["cell", "formula", "expected", "actual", "kind", "functions", "primary"])); + assert_eq!(f["calc"]["mismatches"][0]["expected"], json!(3.0)); + assert_eq!(keys(&f["roundTrip"]), set(&["error", "differing", "categories"])); + assert_eq!( + keys(&f["roundTrip"]["categories"]), + set(&[ + "sheets", + "values", + "formulas", + "numFmts", + "merges", + "names", + "tables", + "condFormats", + "validations", + "charts", + "comments", + "hyperlinks", + "pivots", + "package" + ]) + ); + assert_eq!(keys(&f["roundTrip"]["categories"]["values"]), set(&["equal", "diffs", "examples"])); + assert_eq!(v["files"][1]["opened"], json!(false)); + assert_eq!( + keys(&v["totals"]), + set(&[ + "files", + "opened", + "failedToOpen", + "formulaCells", + "checked", + "matched", + "mismatched", + "noOracle", + "volatile", + "boolAsNumber", + "roundTripFailed", + "roundTripDiffering", + "categoriesDiffering" + ]) + ); + assert_eq!(keys(&v["functions"][0]), set(&["name", "checked", "mismatched", "primary"])); +} diff --git a/apps/gridcraft-cli/tests/it/main.rs b/apps/gridcraft-cli/tests/it/main.rs index 17f8db87f4..5906b39670 100644 --- a/apps/gridcraft-cli/tests/it/main.rs +++ b/apps/gridcraft-cli/tests/it/main.rs @@ -1,5 +1,3 @@ //! The crate's integration tests, one module per file, built as one test binary. - -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod cli; mod text_to_columns_quotes; diff --git a/apps/gridcraft-web/src/web.rs b/apps/gridcraft-web/src/web.rs index 43923bde10..33dc84936e 100644 --- a/apps/gridcraft-web/src/web.rs +++ b/apps/gridcraft-web/src/web.rs @@ -193,7 +193,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { let Some(file) = rfd::AsyncFileDialog::new() - .add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"]) + .add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "slk", "json"]) .pick_file() .await else { @@ -230,8 +230,9 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { && let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url) { // With `noopener` the new browsing context can't hold a reference back to the - // editor window and navigate it while the user reads the linked page. - let _ = w.open_with_url_and_target(&url, "_blank,noopener"); + // editor window and navigate it while the user reads the linked page. It must be a + // window *feature*: inside the target string it would only name the new window. + let _ = w.open_with_url_and_target_and_features(&url, "_blank", "noopener,noreferrer"); } })), inbox: Some(inbox), diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index 8429070b77..a7472821f9 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -24,22 +24,26 @@ chrono = { workspace = true } # Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows. winresource = "0.1" -[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] +[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies] winit = { version = "0.30", default-features = false, features = ["x11"] } +[target.'cfg(target_os = "linux")'.dependencies] +# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts. +winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] } + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # Same craft-libs revision as the workspace's craft-update and craft-window (see the root # Cargo.toml). -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-update = { workspace = true } rfd = { workspace = true } -arboard = { workspace = true } +arboard = { workspace = true, features = ["image-data"] } gridcraft-mcp = { workspace = true } # The control channel's token (OS random numbers); already in the tree. getrandom = "0.4" [target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies] -arboard = { workspace = true, features = ["wayland-data-control"] } +arboard = { workspace = true, features = ["image-data", "wayland-data-control"] } [target.'cfg(target_os = "windows")'.dependencies] # Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe. @@ -52,6 +56,10 @@ muda = { version = "0.21", default-features = false } # by PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which our # workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping. fmv-macos-events = "=0.1.0" +# apple_events.rs brings the app forward for a Dock quit's question. Already in Cargo.lock (muda, +# winit); pinned exactly to the same versions. +objc2 = "=0.6.5" +objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder", "NSWindow"] } # tests/mac_menu_appkit.rs: reads AppKit's menu bar back. Already in Cargo.lock (muda, winit); # pinned exactly to the same versions. diff --git a/apps/gridcraft/src/apple_events.rs b/apps/gridcraft/src/apple_events.rs index 4d596f9571..b0898eced6 100644 --- a/apps/gridcraft/src/apple_events.rs +++ b/apps/gridcraft/src/apple_events.rs @@ -11,6 +11,8 @@ use fmv_macos_events::{Event, Inbox, Registration}; use gridcraft_ui_egui::SheetApp; +use objc2::MainThreadMarker; +use objc2_app_kit::{NSApplication, NSRequestUserAttentionType}; /// Keeps the Apple-event handlers registered; hold it until the event loop returns. pub struct AppleEvents { @@ -44,7 +46,32 @@ pub fn poll(inbox: &Inbox, app: &mut SheetApp, ctx: &egui::Context) { } } // Quit from the Dock or the system: each unsaved workbook is asked about in its window. - Event::Quit => app.request_quit(ctx), + Event::Quit => { + app.request_quit(ctx); + if app.dialog.is_some() { + bring_app_forward(); + } + } } } } + +/// A Dock quit reaches GridCraft behind other apps, hidden or minimized, and its question has to +/// be seen. egui's Focus goes through winit, which skips a minimized window or a hidden app, and +/// macOS may refuse an activation it didn't expect, so ask AppKit directly and bounce the Dock +/// icon until the user switches over. +fn bring_app_forward() { + let Some(mtm) = MainThreadMarker::new() else { return }; + let ns_app = NSApplication::sharedApplication(mtm); + ns_app.unhide(None); + for window in ns_app.windows().to_vec() { + if window.isMiniaturized() { + window.deminiaturize(None); + } + } + #[allow(deprecated)] // `activate` needs macOS 14; this works on every supported version. + ns_app.activateIgnoringOtherApps(true); + if !ns_app.isActive() { + ns_app.requestUserAttention(NSRequestUserAttentionType::CriticalRequest); + } +} diff --git a/apps/gridcraft/src/control_server.rs b/apps/gridcraft/src/control_server.rs index cc5a80c106..7cba6db2c2 100644 --- a/apps/gridcraft/src/control_server.rs +++ b/apps/gridcraft/src/control_server.rs @@ -12,16 +12,47 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::Duration; +use std::time::{Duration, Instant}; use gridcraft_mcp::control_auth; use gridcraft_ui_egui::ControlRequest; use serde_json::{Value as Json, json}; const MAX_LINE: usize = 64 * 1024 * 1024; -/// How long a new connection may take to send its token. +/// How long a new connection may take to send its token, in total. const AUTH_TIMEOUT: Duration = Duration::from_secs(10); +/// How many connections may be waiting to authenticate at once. Anyone on the machine can +/// connect without the token, so past this a new connection is closed before anything is read: +/// each waiting one holds a thread and a socket. +const MAX_PENDING_AUTH: usize = 16; + +/// How the server treats connections that haven't authenticated yet. +#[derive(Clone, Copy)] +struct AuthLimits { + timeout: Duration, + max_pending: usize, +} + +const AUTH_LIMITS: AuthLimits = AuthLimits { timeout: AUTH_TIMEOUT, max_pending: MAX_PENDING_AUTH }; + +/// A connection that is still waiting to authenticate; dropping it frees its place. +struct Pending(Arc); + +impl Pending { + /// A place among the `max` waiting connections, or `None` when they are all taken. + fn claim(waiting: &Arc, max: usize) -> Option { + waiting.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok()?; + Some(Pending(Arc::clone(waiting))) + } +} + +impl Drop for Pending { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} /// The secret of this run: the one the user chose (`--control-token`, `GRIDCRAFT_CONTROL_TOKEN`), /// else 256 random bits from the operating system, written to a file only the user can read. @@ -51,35 +82,75 @@ pub fn start(port: u16, chosen_token: Option, ctx: egui::Context) -> std /// Accept connections on `listener`; requests arrive on the returned receiver. fn serve_listener(listener: TcpListener, token: Arc, ctx: egui::Context) -> std::io::Result> { + serve_listener_with(listener, token, ctx, AUTH_LIMITS) +} + +fn serve_listener_with(listener: TcpListener, token: Arc, ctx: egui::Context, limits: AuthLimits) -> std::io::Result> { let (tx, rx) = channel(); + let waiting = Arc::new(AtomicUsize::new(0)); std::thread::Builder::new().name("control".into()).spawn(move || { - for stream in listener.incoming().flatten() { + for stream in listener.incoming() { + let Ok(stream) = stream else { + // Out of sockets or handles: wait for some to free instead of spinning on the error. + std::thread::sleep(Duration::from_millis(50)); + continue; + }; + // Dropping the stream closes it before anything is read. + let Some(place) = Pending::claim(&waiting, limits.max_pending) else { continue }; let tx = tx.clone(); let ctx = ctx.clone(); let token = Arc::clone(&token); - let _ = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx)); + let _ = + std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx, limits.timeout, Some(place))); } })?; Ok(rx) } /// Read the connection's first line (at most [`control_auth::MAX_AUTH_LINE`] bytes, within -/// [`AUTH_TIMEOUT`]) and check the token. `true` when the peer may go on. -fn authenticate(reader: &mut BufReader, out: &mut TcpStream, token: &str) -> bool { - let _ = out.set_read_timeout(Some(AUTH_TIMEOUT)); - let mut first = String::new(); - let read = reader.by_ref().take(control_auth::MAX_AUTH_LINE as u64).read_line(&mut first); - let verdict = match read { - Ok(n) if n > 0 && first.ends_with('\n') => control_auth::check_first_line(&first, token), +/// `timeout` in total) and check the token. `true` when the peer may go on. +#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it +fn authenticate(reader: &mut BufReader, out: &mut TcpStream, token: &str, timeout: Duration) -> bool { + let deadline = Instant::now().checked_add(timeout).unwrap_or_else(Instant::now); + let mut first = Vec::new(); + let read = read_auth_line(reader, &mut first, deadline); + let verdict = match (read, std::str::from_utf8(&first)) { + (Ok(()), Ok(line)) if line.ends_with('\n') => control_auth::check_first_line(line, token), _ => Err(json!({"ok": false, "error": "authentication required"})), }; let allowed = verdict.is_ok(); let reply = verdict.unwrap_or_else(|e| e); let _ = writeln!(out, "{reply}"); - let _ = out.set_read_timeout(None); + let _ = reader.get_ref().set_read_timeout(None); allowed } +/// Read the first line, at most [`control_auth::MAX_AUTH_LINE`] bytes, by `deadline`. +/// +/// The timeout goes on the handle the reader reads: on Windows a `try_clone` of the stream keeps +/// its own, so one set on the writing half never fired (a silent peer held its thread forever). +/// It is shortened before every read, so a peer sending one byte at a time can't stretch it. +#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it +fn read_auth_line(reader: &mut BufReader, line: &mut Vec, deadline: Instant) -> std::io::Result<()> { + let max = control_auth::MAX_AUTH_LINE; + while line.len() < max && line.last() != Some(&b'\n') { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + reader.get_ref().set_read_timeout(Some(left))?; + let buf = reader.fill_buf()?; + if buf.is_empty() { + break; + } + let room = max.saturating_sub(line.len()); + let take = buf.iter().take(room).position(|b| *b == b'\n').map_or(buf.len().min(room), |i| i + 1); + line.extend(buf.iter().take(take)); + reader.consume(take); + } + Ok(()) +} + /// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). /// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { @@ -148,11 +219,14 @@ fn is_http_request_line(text: &str) -> bool { || text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/")) } -fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context) { +fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context, auth_timeout: Duration, place: Option) { let Ok(read) = stream.try_clone() else { return }; let mut out = stream; let mut reader = BufReader::new(read); - if !authenticate(&mut reader, &mut out, token) { + let allowed = authenticate(&mut reader, &mut out, token, auth_timeout); + // Authenticated or refused, the connection no longer counts as waiting. + drop(place); + if !allowed { return; } let mut buf = Vec::new(); @@ -294,7 +368,7 @@ mod tests { std::thread::spawn(move || { for stream in listener.incoming().flatten() { let tx = tx.clone(); - std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default())); + std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default(), AUTH_TIMEOUT, None)); } }); addr @@ -346,6 +420,81 @@ mod tests { assert_eq!(got[1]["ok"], json!(false)); } + /// Whether the server closed `c` (end of stream, or a refusal and then end of stream) within + /// `within`, and how long it took. + #[allow(clippy::disallowed_methods)] // a native-only test of the desktop app + fn closed_within(c: TcpStream, within: Duration) -> (bool, Duration) { + let start = Instant::now(); + c.set_read_timeout(Some(within)).unwrap(); + let mut r = BufReader::new(c); + let mut line = String::new(); + loop { + line.clear(); + match r.read_line(&mut line) { + Ok(0) => return (true, start.elapsed()), + Ok(_) => continue, + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => return (false, start.elapsed()), + Err(_) => return (true, start.elapsed()), + } + } + } + + /// The token deadline is for the whole first line: neither a silent peer nor one sending a + /// byte at a time keeps the connection (and its thread) past it. + #[test] + fn a_silent_or_slow_peer_is_closed_at_the_auth_deadline() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let limits = AuthLimits { timeout: Duration::from_millis(300), max_pending: MAX_PENDING_AUTH }; + let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap(); + + let silent = TcpStream::connect(addr).unwrap(); + let mut slow = TcpStream::connect(addr).unwrap(); + let mut drip = slow.try_clone().unwrap(); + std::thread::spawn(move || { + for b in control_auth::auth_line(1, TOKEN).bytes() { + if drip.write_all(&[b]).is_err() { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + }); + let (closed, took) = closed_within(silent, Duration::from_secs(5)); + assert!(closed && took < Duration::from_secs(3), "silent peer kept for {took:?}"); + let (closed, took) = closed_within(slow.try_clone().unwrap(), Duration::from_secs(5)); + assert!(closed && took < Duration::from_secs(3), "byte-at-a-time peer kept for {took:?}"); + let _ = slow.flush(); + } + + /// Peers without the token can't pile up threads: past the cap a new connection is closed at + /// once, and a waiting one that authenticates frees its place. + #[test] + fn connections_waiting_to_authenticate_are_capped() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let limits = AuthLimits { timeout: Duration::from_secs(20), max_pending: 2 }; + let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap(); + + let mut first = TcpStream::connect(addr).unwrap(); + let _second = TcpStream::connect(addr).unwrap(); + std::thread::sleep(Duration::from_millis(200)); + let (closed, took) = closed_within(TcpStream::connect(addr).unwrap(), Duration::from_secs(5)); + assert!(closed && took < Duration::from_secs(3), "a third waiting connection was kept"); + + first.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + first.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap(); + let mut reply = String::new(); + BufReader::new(first.try_clone().unwrap()).read_line(&mut reply).unwrap(); + assert_eq!(serde_json::from_str::(&reply).unwrap()["ok"], json!(true), "{reply}"); + std::thread::sleep(Duration::from_millis(200)); + let mut next = TcpStream::connect(addr).unwrap(); + next.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + next.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap(); + let mut reply = String::new(); + BufReader::new(next).read_line(&mut reply).unwrap(); + assert_eq!(serde_json::from_str::(&reply).unwrap()["ok"], json!(true), "a freed place was not reused: {reply}"); + } + #[test] fn a_chosen_token_must_be_long_enough() { assert!(make_token(1, Some("short".into())).is_err()); diff --git a/apps/gridcraft/src/graphics.rs b/apps/gridcraft/src/graphics.rs index 83478eddea..93ec2e4c94 100644 --- a/apps/gridcraft/src/graphics.rs +++ b/apps/gridcraft/src/graphics.rs @@ -1,4 +1,5 @@ -//! Windows graphics instance configuration, applied before wgpu can initialize any driver. +//! Graphics instance configuration, applied before wgpu can initialize any driver: Windows +//! backends and the DirectX 12 shader compiler, and the Intel Mac indirect-validation skip. //! //! Vulkan is never initialized unless `WGPU_BACKEND` asks for it: enumerating Vulkan adapters //! crashes inside Intel's `igvk64.dll` on some UHD Graphics drivers (#120), and that access @@ -8,12 +9,38 @@ //! whichever `dxcompiler.dll` the DLL search path happens to find (#339, #354): see //! [`dx12_compiler`]. +// On macOS only the indirect-validation items are used outside tests; on Windows the other way +// round, so those two carry their own `allow`. +#![cfg_attr(target_os = "macos", allow(dead_code))] + use eframe::{ NativeOptions, egui_wgpu::WgpuSetup, - wgpu::{Backends, DeviceType, Dx12Compiler}, + wgpu::{Backends, DeviceType, Dx12Compiler, InstanceFlags}, }; +/// wgpu compiles its indirect-call validation compute shaders inside `request_device`. On Intel +/// Macs (Iris 5100 in a Mac mini 2014) Metal's compiler aborts on them ("Compiler encountered an +/// internal error"), the device is lost and eframe exits before the window opens. GridCraft issues +/// no indirect draws or dispatches, so Intel Macs skip them; every other GPU keeps wgpu's default. +/// Same as WordCraft (storytold/wordcraft#2652) and PhotoCraft (storytold/PhotoCraft#3171). +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub fn skips_indirect_validation(macos: bool, intel: bool) -> bool { + macos && intel +} + +/// Leaves wgpu's indirect-call validation out of the instance eframe creates when `skip`. +/// `WGPU_VALIDATION_INDIRECT_CALL=1` still turns it back on. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub fn configure_indirect_validation(options: &mut NativeOptions, skip: bool) { + if !skip { + return; + } + if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { + create.instance_descriptor.flags = create.instance_descriptor.flags.difference(InstanceFlags::VALIDATION_INDIRECT_CALL).with_env(); + } +} + /// What the start-up probe learned about one DirectX 12 adapter. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Dx12Adapter { @@ -141,6 +168,55 @@ fn probe_dx12(options: &NativeOptions) -> Vec { mod tests { use super::*; + fn instance_flags(options: &NativeOptions) -> InstanceFlags { + let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { + panic!("default native options must create a wgpu instance"); + }; + create.instance_descriptor.flags + } + + #[test] + fn intel_macs_skip_the_indirect_validation_shaders() { + // Metal's Intel compiler aborted on them, losing the device before the window opened. + assert!(skips_indirect_validation(true, true)); + // Apple silicon, Windows and Linux keep wgpu's validation. + for (macos, intel) in [(true, false), (false, true), (false, false)] { + assert!(!skips_indirect_validation(macos, intel), "macos={macos} intel={intel}"); + } + let mut options = NativeOptions::default(); + let before = instance_flags(&options); + configure_indirect_validation(&mut options, false); + assert_eq!(instance_flags(&options), before, "flags untouched when not skipping"); + if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { + configure_indirect_validation(&mut options, true); + assert!(!instance_flags(&options).contains(InstanceFlags::VALIDATION_INDIRECT_CALL)); + } + } + + /// `WGPU_VALIDATION_INDIRECT_CALL=1` turns the validation back on even when it is skipped. + /// Tests can't set environment variables (`set_var` is unsafe, and unsafe code is forbidden), + /// so this runs itself again as a child process with the variable set. + #[test] + fn the_environment_turns_indirect_validation_back_on() { + const NAME: &str = "graphics::tests::the_environment_turns_indirect_validation_back_on"; + if std::env::var_os("GRIDCRAFT_INDIRECT_VALIDATION_CHILD").is_some() { + let mut options = NativeOptions::default(); + configure_indirect_validation(&mut options, true); + assert!(instance_flags(&options).contains(InstanceFlags::VALIDATION_INDIRECT_CALL)); + return; + } + let exe = std::env::current_exe().unwrap(); + let out = std::process::Command::new(exe) + .args(["--exact", NAME, "--test-threads=1"]) + .env("GRIDCRAFT_INDIRECT_VALIDATION_CHILD", "1") + .env("WGPU_VALIDATION_INDIRECT_CALL", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + // `--exact` matching nothing would pass too, so the child must report this one test. + assert!(out.status.success() && stdout.contains("1 passed"), "child test failed:\n{stdout}{}", String::from_utf8_lossy(&out.stderr)); + } + fn configured_backends(backends: Backends) -> Backends { let mut options = NativeOptions::default(); configure_backends(&mut options, backends); diff --git a/apps/gridcraft/src/logging.rs b/apps/gridcraft/src/logging.rs index a0f62d164a..ca7d05717d 100644 --- a/apps/gridcraft/src/logging.rs +++ b/apps/gridcraft/src/logging.rs @@ -268,9 +268,10 @@ impl log::Log for AppLogger { } // Formatted before the sink is locked, so a message that logs while it is formatted can't deadlock. let thread = std::thread::current(); - #[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it - let line = - format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string()); + let logged_at = gridcraft_engine::core::date::unix_now_ms() + .and_then(|milliseconds| SystemTime::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(milliseconds.max(0.0) as u64))) + .unwrap_or(SystemTime::UNIX_EPOCH); + let line = format_line(×tamp(logged_at), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string()); if self.stderr { // No terminal (a Windows GUI build, a closed pipe) is not an error worth reporting. let _ = std::io::stderr().write_all(line.as_bytes()); @@ -295,303 +296,4 @@ pub fn install() -> Option<&'static AppLogger> { } #[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::{Duration, UNIX_EPOCH}; - - fn temp_dir(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("gridcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - d - } - - fn read(path: &Path) -> String { - std::fs::read_to_string(path).expect("read log") - } - - fn record(logger: &AppLogger, level: log::Level, target: &str, msg: &str) { - use log::Log; - logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build()); - } - - #[test] - fn the_default_filter_shows_gridcraft_info_and_other_crates_warnings() { - let f = Filter::parse(DEFAULT_FILTER); - assert_eq!(f.level_for("gridcraft"), LevelFilter::Info); - assert_eq!(f.level_for("gridcraft::control_server"), LevelFilter::Info); - assert_eq!(f.level_for("gridcraft_engine::sample"), LevelFilter::Info); - assert_eq!(f.level_for("gridcraft_ui_egui::control"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn); - assert_eq!(f.level_for("naga"), LevelFilter::Warn); - assert_eq!(f.max(), LevelFilter::Info); - } - - #[test] - fn directives_follow_env_logger_and_the_most_specific_one_wins() { - let f = Filter::parse("info,wgpu_core=error,gridcraft_calc=trace,gridcraft_calc::recalc=off"); - assert_eq!(f.level_for("eframe"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); - assert_eq!(f.level_for("gridcraft_calc::graph"), LevelFilter::Trace); - assert_eq!(f.level_for("gridcraft_calc::recalc"), LevelFilter::Off); - assert_eq!(f.max(), LevelFilter::Trace); - // A module name is matched at `::` boundaries, not as a bare prefix. - assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info); - // A trailing `*` is a prefix. - assert_eq!(Filter::parse("gridcraft*=debug").level_for("gridcraft_xlsx::read"), LevelFilter::Debug); - assert_eq!(Filter::parse("gridcraft*=debug").level_for("eframe"), LevelFilter::Error); - // A bare target name sets that target to the most verbose level, as env_logger does. - assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace); - assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); - // Levels are case-insensitive and surrounding blanks are ignored. - assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("gridcraft"), LevelFilter::Debug); - assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("eframe"), LevelFilter::Warn); - } - - #[test] - fn hostile_specs_never_panic_and_fall_back_sensibly() { - let long = "x".repeat(100_000); - let many = "a=info,".repeat(10_000); - for spec in [ - "", - ",,,", - "=", - "==", - "=debug", - "gridcraft=", - "nonsense=loud", - "🦀=info", - "*", - "*=", - "=*", - "a=b=c", - "warn,,gridcraft=DEBUG", - "\0", - "é::ü=trace", - &long, - &many, - ] { - let f = Filter::parse(spec); - for target in ["", "gridcraft", "🦀", "a::b", "*"] { - let _ = f.level_for(target); - } - let _ = f.max(); - } - assert_eq!(Filter::parse("warn,,gridcraft=DEBUG").level_for("gridcraft"), LevelFilter::Debug); - // An unknown level is skipped: that target keeps the default. - assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error); - assert_eq!(Filter::parse("gridcraft=").level_for("gridcraft"), LevelFilter::Error); - assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error); - assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info); - } - - #[test] - fn timestamps_are_utc_with_milliseconds() { - assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); - // Leap day, and the day after it. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); - // 2000 is a leap year (divisible by 400), 2100 is not. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); - // Before the epoch (a clock set wrong) clamps instead of panicking. - assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); - // A clock set absurdly far ahead (past chrono's own range) keeps its real year rather than - // collapsing to the epoch. Windows' SystemTime can't hold such an instant, so it is built - // with a checked add and only asserted where it exists. - if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) { - assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z"); - } - if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) { - assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z"); - } - // Years past 9999 keep the plain zero-padded year (no `+`). - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); - } - - #[test] - fn a_line_carries_time_level_thread_target_and_message() { - assert_eq!( - format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "gridcraft", "book.xlsx: file not found"), - "2026-10-08T07:59:17.728Z WARN [main] gridcraft: book.xlsx: file not found\n" - ); - // A multi-line message keeps its lines; the record still ends in one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); - } - - #[test] - fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { - let dir = temp_dir("rotate"); - for run in 1..=4 { - let (path, _file) = rotate(&dir).expect("rotate"); - assert_eq!(path, dir.join(LOG_FILE)); - assert_eq!(read(&path), ""); - std::fs::write(&path, format!("run {run}")).expect("write"); - } - assert_eq!(read(&dir.join(LOG_FILE)), "run 4"); - assert_eq!(read(&dir.join("gridcraft.1.log")), "run 3"); - assert_eq!(read(&dir.join("gridcraft.2.log")), "run 2"); - assert!(!dir.join("gridcraft.3.log").exists(), "only {KEEP} old logs are kept"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { - let dir = temp_dir("blocked"); - std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); - std::fs::write(&dir, "a file where the directory should be").expect("block"); - assert!(rotate(&dir).is_err()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { - let dir = temp_dir("pending"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - sink.write("early 1\n"); - sink.write("early 2\n"); - sink.attach(file); - sink.write("late\n"); - assert_eq!(read(&path), "early 1\nearly 2\nlate\n"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { - let dir = temp_dir("bounded"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING + 5 { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); - assert!(text.contains("5 earlier log lines were dropped"), "{text}"); - assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n"))); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn exactly_a_full_pending_buffer_drops_nothing() { - let dir = temp_dir("full"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().count(), MAX_PENDING); - assert!(!text.contains("dropped"), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn without_a_file_nothing_is_kept_in_memory() { - let mut sink = Sink::new(MAX_FILE_BYTES); - sink.write("early\n"); - sink.no_file(); - sink.write("late\n"); - assert!(sink.pending.is_empty() && sink.dropped == 0); - } - - #[test] - fn the_file_stops_at_its_size_cap_with_one_note() { - let dir = temp_dir("cap"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(100); - sink.attach(file); - for i in 0..50 { - sink.write(&format!("line {i:02} with some padding\n")); - } - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}"); - assert_eq!(text.matches("log file reached").count(), 1, "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_logger_filters_records_and_writes_them_to_the_attached_file() { - use log::Log; - let dir = temp_dir("logger"); - let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); - record(&logger, log::Level::Info, "gridcraft", "before the settings directory"); - record(&logger, log::Level::Info, "wgpu_core::device", "too chatty"); - let path = logger.attach_dir(&dir).expect("attach"); - assert_eq!(path, dir.join(LOG_FILE)); - record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); - record(&logger, log::Level::Error, "gridcraft", "internal error: boom"); - record(&logger, log::Level::Debug, "gridcraft", "below info"); - let text = read(&path); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 3, "{text}"); - assert!(lines[0].contains(" INFO [") && lines[0].ends_with("gridcraft: before the settings directory"), "{text}"); - assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}"); - assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("gridcraft: internal error: boom"), "{text}"); - assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("gridcraft_ui_egui").build())); - assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); - // Attaching again rotates: the first log becomes `.1`. - logger.attach_dir(&dir).expect("attach again"); - assert_eq!(read(&dir.join("gridcraft.1.log")), text); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn records_from_many_threads_are_whole_lines() { - let dir = temp_dir("threads"); - let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); - let path = logger.attach_dir(&dir).expect("attach"); - let workers: Vec<_> = (0..8) - .map(|t| { - let l = std::sync::Arc::clone(&logger); - std::thread::spawn(move || { - for i in 0..100 { - record(&l, log::Level::Info, "gridcraft", &format!("thread {t} record {i}")); - } - }) - }) - .collect(); - for w in workers { - w.join().expect("worker"); - } - let text = read(&path); - assert_eq!(text.lines().count(), 800); - assert!(text.lines().all(|l| l.contains(" gridcraft: thread ")), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() { - let dir = temp_dir("unusable"); - std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); - std::fs::write(&dir, "not a directory").expect("block"); - let logger = AppLogger::new(Filter::parse("info"), false); - assert!(logger.attach_dir(&dir).is_err()); - record(&logger, log::Level::Error, "x", "still fine"); - // Nothing waits in memory for a file that won't come. - assert!(logger.sink.lock().expect("sink").pending.is_empty()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn a_poisoned_sink_still_logs() { - let dir = temp_dir("poison"); - let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); - let l = std::sync::Arc::clone(&logger); - let _ = std::thread::spawn(move || { - let _guard = l.sink.lock().expect("lock"); - panic!("poison the sink"); - }) - .join(); - assert!(logger.sink.is_poisoned()); - let path = logger.attach_dir(&dir).expect("attach"); - record(&logger, log::Level::Warn, "gridcraft", "after the poison"); - assert!(read(&path).contains("gridcraft: after the poison")); - let _ = std::fs::remove_dir_all(&dir); - } -} +mod tests; diff --git a/apps/gridcraft/src/logging/tests.rs b/apps/gridcraft/src/logging/tests.rs new file mode 100644 index 0000000000..bfc0f81a18 --- /dev/null +++ b/apps/gridcraft/src/logging/tests.rs @@ -0,0 +1,298 @@ +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, UNIX_EPOCH}; + +fn temp_dir(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("gridcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).expect("read log") +} + +fn record(logger: &AppLogger, level: log::Level, target: &str, msg: &str) { + use log::Log; + logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build()); +} + +#[test] +fn the_default_filter_shows_gridcraft_info_and_other_crates_warnings() { + let f = Filter::parse(DEFAULT_FILTER); + assert_eq!(f.level_for("gridcraft"), LevelFilter::Info); + assert_eq!(f.level_for("gridcraft::control_server"), LevelFilter::Info); + assert_eq!(f.level_for("gridcraft_engine::sample"), LevelFilter::Info); + assert_eq!(f.level_for("gridcraft_ui_egui::control"), LevelFilter::Info); + assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn); + assert_eq!(f.level_for("naga"), LevelFilter::Warn); + assert_eq!(f.max(), LevelFilter::Info); +} + +#[test] +fn directives_follow_env_logger_and_the_most_specific_one_wins() { + let f = Filter::parse("info,wgpu_core=error,gridcraft_calc=trace,gridcraft_calc::recalc=off"); + assert_eq!(f.level_for("eframe"), LevelFilter::Info); + assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); + assert_eq!(f.level_for("gridcraft_calc::graph"), LevelFilter::Trace); + assert_eq!(f.level_for("gridcraft_calc::recalc"), LevelFilter::Off); + assert_eq!(f.max(), LevelFilter::Trace); + // A module name is matched at `::` boundaries, not as a bare prefix. + assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info); + // A trailing `*` is a prefix. + assert_eq!(Filter::parse("gridcraft*=debug").level_for("gridcraft_xlsx::read"), LevelFilter::Debug); + assert_eq!(Filter::parse("gridcraft*=debug").level_for("eframe"), LevelFilter::Error); + // A bare target name sets that target to the most verbose level, as env_logger does. + assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace); + assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); + // Levels are case-insensitive and surrounding blanks are ignored. + assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("gridcraft"), LevelFilter::Debug); + assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("eframe"), LevelFilter::Warn); +} + +#[test] +fn hostile_specs_never_panic_and_fall_back_sensibly() { + let long = "x".repeat(100_000); + let many = "a=info,".repeat(10_000); + for spec in [ + "", + ",,,", + "=", + "==", + "=debug", + "gridcraft=", + "nonsense=loud", + "🦀=info", + "*", + "*=", + "=*", + "a=b=c", + "warn,,gridcraft=DEBUG", + "\0", + "é::ü=trace", + &long, + &many, + ] { + let f = Filter::parse(spec); + for target in ["", "gridcraft", "🦀", "a::b", "*"] { + let _ = f.level_for(target); + } + let _ = f.max(); + } + assert_eq!(Filter::parse("warn,,gridcraft=DEBUG").level_for("gridcraft"), LevelFilter::Debug); + // An unknown level is skipped: that target keeps the default. + assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error); + assert_eq!(Filter::parse("gridcraft=").level_for("gridcraft"), LevelFilter::Error); + assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error); + assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info); +} + +#[test] +fn timestamps_are_utc_with_milliseconds() { + assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); + // Leap day, and the day after it. + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); + // 2000 is a leap year (divisible by 400), 2100 is not. + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); + // Before the epoch (a clock set wrong) clamps instead of panicking. + assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); + // A clock set absurdly far ahead (past chrono's own range) keeps its real year rather than + // collapsing to the epoch. Windows' SystemTime can't hold such an instant, so it is built + // with a checked add and only asserted where it exists. + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) { + assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z"); + } + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) { + assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z"); + } + // Years past 9999 keep the plain zero-padded year (no `+`). + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); +} + +#[test] +fn a_line_carries_time_level_thread_target_and_message() { + assert_eq!( + format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "gridcraft", "book.xlsx: file not found"), + "2026-10-08T07:59:17.728Z WARN [main] gridcraft: book.xlsx: file not found\n" + ); + // A multi-line message keeps its lines; the record still ends in one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); +} + +#[test] +fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { + let dir = temp_dir("rotate"); + for run in 1..=4 { + let (path, _file) = rotate(&dir).expect("rotate"); + assert_eq!(path, dir.join(LOG_FILE)); + assert_eq!(read(&path), ""); + std::fs::write(&path, format!("run {run}")).expect("write"); + } + assert_eq!(read(&dir.join(LOG_FILE)), "run 4"); + assert_eq!(read(&dir.join("gridcraft.1.log")), "run 3"); + assert_eq!(read(&dir.join("gridcraft.2.log")), "run 2"); + assert!(!dir.join("gridcraft.3.log").exists(), "only {KEEP} old logs are kept"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { + let dir = temp_dir("blocked"); + std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); + std::fs::write(&dir, "a file where the directory should be").expect("block"); + assert!(rotate(&dir).is_err()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { + let dir = temp_dir("pending"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + sink.write("early 1\n"); + sink.write("early 2\n"); + sink.attach(file); + sink.write("late\n"); + assert_eq!(read(&path), "early 1\nearly 2\nlate\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { + let dir = temp_dir("bounded"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING + 5 { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + let text = read(&path); + assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); + assert!(text.contains("5 earlier log lines were dropped"), "{text}"); + assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n"))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn exactly_a_full_pending_buffer_drops_nothing() { + let dir = temp_dir("full"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + let text = read(&path); + assert_eq!(text.lines().count(), MAX_PENDING); + assert!(!text.contains("dropped"), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn without_a_file_nothing_is_kept_in_memory() { + let mut sink = Sink::new(MAX_FILE_BYTES); + sink.write("early\n"); + sink.no_file(); + sink.write("late\n"); + assert!(sink.pending.is_empty() && sink.dropped == 0); +} + +#[test] +fn the_file_stops_at_its_size_cap_with_one_note() { + let dir = temp_dir("cap"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(100); + sink.attach(file); + for i in 0..50 { + sink.write(&format!("line {i:02} with some padding\n")); + } + let text = read(&path); + assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}"); + assert_eq!(text.matches("log file reached").count(), 1, "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_logger_filters_records_and_writes_them_to_the_attached_file() { + use log::Log; + let dir = temp_dir("logger"); + let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); + record(&logger, log::Level::Info, "gridcraft", "before the settings directory"); + record(&logger, log::Level::Info, "wgpu_core::device", "too chatty"); + let path = logger.attach_dir(&dir).expect("attach"); + assert_eq!(path, dir.join(LOG_FILE)); + record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); + record(&logger, log::Level::Error, "gridcraft", "internal error: boom"); + record(&logger, log::Level::Debug, "gridcraft", "below info"); + let text = read(&path); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 3, "{text}"); + assert!(lines[0].contains(" INFO [") && lines[0].ends_with("gridcraft: before the settings directory"), "{text}"); + assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}"); + assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("gridcraft: internal error: boom"), "{text}"); + assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("gridcraft_ui_egui").build())); + assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); + // Attaching again rotates: the first log becomes `.1`. + logger.attach_dir(&dir).expect("attach again"); + assert_eq!(read(&dir.join("gridcraft.1.log")), text); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn records_from_many_threads_are_whole_lines() { + let dir = temp_dir("threads"); + let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); + let path = logger.attach_dir(&dir).expect("attach"); + let workers: Vec<_> = (0..8) + .map(|t| { + let l = std::sync::Arc::clone(&logger); + std::thread::spawn(move || { + for i in 0..100 { + record(&l, log::Level::Info, "gridcraft", &format!("thread {t} record {i}")); + } + }) + }) + .collect(); + for w in workers { + w.join().expect("worker"); + } + let text = read(&path); + assert_eq!(text.lines().count(), 800); + assert!(text.lines().all(|l| l.contains(" gridcraft: thread ")), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() { + let dir = temp_dir("unusable"); + std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); + std::fs::write(&dir, "not a directory").expect("block"); + let logger = AppLogger::new(Filter::parse("info"), false); + assert!(logger.attach_dir(&dir).is_err()); + record(&logger, log::Level::Error, "x", "still fine"); + // Nothing waits in memory for a file that won't come. + assert!(logger.sink.lock().expect("sink").pending.is_empty()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn a_poisoned_sink_still_logs() { + let dir = temp_dir("poison"); + let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); + let l = std::sync::Arc::clone(&logger); + let _ = std::thread::spawn(move || { + let _guard = l.sink.lock().expect("lock"); + panic!("poison the sink"); + }) + .join(); + assert!(logger.sink.is_poisoned()); + let path = logger.attach_dir(&dir).expect("attach"); + record(&logger, log::Level::Warn, "gridcraft", "after the poison"); + assert!(read(&path).contains("gridcraft: after the poison")); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 988bf738b0..2aa98b6eb4 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -12,7 +12,7 @@ #[cfg(target_os = "macos")] mod apple_events; mod control_server; -#[cfg(any(target_os = "windows", test))] +#[cfg(any(target_os = "windows", target_os = "macos", test))] mod graphics; mod logging; #[cfg(target_os = "macos")] @@ -154,7 +154,7 @@ fn read_clipboard( fn services() -> Services { // Keep the owner alive: X11/Wayland serve clipboard data from this handle. let clipboard: Rc>> = Rc::default(); - let (html_clipboard, text_clipboard) = (clipboard.clone(), clipboard.clone()); + let (html_clipboard, text_clipboard, image_clipboard) = (clipboard.clone(), clipboard.clone(), clipboard.clone()); Services { copy_html: Some(Box::new(move |html, text| { let mut clipboard = clipboard.borrow_mut(); @@ -165,9 +165,13 @@ fn services() -> Services { })), paste_html: Some(Box::new(move || read_clipboard(&html_clipboard, |clipboard| clipboard.get().html()))), paste_text: Some(Box::new(move || read_clipboard(&text_clipboard, |clipboard| clipboard.get_text()))), + paste_image: Some(Box::new(move || { + let image = read_clipboard(&image_clipboard, |clipboard| clipboard.get_image())?; + image::RgbaImage::from_raw(u32::try_from(image.width).ok()?, u32::try_from(image.height).ok()?, image.bytes.into_owned()) + })), pick_open: Some(Box::new(|| { rfd::FileDialog::new() - .add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"]) + .add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "slk", "json"]) .add_filter("Excel Workbook", &["xlsx", "xlsm"]) .add_filter("Excel 97-2003 Workbook (import)", &["xls"]) .add_filter("Excel Binary Workbook (data import)", &["xlsb"]) @@ -256,7 +260,7 @@ fn main() -> eframe::Result<()> { })); let args: Vec = std::env::args().skip(1).collect(); // The restart helper a self-update spawns: it finishes the swap and relaunches, then exits. - if let Some(done) = craft_update::self_update::finish(&craft_update::suite::GRIDCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { if let Err(e) = done { eprintln!("GridCraft update helper failed: {e}"); std::process::exit(1); @@ -311,15 +315,16 @@ fn main() -> eframe::Result<()> { { log::warn!("sample {s}: {e}"); } - if session.documents().is_empty() { - session.new_workbook(); - } let mut app = SheetApp::new(session, services()); app.watch_desktop_theme(); app.start_update_check(); - app.after_engine(); // Show warnings from the sample. let control_port = control_port; load_prefs(&mut app); + // Stamp the startup workbook's author from the persisted user name. + if app.session.documents().is_empty() { + app.session.new_workbook(); + } + app.after_engine(); // Show warnings from the sample. // Files named on the command line (a double-click on Windows and Linux) open as File › Open // opens them: a password-protected one asks for its password, and errors are shown, not // only logged. Each replaces the untouched blank Book1, as a file opened from Finder does. @@ -340,8 +345,11 @@ fn main() -> eframe::Result<()> { } let window_builder = viewport.clone(); let options = eframe::NativeOptions { viewport, ..Default::default() }; - #[cfg(all(unix, not(target_os = "macos")))] + #[cfg(unix)] let mut options = options; + // Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs). + #[cfg(target_os = "macos")] + graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64"))); // winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file // manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1 // keeps the native Wayland backend. diff --git a/apps/gridcraft/src/native_menu.rs b/apps/gridcraft/src/native_menu.rs index 522f4fd686..04139297d6 100644 --- a/apps/gridcraft/src/native_menu.rs +++ b/apps/gridcraft/src/native_menu.rs @@ -390,11 +390,12 @@ impl NativeMenu { #[cfg(test)] mod tests { - use super::*; + // No `use super::*`: tests/mac_menu_appkit.rs builds this file with cfg(test) but no test + // harness, so the #[test] functions are left out and a module-level import would be unused. #[test] fn file_menu_has_export_as_pdf_dispatching_the_command() { - let tree = tree(); + let tree = super::tree(); let (_, file) = tree.iter().find(|(title, _)| *title == "File").expect("File menu"); let item = file.iter().find(|e| e.0 == "Export as PDF…").expect("Export as PDF… in the File menu"); assert_eq!(item.1, "file.exportPdf"); @@ -403,23 +404,23 @@ mod tests { #[test] fn help_menu_checks_for_updates_through_the_registered_command() { - let tree = tree(); + let tree = super::tree(); let (_, help) = tree.iter().find(|(title, _)| *title == "Help").expect("Help menu"); let item = help.iter().find(|e| e.0 == "Check for Updates…").expect("Check for Updates… in the Help menu"); assert_eq!(item.1, "app.checkForUpdates"); - let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default()); + let mut app = super::SheetApp::new(gridcraft_engine::Session::new(), Default::default()); assert!(app.run(item.1, serde_json::json!({})).is_ok()); } #[test] fn theme_choices_use_the_shared_preference_command() { - let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default()); + let mut app = super::SheetApp::new(gridcraft_engine::Session::new(), Default::default()); for mode in ["dark", "system", "light"] { - assert!(select_theme(&mut app, &format!("theme:{mode}"))); + assert!(super::select_theme(&mut app, &format!("theme:{mode}"))); assert_eq!(app.ui.theme_mode(), mode); assert!(app.message.is_none()); } - assert!(!select_theme(&mut app, "view.formulaBar")); + assert!(!super::select_theme(&mut app, "view.formulaBar")); assert_eq!(app.ui.theme_mode(), "light"); } } diff --git a/apps/gridcraft/tests/mac_menu_appkit.rs b/apps/gridcraft/tests/mac_menu_appkit.rs index e713f6699b..ca1eef5098 100644 --- a/apps/gridcraft/tests/mac_menu_appkit.rs +++ b/apps/gridcraft/tests/mac_menu_appkit.rs @@ -7,7 +7,6 @@ // unit tests compile here too without a harness to run them). #[cfg(target_os = "macos")] #[path = "../src/native_menu.rs"] -#[allow(unused_imports, dead_code)] mod native_menu; #[cfg(target_os = "macos")] @@ -20,12 +19,23 @@ fn main() { nsapp.finishLaunching(); let ctx = egui::Context::default(); - let _menu = native_menu::NativeMenu::install(&ctx); + let mut menu = native_menu::NativeMenu::install(&ctx); let bar = nsapp.mainMenu().expect("a main menu"); let tops: Vec = (0..bar.numberOfItems()).filter_map(|i| bar.itemAtIndex(i)?.submenu()).map(|m| m.title().to_string()).collect(); assert_eq!(tops, ["GridCraft", "File", "Edit", "View", "Insert", "Format", "Tools", "Data", "Window", "Help"]); - assert_eq!(nsapp.windowsMenu().map(|m| m.title().to_string()).as_deref(), Some("Window"), "AppKit knows the Window menu"); + let windows_menu = nsapp.windowsMenu().expect("AppKit knows the Window menu"); + assert_eq!(windows_menu.title().to_string(), "Window"); + + // A poll lists the open workbook windows at the end of the Window menu (#716). + let mut session = gridcraft_engine::Session::new(); + session.new_workbook(); + let mut app = gridcraft_ui_egui::SheetApp::new(session, Default::default()); + menu.poll(&mut app, &ctx, egui::ViewportId::ROOT); + let open = app.open_windows(); + assert_eq!(open.len(), 1, "one workbook window"); + let last = windows_menu.itemAtIndex(windows_menu.numberOfItems() - 1).expect("a Window menu item"); + assert_eq!(last.title().to_string(), open[0].label(), "the Window menu lists the open workbook"); println!("mac_menu_appkit: ok"); } diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index fdf0b0e091..349dcfd5ab 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -1,7 +1,7 @@ # GridCraft app icon (PLACEHOLDER) **This icon is temporary.** Every Crafting App's icon is an engraved creature portrait that the -product owner makes (craftrules `standards/icon-design.md`); GridCraft's hasn't been made yet. +product owner makes; GridCraft's hasn't been made yet. Until it is, this placeholder stands in: a simple ledger page with a header row, a row-number column, a selected cell with its fill handle and a double rule under a total, on a full-bleed GridCraft-green tile. It is original geometry written by hand for this repository, deliberately diff --git a/assets/app-icon/gridcraft.svg b/assets/app-icon/gridcraft.svg index fd53f9e1bf..38e3e802a1 100644 --- a/assets/app-icon/gridcraft.svg +++ b/assets/app-icon/gridcraft.svg @@ -1,7 +1,7 @@ diff --git a/assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg b/assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg index fd53f9e1bf..38e3e802a1 100644 --- a/assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg +++ b/assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg @@ -1,7 +1,7 @@ diff --git a/clippy.toml b/clippy.toml index 8b8bc5a3ac..c6fbddafdf 100644 --- a/clippy.toml +++ b/clippy.toml @@ -10,3 +10,8 @@ disallowed-methods = [ { path = "std::time::Instant::now", reason = "traps on wasm; read the clock only off wasm" }, { path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" }, ] + +disallowed-types = [ + { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, +] +cognitive-complexity-threshold = 30 diff --git a/contributors/people.toml b/contributors/people.toml index 5ce80fe59e..00f6ce76a1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -1,13 +1,10 @@ -# Contributor names for the About window (craftrules standards/contributors.md). +# Contributor names for the About window. # # Everyone who contributes is credited by GitHub username automatically. Anything more is up to # you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a # maintainer may add a person only when that person asked, recording where in consent_source. # -# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \ -# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name] -# -# Or copy this block, replacing your-github-username (every field is optional): +# Copy this block, replacing your-github-username (every field is optional): # # [people.your-github-username] # real_name = "Your Name" # shown when the viewer picks "Real name" @@ -103,3 +100,12 @@ real_name = "Helen Kwok" [people.dotCooCoo] real_name = "Robert Lee" sync_github_name = true + +[people.dylanmtaylor] +sync_github_name = true + +[people.Plutonium-fream] +sync_github_name = true + +[people.maxm11] +sync_github_name = true diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4bdb3a30d4..7a957f3a4a 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -7,10 +7,22 @@ use std::sync::Arc; use gridcraft_core::{Array, CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, compare}; -use gridcraft_formula::{BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, UnOp}; +use gridcraft_formula::{BinOp, Expr, Reference, SheetSel, StructItem, StructRef, UnOp}; use gridcraft_functions::{Arg, Ctx}; use gridcraft_model::Workbook; +mod array; +mod call; +mod format; +mod lambda; +mod reference_fns; +mod special; + +use array::map_unary; +pub use array::{binary_values, zip2}; +pub use format::r1c1_to_a1; +pub use special::{SPECIAL_FUNCTIONS, is_known_function, precedents, resized_sum_range}; + /// Largest array a reference may expand to. pub const MAX_CELLS: u64 = 16_000_000; /// References up to this many cells (one whole row) are always read at their full size. @@ -347,9 +359,10 @@ impl<'h> Evaluator<'h> { return v.clone(); } let wb = self.host.workbook(); - // Sheet-qualified `Sheet1!Name`. - let (scope_sheet, bare) = match n.split_once('!') { - Some((s, b)) => match wb.sheet_index(&gridcraft_core::unquote_sheet(s)) { + // Sheet-qualified `Sheet1!Name`. The parser stores the sheet unquoted, so it is used as + // is (`' Sales '` keeps its spaces) and split at the last `!` (`'a!b'!Name`). + let (scope_sheet, bare) = match n.rsplit_once('!') { + Some((s, b)) => match wb.sheet_index(s) { Some(i) => (i, b), None => return err(CellError::Name), }, @@ -615,1021 +628,6 @@ impl<'h> Evaluator<'h> { } } } - - fn call(&mut self, name: &str, args: &[Expr]) -> Ev { - match name { - "IF" => { - if args.is_empty() || args.len() > 3 { - return err(CellError::Value); - } - let c = self.arg_val(args, 0).unwrap_or_default(); - if let Value::Array(arr) = &c { - // Array condition: element-wise. - 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) }; - return 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), - })); - } - match c.to_bool() { - Ok(true) => match args.get(1) { - Some(Expr::Missing) => Ev::V(Value::Number(0.0)), - Some(e) => self.eval(e), - None => Ev::V(Value::Bool(true)), - }, - Ok(false) => match args.get(2) { - Some(Expr::Missing) => Ev::V(Value::Number(0.0)), - Some(e) => self.eval(e), - None => Ev::V(Value::Bool(false)), - }, - Err(e) => err(e), - } - } - "IFS" => { - if args.len() < 2 || !args.len().is_multiple_of(2) { - return err(CellError::Value); - } - for pair in args.chunks(2) { - let [c, v] = pair else { break }; - let cv = self.value(c); - match cv.scalar().to_bool() { - Ok(true) => return self.eval(v), - Ok(false) => {} - Err(e) => return err(e), - } - } - err(CellError::NA) - } - "IFERROR" | "IFNA" => { - if args.len() != 2 { - return err(CellError::Value); - } - let v = self.arg_ev(args, 0).unwrap_or(Ev::V(Value::Empty)); - let na_only = name == "IFNA"; - let catch = |e: CellError| if na_only { e == CellError::NA } else { true }; - match &v { - Ev::V(Value::Error(e)) if catch(*e) => self.eval(&args[1]), - Ev::V(Value::Array(a)) if a.data.iter().any(|x| x.as_error().is_some_and(catch)) => { - let alt = self.arg_val(args, 1).unwrap_or_default(); - let data = a.data.iter().map(|x| if x.as_error().is_some_and(catch) { alt.scalar() } else { x.clone() }).collect(); - Ev::V(Array::new(a.rows, a.cols, data).map(Value::from).unwrap_or(Value::Error(CellError::Value))) - } - Ev::R(_) => { - let val = self.deref(v.clone()); - match val { - Value::Error(e) if catch(e) => self.eval(&args[1]), - Value::Array(ref a) if a.data.iter().any(|x| x.as_error().is_some_and(catch)) => { - let alt = self.arg_val(args, 1).unwrap_or_default(); - let data = a.data.iter().map(|x| if x.as_error().is_some_and(catch) { alt.scalar() } else { x.clone() }).collect(); - Ev::V(Array::new(a.rows, a.cols, data).map(Value::from).unwrap_or(Value::Error(CellError::Value))) - } - _ => v, - } - } - _ => v, - } - } - "CHOOSE" => { - if args.len() < 2 { - return err(CellError::Value); - } - let index = self.value(&args[0]); - if let Value::Array(_) = index { - // An array of indexes picks element by element: `CHOOSE({1,2},A1:A3,B1:B3)` - // is a two-column array. The library CHOOSE lifts over its arguments. - let Some(spec) = gridcraft_functions::lookup(name) else { return err(CellError::Name) }; - let mut evaluated = vec![Arg { value: index, from_ref: false }]; - for a in &args[1..] { - let value = self.value(a); - evaluated.push(Arg { value, from_ref: false }); - } - let mut ctx = FnCtx { ev: self, criteria: None, lambda: None }; - return gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V); - } - let i = match index.to_number() { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - if i < 1 || i as usize >= args.len() { - return err(CellError::Value); - } - self.eval(&args[i as usize]) - } - "SWITCH" => { - if args.len() < 3 { - return err(CellError::Value); - } - let v = self.arg_val(args, 0).unwrap_or_default().scalar(); - if let Value::Error(e) = v { - return err(e); - } - let rest = &args[1..]; - let mut i = 0; - while i + 1 < rest.len() { - let cand = self.value(&rest[i]).scalar(); - if !cand.is_error() && compare(&v, &cand) == std::cmp::Ordering::Equal && same_kind(&v, &cand) { - return self.eval(&rest[i + 1]); - } - i += 2; - } - if rest.len() % 2 == 1 { rest.last().map_or(err(CellError::NA), |d| self.eval(d)) } else { err(CellError::NA) } - } - "ROW" | "COLUMN" => { - let is_row = name == "ROW"; - if args.is_empty() || matches!(args.first(), Some(Expr::Missing)) { - return Ev::V(Value::number(if is_row { self.at.row + 1 } else { self.at.col + 1 } as f64)); - } - match self.eval(&args[0]) { - Ev::R(a) => { - let Some(a) = a.first() else { return err(CellError::Ref) }; - let r = self.trim_lines(a); - if is_row { - let rows: Vec = (r.start.row..=r.end.row).map(|x| Value::number(x as f64 + 1.0)).collect(); - if rows.len() == 1 { Ev::V(rows.into_iter().next().unwrap_or_default()) } else { Ev::V(Array::column(rows).into()) } - } else { - let cols: Vec = (r.start.col..=r.end.col).map(|x| Value::number(x as f64 + 1.0)).collect(); - if cols.len() == 1 { Ev::V(cols.into_iter().next().unwrap_or_default()) } else { Ev::V(Array::row(cols).into()) } - } - } - Ev::V(Value::Error(e)) => err(e), - _ => err(CellError::Value), - } - } - "ROWS" | "COLUMNS" => { - if args.len() != 1 { - return err(CellError::Value); - } - let is_rows = name == "ROWS"; - match self.eval(&args[0]) { - Ev::R(a) => match a.as_slice() { - [a] => Ev::V(Value::number(if is_rows { a.range.height() } else { a.range.width() } as f64)), - _ => err(CellError::Ref), - }, - Ev::V(Value::Array(arr)) => Ev::V(Value::number(if is_rows { arr.rows } else { arr.cols } as f64)), - Ev::V(Value::Error(e)) => err(e), - Ev::V(_) => Ev::V(Value::Number(1.0)), - Ev::L(_) => err(CellError::Value), - } - } - "AREAS" => match args.first().map(|a| self.eval(a)) { - Some(Ev::R(a)) => Ev::V(Value::number(a.len() as f64)), - Some(Ev::V(Value::Error(e))) => err(e), - _ => err(CellError::Value), - }, - "ISREF" => Ev::V(Value::Bool(matches!(args.first().map(|a| self.eval(a)), Some(Ev::R(_))))), - "ISFORMULA" | "FORMULATEXT" => { - let Some(Ev::R(a)) = args.first().map(|a| self.eval(a)) else { return err(CellError::NA) }; - let Some(a) = a.first() else { return err(CellError::NA) }; - let f = self.host.workbook().sheet(a.sheet).and_then(|s| s.cell(a.range.start)).and_then(|c| c.formula.clone()); - if name == "ISFORMULA" { - Ev::V(Value::Bool(f.is_some())) - } else { - match f { - Some(f) => Ev::V(Value::text(format!("={}", f.text))), - None => err(CellError::NA), - } - } - } - "SHEET" | "SHEETS" => { - let wb = self.host.workbook(); - if args.is_empty() { - return Ev::V(Value::number(if name == "SHEET" { self.sheet + 1 } else { wb.sheets.len() } as f64)); - } - match self.eval(&args[0]) { - Ev::R(a) => { - if name == "SHEET" { - a.first().map_or(err(CellError::Ref), |a| Ev::V(Value::number(a.sheet as f64 + 1.0))) - } else { - let mut s: Vec = a.iter().map(|x| x.sheet).collect(); - s.dedup(); - Ev::V(Value::number(s.len() as f64)) - } - } - Ev::V(Value::Text(t)) if name == "SHEET" => { - let wb = self.host.workbook(); - wb.sheet_index(&t).map_or(err(CellError::NA), |i| Ev::V(Value::number(i as f64 + 1.0))) - } - _ => err(CellError::NA), - } - } - "OFFSET" => self.offset(args), - "INDIRECT" => self.indirect(args), - "INDEX" => self.index(args), - "XLOOKUP" => self.xlookup(args), - "CELL" => self.cell_info(args), - "TRIMRANGE" => self.trimrange(args), - "SUBTOTAL" | "AGGREGATE" => self.subtotal(name, args), - "TEXT" => { - if args.len() != 2 { - return err(CellError::Value); - } - let v = self.arg_val(args, 0).unwrap_or_default(); - let f = self.arg_val(args, 1).unwrap_or_default(); - let sys = self.host.workbook().date_system; - let one = |v: &Value, f: &Value| -> Value { - if let Value::Error(e) = v { - return Value::Error(*e); - } - let code = match f.to_text() { - Ok(c) => c, - Err(e) => return Value::Error(e), - }; - match gridcraft_numfmt::text_function(v, &code, sys) { - Ok(s) => Value::text(s), - Err(e) => Value::Error(e), - } - }; - Ev::V(zip2(&v, &f, one)) - } - "LET" => self.let_(args), - "LAMBDA" => { - if args.is_empty() { - return err(CellError::Value); - } - let mut params = Vec::new(); - for p in &args[..args.len() - 1] { - match p { - Expr::Name(n) => params.push(n.trim_start_matches('[').trim_end_matches(']').to_string()), - _ => return err(CellError::Value), - } - } - let Some(body) = args.last() else { return err(CellError::Value) }; - Ev::L(Arc::new(Lambda { params, body: body.clone(), env: self.env.clone() })) - } - "ISOMITTED" => { - let r = matches!(args.first(), Some(Expr::Name(n)) if self.env.iter().rev().find(|(k, _)| gridcraft_formula::same_name(k, n)).is_some_and(|(_, v)| matches!(v, Ev::V(Value::Empty)))); - Ev::V(Value::Bool(r)) - } - "MAP" | "REDUCE" | "SCAN" | "BYROW" | "BYCOL" | "MAKEARRAY" => self.higher_order(name, args), - "GROUPBY" | "PIVOTBY" => { - // The aggregation may be a function given by name (`SUM`): pass it as its name. - let i = if name == "GROUPBY" { 2 } else { 3 }; - match args.get(i).and_then(|a| self.function_by_name(a)) { - Some(f) => { - let mut args = args.to_vec(); - if let Some(a) = args.get_mut(i) { - *a = Expr::Text(f.into()); - } - self.builtin(name, &args) - } - None => self.builtin(name, args), - } - } - "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" => { - self.host.note_volatile(); - self.builtin(name, args) - } - _ => self.builtin(name, args), - } - } - - fn builtin(&mut self, name: &str, args: &[Expr]) -> Ev { - let Some(spec) = gridcraft_functions::lookup(name) else { - // A defined name holding a LAMBDA, or a LET-bound lambda. - return match self.name(name) { - Ev::L(l) => self.apply_lambda(&l, args), - Ev::V(Value::Error(x)) => err(x), - _ => err(CellError::Name), - }; - }; - if args.len() < spec.min_args || args.len() > spec.max_args { - return err(CellError::Value); - } - if let Some(kind) = Agg::of(spec.name) { - return self.aggregate(kind, args); - } - let mut evaluated = Vec::with_capacity(args.len()); - // SUMIF/AVERAGEIF: the size of the criteria range (argument 1), which the sum range takes. - let mut criteria_shape = None; - // Database functions: the criteria range (argument 2), whose formulas are computed criteria. - let mut criteria = None; - // GROUPBY/PIVOTBY: the LAMBDA given as their function. - let mut lambda = None; - let lambda_at = match name { - "GROUPBY" => Some(2), - "PIVOTBY" => Some(3), - _ => None, - }; - for (i, a) in args.iter().enumerate() { - let mut ev = self.eval(a); - if lambda_at == Some(i) - && let Ev::L(l) = &ev - { - lambda = Some(l.clone()); - ev = Ev::V(Value::Empty); - } - if spec.category == gridcraft_functions::Category::Database - && i == 2 - && let Ev::R(areas) = &ev - && let [area] = areas.as_slice() - { - criteria = Some(*area); - } - if resizes_sum_range(name, args.len()) { - if i == 0 { - criteria_shape = ev_shape(&ev); - } else if i == 2 - && let (Some((h, w)), Ev::R(areas)) = (criteria_shape, &ev) - && let [area] = areas.as_slice() - { - ev = Ev::R(vec![Area { sheet: area.sheet, range: resized_sum_range(area.range, h, w) }]); - } - } - let from_ref = matches!(ev, Ev::R(_)); - let value = match ev { - Ev::R(areas) if areas.len() > 1 => { - // Multi-area references (unions): flatten into one row for aggregates. - let mut vals = Vec::new(); - for ar in &areas { - match self.area_value(ar) { - Value::Array(a) => vals.extend(a.data.iter().cloned()), - v => vals.push(v), - } - } - Value::from(Array::row(vals)) - } - ev => self.deref(ev), - }; - evaluated.push(Arg { value, from_ref }); - } - let mut ctx = FnCtx { ev: self, criteria, lambda }; - gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V) - } - - /// Performs aggregation operations without copying its ranges: blocks are folded over the stored - /// cells, so no array is built and there is no `MAX_CELLS` limit. Arguments are evaluated and read one - /// after another, as the array path does, so volatile formulas (like `RAND`) see the same order. - /// Only `SUM`, `COUNT` and `AVG` are supported currently. - fn aggregate(&mut self, kind: Agg, args: &[Expr]) -> Ev { - let mut acc = Acc::default(); - let mut first_error = None; - for a in args { - let ev = self.eval(a); - let steps = match ev { - Ev::R(areas) => areas.iter().map(|area| self.aggregate_area(kind, area, &mut acc)).collect(), - ev => { - let value = self.deref(ev); - vec![self.aggregate_value(kind, value, false, &mut acc)] - } - }; - if first_error.is_none() { - first_error = steps.into_iter().find_map(Result::err); - } - } - first_error.unwrap_or_else(|| Ev::V(acc.finish(kind))) - } - - /// Adds one area to `acc`; `Err` is the result the function ends with. - fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> { - if !a.range.is_single() { - let mut error = None; - let walked = self.host.visit_range(a.sheet, a.range, &mut |v| match acc.add_cell(kind, v) { - Ok(()) => true, - Err(e) => { - error = Some(e); - false - } - }); - if walked { - return error.map_or(Ok(()), |e| Err(err(e))); - } - } - let value = self.area_value(a); - self.aggregate_value(kind, value, true, acc) - } - - /// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules - /// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`). - fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> { - let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else { - return Err(err(CellError::Name)); - }; - let args = [Arg { value, from_ref }]; - if kind != Agg::Count { - match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) { - Value::Number(n) => acc.sum += n, - other => return Err(Ev::V(other)), - } - } - if kind != Agg::Sum { - match gridcraft_functions::call(count, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) { - Value::Number(n) => acc.count = acc.count.saturating_add(n as u64), - other => return Err(Ev::V(other)), - } - } - Ok(()) - } - - pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> 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(CellError::Value); - } - let mut bound = Vec::with_capacity(l.params.len()); - for (i, p) in l.params.iter().enumerate() { - let v = match args.get(i) { - Some(Expr::Missing) | None => Ev::V(Value::Empty), - Some(e) => self.eval(e), - }; - bound.push((p.clone(), v)); - } - self.call_lambda_values(l, bound) - } - - fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev { - if self.calls >= MAX_LAMBDA_CALLS { - return err(CellError::Num); - } - // #2382: one charge per invocation, so a cell's total work stays bounded however the - // lambdas nest. Foregrounding the charge here means every path into a body (direct - // `(2,3)` application, `MAP`/`REDUCE`/`BYROW` helpers, D-function criteria) meters. - self.fuel = match self.fuel.checked_sub(1) { - Some(f) => f, - None => return err(CellError::Calc), - }; - self.calls += 1; - let saved = std::mem::replace(&mut self.env, l.env.clone()); - self.env.extend(bound); - let r = self.eval(&l.body); - self.env = saved; - self.calls -= 1; - r - } - - fn let_(&mut self, args: &[Expr]) -> Ev { - if args.len() < 3 || args.len().is_multiple_of(2) { - return err(CellError::Value); - } - let base = self.env.len(); - for pair in args[..args.len() - 1].chunks(2) { - let [Expr::Name(n), v] = pair else { - self.env.truncate(base); - return err(CellError::Value); - }; - let val = self.eval(v); - self.env.push((n.clone(), val)); - } - let r = match args.last() { - Some(body) => self.eval(body), - None => err(CellError::Value), - }; - self.env.truncate(base); - r - } - - /// A worksheet function given by name where a function is expected (`BYROW(A1:C3,SUM)`, - /// `GROUPBY(A2:A9,B2:B9,SUM)`): its name, unless a LET/LAMBDA variable or a defined name has - /// that name. - fn function_by_name(&self, e: &Expr) -> Option { - let Expr::Name(n) = e else { return None }; - if self.env.iter().any(|(k, _)| gridcraft_formula::same_name(k, n)) || self.host.workbook().name(n, self.sheet).is_some() { - return None; - } - let u = n.to_ascii_uppercase(); - gridcraft_functions::lookup(&u).map(|_| u) - } - - /// The function argument of a LAMBDA helper; a function given by name takes `arity` - /// arguments. - fn lambda_arg(&mut self, e: Option<&Expr>, arity: usize) -> Option> { - if let Some(f) = e.and_then(|x| self.function_by_name(x)) { - let params: Vec = (0..arity).map(|i| format!("_xleta.{i}")).collect(); - let body = Expr::Call(f, params.iter().map(|p| Expr::Name(p.clone())).collect()); - return Some(Arc::new(Lambda { params, body, env: Vec::new() })); - } - match e.map(|x| self.eval(x)) { - Some(Ev::L(l)) => Some(l), - _ => None, - } - } - - fn higher_order(&mut self, name: &str, args: &[Expr]) -> Ev { - let as_array = |v: Value| -> Arc { - match v { - Value::Array(a) => a, - other => Arc::new(Array::scalar(other)), - } - }; - match name { - "MAP" => { - if args.len() < 2 { - return err(CellError::Value); - } - let Some(l) = self.lambda_arg(args.last(), args.len() - 1) else { return err(CellError::Value) }; - let arrays: Vec> = args[..args.len() - 1].iter().map(|a| as_array(self.value(a))).collect(); - let rows = arrays.iter().map(|a| a.rows).max().unwrap_or(1); - let cols = arrays.iter().map(|a| a.cols).max().unwrap_or(1); - let Some(n) = broadcast_len(rows, cols) else { return err(CellError::Num) }; - // The LAMBDA takes one parameter per array. - if l.params.len() != arrays.len() { - return err(CellError::Value); - } - let mut out = Vec::with_capacity(n); - for r in 0..rows { - for c in 0..cols { - let bound = l.params.iter().zip(arrays.iter()).map(|(p, a)| (p.clone(), Ev::V(a.get_broadcast(r, c)))).collect(); - let v = self.call_lambda_values(&l, bound); - let Some(one) = single(self.deref(v)) else { return err(CellError::Calc) }; - out.push(one); - } - } - Ev::V(Array::new(rows, cols, out).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) - } - "REDUCE" | "SCAN" => { - if args.len() != 3 { - return err(CellError::Value); - } - let mut acc = self.value(&args[0]); - let arr = as_array(self.value(&args[1])); - let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) }; - if l.params.len() != 2 { - return err(CellError::Value); - } - let mut scan = Vec::with_capacity(arr.data.len()); - for v in arr.data.iter() { - let bound = vec![(l.params[0].clone(), Ev::V(acc.clone())), (l.params[1].clone(), Ev::V(v.clone()))]; - let r = self.call_lambda_values(&l, bound); - acc = self.deref(r); - if name == "SCAN" { - let Some(one) = single(acc.clone()) else { return err(CellError::Calc) }; - scan.push(one); - } - } - if name == "SCAN" { - Ev::V(Array::new(arr.rows, arr.cols, scan).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) - } else { - Ev::V(acc) - } - } - "BYROW" | "BYCOL" => { - if args.len() != 2 { - return err(CellError::Value); - } - let arr = as_array(self.value(&args[0])); - let Some(l) = self.lambda_arg(args.get(1), 1) else { return err(CellError::Value) }; - let Some(p) = l.params.first().cloned() else { return err(CellError::Value) }; - if l.params.len() != 1 { - return err(CellError::Value); - } - let by_row = name == "BYROW"; - let n = if by_row { arr.rows } else { arr.cols }; - let mut out = Vec::with_capacity(n); - for i in 0..n { - let slice: Vec = if by_row { - (0..arr.cols).map(|c| arr.get(i, c).cloned().unwrap_or_default()).collect() - } else { - (0..arr.rows).map(|r| arr.get(r, i).cloned().unwrap_or_default()).collect() - }; - let a = if by_row { Array::row(slice) } else { Array::column(slice) }; - let r = self.call_lambda_values(&l, vec![(p.clone(), Ev::V(a.into()))]); - let Some(one) = single(self.deref(r)) else { return err(CellError::Calc) }; - out.push(one); - } - let a = if by_row { Array::column(out) } else { Array::row(out) }; - Ev::V(a.into()) - } - "MAKEARRAY" => { - if args.len() != 3 { - return err(CellError::Value); - } - let (rows, cols) = match (self.arg_num(args, 0, 0.0), self.arg_num(args, 1, 0.0)) { - (Ok(r), Ok(c)) => (r.trunc(), c.trunc()), - (Err(e), _) | (_, Err(e)) => return err(e), - }; - if rows < 1.0 || cols < 1.0 || rows * cols > MAX_CELLS as f64 { - return err(CellError::Value); - } - let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) }; - if l.params.len() != 2 { - return err(CellError::Value); - } - let (rows, cols) = (rows as usize, cols as usize); - let mut out = Vec::with_capacity(rows * cols); - for r in 0..rows { - for c in 0..cols { - let bound = vec![ - (l.params[0].clone(), Ev::V(Value::number(r as f64 + 1.0))), - (l.params[1].clone(), Ev::V(Value::number(c as f64 + 1.0))), - ]; - let v = self.call_lambda_values(&l, bound); - let Some(one) = single(self.deref(v)) else { return err(CellError::Calc) }; - out.push(one); - } - } - Ev::V(Array::new(rows, cols, out).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) - } - _ => err(CellError::Name), - } - } - - /// Whole rows/columns trimmed for ROW()/COLUMN() arrays. - fn trim_lines(&mut self, a: &Area) -> RangeRef { - if a.range.is_full_cols() || a.range.is_full_rows() { self.trim(a) } else { a.range } - } - - fn offset(&mut self, args: &[Expr]) -> Ev { - self.host.note_volatile(); - if args.len() < 3 || args.len() > 5 { - return err(CellError::Value); - } - let base = match self.eval(&args[0]) { - Ev::R(a) if a.len() == 1 => a[0], - Ev::V(Value::Error(e)) => return err(e), - _ => return err(CellError::Value), - }; - let rows = match self.arg_num(args, 1, 0.0) { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - let cols = match self.arg_num(args, 2, 0.0) { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - let h = match self.arg_num(args, 3, base.range.height() as f64) { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - let w = match self.arg_num(args, 4, base.range.width() as f64) { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - if h == 0 || w == 0 { - return err(CellError::Ref); - } - let r0 = (base.range.start.row as i64).saturating_add(rows); - let c0 = (base.range.start.col as i64).saturating_add(cols); - let (r0, r1) = if h > 0 { (r0, r0.saturating_add(h - 1)) } else { (r0.saturating_add(h + 1), r0) }; - let (c0, c1) = if w > 0 { (c0, c0.saturating_add(w - 1)) } else { (c0.saturating_add(w + 1), c0) }; - if r0 < 0 || c0 < 0 || r1 >= MAX_ROWS as i64 || c1 >= MAX_COLS as i64 { - return err(CellError::Ref); - } - Ev::R(vec![Area { sheet: base.sheet, range: RangeRef::new(CellRef::new(r0 as u32, c0 as u32), CellRef::new(r1 as u32, c1 as u32)) }]) - } - - fn indirect(&mut self, args: &[Expr]) -> Ev { - self.host.note_volatile(); - if args.is_empty() || args.len() > 2 { - return err(CellError::Value); - } - let text = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) { - Some(Ok(t)) => t, - Some(Err(e)) => return err(e), - None => return err(CellError::Value), - }; - let a1 = match args.get(1) { - None | Some(Expr::Missing) => true, - Some(e) => { - let v = self.value(e); - v.scalar().to_bool().unwrap_or(true) - } - }; - // With a1 = FALSE, text that isn't R1C1 can still be a name, but never an A1 reference. - let (text, a1_ok) = if a1 { - (text, true) - } else { - match r1c1_to_a1(&text, self.at) { - Ok(Some(a1_text)) => (a1_text, true), - Ok(None) => (text, false), - Err(e) => return err(e), - } - }; - match gridcraft_formula::parse(&text) { - Ok(Expr::Ref(_)) if !a1_ok => err(CellError::Ref), - Ok(e @ (Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_))) => match self.eval(&e) { - r @ Ev::R(_) => r, - _ => err(CellError::Ref), - }, - _ => err(CellError::Ref), - } - } - - fn index(&mut self, args: &[Expr]) -> Ev { - if args.is_empty() || args.len() > 4 { - return err(CellError::Value); - } - let src = self.eval(&args[0]); - let mut arg = |i: usize| match args.get(i) { - None | Some(Expr::Missing) => None, - Some(e) => Some(self.value(e)), - }; - let (rows, cols) = (arg(1), arg(2)); - let area_n = match self.arg_num(args, 3, 1.0) { - Ok(n) => n.trunc() as i64, - Err(e) => return err(e), - }; - let two = args.len() == 2; - let num = |v: &Option| v.as_ref().map_or(Ok(0.0), |v| v.to_number()).map(|n| n.trunc() as i64); - // Arrays of positions pick a value for each: INDEX(A1:C10,{1;2},{1,3}) is 2×2. - if let (Some(Value::Array(_)), _) | (_, Some(Value::Array(_))) = (&rows, &cols) { - let as_array = |v: &Option| match v { - Some(Value::Array(a)) => Arc::clone(a), - Some(v) => Arc::new(Array::scalar(v.clone())), - None => Arc::new(Array::scalar(Value::Number(0.0))), - }; - let (ra, ca) = (as_array(&rows), as_array(&cols)); - let (h, w) = (ra.rows.max(ca.rows), ra.cols.max(ca.cols)); - if (h as u64).saturating_mul(w as u64) > MAX_CELLS { - return err(CellError::Num); - } - let mut out = Vec::with_capacity(h * w); - for r in 0..h { - for c in 0..w { - let pos = (num(&Some(ra.get_broadcast(r, c))), num(&Some(ca.get_broadcast(r, c)))); - let v = match pos { - (Ok(row), Ok(col)) => { - let one = self.index_one(src.clone(), row, col, area_n, two); - match self.deref(one) { - Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc), - v => v.scalar(), - } - } - (Err(e), _) | (_, Err(e)) => Value::Error(e), - }; - out.push(v); - } - } - return Ev::V(Array::new(h, w, out).map(Value::from).unwrap_or(Value::Error(CellError::Value))); - } - let (row, col) = match (num(&rows), num(&cols)) { - (Ok(r), Ok(c)) => (r, c), - (Err(e), _) | (_, Err(e)) => return err(e), - }; - self.index_one(src, row, col, area_n, two) - } - - /// INDEX for one row and column position (0 = the whole column or row). - fn index_one(&mut self, src: Ev, row: i64, col: i64, area_n: i64, two_args: bool) -> Ev { - if row < 0 || col < 0 { - return err(CellError::Value); - } - match src { - Ev::R(areas) => { - let area = usize::try_from((area_n as u64).saturating_sub(1)).ok(); - let Some(a) = area.and_then(|i| areas.get(i)).copied() else { return err(CellError::Ref) }; - let r = a.range; - // A single row or column with one index picks along it. An area with several rows - // and columns needs both: `INDEX(A1:C3,2)` is #REF! in Excel (an empty third - // argument, `INDEX(A1:C3,2,)`, still means the whole row). Arrays differ: - // `INDEX({1,2;3,4},2)` is the row. - if two_args && r.height() > 1 && r.width() > 1 { - return err(CellError::Ref); - } - let (row, col) = if two_args && r.height() == 1 { (1, row) } else { (row, col) }; - if row as u64 > r.height() as u64 || col as u64 > r.width() as u64 { - return err(CellError::Ref); - } - let (r0, r1) = if row == 0 { (r.start.row, r.end.row) } else { (r.start.row + row as u32 - 1, r.start.row + row as u32 - 1) }; - let (c0, c1) = if col == 0 { (r.start.col, r.end.col) } else { (r.start.col + col as u32 - 1, r.start.col + col as u32 - 1) }; - Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) }]) - } - Ev::V(Value::Array(arr)) => { - let (row, col) = if two_args && arr.rows == 1 { (1, row) } else { (row, col) }; - if row as usize > arr.rows || col as usize > arr.cols { - return err(CellError::Ref); - } - match (row, col) { - (0, 0) => Ev::V(Value::Array(arr)), - (0, c) => Ev::V(Array::column((0..arr.rows).map(|r| arr.get(r, c as usize - 1).cloned().unwrap_or_default()).collect()).into()), - (r, 0) => Ev::V(Array::row((0..arr.cols).map(|c| arr.get(r as usize - 1, c).cloned().unwrap_or_default()).collect()).into()), - (r, c) => Ev::V(arr.get(r as usize - 1, c as usize - 1).cloned().unwrap_or(Value::Error(CellError::Ref))), - } - } - Ev::V(Value::Error(e)) => err(e), - Ev::V(v) => { - if row <= 1 && col <= 1 { - Ev::V(v) - } else { - err(CellError::Ref) - } - } - Ev::L(_) => err(CellError::Value), - } - } - - /// XLOOKUP whose result range is a reference returns a reference, as in Excel, so that it can - /// end a range (`SUM(XLOOKUP(a,…):XLOOKUP(b,…))`) or feed CELL. Everything else (arrays of - /// lookup values, array arguments, errors) goes to the library function. - fn xlookup(&mut self, args: &[Expr]) -> Ev { - if (3..=6).contains(&args.len()) - && let (Ev::R(look), Ev::R(ret)) = (self.eval(&args[1]), self.eval(&args[2])) - && let ([l], [r]) = (look.as_slice(), ret.as_slice()) - && let Some(spec) = gridcraft_functions::lookup("XMATCH") - { - let key = self.value(&args[0]); - let (l, r) = (*l, *r); - let vertical = l.range.width() == 1 && l.range.height() > 1; - let horizontal = l.range.height() == 1 && l.range.width() > 1; - let same_len = if vertical { r.range.height() == l.range.height() } else { r.range.width() == l.range.width() }; - if !matches!(key, Value::Array(_)) && (vertical || horizontal) && same_len { - let mut xargs = vec![Arg { value: key, from_ref: false }, Arg { value: self.area_value(&l), from_ref: true }]; - // An empty match_mode before a given search_mode is the default (0), not the end. - let given = |i: usize| args.get(i).is_some_and(|e| !matches!(e, Expr::Missing)); - let last = if given(5) { - 5 - } else if given(4) { - 4 - } else { - 3 - }; - for i in 4..=last { - match args.get(i) { - Some(Expr::Missing) | None => xargs.push(Arg { value: Value::Number(0.0), from_ref: false }), - Some(e) => { - let value = self.value(e); - xargs.push(Arg { value, from_ref: false }); - } - } - } - let mut ctx = FnCtx { ev: self, criteria: None, lambda: None }; - return match gridcraft_functions::call(spec, &xargs, &mut ctx) { - Value::Number(p) if p >= 1.0 => { - let k = p as u32 - 1; - let range = if vertical { - RangeRef::new( - CellRef::new(r.range.start.row + k, r.range.start.col), - CellRef::new(r.range.start.row + k, r.range.end.col), - ) - } else { - RangeRef::new( - CellRef::new(r.range.start.row, r.range.start.col + k), - CellRef::new(r.range.end.row, r.range.start.col + k), - ) - }; - Ev::R(vec![Area { sheet: r.sheet, range }]) - } - Value::Error(CellError::NA) if args.get(3).is_some_and(|e| !matches!(e, Expr::Missing)) => self.eval(&args[3]), - Value::Error(e) => err(e), - _ => err(CellError::Value), - }; - } - } - self.builtin("XLOOKUP", args) - } - - fn cell_info(&mut self, args: &[Expr]) -> Ev { - let kind = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) { - Some(Ok(t)) => t.to_ascii_lowercase(), - Some(Err(e)) => return err(e), - None => return err(CellError::Value), - }; - let area = match args.get(1).map(|a| self.eval(a)) { - Some(Ev::R(a)) => a.first().copied(), - None => Some(Area { sheet: self.sheet, range: RangeRef::cell(self.at) }), - _ => return err(CellError::Value), - }; - let Some(a) = area else { return err(CellError::Ref) }; - let c = a.range.start; - let wb = self.host.workbook(); - let sheet = wb.sheet(a.sheet); - match kind.as_str() { - "address" => Ev::V(Value::text(format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1))), - "row" => Ev::V(Value::number(c.row as f64 + 1.0)), - "col" => Ev::V(Value::number(c.col as f64 + 1.0)), - "contents" => Ev::V(self.host.cell_value(a.sheet, c)), - "type" => { - let v = self.host.cell_value(a.sheet, c); - Ev::V(Value::text(match v { - Value::Empty => "b", - Value::Text(_) => "l", - _ => "v", - })) - } - "width" => Ev::V(Value::number(sheet.map_or(8.43, |s| gridcraft_model::points_to_chars(s.col_width(c.col) as f64)).round())), - // Excel's `/[]`, which the classic sheet-name formula splits on - // the `]`. Empty until the workbook has a file of its own, as in Excel (#1489). - "filename" => Ev::V(Value::text(match &wb.source_path { - Some(file) => { - let name = file.file_name().unwrap_or_default().to_string_lossy(); - let on = sheet.map_or("", |s| s.name.as_str()); - file.parent().unwrap_or(std::path::Path::new("")).join(format!("[{name}]{on}")).to_string_lossy().into_owned() - } - None => String::new(), - })), - "sheetname" => Ev::V(Value::text(sheet.map(|s| s.name.clone()).unwrap_or_default())), - "protect" => Ev::V(Value::number(if sheet.is_some_and(|s| wb.styles.get(s.style_id(c)).protection.locked) { 1.0 } else { 0.0 })), - "format" => { - let code = sheet.map(|s| wb.styles.get(s.style_id(c)).num_fmt.as_str().to_string()).unwrap_or_default(); - Ev::V(Value::text(cell_format_code(&code))) - } - "color" | "parentheses" => Ev::V(Value::Number(0.0)), - "prefix" => Ev::V(Value::text("")), - _ => err(CellError::Value), - } - } - - fn subtotal(&mut self, name: &str, args: &[Expr]) -> Ev { - // SUBTOTAL needs function_num and ref1; AGGREGATE needs function_num, options and ref1. - let min_args = if name == "AGGREGATE" { 3 } else { 2 }; - if args.len() < min_args { - return err(CellError::Value); - } - let code = match self.arg_num(args, 0, 0.0) { - Ok(n) => n.trunc() as u32, - Err(e) => return err(e), - }; - let (func, options, rest) = if name == "AGGREGATE" { - let opt = match self.arg_num(args, 1, 0.0) { - Ok(n) => n.trunc() as u32, - Err(e) => return err(e), - }; - (code, opt, &args[2..]) - } else { - let (f, ignore_hidden) = if code > 100 { (code - 100, true) } else { (code, false) }; - (f, if ignore_hidden { 5 } else { 0 }, &args[1..]) - }; - if !(1..=19).contains(&func) || (name == "SUBTOTAL" && func > 11) { - return err(CellError::Value); - } - let skip_hidden = matches!(options, 1 | 3 | 5 | 7); - // SUBTOTAL leaves out rows a filter hides whatever the function number (Microsoft's - // SUBTOTAL documentation); 101-111 also leave out rows hidden by hand. - let skip_filtered = name == "SUBTOTAL"; - let skip_errors = matches!(options, 2 | 3 | 6 | 7); - // SUBTOTAL always leaves out nested SUBTOTAL/AGGREGATE cells (101-111 too); AGGREGATE does so for options 0-3. - let skip_nested = name == "SUBTOTAL" || options <= 3; - let mut values = Vec::new(); - let mut k = None; - let refs = if name == "AGGREGATE" && func >= 14 { &rest[..1.min(rest.len())] } else { rest }; - if name == "AGGREGATE" && func >= 14 { - k = rest.get(1).map(|e| self.value(e)); - } - // Every cell visited (even one skipped as hidden, nested or an error) and every value - // counts against one budget for the whole call. All arguments are evaluated (references - // stay lazy) and charged before any cell is read: a value stored in XFD1048576 makes - // `A:XFD` trim to the whole sheet, ~17 billion cells (#2175). - enum Input { - Cells(usize, RangeRef), - Values(Value), - } - let mut inputs = Vec::new(); - let mut budget = MAX_CELLS; - for e in refs { - match self.eval(e) { - Ev::R(areas) => { - for a in areas { - let range = self.trim(&a); - budget = match budget.checked_sub(range.count()) { - Some(left) => left, - None => return err(CellError::Num), - }; - inputs.push(Input::Cells(a.sheet, range)); - } - } - Ev::V(v) => { - let n = match &v { - Value::Array(a) => u64::try_from(a.data.len()).unwrap_or(u64::MAX), - _ => 1, - }; - budget = match budget.checked_sub(n) { - Some(left) => left, - None => return err(CellError::Num), - }; - inputs.push(Input::Values(v)); - } - Ev::L(_) => return err(CellError::Value), - } - } - for input in inputs { - match input { - Input::Cells(sheet, range) => { - for c in range.iter() { - let (hidden, nested) = { - let wb = self.host.workbook(); - let s = wb.sheet(sheet); - let hidden = - s.is_some_and(|s| if skip_hidden { s.is_row_hidden(c.row) } else { skip_filtered && s.is_row_filtered(c.row) }); - let nested = skip_nested - && s.and_then(|s| s.cell(c)).and_then(|cell| cell.formula.as_ref()).is_some_and(|f| { - let u = f.text.to_ascii_uppercase(); - u.contains("SUBTOTAL(") || u.contains("AGGREGATE(") - }); - (hidden, nested) - }; - if hidden || nested { - continue; - } - let v = self.host.cell_value(sheet, c); - if skip_errors && v.is_error() { - continue; - } - values.push(v); - } - } - Input::Values(Value::Array(a)) => values.extend(a.data.iter().filter(|v| !(skip_errors && v.is_error())).cloned()), - Input::Values(v) => values.push(v), - } - } - if let Some(k) = k { - return Ev::V(gridcraft_functions::aggregate_values_k(func, &values, &k)); - } - Ev::V(gridcraft_functions::aggregate_values(func, &values)) - } } trait Pipe: Sized { @@ -1639,424 +637,6 @@ trait Pipe: Sized { } impl Pipe for T {} -/// CELL("format") code for a number format. -fn cell_format_code(code: &str) -> String { - let c = code.to_ascii_lowercase(); - if c == "general" { - return "G".into(); - } - if c.contains('%') { - return format!("P{}", decimals(&c)); - } - if c.contains('e') && c.contains('0') { - return format!("S{}", decimals(&c)); - } - if c.contains('$') { - return format!("C{}", decimals(&c)); - } - if c.contains('y') || c.contains('d') { - return "D1".into(); - } - if c.contains('h') { - return "D9".into(); - } - if c.contains(',') { - return format!(",{}", decimals(&c)); - } - format!("F{}", decimals(&c)) -} - -fn decimals(c: &str) -> usize { - c.split_once('.').map_or(0, |(_, d)| d.chars().take_while(|ch| *ch == '0').count()) -} - -fn same_kind(a: &Value, b: &Value) -> bool { - std::mem::discriminant(a) == std::mem::discriminant(b) || (a.is_empty() || b.is_empty()) -} - -/// Converts an R1C1 reference text to A1 (for INDIRECT(…, FALSE)). `Ok(None)` means the text is -/// not R1C1; `Err` means it is R1C1 but points past the sheet. -pub fn r1c1_to_a1(s: &str, at: CellRef) -> Result, CellError> { - let (sheet, body) = match s.rsplit_once('!') { - Some((sh, b)) => (format!("{sh}!"), b), - None => (String::new(), s), - }; - let conv = |part: &str| -> Result, CellError> { - let u = part.to_ascii_uppercase(); - let Some((rpart, cpart)) = u.strip_prefix('R').and_then(|rest| rest.split_once('C')) else { return Ok(None) }; - // `None`: not R1C1. `Some(None)`: R1C1, but past the sheet. - let num = |p: &str, base: u32, max: u32| -> Option> { - let (v, absolute) = if p.is_empty() { - (Some(i64::from(base)), false) - } else if let Some(inner) = p.strip_prefix('[').and_then(|x| x.strip_suffix(']')) { - (i64::from(base).checked_add(inner.parse().ok()?), false) - } else { - (p.parse::().ok()?.checked_sub(1).map(i64::from), true) - }; - Some(v.filter(|v| (0..i64::from(max)).contains(v)).map(|v| (v as u32, absolute))) - }; - let (Some(r), Some(c)) = (num(rpart, at.row, MAX_ROWS), num(cpart, at.col, MAX_COLS)) else { return Ok(None) }; - let (Some((r, ra)), Some((c, ca))) = (r, c) else { return Err(CellError::Ref) }; - Ok(Some(format!("{}{}{}{}", if ca { "$" } else { "" }, gridcraft_core::col_to_letters(c), if ra { "$" } else { "" }, r + 1))) - }; - let out = match body.split_once(':') { - Some((a, b)) => match (conv(a)?, conv(b)?) { - (Some(a), Some(b)) => format!("{a}:{b}"), - _ => return Ok(None), - }, - None => match conv(body)? { - Some(x) => x, - None => return Ok(None), - }, - }; - Ok(Some(format!("{sheet}{out}"))) -} - -/// The aggregates that can fold a reference without building an array. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Agg { - Sum, - Count, - Average, -} - -impl Agg { - fn of(name: &str) -> Option { - match name { - "SUM" => Some(Agg::Sum), - "COUNT" => Some(Agg::Count), - "AVERAGE" => Some(Agg::Average), - _ => None, - } - } -} - -/// What a folded aggregate carries from one value to the next. -#[derive(Default)] -struct Acc { - sum: f64, - count: u64, -} - -impl Acc { - /// Takes a value found inside a reference: only numbers count. `Err` is an error value that - /// ends `SUM` and `AVERAGE`; `COUNT` skips errors. - fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> { - match v { - Value::Number(n) => { - self.sum += n; - self.count = self.count.saturating_add(1); - Ok(()) - } - Value::Error(e) if kind != Agg::Count => Err(*e), - _ => Ok(()), - } - } - - fn finish(&self, kind: Agg) -> Value { - match kind { - Agg::Sum => Value::number(self.sum), - Agg::Count => Value::number(self.count as f64), - Agg::Average if self.count == 0 => Value::Error(CellError::Div0), - Agg::Average => Value::number(self.sum / self.count as f64), - } - } -} - -// ---------------------------------------------------------------- operators - -fn map_unary(v: &Value, f: &dyn Fn(f64) -> Value, plus: bool, sys: gridcraft_core::DateSystem) -> Value { - match v { - Value::Array(a) => Value::from(Array { rows: a.rows, cols: a.cols, data: a.data.iter().map(|x| map_unary(x, f, plus, sys)).collect() }), - Value::Error(e) => Value::Error(*e), - Value::Text(_) if plus => v.clone(), - other => match other.to_number_in(sys) { - Ok(n) => f(n), - Err(e) => Value::Error(e), - }, - } -} - -/// Element-wise combination with Excel's broadcasting. -pub fn zip2(a: &Value, b: &Value, f: impl Fn(&Value, &Value) -> Value) -> Value { - match (a, b) { - (Value::Array(x), Value::Array(y)) => { - let rows = broadcast_dim(x.rows, y.rows); - let cols = broadcast_dim(x.cols, y.cols); - let Some(n) = broadcast_len(rows, cols) else { return Value::Error(CellError::Num) }; - let mut data = Vec::with_capacity(n); - for r in 0..rows { - for c in 0..cols { - data.push(f(&x.get_broadcast(r, c), &y.get_broadcast(r, c))); - } - } - Value::from(Array { rows, cols, data }) - } - (Value::Array(x), s) => Value::from(Array { rows: x.rows, cols: x.cols, data: x.data.iter().map(|v| f(v, s)).collect() }), - (s, Value::Array(y)) => Value::from(Array { rows: y.rows, cols: y.cols, data: y.data.iter().map(|v| f(s, v)).collect() }), - (x, y) => f(x, y), - } -} - -/// Cell count of a `rows`×`cols` broadcast result, or `None` when it would exceed [`MAX_CELLS`]. -/// Each operand passes its own size cap, but their broadcast product can be far larger -/// (`SEQUENCE(1048576)*SEQUENCE(1,16384)` is 17 billion cells), so it is checked before allocating. -fn broadcast_len(rows: usize, cols: usize) -> Option { - rows.checked_mul(cols).filter(|&n| n as u64 <= MAX_CELLS) -} - -fn broadcast_dim(a: usize, b: usize) -> usize { - if a == 1 { - b - } else if b == 1 { - a - } else { - a.max(b) - } -} - -fn zip3(c: &Array, t: &Value, f: &Value, g: impl Fn(&Value, &Value, &Value) -> Value) -> Value { - let dims = |v: &Value| if let Value::Array(a) = v { (a.rows, a.cols) } else { (1, 1) }; - let (tr, tc) = dims(t); - let (fr, fc) = dims(f); - let rows = broadcast_dim(broadcast_dim(c.rows, tr), fr); - let cols = broadcast_dim(broadcast_dim(c.cols, tc), fc); - let Some(n) = broadcast_len(rows, cols) else { return Value::Error(CellError::Num) }; - let get = |v: &Value, r: usize, col: usize| if let Value::Array(a) = v { a.get_broadcast(r, col) } else { v.clone() }; - let mut data = Vec::with_capacity(n); - for r in 0..rows { - for col in 0..cols { - data.push(g(&c.get_broadcast(r, col), &get(t, r, col), &get(f, r, col))); - } - } - Value::from(Array { rows, cols, data }) -} - -/// One cell of a LAMBDA helper's result, or `None` for an array of more than one value: arrays -/// can't nest, so the whole helper gives `#CALC!`, as in Excel. -fn single(v: Value) -> Option { - match v { - Value::Array(a) if a.rows * a.cols > 1 => None, - v => Some(v.scalar()), - } -} - -pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateSystem) -> Value { - zip2(x, y, |a, b| binary_scalar(op, a, b, sys)) -} - -fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value { - if let Value::Error(e) = a { - return Value::Error(*e); - } - if let Value::Error(e) = b { - return Value::Error(*e); - } - let num = |f: fn(f64, f64) -> Value| match (a.to_number_in(sys), b.to_number_in(sys)) { - (Ok(x), Ok(y)) => f(x, y), - (Err(e), _) | (_, Err(e)) => Value::Error(e), - }; - use std::cmp::Ordering::*; - match op { - BinOp::Add => num(|x, y| Value::number(x + y)), - BinOp::Sub => num(|x, y| Value::number(x - y)), - BinOp::Mul => num(|x, y| Value::number(x * y)), - BinOp::Div => num(|x, y| if y == 0.0 { Value::Error(CellError::Div0) } else { Value::number(x / y) }), - BinOp::Pow => num(|x, y| { - if x == 0.0 && y == 0.0 { - Value::Error(CellError::Num) - } else if x == 0.0 && y < 0.0 { - Value::Error(CellError::Div0) - } else { - Value::number(x.powf(y)) - } - }), - BinOp::Concat => match (a.to_text(), b.to_text()) { - (Ok(x), Ok(y)) => { - if x.len() + y.len() > 32767 * 4 { - Value::Error(CellError::Value) - } else { - Value::text(x + &y) - } - } - (Err(e), _) | (_, Err(e)) => Value::Error(e), - }, - BinOp::Eq => Value::Bool(compare(a, b) == Equal), - BinOp::Ne => Value::Bool(compare(a, b) != Equal), - BinOp::Lt => Value::Bool(compare(a, b) == Less), - BinOp::Gt => Value::Bool(compare(a, b) == Greater), - BinOp::Le => Value::Bool(compare(a, b) != Greater), - BinOp::Ge => Value::Bool(compare(a, b) != Less), - BinOp::Range | BinOp::Union | BinOp::Intersect => Value::Error(CellError::Value), - } -} - -/// SUMIF and AVERAGEIF with a sum range: Excel sizes the sum range like the criteria range. -fn resizes_sum_range(name: &str, args: usize) -> bool { - args == 3 && matches!(name, "SUMIF" | "AVERAGEIF") -} - -/// Height and width of a single-area reference or an array argument. -fn ev_shape(ev: &Ev) -> Option<(u32, u32)> { - match ev { - Ev::R(areas) => match areas.as_slice() { - [a] => Some((a.range.height(), a.range.width())), - _ => None, - }, - Ev::V(Value::Array(a)) => Some((u32::try_from(a.rows).unwrap_or(u32::MAX), u32::try_from(a.cols).unwrap_or(u32::MAX))), - Ev::V(_) => Some((1, 1)), - Ev::L(_) => None, - } -} - -/// The range SUMIF/AVERAGEIF add up: from the sum range's top-left cell, as many rows and columns -/// as the criteria range (`height` × `width`), cut off at the sheet's edge. -pub fn resized_sum_range(sum: RangeRef, height: u32, width: u32) -> RangeRef { - let row = sum.start.row.saturating_add(height.saturating_sub(1)).min(MAX_ROWS - 1); - let col = sum.start.col.saturating_add(width.saturating_sub(1)).min(MAX_COLS - 1); - RangeRef::new(sum.start, CellRef::new(row, col)) -} - -/// Collects the static references of an expression with their sheets resolved; `dynamic` is -/// set when the formula uses INDIRECT/OFFSET/names/tables whose targets can change. -pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec, bool) { - let mut out = Vec::new(); - let mut dynamic = false; - let push = |out: &mut Vec, r: &Reference, range: RangeRef| match &r.sheet { - SheetSel::Current => out.push(Area { sheet, range }), - SheetSel::Named(n) => { - if let Some(i) = wb.sheet_index(n) { - out.push(Area { sheet: i, range }); - } - } - SheetSel::Span(a, b) => { - if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) { - for s in i.min(j)..=i.max(j) { - out.push(Area { sheet: s, range }); - } - } - } - }; - e.walk(&mut |x| match x { - Expr::Ref(r) => push(&mut out, r, r.range()), - // The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when - // the criteria range's size isn't known statically, recalculate the formula every time. - Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) { - (Some(Expr::Ref(c)), Some(Expr::Ref(s))) => { - let (crit, sum) = (c.range(), s.range()); - push(&mut out, s, resized_sum_range(sum, crit.height(), crit.width())); - } - (_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {} - _ => dynamic = true, - }, - Expr::Call(n, _) - if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") => - { - dynamic = true - } - Expr::Name(_) | Expr::Struct(_) => dynamic = true, - Expr::Call(n, _) if gridcraft_functions::lookup(n).is_none() && !is_special(n) => dynamic = true, - // A range ending in a function's result (`A1:INDEX(B1:B9,n)`) covers the cells between - // the references inside it, not only those references. - Expr::Binary(BinOp::Range, a, b) if !matches!((&**a, &**b), (Expr::Ref(_), Expr::Ref(_))) => { - let mut inner = precedents(wb, sheet, a).0; - inner.extend(precedents(wb, sheet, b).0); - let mut boxes: Vec = Vec::new(); - for area in inner { - match boxes.iter_mut().find(|x| x.sheet == area.sheet) { - Some(x) => x.range = x.range.union(&area.range), - None => boxes.push(area), - } - } - out.extend(boxes); - } - _ => {} - }); - (out, dynamic) -} - -fn is_special(n: &str) -> bool { - matches!( - n, - "IF" | "IFS" - | "IFERROR" - | "IFNA" - | "CHOOSE" - | "SWITCH" - | "ROW" - | "COLUMN" - | "ROWS" - | "COLUMNS" - | "AREAS" - | "ISREF" - | "ISFORMULA" - | "FORMULATEXT" - | "SHEET" - | "SHEETS" - | "OFFSET" - | "INDIRECT" - | "INDEX" - | "CELL" - | "TRIMRANGE" - | "SUBTOTAL" - | "AGGREGATE" - | "TEXT" - | "LET" - | "LAMBDA" - | "ISOMITTED" - | "MAP" - | "REDUCE" - | "SCAN" - | "BYROW" - | "BYCOL" - | "MAKEARRAY" - ) -} - -/// Names of functions the evaluator implements itself (merged into the function list for UI). -pub const SPECIAL_FUNCTIONS: &[&str] = &[ - "IF", - "IFS", - "IFERROR", - "IFNA", - "CHOOSE", - "SWITCH", - "ROW", - "COLUMN", - "ROWS", - "COLUMNS", - "AREAS", - "ISREF", - "ISFORMULA", - "FORMULATEXT", - "SHEET", - "SHEETS", - "OFFSET", - "INDIRECT", - "INDEX", - "CELL", - "TRIMRANGE", - "SUBTOTAL", - "AGGREGATE", - "TEXT", - "LET", - "LAMBDA", - "ISOMITTED", - "MAP", - "REDUCE", - "SCAN", - "BYROW", - "BYCOL", - "MAKEARRAY", -]; - -pub fn is_known_function(n: &str) -> bool { - is_special(&n.to_ascii_uppercase()) || gridcraft_functions::lookup(n).is_some() -} - -#[allow(dead_code)] -fn unused(_: RefKind) {} - #[cfg(test)] mod fuel_tests { use super::*; diff --git a/crates/calc/src/eval/array.rs b/crates/calc/src/eval/array.rs new file mode 100644 index 0000000000..67662c83cc --- /dev/null +++ b/crates/calc/src/eval/array.rs @@ -0,0 +1,207 @@ +use super::{Array, BinOp, CellError, MAX_CELLS, Value, compare}; + +/// The aggregates that can fold a reference without building an array. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Agg { + Sum, + Count, + Average, +} + +impl Agg { + pub(super) fn of(name: &str) -> Option { + match name { + "SUM" => Some(Agg::Sum), + "COUNT" => Some(Agg::Count), + "AVERAGE" => Some(Agg::Average), + _ => None, + } + } +} + +/// What a folded aggregate carries from one value to the next. +#[derive(Default)] +pub(super) struct Acc { + pub(super) sum: f64, + pub(super) count: u64, +} + +impl Acc { + /// Takes a value found inside a reference: only numbers count. `Err` is an error value that + /// ends `SUM` and `AVERAGE`; `COUNT` skips errors. + pub(super) fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> { + match v { + Value::Number(n) => { + self.sum += n; + self.count = self.count.saturating_add(1); + Ok(()) + } + Value::Error(e) if kind != Agg::Count => Err(*e), + _ => Ok(()), + } + } + + pub(super) fn finish(&self, kind: Agg) -> Value { + match kind { + Agg::Sum => Value::number(self.sum), + Agg::Count => Value::number(self.count as f64), + Agg::Average if self.count == 0 => Value::Error(CellError::Div0), + Agg::Average => Value::number(self.sum / self.count as f64), + } + } +} + +// ---------------------------------------------------------------- operators + +pub(super) fn map_unary(v: &Value, f: &dyn Fn(f64) -> Value, plus: bool, sys: gridcraft_core::DateSystem) -> Value { + match v { + Value::Array(a) => Value::from(Array { rows: a.rows, cols: a.cols, data: a.data.iter().map(|x| map_unary(x, f, plus, sys)).collect() }), + Value::Error(e) => Value::Error(*e), + Value::Text(_) if plus => v.clone(), + other => match other.to_number_in(sys) { + Ok(n) => f(n), + Err(e) => Value::Error(e), + }, + } +} + +/// Element-wise combination with Excel's broadcasting. +pub fn zip2(a: &Value, b: &Value, f: impl Fn(&Value, &Value) -> Value) -> Value { + match (a, b) { + (Value::Array(x), Value::Array(y)) => { + let rows = broadcast_dim(x.rows, y.rows); + let cols = broadcast_dim(x.cols, y.cols); + let Some(n) = broadcast_len(rows, cols) else { return Value::Error(CellError::Num) }; + let mut data = Vec::with_capacity(n); + for r in 0..rows { + for c in 0..cols { + data.push(f(&x.get_broadcast(r, c), &y.get_broadcast(r, c))); + } + } + Value::from(Array { rows, cols, data }) + } + (Value::Array(x), s) => Value::from(Array { rows: x.rows, cols: x.cols, data: x.data.iter().map(|v| f(v, s)).collect() }), + (s, Value::Array(y)) => Value::from(Array { rows: y.rows, cols: y.cols, data: y.data.iter().map(|v| f(s, v)).collect() }), + (x, y) => f(x, y), + } +} + +/// Cell count of a `rows`×`cols` broadcast result, or `None` when it would exceed [`MAX_CELLS`]. +/// Each operand passes its own size cap, but their broadcast product can be far larger +/// (`SEQUENCE(1048576)*SEQUENCE(1,16384)` is 17 billion cells), so it is checked before allocating. +/// The product is formed in `u64`: on wasm32 `usize` is 32 bits, where a `usize` product above +/// `u32::MAX` would wrap (2^32 cells → 0) and slip past the cap. +pub(super) fn broadcast_len(rows: usize, cols: usize) -> Option { + let cells = u64::try_from(rows).ok()?.checked_mul(u64::try_from(cols).ok()?)?; + if cells > MAX_CELLS { + return None; + } + usize::try_from(cells).ok() +} + +fn broadcast_dim(a: usize, b: usize) -> usize { + if a == 1 { + b + } else if b == 1 { + a + } else { + a.max(b) + } +} + +pub(super) fn zip3(c: &Array, t: &Value, f: &Value, g: impl Fn(&Value, &Value, &Value) -> Value) -> Value { + let dims = |v: &Value| if let Value::Array(a) = v { (a.rows, a.cols) } else { (1, 1) }; + let (tr, tc) = dims(t); + let (fr, fc) = dims(f); + let rows = broadcast_dim(broadcast_dim(c.rows, tr), fr); + let cols = broadcast_dim(broadcast_dim(c.cols, tc), fc); + let Some(n) = broadcast_len(rows, cols) else { return Value::Error(CellError::Num) }; + let get = |v: &Value, r: usize, col: usize| if let Value::Array(a) = v { a.get_broadcast(r, col) } else { v.clone() }; + let mut data = Vec::with_capacity(n); + for r in 0..rows { + for col in 0..cols { + data.push(g(&c.get_broadcast(r, col), &get(t, r, col), &get(f, r, col))); + } + } + Value::from(Array { rows, cols, data }) +} + +/// One cell of a LAMBDA helper's result, or `None` for an array of more than one value: arrays +/// can't nest, so the whole helper gives `#CALC!`, as in Excel. +pub(super) fn single(v: Value) -> Option { + match v { + Value::Array(a) if a.data.len() > 1 => None, + v => Some(v.scalar()), + } +} + +pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateSystem) -> Value { + zip2(x, y, |a, b| binary_scalar(op, a, b, sys)) +} + +fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value { + if let Value::Error(e) = a { + return Value::Error(*e); + } + if let Value::Error(e) = b { + return Value::Error(*e); + } + let num = |f: fn(f64, f64) -> Value| match (a.to_number_in(sys), b.to_number_in(sys)) { + (Ok(x), Ok(y)) => f(x, y), + (Err(e), _) | (_, Err(e)) => Value::Error(e), + }; + use std::cmp::Ordering::*; + match op { + BinOp::Add => num(|x, y| Value::number(x + y)), + BinOp::Sub => num(|x, y| Value::number(x - y)), + BinOp::Mul => num(|x, y| Value::number(x * y)), + BinOp::Div => num(|x, y| if y == 0.0 { Value::Error(CellError::Div0) } else { Value::number(x / y) }), + BinOp::Pow => num(|x, y| { + if x == 0.0 && y == 0.0 { + Value::Error(CellError::Num) + } else if x == 0.0 && y < 0.0 { + Value::Error(CellError::Div0) + } else { + Value::number(x.powf(y)) + } + }), + BinOp::Concat => match (a.to_text(), b.to_text()) { + (Ok(x), Ok(y)) => { + if x.len() + y.len() > 32767 * 4 { + Value::Error(CellError::Value) + } else { + Value::text(x + &y) + } + } + (Err(e), _) | (_, Err(e)) => Value::Error(e), + }, + BinOp::Eq => Value::Bool(compare(a, b) == Equal), + BinOp::Ne => Value::Bool(compare(a, b) != Equal), + BinOp::Lt => Value::Bool(compare(a, b) == Less), + BinOp::Gt => Value::Bool(compare(a, b) == Greater), + BinOp::Le => Value::Bool(compare(a, b) != Greater), + BinOp::Ge => Value::Bool(compare(a, b) != Less), + BinOp::Range | BinOp::Union | BinOp::Intersect => Value::Error(CellError::Value), + } +} + +#[cfg(test)] +mod tests { + use super::{MAX_CELLS, broadcast_len}; + + #[test] + fn broadcast_len_caps_at_max_cells() { + assert_eq!(broadcast_len(4_000, 4_000), Some(MAX_CELLS as usize)); + assert_eq!(broadcast_len(4_000, 4_001), None); + assert_eq!(broadcast_len(1, MAX_CELLS as usize), Some(MAX_CELLS as usize)); + } + + /// `65_536 * 65_536` is 2^32. Multiplied as `usize` on wasm32 it wraps to 0, which a + /// `> MAX_CELLS` test would let through; the guard must reject the true product. + #[test] + fn broadcast_len_rejects_a_product_that_wraps_to_zero_on_32_bits() { + assert_eq!(65_536u32.wrapping_mul(65_536), 0); + assert_eq!(broadcast_len(65_536, 65_536), None); + assert_eq!(broadcast_len(1_048_576, 16_384), None); + } +} diff --git a/crates/calc/src/eval/call.rs b/crates/calc/src/eval/call.rs new file mode 100644 index 0000000000..08d563d439 --- /dev/null +++ b/crates/calc/src/eval/call.rs @@ -0,0 +1,435 @@ +use super::array::{Acc, Agg, zip2, zip3}; +use super::format::same_kind; +use super::special::{ev_shape, resized_sum_range, resizes_sum_range}; +use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pipe, Value, compare, err}; +use std::sync::Arc; + +impl<'h> Evaluator<'h> { + pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev { + match name { + "IF" => self.if_call(args), + "IFS" => { + if args.len() < 2 || !args.len().is_multiple_of(2) { + return err(CellError::Value); + } + for pair in args.chunks(2) { + let [c, v] = pair else { break }; + let cv = self.value(c); + match cv.scalar().to_bool() { + Ok(true) => return self.eval(v), + Ok(false) => {} + Err(e) => return err(e), + } + } + err(CellError::NA) + } + "IFERROR" | "IFNA" => self.if_error_call(name, args), + "CHOOSE" => self.choose_call(args), + "SWITCH" => self.switch_call(args), + "ROW" | "COLUMN" => self.row_column_call(name, args), + "ROWS" | "COLUMNS" => { + if args.len() != 1 { + return err(CellError::Value); + } + let is_rows = name == "ROWS"; + match self.eval(&args[0]) { + Ev::R(a) => match a.as_slice() { + [a] => Ev::V(Value::number(if is_rows { a.range.height() } else { a.range.width() } as f64)), + _ => err(CellError::Ref), + }, + Ev::V(Value::Array(arr)) => Ev::V(Value::number(if is_rows { arr.rows } else { arr.cols } as f64)), + Ev::V(Value::Error(e)) => err(e), + Ev::V(_) => Ev::V(Value::Number(1.0)), + Ev::L(_) => err(CellError::Value), + } + } + "AREAS" => match args.first().map(|a| self.eval(a)) { + Some(Ev::R(a)) => Ev::V(Value::number(a.len() as f64)), + Some(Ev::V(Value::Error(e))) => err(e), + _ => err(CellError::Value), + }, + "ISREF" => Ev::V(Value::Bool(matches!(args.first().map(|a| self.eval(a)), Some(Ev::R(_))))), + "ISFORMULA" | "FORMULATEXT" => { + let Some(Ev::R(a)) = args.first().map(|a| self.eval(a)) else { return err(CellError::NA) }; + let Some(a) = a.first() else { return err(CellError::NA) }; + let f = self.host.workbook().sheet(a.sheet).and_then(|s| s.cell(a.range.start)).and_then(|c| c.formula.clone()); + if name == "ISFORMULA" { + Ev::V(Value::Bool(f.is_some())) + } else { + match f { + Some(f) => Ev::V(Value::text(format!("={}", f.text))), + None => err(CellError::NA), + } + } + } + "SHEET" | "SHEETS" => self.sheet_call(name, args), + "OFFSET" => self.offset(args), + "INDIRECT" => self.indirect(args), + "INDEX" => self.index(args), + "XLOOKUP" => self.xlookup(args), + "CELL" => self.cell_info(args), + "TRIMRANGE" => self.trimrange(args), + "SUBTOTAL" | "AGGREGATE" => self.subtotal(name, args), + "TEXT" => { + if args.len() != 2 { + return err(CellError::Value); + } + let v = self.arg_val(args, 0).unwrap_or_default(); + let f = self.arg_val(args, 1).unwrap_or_default(); + let sys = self.host.workbook().date_system; + let one = |v: &Value, f: &Value| -> Value { + if let Value::Error(e) = v { + return Value::Error(*e); + } + let code = match f.to_text() { + Ok(c) => c, + Err(e) => return Value::Error(e), + }; + match gridcraft_numfmt::text_function(v, &code, sys) { + Ok(s) => Value::text(s), + Err(e) => Value::Error(e), + } + }; + Ev::V(zip2(&v, &f, one)) + } + "LET" => self.let_(args), + "LAMBDA" => { + if args.is_empty() { + return err(CellError::Value); + } + let mut params = Vec::new(); + for p in &args[..args.len() - 1] { + match p { + Expr::Name(n) => params.push(n.trim_start_matches('[').trim_end_matches(']').to_string()), + _ => return err(CellError::Value), + } + } + let Some(body) = args.last() else { return err(CellError::Value) }; + Ev::L(Arc::new(Lambda { params, body: body.clone(), env: self.env.clone() })) + } + "ISOMITTED" => { + let r = matches!(args.first(), Some(Expr::Name(n)) if self.env.iter().rev().find(|(k, _)| gridcraft_formula::same_name(k, n)).is_some_and(|(_, v)| matches!(v, Ev::V(Value::Empty)))); + Ev::V(Value::Bool(r)) + } + "MAP" | "REDUCE" | "SCAN" | "BYROW" | "BYCOL" | "MAKEARRAY" => self.higher_order(name, args), + "GROUPBY" | "PIVOTBY" => { + // The aggregation may be a function given by name (`SUM`): pass it as its name. + let i = if name == "GROUPBY" { 2 } else { 3 }; + match args.get(i).and_then(|a| self.function_by_name(a)) { + Some(f) => { + let mut args = args.to_vec(); + if let Some(a) = args.get_mut(i) { + *a = Expr::Text(f.into()); + } + self.builtin(name, &args) + } + None => self.builtin(name, args), + } + } + "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" => { + self.host.note_volatile(); + self.builtin(name, args) + } + _ => self.builtin(name, args), + } + } + + fn if_call(&mut self, args: &[Expr]) -> Ev { + if args.is_empty() || args.len() > 3 { + return err(CellError::Value); + } + let condition = self.arg_val(args, 0).unwrap_or_default(); + if let Value::Array(array) = &condition { + let when_true = self.arg_val(args, 1).unwrap_or(Value::Bool(true)); + let when_false = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) }; + return Ev::V(zip3(array, &when_true, &when_false, |condition, when_true, when_false| match condition.to_bool() { + Ok(true) => when_true.clone(), + Ok(false) => when_false.clone(), + Err(error) => Value::Error(error), + })); + } + match condition.to_bool() { + Ok(true) => match args.get(1) { + Some(Expr::Missing) => Ev::V(Value::Number(0.0)), + Some(expression) => self.eval(expression), + None => Ev::V(Value::Bool(true)), + }, + Ok(false) => match args.get(2) { + Some(Expr::Missing) => Ev::V(Value::Number(0.0)), + Some(expression) => self.eval(expression), + None => Ev::V(Value::Bool(false)), + }, + Err(error) => err(error), + } + } + + fn if_error_call(&mut self, name: &str, args: &[Expr]) -> Ev { + if args.len() != 2 { + return err(CellError::Value); + } + let value = self.arg_ev(args, 0).unwrap_or(Ev::V(Value::Empty)); + let na_only = name == "IFNA"; + let catches = |error: CellError| !na_only || error == CellError::NA; + match &value { + Ev::V(Value::Error(error)) if catches(*error) => self.eval(&args[1]), + Ev::V(Value::Array(array)) if array.data.iter().any(|item| item.as_error().is_some_and(catches)) => { + let alternate = self.arg_val(args, 1).unwrap_or_default(); + let data = + array.data.iter().map(|item| if item.as_error().is_some_and(catches) { alternate.scalar() } else { item.clone() }).collect(); + Ev::V(Array::new(array.rows, array.cols, data).map(Value::from).unwrap_or(Value::Error(CellError::Value))) + } + Ev::R(_) => self.if_error_reference(value.clone(), args, catches), + _ => value, + } + } + + fn if_error_reference(&mut self, value: Ev, args: &[Expr], catches: impl Fn(CellError) -> bool + Copy) -> Ev { + match self.deref(value.clone()) { + Value::Error(error) if catches(error) => self.eval(&args[1]), + Value::Array(ref array) if array.data.iter().any(|item| item.as_error().is_some_and(catches)) => { + let alternate = self.arg_val(args, 1).unwrap_or_default(); + let data = + array.data.iter().map(|item| if item.as_error().is_some_and(catches) { alternate.scalar() } else { item.clone() }).collect(); + Ev::V(Array::new(array.rows, array.cols, data).map(Value::from).unwrap_or(Value::Error(CellError::Value))) + } + _ => value, + } + } + + fn choose_call(&mut self, args: &[Expr]) -> Ev { + if args.len() < 2 { + return err(CellError::Value); + } + let index = self.value(&args[0]); + if let Value::Array(_) = index { + let Some(spec) = gridcraft_functions::lookup("CHOOSE") else { return err(CellError::Name) }; + let mut evaluated = vec![Arg { value: index, from_ref: false }]; + for argument in &args[1..] { + evaluated.push(Arg { value: self.value(argument), from_ref: false }); + } + let mut context = FnCtx { ev: self, criteria: None, lambda: None }; + return gridcraft_functions::call(spec, &evaluated, &mut context).pipe(Ev::V); + } + let index = match index.to_number() { + Ok(number) => number.trunc() as i64, + Err(error) => return err(error), + }; + if index < 1 || index as usize >= args.len() { + return err(CellError::Value); + } + self.eval(&args[index as usize]) + } + + fn switch_call(&mut self, args: &[Expr]) -> Ev { + if args.len() < 3 { + return err(CellError::Value); + } + let value = self.arg_val(args, 0).unwrap_or_default().scalar(); + if let Value::Error(error) = value { + return err(error); + } + let choices = &args[1..]; + for pair in choices.as_chunks::<2>().0 { + let (candidate, result) = (&pair[0], &pair[1]); + let candidate = self.value(candidate).scalar(); + if !candidate.is_error() && compare(&value, &candidate) == std::cmp::Ordering::Equal && same_kind(&value, &candidate) { + return self.eval(result); + } + } + if let Some(default) = choices.get(choices.len().saturating_sub(1)).filter(|_| choices.len() % 2 == 1) { + self.eval(default) + } else { + err(CellError::NA) + } + } + + fn row_column_call(&mut self, name: &str, args: &[Expr]) -> Ev { + let is_row = name == "ROW"; + if args.is_empty() || matches!(args.first(), Some(Expr::Missing)) { + return Ev::V(Value::number(if is_row { self.at.row + 1 } else { self.at.col + 1 } as f64)); + } + let areas = match self.eval(&args[0]) { + Ev::R(areas) => areas, + Ev::V(Value::Error(error)) => return err(error), + _ => return err(CellError::Value), + }; + let Some(area) = areas.first() else { return err(CellError::Ref) }; + let range = self.trim_lines(area); + if is_row { + let values: Vec = (range.start.row..=range.end.row).map(|row| Value::number(row as f64 + 1.0)).collect(); + if values.len() == 1 { Ev::V(values.into_iter().next().unwrap_or_default()) } else { Ev::V(Array::column(values).into()) } + } else { + let values: Vec = (range.start.col..=range.end.col).map(|col| Value::number(col as f64 + 1.0)).collect(); + if values.len() == 1 { Ev::V(values.into_iter().next().unwrap_or_default()) } else { Ev::V(Array::row(values).into()) } + } + } + + fn sheet_call(&mut self, name: &str, args: &[Expr]) -> Ev { + let is_sheet = name == "SHEET"; + if args.is_empty() { + let count = if is_sheet { self.sheet + 1 } else { self.host.workbook().sheets.len() }; + return Ev::V(Value::number(count as f64)); + } + match self.eval(&args[0]) { + Ev::R(areas) if is_sheet => areas.first().map_or(err(CellError::Ref), |area| Ev::V(Value::number(area.sheet as f64 + 1.0))), + Ev::R(areas) => { + let mut sheets: Vec = areas.iter().map(|area| area.sheet).collect(); + sheets.dedup(); + Ev::V(Value::number(sheets.len() as f64)) + } + Ev::V(Value::Text(name)) if is_sheet => { + self.host.workbook().sheet_index(&name).map_or(err(CellError::NA), |index| Ev::V(Value::number(index as f64 + 1.0))) + } + _ => err(CellError::NA), + } + } + + pub(super) fn builtin(&mut self, name: &str, args: &[Expr]) -> Ev { + let Some(spec) = gridcraft_functions::lookup(name) else { + // A defined name holding a LAMBDA, or a LET-bound lambda. + return match self.name(name) { + Ev::L(l) => self.apply_lambda(&l, args), + Ev::V(Value::Error(x)) => err(x), + _ => err(CellError::Name), + }; + }; + if args.len() < spec.min_args || args.len() > spec.max_args { + return err(CellError::Value); + } + if let Some(kind) = Agg::of(spec.name) { + return self.aggregate(kind, args); + } + let mut evaluated = Vec::with_capacity(args.len()); + // SUMIF/AVERAGEIF: the size of the criteria range (argument 1), which the sum range takes. + let mut criteria_shape = None; + // Database functions: the criteria range (argument 2), whose formulas are computed criteria. + let mut criteria = None; + // GROUPBY/PIVOTBY: the LAMBDA given as their function. + let mut lambda = None; + let lambda_at = match name { + "GROUPBY" => Some(2), + "PIVOTBY" => Some(3), + _ => None, + }; + for (i, a) in args.iter().enumerate() { + let mut ev = self.eval(a); + if lambda_at == Some(i) + && let Ev::L(l) = &ev + { + lambda = Some(l.clone()); + ev = Ev::V(Value::Empty); + } + if spec.category == gridcraft_functions::Category::Database + && i == 2 + && let Ev::R(areas) = &ev + && let [area] = areas.as_slice() + { + criteria = Some(*area); + } + if resizes_sum_range(name, args.len()) { + if i == 0 { + criteria_shape = ev_shape(&ev); + } else if i == 2 + && let (Some((h, w)), Ev::R(areas)) = (criteria_shape, &ev) + && let [area] = areas.as_slice() + { + ev = Ev::R(vec![Area { sheet: area.sheet, range: resized_sum_range(area.range, h, w) }]); + } + } + let from_ref = matches!(ev, Ev::R(_)); + let value = match ev { + Ev::R(areas) if areas.len() > 1 => { + // Multi-area references (unions): flatten into one row for aggregates. + let mut vals = Vec::new(); + for ar in &areas { + match self.area_value(ar) { + Value::Array(a) => vals.extend(a.data.iter().cloned()), + v => vals.push(v), + } + } + Value::from(Array::row(vals)) + } + ev => self.deref(ev), + }; + evaluated.push(Arg { value, from_ref }); + } + let mut ctx = FnCtx { ev: self, criteria, lambda }; + gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V) + } + + /// Performs aggregation operations without copying its ranges: blocks are folded over the stored + /// cells, so no array is built and there is no `MAX_CELLS` limit. Arguments are evaluated and read one + /// after another, as the array path does, so volatile formulas (like `RAND`) see the same order. + /// Only `SUM`, `COUNT` and `AVG` are supported currently. + fn aggregate(&mut self, kind: Agg, args: &[Expr]) -> Ev { + let mut acc = Acc::default(); + let mut first_error = None; + for a in args { + let ev = self.eval(a); + let steps = match ev { + Ev::R(areas) => areas.iter().map(|area| self.aggregate_area(kind, area, &mut acc)).collect(), + ev => { + let value = self.deref(ev); + vec![self.aggregate_value(kind, value, false, &mut acc)] + } + }; + if first_error.is_none() { + first_error = steps.into_iter().find_map(Result::err); + } + } + first_error.unwrap_or_else(|| Ev::V(acc.finish(kind))) + } + + /// Adds one area to `acc`; `Err` is the result the function ends with. + fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> { + if !a.range.is_single() { + let mut error = None; + let walked = self.host.visit_range(a.sheet, a.range, &mut |v| match acc.add_cell(kind, v) { + Ok(()) => true, + Err(e) => { + error = Some(e); + false + } + }); + if walked { + return error.map_or(Ok(()), |e| Err(err(e))); + } + } + let value = self.area_value(a); + self.aggregate_value(kind, value, true, acc) + } + + /// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules + /// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`). + fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> { + let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else { + return Err(err(CellError::Name)); + }; + let args = [Arg { value, from_ref }]; + if kind != Agg::Count { + match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) { + Value::Number(n) => acc.sum += n, + other => return Err(Ev::V(other)), + } + } + if kind != Agg::Sum { + match gridcraft_functions::call(count, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) { + Value::Number(n) => acc.count = acc.count.saturating_add(n as u64), + other => return Err(Ev::V(other)), + } + } + Ok(()) + } + + /// A worksheet function given by name where a function is expected (`BYROW(A1:C3,SUM)`, + /// `GROUPBY(A2:A9,B2:B9,SUM)`): its name, unless a LET/LAMBDA variable or a defined name has + /// that name. + pub(super) fn function_by_name(&self, e: &Expr) -> Option { + let Expr::Name(n) = e else { return None }; + if self.env.iter().any(|(k, _)| gridcraft_formula::same_name(k, n)) || self.host.workbook().name(n, self.sheet).is_some() { + return None; + } + let u = n.to_ascii_uppercase(); + gridcraft_functions::lookup(&u).map(|_| u) + } +} diff --git a/crates/calc/src/eval/format.rs b/crates/calc/src/eval/format.rs new file mode 100644 index 0000000000..a288b410ee --- /dev/null +++ b/crates/calc/src/eval/format.rs @@ -0,0 +1,75 @@ +use super::{CellError, Value}; +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS}; + +/// CELL("format") code for a number format. +pub(super) fn cell_format_code(code: &str) -> String { + let c = code.to_ascii_lowercase(); + if c == "general" { + return "G".into(); + } + if c.contains('%') { + return format!("P{}", decimals(&c)); + } + if c.contains('e') && c.contains('0') { + return format!("S{}", decimals(&c)); + } + if c.contains('$') { + return format!("C{}", decimals(&c)); + } + if c.contains('y') || c.contains('d') { + return "D1".into(); + } + if c.contains('h') { + return "D9".into(); + } + if c.contains(',') { + return format!(",{}", decimals(&c)); + } + format!("F{}", decimals(&c)) +} + +fn decimals(c: &str) -> usize { + c.split_once('.').map_or(0, |(_, d)| d.chars().take_while(|ch| *ch == '0').count()) +} + +pub(super) fn same_kind(a: &Value, b: &Value) -> bool { + std::mem::discriminant(a) == std::mem::discriminant(b) || (a.is_empty() || b.is_empty()) +} + +/// Converts an R1C1 reference text to A1 (for INDIRECT(…, FALSE)). `Ok(None)` means the text is +/// not R1C1; `Err` means it is R1C1 but points past the sheet. +pub fn r1c1_to_a1(s: &str, at: CellRef) -> Result, CellError> { + let (sheet, body) = match s.rsplit_once('!') { + Some((sh, b)) => (format!("{sh}!"), b), + None => (String::new(), s), + }; + let conv = |part: &str| -> Result, CellError> { + let u = part.to_ascii_uppercase(); + let Some((rpart, cpart)) = u.strip_prefix('R').and_then(|rest| rest.split_once('C')) else { return Ok(None) }; + // `None`: not R1C1. `Some(None)`: R1C1, but past the sheet. + let num = |p: &str, base: u32, max: u32| -> Option> { + let (v, absolute) = if p.is_empty() { + (Some(i64::from(base)), false) + } else if let Some(inner) = p.strip_prefix('[').and_then(|x| x.strip_suffix(']')) { + (i64::from(base).checked_add(inner.parse().ok()?), false) + } else { + (p.parse::().ok()?.checked_sub(1).map(i64::from), true) + }; + Some(v.filter(|v| (0..i64::from(max)).contains(v)).map(|v| (v as u32, absolute))) + }; + let (Some(r), Some(c)) = (num(rpart, at.row, MAX_ROWS), num(cpart, at.col, MAX_COLS)) else { return Ok(None) }; + let (Some((r, ra)), Some((c, ca))) = (r, c) else { return Err(CellError::Ref) }; + Ok(Some(format!("{}{}{}{}", if ca { "$" } else { "" }, gridcraft_core::col_to_letters(c), if ra { "$" } else { "" }, r + 1))) + }; + let out = match body.split_once(':') { + Some((a, b)) => match (conv(a)?, conv(b)?) { + (Some(a), Some(b)) => format!("{a}:{b}"), + _ => return Ok(None), + }, + None => match conv(body)? { + Some(x) => x, + None => return Ok(None), + }, + }; + Ok(Some(format!("{sheet}{out}"))) +} diff --git a/crates/calc/src/eval/lambda.rs b/crates/calc/src/eval/lambda.rs new file mode 100644 index 0000000000..dfb30029ac --- /dev/null +++ b/crates/calc/src/eval/lambda.rs @@ -0,0 +1,200 @@ +use super::MAX_LAMBDA_CALLS; +use super::array::{broadcast_len, single}; +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 { + // 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(CellError::Value); + } + let mut bound = Vec::with_capacity(l.params.len()); + for (i, p) in l.params.iter().enumerate() { + let v = match args.get(i) { + Some(Expr::Missing) | None => Ev::V(Value::Empty), + Some(e) => self.eval(e), + }; + bound.push((p.clone(), v)); + } + self.call_lambda_values(l, bound) + } + + pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev { + if self.calls >= MAX_LAMBDA_CALLS { + return err(CellError::Num); + } + // #2382: one charge per invocation, so a cell's total work stays bounded however the + // lambdas nest. Foregrounding the charge here means every path into a body (direct + // `(2,3)` application, `MAP`/`REDUCE`/`BYROW` helpers, D-function criteria) meters. + self.fuel = match self.fuel.checked_sub(1) { + Some(f) => f, + None => return err(CellError::Calc), + }; + self.calls += 1; + let saved = std::mem::replace(&mut self.env, l.env.clone()); + self.env.extend(bound); + let r = self.eval(&l.body); + self.env = saved; + self.calls -= 1; + r + } + + pub(super) fn let_(&mut self, args: &[Expr]) -> Ev { + if args.len() < 3 || args.len().is_multiple_of(2) { + return err(CellError::Value); + } + let base = self.env.len(); + for pair in args[..args.len() - 1].chunks(2) { + let [Expr::Name(n), v] = pair else { + self.env.truncate(base); + return err(CellError::Value); + }; + let val = self.eval(v); + self.env.push((n.clone(), val)); + } + let r = match args.last() { + Some(body) => self.eval(body), + None => err(CellError::Value), + }; + self.env.truncate(base); + r + } + + /// The function argument of a LAMBDA helper; a function given by name takes `arity` + /// arguments. + fn lambda_arg(&mut self, e: Option<&Expr>, arity: usize) -> Option> { + if let Some(f) = e.and_then(|x| self.function_by_name(x)) { + let params: Vec = (0..arity).map(|i| format!("_xleta.{i}")).collect(); + let body = Expr::Call(f, params.iter().map(|p| Expr::Name(p.clone())).collect()); + return Some(Arc::new(Lambda { params, body, env: Vec::new() })); + } + match e.map(|x| self.eval(x)) { + Some(Ev::L(l)) => Some(l), + _ => None, + } + } + + pub(super) fn higher_order(&mut self, name: &str, args: &[Expr]) -> Ev { + let as_array = |v: Value| -> Arc { + match v { + Value::Array(a) => a, + other => Arc::new(Array::scalar(other)), + } + }; + match name { + "MAP" => { + if args.len() < 2 { + return err(CellError::Value); + } + let Some(l) = self.lambda_arg(args.last(), args.len() - 1) else { return err(CellError::Value) }; + let arrays: Vec> = args[..args.len() - 1].iter().map(|a| as_array(self.value(a))).collect(); + let rows = arrays.iter().map(|a| a.rows).max().unwrap_or(1); + let cols = arrays.iter().map(|a| a.cols).max().unwrap_or(1); + let Some(n) = broadcast_len(rows, cols) else { return err(CellError::Num) }; + // The LAMBDA takes one parameter per array. + if l.params.len() != arrays.len() { + return err(CellError::Value); + } + let mut out = Vec::with_capacity(n); + for r in 0..rows { + for c in 0..cols { + let bound = l.params.iter().zip(arrays.iter()).map(|(p, a)| (p.clone(), Ev::V(a.get_broadcast(r, c)))).collect(); + let v = self.call_lambda_values(&l, bound); + let Some(one) = single(self.deref(v)) else { return err(CellError::Calc) }; + out.push(one); + } + } + Ev::V(Array::new(rows, cols, out).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) + } + "REDUCE" | "SCAN" => { + if args.len() != 3 { + return err(CellError::Value); + } + let mut acc = self.value(&args[0]); + let arr = as_array(self.value(&args[1])); + let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) }; + if l.params.len() != 2 { + return err(CellError::Value); + } + let mut scan = Vec::with_capacity(arr.data.len()); + for v in arr.data.iter() { + let bound = vec![(l.params[0].clone(), Ev::V(acc.clone())), (l.params[1].clone(), Ev::V(v.clone()))]; + let r = self.call_lambda_values(&l, bound); + acc = self.deref(r); + if name == "SCAN" { + let Some(one) = single(acc.clone()) else { return err(CellError::Calc) }; + scan.push(one); + } + } + if name == "SCAN" { + Ev::V(Array::new(arr.rows, arr.cols, scan).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) + } else { + Ev::V(acc) + } + } + "BYROW" | "BYCOL" => { + if args.len() != 2 { + return err(CellError::Value); + } + let arr = as_array(self.value(&args[0])); + let Some(l) = self.lambda_arg(args.get(1), 1) else { return err(CellError::Value) }; + let Some(p) = l.params.first().cloned() else { return err(CellError::Value) }; + if l.params.len() != 1 { + return err(CellError::Value); + } + let by_row = name == "BYROW"; + let n = if by_row { arr.rows } else { arr.cols }; + let mut out = Vec::with_capacity(n); + for i in 0..n { + let slice: Vec = if by_row { + (0..arr.cols).map(|c| arr.get(i, c).cloned().unwrap_or_default()).collect() + } else { + (0..arr.rows).map(|r| arr.get(r, i).cloned().unwrap_or_default()).collect() + }; + let a = if by_row { Array::row(slice) } else { Array::column(slice) }; + let r = self.call_lambda_values(&l, vec![(p.clone(), Ev::V(a.into()))]); + let Some(one) = single(self.deref(r)) else { return err(CellError::Calc) }; + out.push(one); + } + let a = if by_row { Array::column(out) } else { Array::row(out) }; + Ev::V(a.into()) + } + "MAKEARRAY" => { + if args.len() != 3 { + return err(CellError::Value); + } + let (rows, cols) = match (self.arg_num(args, 0, 0.0), self.arg_num(args, 1, 0.0)) { + (Ok(r), Ok(c)) => (r.trunc(), c.trunc()), + (Err(e), _) | (_, Err(e)) => return err(e), + }; + if rows < 1.0 || cols < 1.0 || rows * cols > MAX_CELLS as f64 { + return err(CellError::Value); + } + let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) }; + if l.params.len() != 2 { + return err(CellError::Value); + } + let (rows, cols) = (rows as usize, cols as usize); + let mut out = Vec::with_capacity(rows * cols); + for r in 0..rows { + for c in 0..cols { + let bound = vec![ + (l.params[0].clone(), Ev::V(Value::number(r as f64 + 1.0))), + (l.params[1].clone(), Ev::V(Value::number(c as f64 + 1.0))), + ]; + let v = self.call_lambda_values(&l, bound); + let Some(one) = single(self.deref(v)) else { return err(CellError::Calc) }; + out.push(one); + } + } + Ev::V(Array::new(rows, cols, out).map(Value::from).unwrap_or(Value::Error(CellError::Calc))) + } + _ => err(CellError::Name), + } + } +} diff --git a/crates/calc/src/eval/reference_fns.rs b/crates/calc/src/eval/reference_fns.rs new file mode 100644 index 0000000000..4f5154c2db --- /dev/null +++ b/crates/calc/src/eval/reference_fns.rs @@ -0,0 +1,409 @@ +use super::format::{cell_format_code, r1c1_to_a1}; +use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, MAX_CELLS, Value, err}; +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; +use std::sync::Arc; + +impl<'h> Evaluator<'h> { + /// Whole rows/columns trimmed for ROW()/COLUMN() arrays. + pub(super) fn trim_lines(&mut self, a: &Area) -> RangeRef { + if a.range.is_full_cols() || a.range.is_full_rows() { self.trim(a) } else { a.range } + } + + pub(super) fn offset(&mut self, args: &[Expr]) -> Ev { + self.host.note_volatile(); + if args.len() < 3 || args.len() > 5 { + return err(CellError::Value); + } + let base = match self.eval(&args[0]) { + Ev::R(a) if a.len() == 1 => a[0], + Ev::V(Value::Error(e)) => return err(e), + _ => return err(CellError::Value), + }; + let rows = match self.arg_num(args, 1, 0.0) { + Ok(n) => n.trunc() as i64, + Err(e) => return err(e), + }; + let cols = match self.arg_num(args, 2, 0.0) { + Ok(n) => n.trunc() as i64, + Err(e) => return err(e), + }; + let h = match self.arg_num(args, 3, base.range.height() as f64) { + Ok(n) => n.trunc() as i64, + Err(e) => return err(e), + }; + let w = match self.arg_num(args, 4, base.range.width() as f64) { + Ok(n) => n.trunc() as i64, + Err(e) => return err(e), + }; + if h == 0 || w == 0 { + return err(CellError::Ref); + } + let r0 = (base.range.start.row as i64).saturating_add(rows); + let c0 = (base.range.start.col as i64).saturating_add(cols); + let (r0, r1) = if h > 0 { (r0, r0.saturating_add(h - 1)) } else { (r0.saturating_add(h + 1), r0) }; + let (c0, c1) = if w > 0 { (c0, c0.saturating_add(w - 1)) } else { (c0.saturating_add(w + 1), c0) }; + if r0 < 0 || c0 < 0 || r1 >= MAX_ROWS as i64 || c1 >= MAX_COLS as i64 { + return err(CellError::Ref); + } + Ev::R(vec![Area { sheet: base.sheet, range: RangeRef::new(CellRef::new(r0 as u32, c0 as u32), CellRef::new(r1 as u32, c1 as u32)) }]) + } + + pub(super) fn indirect(&mut self, args: &[Expr]) -> Ev { + self.host.note_volatile(); + if args.is_empty() || args.len() > 2 { + return err(CellError::Value); + } + let text = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) { + Some(Ok(t)) => t, + Some(Err(e)) => return err(e), + None => return err(CellError::Value), + }; + let a1 = match args.get(1) { + None | Some(Expr::Missing) => true, + Some(e) => { + let v = self.value(e); + v.scalar().to_bool().unwrap_or(true) + } + }; + // With a1 = FALSE, text that isn't R1C1 can still be a name, but never an A1 reference. + let (text, a1_ok) = if a1 { + (text, true) + } else { + match r1c1_to_a1(&text, self.at) { + Ok(Some(a1_text)) => (a1_text, true), + Ok(None) => (text, false), + Err(e) => return err(e), + } + }; + match gridcraft_formula::parse(&text) { + Ok(Expr::Ref(_)) if !a1_ok => err(CellError::Ref), + Ok(e @ (Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_))) => match self.eval(&e) { + r @ Ev::R(_) => r, + _ => err(CellError::Ref), + }, + _ => err(CellError::Ref), + } + } + + pub(super) fn index(&mut self, args: &[Expr]) -> Ev { + if args.is_empty() || args.len() > 4 { + return err(CellError::Value); + } + let src = self.eval(&args[0]); + let mut arg = |i: usize| match args.get(i) { + None | Some(Expr::Missing) => None, + Some(e) => Some(self.value(e)), + }; + let (rows, cols) = (arg(1), arg(2)); + let area_n = match self.arg_num(args, 3, 1.0) { + Ok(n) => n.trunc() as i64, + Err(e) => return err(e), + }; + let two = args.len() == 2; + let num = |v: &Option| v.as_ref().map_or(Ok(0.0), |v| v.to_number()).map(|n| n.trunc() as i64); + // Arrays of positions pick a value for each: INDEX(A1:C10,{1;2},{1,3}) is 2×2. + if let (Some(Value::Array(_)), _) | (_, Some(Value::Array(_))) = (&rows, &cols) { + let as_array = |v: &Option| match v { + Some(Value::Array(a)) => Arc::clone(a), + Some(v) => Arc::new(Array::scalar(v.clone())), + None => Arc::new(Array::scalar(Value::Number(0.0))), + }; + let (ra, ca) = (as_array(&rows), as_array(&cols)); + let (h, w) = (ra.rows.max(ca.rows), ra.cols.max(ca.cols)); + if (h as u64).saturating_mul(w as u64) > MAX_CELLS { + return err(CellError::Num); + } + let mut out = Vec::with_capacity(h * w); + for r in 0..h { + for c in 0..w { + let pos = (num(&Some(ra.get_broadcast(r, c))), num(&Some(ca.get_broadcast(r, c)))); + let v = match pos { + (Ok(row), Ok(col)) => { + let one = self.index_one(src.clone(), row, col, area_n, two); + match self.deref(one) { + Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc), + v => v.scalar(), + } + } + (Err(e), _) | (_, Err(e)) => Value::Error(e), + }; + out.push(v); + } + } + return Ev::V(Array::new(h, w, out).map(Value::from).unwrap_or(Value::Error(CellError::Value))); + } + let (row, col) = match (num(&rows), num(&cols)) { + (Ok(r), Ok(c)) => (r, c), + (Err(e), _) | (_, Err(e)) => return err(e), + }; + self.index_one(src, row, col, area_n, two) + } + + /// INDEX for one row and column position (0 = the whole column or row). + fn index_one(&mut self, src: Ev, row: i64, col: i64, area_n: i64, two_args: bool) -> Ev { + if row < 0 || col < 0 { + return err(CellError::Value); + } + match src { + Ev::R(areas) => { + let area = usize::try_from((area_n as u64).saturating_sub(1)).ok(); + let Some(a) = area.and_then(|i| areas.get(i)).copied() else { return err(CellError::Ref) }; + let r = a.range; + // A single row or column with one index picks along it. An area with several rows + // and columns needs both: `INDEX(A1:C3,2)` is #REF! in Excel (an empty third + // argument, `INDEX(A1:C3,2,)`, still means the whole row). Arrays differ: + // `INDEX({1,2;3,4},2)` is the row. + if two_args && r.height() > 1 && r.width() > 1 { + return err(CellError::Ref); + } + let (row, col) = if two_args && r.height() == 1 { (1, row) } else { (row, col) }; + if row as u64 > r.height() as u64 || col as u64 > r.width() as u64 { + return err(CellError::Ref); + } + let (r0, r1) = if row == 0 { (r.start.row, r.end.row) } else { (r.start.row + row as u32 - 1, r.start.row + row as u32 - 1) }; + let (c0, c1) = if col == 0 { (r.start.col, r.end.col) } else { (r.start.col + col as u32 - 1, r.start.col + col as u32 - 1) }; + Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) }]) + } + Ev::V(Value::Array(arr)) => { + let (row, col) = if two_args && arr.rows == 1 { (1, row) } else { (row, col) }; + if row as usize > arr.rows || col as usize > arr.cols { + return err(CellError::Ref); + } + match (row, col) { + (0, 0) => Ev::V(Value::Array(arr)), + (0, c) => Ev::V(Array::column((0..arr.rows).map(|r| arr.get(r, c as usize - 1).cloned().unwrap_or_default()).collect()).into()), + (r, 0) => Ev::V(Array::row((0..arr.cols).map(|c| arr.get(r as usize - 1, c).cloned().unwrap_or_default()).collect()).into()), + (r, c) => Ev::V(arr.get(r as usize - 1, c as usize - 1).cloned().unwrap_or(Value::Error(CellError::Ref))), + } + } + Ev::V(Value::Error(e)) => err(e), + Ev::V(v) => { + if row <= 1 && col <= 1 { + Ev::V(v) + } else { + err(CellError::Ref) + } + } + Ev::L(_) => err(CellError::Value), + } + } + + /// XLOOKUP whose result range is a reference returns a reference, as in Excel, so that it can + /// end a range (`SUM(XLOOKUP(a,…):XLOOKUP(b,…))`) or feed CELL. Everything else (arrays of + /// lookup values, array arguments, errors) goes to the library function. + pub(super) fn xlookup(&mut self, args: &[Expr]) -> Ev { + if (3..=6).contains(&args.len()) + && let (Ev::R(look), Ev::R(ret)) = (self.eval(&args[1]), self.eval(&args[2])) + && let ([l], [r]) = (look.as_slice(), ret.as_slice()) + && let Some(spec) = gridcraft_functions::lookup("XMATCH") + { + let key = self.value(&args[0]); + let (l, r) = (*l, *r); + let vertical = l.range.width() == 1 && l.range.height() > 1; + let horizontal = l.range.height() == 1 && l.range.width() > 1; + let same_len = if vertical { r.range.height() == l.range.height() } else { r.range.width() == l.range.width() }; + if !matches!(key, Value::Array(_)) && (vertical || horizontal) && same_len { + let mut xargs = vec![Arg { value: key, from_ref: false }, Arg { value: self.area_value(&l), from_ref: true }]; + // An empty match_mode before a given search_mode is the default (0), not the end. + let given = |i: usize| args.get(i).is_some_and(|e| !matches!(e, Expr::Missing)); + let last = if given(5) { + 5 + } else if given(4) { + 4 + } else { + 3 + }; + for i in 4..=last { + match args.get(i) { + Some(Expr::Missing) | None => xargs.push(Arg { value: Value::Number(0.0), from_ref: false }), + Some(e) => { + let value = self.value(e); + xargs.push(Arg { value, from_ref: false }); + } + } + } + let mut ctx = FnCtx { ev: self, criteria: None, lambda: None }; + return match gridcraft_functions::call(spec, &xargs, &mut ctx) { + Value::Number(p) if p >= 1.0 => { + let k = p as u32 - 1; + let range = if vertical { + RangeRef::new( + CellRef::new(r.range.start.row + k, r.range.start.col), + CellRef::new(r.range.start.row + k, r.range.end.col), + ) + } else { + RangeRef::new( + CellRef::new(r.range.start.row, r.range.start.col + k), + CellRef::new(r.range.end.row, r.range.start.col + k), + ) + }; + Ev::R(vec![Area { sheet: r.sheet, range }]) + } + Value::Error(CellError::NA) if args.get(3).is_some_and(|e| !matches!(e, Expr::Missing)) => self.eval(&args[3]), + Value::Error(e) => err(e), + _ => err(CellError::Value), + }; + } + } + self.builtin("XLOOKUP", args) + } + + pub(super) fn cell_info(&mut self, args: &[Expr]) -> Ev { + let kind = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) { + Some(Ok(t)) => t.to_ascii_lowercase(), + Some(Err(e)) => return err(e), + None => return err(CellError::Value), + }; + let area = match args.get(1).map(|a| self.eval(a)) { + Some(Ev::R(a)) => a.first().copied(), + None => Some(Area { sheet: self.sheet, range: RangeRef::cell(self.at) }), + _ => return err(CellError::Value), + }; + let Some(a) = area else { return err(CellError::Ref) }; + let c = a.range.start; + let wb = self.host.workbook(); + let sheet = wb.sheet(a.sheet); + match kind.as_str() { + "address" => Ev::V(Value::text(format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1))), + "row" => Ev::V(Value::number(c.row as f64 + 1.0)), + "col" => Ev::V(Value::number(c.col as f64 + 1.0)), + "contents" => Ev::V(self.host.cell_value(a.sheet, c)), + "type" => { + let v = self.host.cell_value(a.sheet, c); + Ev::V(Value::text(match v { + Value::Empty => "b", + Value::Text(_) => "l", + _ => "v", + })) + } + "width" => Ev::V(Value::number(sheet.map_or(8.43, |s| gridcraft_model::points_to_chars(s.col_width(c.col) as f64)).round())), + // Excel's `/[]`, which the classic sheet-name formula splits on + // the `]`. Empty until the workbook has a file of its own, as in Excel (#1489). + "filename" => Ev::V(Value::text(match &wb.source_path { + Some(file) => { + let name = file.file_name().unwrap_or_default().to_string_lossy(); + let on = sheet.map_or("", |s| s.name.as_str()); + file.parent().unwrap_or(std::path::Path::new("")).join(format!("[{name}]{on}")).to_string_lossy().into_owned() + } + None => String::new(), + })), + "sheetname" => Ev::V(Value::text(sheet.map(|s| s.name.clone()).unwrap_or_default())), + "protect" => Ev::V(Value::number(if sheet.is_some_and(|s| wb.styles.get(s.style_id(c)).protection.locked) { 1.0 } else { 0.0 })), + "format" => { + let code = sheet.map(|s| wb.styles.get(s.style_id(c)).num_fmt.as_str().to_string()).unwrap_or_default(); + Ev::V(Value::text(cell_format_code(&code))) + } + "color" | "parentheses" => Ev::V(Value::Number(0.0)), + "prefix" => Ev::V(Value::text("")), + _ => err(CellError::Value), + } + } + + pub(super) fn subtotal(&mut self, name: &str, args: &[Expr]) -> Ev { + // SUBTOTAL needs function_num and ref1; AGGREGATE needs function_num, options and ref1. + let min_args = if name == "AGGREGATE" { 3 } else { 2 }; + if args.len() < min_args { + return err(CellError::Value); + } + let code = match self.arg_num(args, 0, 0.0) { + Ok(n) => n.trunc() as u32, + Err(e) => return err(e), + }; + let (func, options, rest) = if name == "AGGREGATE" { + let opt = match self.arg_num(args, 1, 0.0) { + Ok(n) => n.trunc() as u32, + Err(e) => return err(e), + }; + (code, opt, &args[2..]) + } else { + let (f, ignore_hidden) = if code > 100 { (code - 100, true) } else { (code, false) }; + (f, if ignore_hidden { 5 } else { 0 }, &args[1..]) + }; + if !(1..=19).contains(&func) || (name == "SUBTOTAL" && func > 11) { + return err(CellError::Value); + } + let skip_hidden = matches!(options, 1 | 3 | 5 | 7); + // SUBTOTAL leaves out rows a filter hides whatever the function number (Microsoft's + // SUBTOTAL documentation); 101-111 also leave out rows hidden by hand. + let skip_filtered = name == "SUBTOTAL"; + let skip_errors = matches!(options, 2 | 3 | 6 | 7); + // SUBTOTAL always leaves out nested SUBTOTAL/AGGREGATE cells (101-111 too); AGGREGATE does so for options 0-3. + let skip_nested = name == "SUBTOTAL" || options <= 3; + let mut values = Vec::new(); + let mut k = None; + let refs = if name == "AGGREGATE" && func >= 14 { &rest[..1.min(rest.len())] } else { rest }; + if name == "AGGREGATE" && func >= 14 { + k = rest.get(1).map(|e| self.value(e)); + } + // Every cell visited (even one skipped as hidden, nested or an error) and every value + // counts against one budget for the whole call. All arguments are evaluated (references + // stay lazy) and charged before any cell is read: a value stored in XFD1048576 makes + // `A:XFD` trim to the whole sheet, ~17 billion cells (#2175). + enum Input { + Cells(usize, RangeRef), + Values(Value), + } + let mut inputs = Vec::new(); + let mut budget = MAX_CELLS; + for e in refs { + match self.eval(e) { + Ev::R(areas) => { + for a in areas { + let range = self.trim(&a); + budget = match budget.checked_sub(range.count()) { + Some(left) => left, + None => return err(CellError::Num), + }; + inputs.push(Input::Cells(a.sheet, range)); + } + } + Ev::V(v) => { + let n = match &v { + Value::Array(a) => u64::try_from(a.data.len()).unwrap_or(u64::MAX), + _ => 1, + }; + budget = match budget.checked_sub(n) { + Some(left) => left, + None => return err(CellError::Num), + }; + inputs.push(Input::Values(v)); + } + Ev::L(_) => return err(CellError::Value), + } + } + for input in inputs { + match input { + Input::Cells(sheet, range) => { + for c in range.iter() { + let (hidden, nested) = { + let wb = self.host.workbook(); + let s = wb.sheet(sheet); + let hidden = + s.is_some_and(|s| if skip_hidden { s.is_row_hidden(c.row) } else { skip_filtered && s.is_row_filtered(c.row) }); + let nested = skip_nested + && s.and_then(|s| s.cell(c)).and_then(|cell| cell.formula.as_ref()).is_some_and(|f| { + let u = f.text.to_ascii_uppercase(); + u.contains("SUBTOTAL(") || u.contains("AGGREGATE(") + }); + (hidden, nested) + }; + if hidden || nested { + continue; + } + let v = self.host.cell_value(sheet, c); + if skip_errors && v.is_error() { + continue; + } + values.push(v); + } + } + Input::Values(Value::Array(a)) => values.extend(a.data.iter().filter(|v| !(skip_errors && v.is_error())).cloned()), + Input::Values(v) => values.push(v), + } + } + if let Some(k) = k { + return Ev::V(gridcraft_functions::aggregate_values_k(func, &values, &k)); + } + Ev::V(gridcraft_functions::aggregate_values(func, &values)) + } +} diff --git a/crates/calc/src/eval/special.rs b/crates/calc/src/eval/special.rs new file mode 100644 index 0000000000..0151ea2f9a --- /dev/null +++ b/crates/calc/src/eval/special.rs @@ -0,0 +1,165 @@ +use super::{Area, BinOp, Ev, Expr, Reference, SheetSel, Value, Workbook}; +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; + +/// SUMIF and AVERAGEIF with a sum range: Excel sizes the sum range like the criteria range. +pub(super) fn resizes_sum_range(name: &str, args: usize) -> bool { + args == 3 && matches!(name, "SUMIF" | "AVERAGEIF") +} + +/// Height and width of a single-area reference or an array argument. +pub(super) fn ev_shape(ev: &Ev) -> Option<(u32, u32)> { + match ev { + Ev::R(areas) => match areas.as_slice() { + [a] => Some((a.range.height(), a.range.width())), + _ => None, + }, + Ev::V(Value::Array(a)) => Some((u32::try_from(a.rows).unwrap_or(u32::MAX), u32::try_from(a.cols).unwrap_or(u32::MAX))), + Ev::V(_) => Some((1, 1)), + Ev::L(_) => None, + } +} + +/// The range SUMIF/AVERAGEIF add up: from the sum range's top-left cell, as many rows and columns +/// as the criteria range (`height` × `width`), cut off at the sheet's edge. +pub fn resized_sum_range(sum: RangeRef, height: u32, width: u32) -> RangeRef { + let row = sum.start.row.saturating_add(height.saturating_sub(1)).min(MAX_ROWS - 1); + let col = sum.start.col.saturating_add(width.saturating_sub(1)).min(MAX_COLS - 1); + RangeRef::new(sum.start, CellRef::new(row, col)) +} + +/// Collects the static references of an expression with their sheets resolved; `dynamic` is +/// set when the formula uses INDIRECT/OFFSET/names/tables whose targets can change. +pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec, bool) { + let mut out = Vec::new(); + let mut dynamic = false; + let push = |out: &mut Vec, r: &Reference, range: RangeRef| match &r.sheet { + SheetSel::Current => out.push(Area { sheet, range }), + SheetSel::Named(n) => { + if let Some(i) = wb.sheet_index(n) { + out.push(Area { sheet: i, range }); + } + } + SheetSel::Span(a, b) => { + if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) { + for s in i.min(j)..=i.max(j) { + out.push(Area { sheet: s, range }); + } + } + } + }; + e.walk(&mut |x| match x { + Expr::Ref(r) => push(&mut out, r, r.range()), + // The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when + // the criteria range's size isn't known statically, recalculate the formula every time. + Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) { + (Some(Expr::Ref(c)), Some(Expr::Ref(s))) => { + let (crit, sum) = (c.range(), s.range()); + push(&mut out, s, resized_sum_range(sum, crit.height(), crit.width())); + } + (_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {} + _ => dynamic = true, + }, + Expr::Call(n, _) + if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") => + { + dynamic = true + } + Expr::Name(_) | Expr::Struct(_) => dynamic = true, + Expr::Call(n, _) if gridcraft_functions::lookup(n).is_none() && !is_special(n) => dynamic = true, + // A range ending in a function's result (`A1:INDEX(B1:B9,n)`) covers the cells between + // the references inside it, not only those references. + Expr::Binary(BinOp::Range, a, b) if !matches!((&**a, &**b), (Expr::Ref(_), Expr::Ref(_))) => { + let mut inner = precedents(wb, sheet, a).0; + inner.extend(precedents(wb, sheet, b).0); + let mut boxes: Vec = Vec::new(); + for area in inner { + match boxes.iter_mut().find(|x| x.sheet == area.sheet) { + Some(x) => x.range = x.range.union(&area.range), + None => boxes.push(area), + } + } + out.extend(boxes); + } + _ => {} + }); + (out, dynamic) +} + +fn is_special(n: &str) -> bool { + matches!( + n, + "IF" | "IFS" + | "IFERROR" + | "IFNA" + | "CHOOSE" + | "SWITCH" + | "ROW" + | "COLUMN" + | "ROWS" + | "COLUMNS" + | "AREAS" + | "ISREF" + | "ISFORMULA" + | "FORMULATEXT" + | "SHEET" + | "SHEETS" + | "OFFSET" + | "INDIRECT" + | "INDEX" + | "CELL" + | "TRIMRANGE" + | "SUBTOTAL" + | "AGGREGATE" + | "TEXT" + | "LET" + | "LAMBDA" + | "ISOMITTED" + | "MAP" + | "REDUCE" + | "SCAN" + | "BYROW" + | "BYCOL" + | "MAKEARRAY" + ) +} + +/// Names of functions the evaluator implements itself (merged into the function list for UI). +pub const SPECIAL_FUNCTIONS: &[&str] = &[ + "IF", + "IFS", + "IFERROR", + "IFNA", + "CHOOSE", + "SWITCH", + "ROW", + "COLUMN", + "ROWS", + "COLUMNS", + "AREAS", + "ISREF", + "ISFORMULA", + "FORMULATEXT", + "SHEET", + "SHEETS", + "OFFSET", + "INDIRECT", + "INDEX", + "CELL", + "TRIMRANGE", + "SUBTOTAL", + "AGGREGATE", + "TEXT", + "LET", + "LAMBDA", + "ISOMITTED", + "MAP", + "REDUCE", + "SCAN", + "BYROW", + "BYCOL", + "MAKEARRAY", +]; + +pub fn is_known_function(n: &str) -> bool { + is_special(&n.to_ascii_uppercase()) || gridcraft_functions::lookup(n).is_some() +} diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e66494..63ac533def 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -10,362 +10,22 @@ //! and the formulas that read one are evaluated again until the loop settles //! (`PassHost::iterate_loops`). -use std::collections::{BTreeSet, VecDeque}; -use std::hash::{BuildHasherDefault, Hasher}; - -/// A fast, non-cryptographic hasher for cell keys (FxHash-style multiply-rotate). -#[derive(Default, Clone, Copy)] -pub struct FxHasher(u64); - -impl Hasher for FxHasher { - fn finish(&self) -> u64 { - self.0 - } - fn write(&mut self, bytes: &[u8]) { - for b in bytes { - self.write_u64(*b as u64); - } - } - fn write_u64(&mut self, i: u64) { - self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); - } - fn write_u32(&mut self, i: u32) { - self.write_u64(i as u64); - } - fn write_usize(&mut self, i: usize) { - self.write_u64(i as u64); - } -} - -type HashMap = std::collections::HashMap>; -type HashSet = std::collections::HashSet>; +use std::collections::VecDeque; use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; use gridcraft_formula::Expr; use gridcraft_model::{CalcMode, Workbook}; -use crate::eval::{Area, Evaluator, Host, precedents, stack_position}; +use crate::eval::{Evaluator, Host, precedents, stack_position}; -pub type Key = (usize, CellRef); +mod graph; +mod pass_host; -#[derive(Clone, Debug, Default)] -struct Node { - areas: Vec, - dynamic: bool, -} - -/// Ranges wider than this many columns go to the per-sheet wide index instead of per-column ones. -const WIDE: u32 = 64; - -/// Insertions an [`Intervals`] keeps aside (scanned by every query) before merging them in. -const PENDING: usize = 32; - -/// Formulas a formula may calculate on demand one inside the other (each needing one another's -/// value before it is done). Each level takes stack, so a chain deeper than this is suspended and -/// calculated from the top instead (see [`PassHost::calculate`]): long dependency chains calculate -/// whatever order they come in, with bounded stack. -const MAX_NESTED: usize = 64; - -/// Formula evaluations iterative calculation may spend on one recalculation (passes × formulas -/// evaluated again), however high Maximum Iterations is. -const MAX_ITERATION_WORK: usize = 10_000_000; - -/// Row intervals `[r0, r1]`, each with a payload, answering "which intervals overlap rows -/// `a..=b`?" in O(log n + k). -/// -/// The intervals are sorted by start with an implicit segment tree of their largest end, so a query -/// only descends into subtrees that hold a match. Removals mark entries dead (re-inserting one -/// revives it); insertions wait in a small sorted set. [`Intervals::settle`] merges them and drops -/// dead entries once either grows, so mutations cost O(log n) amortised. -#[derive(Clone, Debug)] -struct Intervals { - /// Sorted, without duplicates. - items: Vec<(u32, u32, T)>, - dead: Vec, - dead_count: usize, - /// Segment tree over `items`: node `i` has children `2i` and `2i + 1`, leaves start at - /// `max_end.len() / 2`. Each node holds the largest end below it (dead entries included). - max_end: Vec, - /// Inserted since the last merge. - pending: BTreeSet<(u32, u32, T)>, -} - -impl Default for Intervals { - fn default() -> Self { - Intervals { items: Vec::new(), dead: Vec::new(), dead_count: 0, max_end: Vec::new(), pending: BTreeSet::new() } - } -} - -impl Intervals { - fn is_empty(&self) -> bool { - self.items.len() == self.dead_count && self.pending.is_empty() - } - - fn insert(&mut self, r0: u32, r1: u32, t: T) { - let it = (r0, r1, t); - if let Ok(i) = self.items.binary_search(&it) { - if let Some(d) = self.dead.get_mut(i) - && *d - { - *d = false; - self.dead_count -= 1; - } - return; - } - self.pending.insert(it); - } - - fn remove(&mut self, r0: u32, r1: u32, t: T) { - let it = (r0, r1, t); - if let Ok(i) = self.items.binary_search(&it) { - if let Some(d) = self.dead.get_mut(i) - && !*d - { - *d = true; - self.dead_count += 1; - } - return; - } - self.pending.remove(&it); - } - - /// Merges pending insertions and drops dead entries when there are enough of them. - fn settle(&mut self) { - if self.pending.len() <= PENDING && self.dead_count <= (self.items.len() / 2).max(PENDING) { - return; - } - let mut all: Vec<(u32, u32, T)> = Vec::with_capacity(self.items.len() - self.dead_count + self.pending.len()); - all.extend(self.items.iter().zip(&self.dead).filter(|(_, d)| !**d).map(|(it, _)| *it)); - all.extend(std::mem::take(&mut self.pending)); - // Two sorted runs: the stable sort merges them in linear time. - all.sort(); - all.dedup(); - let size = all.len().next_power_of_two(); - let mut max_end = vec![0; 2 * size]; - if let Some(leaves) = max_end.get_mut(size..) { - for (slot, it) in leaves.iter_mut().zip(&all) { - *slot = it.1; - } - } - for i in (1..size).rev() { - let m = max_end.get(2 * i).copied().unwrap_or(0).max(max_end.get(2 * i + 1).copied().unwrap_or(0)); - if let Some(slot) = max_end.get_mut(i) { - *slot = m; - } - } - self.dead = vec![false; all.len()]; - self.dead_count = 0; - self.items = all; - self.max_end = max_end; - } - - /// Calls `f` for every interval overlapping rows `a..=b` (`r0 <= b && r1 >= a`). Returns the - /// number of tree nodes visited. - fn query(&self, a: u32, b: u32, f: &mut dyn FnMut(&T)) -> usize { - for it in &self.pending { - if it.0 <= b && it.1 >= a { - f(&it.2); - } - } - // Entries before `p` start at or before row `b`. - let p = self.items.partition_point(|it| it.0 <= b); - if p == 0 { - return 0; - } - self.walk(1, 0, self.max_end.len() / 2, p, a, f) - } - - fn walk(&self, node: usize, lo: usize, hi: usize, p: usize, a: u32, f: &mut dyn FnMut(&T)) -> usize { - if lo >= p || self.max_end.get(node).is_none_or(|m| *m < a) { - return 1; - } - if hi - lo <= 1 { - if let (Some(it), Some(false)) = (self.items.get(lo), self.dead.get(lo)) - && it.1 >= a - { - f(&it.2); - } - return 1; - } - let mid = lo + (hi - lo) / 2; - 1 + self.walk(2 * node, lo, mid, p, a, f) + self.walk(2 * node + 1, mid, hi, p, a, f) - } -} - -#[derive(Clone, Debug, Default)] -pub struct Graph { - nodes: HashMap, - /// single cell → dependents - cell_deps: HashMap>, - /// (sheet, col) → row intervals of the ranges (up to `WIDE` columns) that cover the column - col_deps: HashMap<(usize, u32), Intervals>, - /// sheet → row intervals of wider ranges, with their columns: (first, last, dependent) - wide_deps: HashMap>, - dynamic: HashSet, - /// Range indexes changed since the last [`Graph::settle`]. - unsettled_cols: HashSet<(usize, u32)>, - unsettled_wide: HashSet, -} - -impl Graph { - pub fn len(&self) -> usize { - self.nodes.len() - } - pub fn is_empty(&self) -> bool { - self.nodes.is_empty() - } - - /// Index entries of a formula's precedents, without duplicates: single cells, column - /// intervals and wide ranges. - fn entries(areas: &[Area]) -> (Vec, Vec<(usize, u32, u32, u32)>, Vec<(usize, RangeRef)>) { - let (mut cells, mut cols, mut wide) = (Vec::new(), Vec::new(), Vec::new()); - for a in areas { - if a.range.is_single() { - cells.push((a.sheet, a.range.start)); - } else if a.range.width() > WIDE { - wide.push((a.sheet, a.range)); - } else { - for c in a.range.start.col..=a.range.end.col { - cols.push((a.sheet, c, a.range.start.row, a.range.end.row)); - } - } - } - cells.sort_unstable(); - cells.dedup(); - cols.sort_unstable(); - cols.dedup(); - wide.sort_unstable_by_key(|(s, r)| (*s, r.start, r.end)); - wide.dedup(); - (cells, cols, wide) - } - - fn insert(&mut self, k: Key, node: Node) { - self.remove(k); - let (cells, cols, wide) = Self::entries(&node.areas); - for c in cells { - self.cell_deps.entry(c).or_default().insert(k); - } - for (s, c, r0, r1) in cols { - self.col_deps.entry((s, c)).or_default().insert(r0, r1, k); - self.unsettled_cols.insert((s, c)); - } - for (s, r) in wide { - self.wide_deps.entry(s).or_default().insert(r.start.row, r.end.row, (r.start.col, r.end.col, k)); - self.unsettled_wide.insert(s); - } - if node.dynamic { - self.dynamic.insert(k); - } - self.nodes.insert(k, node); - } - - fn remove(&mut self, k: Key) { - let Some(old) = self.nodes.remove(&k) else { return }; - let (cells, cols, wide) = Self::entries(&old.areas); - for c in cells { - if let Some(v) = self.cell_deps.get_mut(&c) { - v.remove(&k); - if v.is_empty() { - self.cell_deps.remove(&c); - } - } - } - for (s, c, r0, r1) in cols { - if let Some(v) = self.col_deps.get_mut(&(s, c)) { - v.remove(r0, r1, k); - self.unsettled_cols.insert((s, c)); - } - } - for (s, r) in wide { - if let Some(v) = self.wide_deps.get_mut(&s) { - v.remove(r.start.row, r.end.row, (r.start.col, r.end.col, k)); - self.unsettled_wide.insert(s); - } - } - self.dynamic.remove(&k); - } - - /// Tidies the range indexes changed by `insert`/`remove` (queries stay correct without it, - /// just slower). - fn settle(&mut self) { - for key in std::mem::take(&mut self.unsettled_cols) { - if let Some(v) = self.col_deps.get_mut(&key) { - v.settle(); - if v.is_empty() { - self.col_deps.remove(&key); - } - } - } - for key in std::mem::take(&mut self.unsettled_wide) { - if let Some(v) = self.wide_deps.get_mut(&key) { - v.settle(); - if v.is_empty() { - self.wide_deps.remove(&key); - } - } - } - } - - /// Formulas that read cell `c` of `sheet`. - pub fn dependents(&self, sheet: usize, c: CellRef, out: &mut Vec) { - if let Some(v) = self.cell_deps.get(&(sheet, c)) { - out.extend(v.iter().copied()); - } - if let Some(v) = self.col_deps.get(&(sheet, c.col)) { - v.query(c.row, c.row, &mut |k| out.push(*k)); - } - if let Some(v) = self.wide_deps.get(&sheet) { - v.query(c.row, c.row, &mut |(c0, c1, k)| { - if *c0 <= c.col && c.col <= *c1 { - out.push(*k); - } - }); - } - } - - /// Formulas that read any cell of `range` (a formula can be listed more than once). - pub fn dependents_of_range(&self, sheet: usize, range: RangeRef, out: &mut Vec) { - if range.count() <= 4096 { - for c in range.iter() { - if let Some(v) = self.cell_deps.get(&(sheet, c)) { - out.extend(v.iter().copied()); - } - } - } else { - for ((s, c), v) in &self.cell_deps { - if *s == sheet && range.contains(*c) { - out.extend(v.iter().copied()); - } - } - } - let (r0, r1) = (range.start.row, range.end.row); - if (range.width() as usize) <= self.col_deps.len() { - for col in range.start.col..=range.end.col { - if let Some(v) = self.col_deps.get(&(sheet, col)) { - v.query(r0, r1, &mut |k| out.push(*k)); - } - } - } else { - for ((s, col), v) in &self.col_deps { - if *s == sheet && range.start.col <= *col && *col <= range.end.col { - v.query(r0, r1, &mut |k| out.push(*k)); - } - } - } - if let Some(v) = self.wide_deps.get(&sheet) { - v.query(r0, r1, &mut |(c0, c1, k)| { - if *c0 <= range.end.col && range.start.col <= *c1 { - out.push(*k); - } - }); - } - } - - /// Precedent areas of a formula cell (for Trace Precedents). - pub fn precedents_of(&self, k: Key) -> Vec { - self.nodes.get(&k).map(|n| n.areas.clone()).unwrap_or_default() - } -} +#[cfg(test)] +use graph::Intervals; +pub use graph::{FxHasher, Graph, Key}; +use graph::{HashMap, HashSet, Node}; +use pass_host::{PassHost, spills_as_before}; /// Calculation state kept beside a workbook. #[derive(Clone, Debug)] @@ -385,548 +45,6 @@ impl Default for Calc { } } -struct PassHost<'a> { - wb: &'a Workbook, - exprs: &'a HashMap>, - results: HashMap, - pending: HashSet, - in_progress: HashSet, - /// New spills found during the pass: anchor → array. - spills: HashMap>, - /// Used range per sheet: the workbook doesn't change during a pass, and working it out walks - /// every row, so once per sheet rather than once per range read. - used: HashMap>, - rng: &'a mut u64, - now: f64, - cycle: bool, - cycles: Vec, - depth: usize, - /// A formula needed at [`MAX_NESTED`] levels deep: the evaluations in progress are abandoned - /// and it is calculated first. - suspend: Option, - /// Formulas whose evaluation was abandoned for another one, to be calculated again after it. - /// They all need it, so reading one of them while it is calculated is a circular reference, - /// as reading a formula in progress is. - waiting: HashSet, - /// The formulas abandoned since the last suspension. - abandoned: Vec, - /// Other formulas read at [`MAX_NESTED`] levels deep by the evaluations being abandoned. They - /// are calculated along with the suspended one, rather than one per restart (a wide range - /// read at the limit would restart the abandoned evaluations once per cell in it). - also: Vec, - /// Suspensions so far (tests check that a wide read at the limit needs one, not one per cell). - #[cfg(test)] - suspensions: usize, - /// The formulas in `cycles`. - cycle_seen: HashSet, - /// Iterative calculation: a circular reference reads the cell's previous value instead of - /// giving `#CIRC!`. - iterate: bool, - /// Values from the previous iteration; cells not in it read their stored value. - prev: HashMap, - /// Formulas being evaluated, innermost last (kept only when iterating). - stack: Vec, - /// Formulas found on a circular reference (when iterating). - members: HashSet, - /// Results that read a previous value, directly or through other formulas. - tainted: HashSet, - /// Whether the formula being evaluated has read a previous value. - taint: bool, - /// `stack_position()` where the outermost formula being calculated started. - stack_top: usize, - /// Whether an evaluation ran past the stack budget since the innermost formula started. - out_of_stack: bool, -} - -impl<'a> PassHost<'a> { - fn new(wb: &'a Workbook, exprs: &'a HashMap>, rng: &'a mut u64, now: f64) -> Self { - PassHost { - wb, - exprs, - results: HashMap::with_capacity_and_hasher(exprs.len(), Default::default()), - pending: exprs.keys().copied().collect(), - in_progress: HashSet::default(), - spills: HashMap::default(), - used: HashMap::default(), - rng, - now, - cycle: false, - cycles: vec![], - depth: 0, - suspend: None, - waiting: HashSet::default(), - abandoned: Vec::new(), - also: Vec::new(), - #[cfg(test)] - suspensions: 0, - cycle_seen: HashSet::default(), - iterate: false, - prev: HashMap::default(), - stack: Vec::new(), - members: HashSet::default(), - tainted: HashSet::default(), - taint: false, - stack_top: 0, - out_of_stack: false, - } - } -} - -/// 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 another formula's spill (unless that formula is -/// recalculated in this pass, and so may spill elsewhere now). -fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool { - let Some(sh) = host.wb.sheet(sheet) else { return false }; - let end = - CellRef::new(anchor.row.saturating_add((a.rows as u32).saturating_sub(1)), anchor.col.saturating_add((a.cols as u32).saturating_sub(1))); - let range = RangeRef::new(anchor, end); - let own = sh.spill_ranges.get(&anchor); - let spilled_over = |c: CellRef| { - !own.is_some_and(|o| o.contains(c)) - && sh.spill_ranges.iter().any(|(o, r)| *o != anchor && r.contains(c) && !host.exprs.contains_key(&(sheet, *o))) - }; - end.row >= gridcraft_core::MAX_ROWS - || end.col >= gridcraft_core::MAX_COLS - || sh.merges.iter().any(|m| m.intersects(&range)) - || 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)) -} - -/// Whether `arr`, anchored at `anchor`, would spill exactly what the sheet already holds over -/// `range`: the same area, nothing new in the way, and the same values. -fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, arr: &Array) -> bool { - let end = - 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)) - && !sheet.tables.iter().any(|t| t.range.contains(anchor)) - && range - .iter() - .enumerate() - .all(|(i, c)| c == anchor || (!sheet.cells.has(c) && sheet.spill.get(&c) == Some(arr.data.get(i).unwrap_or(&Value::Empty)))) -} - -impl PassHost<'_> { - /// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would - /// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is - /// calculated from here, then the suspended ones again (reading the results kept so far). - fn calculate(&mut self, k: Key) { - // Formulas to calculate, innermost last, each with the ones abandoned to calculate the - // next. - let mut work: Vec<(Key, Vec)> = vec![(k, Vec::new())]; - while let Some(&(top, _)) = work.last() { - self.compute(top); - match self.suspend.take() { - Some(next) => { - #[cfg(test)] - { - self.suspensions += 1; - } - let held = std::mem::take(&mut self.abandoned); - self.waiting.extend(held.iter().copied()); - if let Some(entry) = work.last_mut() { - entry.1 = held; - } - // The other formulas read at the limit are calculated after `next`, before the - // held evaluations restart. Each has nothing held of its own, so the held ones - // are released only when the last of them is done. - let mut seen: HashSet = HashSet::default(); - seen.insert(next); - for s in std::mem::take(&mut self.also) { - if seen.insert(s) { - work.push((s, Vec::new())); - } - } - work.push((next, Vec::new())); - } - None => { - work.pop(); - if let Some(entry) = work.last_mut() { - for a in entry.1.drain(..) { - self.waiting.remove(&a); - } - } - } - } - } - } - - fn compute(&mut self, k: Key) -> Value { - if let Some(v) = self.results.get(&k) { - let v = v.clone(); - if self.iterate && self.tainted.contains(&k) { - self.taint = true; - } - return v; - } - let Some(expr) = self.exprs.get(&k) else { - return self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(); - }; - if self.suspend.is_some() { - // Unwinding to `calculate`: the value is thrown away. A formula read at the limit is - // calculated with the suspended one, so the evaluations are not restarted for each. - if self.depth >= MAX_NESTED && !self.in_progress.contains(&k) && !self.waiting.contains(&k) { - self.also.push(k); - } - return Value::Error(CellError::Calc); - } - if self.in_progress.contains(&k) || self.waiting.contains(&k) { - self.cycle = true; - if self.iterate { - return self.circular_read(k); - } - // Once each, though a suspended evaluation meets it again. - if self.cycle_seen.insert(k) { - self.cycles.push(k); - } - return Value::Error(CellError::Circ); - } - if self.depth >= MAX_NESTED { - self.suspend = Some(k); - return Value::Error(CellError::Calc); - } - if self.depth == 0 { - self.stack_top = stack_position(); - } - self.in_progress.insert(k); - self.depth += 1; - let outer_taint = std::mem::replace(&mut self.taint, false); - if self.iterate { - self.stack.push(k); - } - let expr = std::sync::Arc::clone(expr); - let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false); - let v = { - let mut ev = Evaluator::new(self, k.0, k.1); - ev.value(&expr) - }; - let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack); - if out_of_stack && self.depth > 1 && self.suspend.is_none() { - // It ran out of the stack left below the formulas that read it: it is calculated - // from the top instead, as a formula needed at `MAX_NESTED` levels deep is. - self.suspend = Some(k); - self.depth -= 1; - self.in_progress.remove(&k); - if self.iterate { - self.stack.pop(); - } - self.taint = outer_taint; - return Value::Error(CellError::Calc); - } - if self.suspend.is_some() { - // Abandoned: `calculate` evaluates this formula again once the one it needs is done. - self.depth -= 1; - self.in_progress.remove(&k); - self.abandoned.push(k); - if self.iterate { - self.stack.pop(); - } - self.taint = outer_taint; - return Value::Error(CellError::Calc); - } - // A legacy array formula fills the range it was entered in. - let legacy = self.wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.as_ref()).and_then(|f| f.array); - let v = match legacy { - Some(range) => fit_to_range(v, range), - None => v, - }; - self.depth -= 1; - self.in_progress.remove(&k); - self.pending.remove(&k); - if self.iterate { - self.stack.pop(); - if self.taint { - self.tainted.insert(k); - } else { - self.tainted.remove(&k); - } - } - self.taint |= outer_taint; - // A blank cell shows as 0 in a formula's result, inside an array as well (`=A1:A3`, - // FILTER or SORT of a range with blanks). GROUPBY and PIVOTBY lay out blank cells - // of their own, which stay blank. - let keep_blanks = matches!(&*expr, Expr::Call(n, _) if matches!(n.as_str(), "GROUPBY" | "PIVOTBY")); - let v = match v { - Value::Array(a) => { - let a = if keep_blanks || !a.data.iter().any(|x| matches!(x, Value::Empty)) { - a - } else { - let data = a.data.iter().map(|x| if matches!(x, Value::Empty) { Value::Number(0.0) } else { x.clone() }).collect(); - Array::new(a.rows, a.cols, data).map(std::sync::Arc::new).unwrap_or(a) - }; - // A dynamic-array formula anchors a spill range even while its result is one - // value -- a FILTER matching one row, a SORT or UNIQUE over one item -- so `C1#` - // is the 1 x 1 range and `ROWS(C1#)` is 1, as in Excel (#1491). A formula that - // returns a scalar never reaches this arm, so it does not become an anchor. - self.spills.insert(k, a.clone()); - a.data.first().cloned().unwrap_or_default() - } - Value::Empty => Value::Number(0.0), - v => v, - }; - // An array that can't spill is #SPILL! for the formulas evaluated after it in this pass too. - let v = match self.spills.get(&k) { - Some(a) if spill_blocked(self, k, a) => { - self.spills.remove(&k); - Value::Error(CellError::Spill) - } - _ => v, - }; - self.results.insert(k, v.clone()); - v - } - - /// A formula's previous value for iterative calculation: from the last iteration, else the - /// value it shows. Blank, and the `#CIRC!` of a loop calculated with iteration off, are 0. - fn previous(&self, k: Key) -> Value { - let v = match self.prev.get(&k) { - Some(v) => v.clone(), - None => self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(), - }; - if matches!(v, Value::Empty | Value::Error(CellError::Circ)) { Value::Number(0.0) } else { v } - } - - /// Reading `k` while it is being evaluated, with iterative calculation on: its previous value. - /// The formulas around the loop are the ones whose changes decide when iteration stops. - fn circular_read(&mut self, k: Key) -> Value { - self.taint = true; - match self.stack.iter().rposition(|s| *s == k) { - Some(i) => self.members.extend(self.stack.get(i..).unwrap_or_default().iter().copied()), - // Too deep to follow: the formula itself is watched. - None => { - self.members.insert(k); - } - } - self.previous(k) - } - - /// Iterative calculation, after a first pass over `order` that met circular references. The - /// formulas that read a previous value (the loops and what depends on them) are evaluated - /// again in the same order, each pass starting from the last one's values and reading what it - /// has already produced (Gauss-Seidel), until no formula on a loop changes by `max_change` or - /// more, or after `max_iterations` passes in all. Returns the number of passes. - fn iterate_loops(&mut self, order: &[Key], max_iterations: u32, max_change: f64) -> u32 { - let again: Vec = order.iter().copied().filter(|k| self.tainted.contains(k)).collect(); - let set: HashSet = again.iter().copied().collect(); - // Bounds the work whatever Maximum Iterations says. - let max_passes = u32::try_from(MAX_ITERATION_WORK / again.len().max(1)).unwrap_or(u32::MAX).max(1); - let mut passes = 1u32; - while passes < max_iterations.min(max_passes) && !self.converged(max_change) { - self.prev = again.iter().filter_map(|k| self.results.remove(k).map(|v| (*k, v))).collect(); - self.pending = set.clone(); - self.spills.retain(|a, _| !set.contains(a)); - for k in &again { - self.calculate(*k); - } - passes += 1; - } - passes - } - - /// Whether every formula on a loop changed by less than `max_change` in the last pass (text, - /// logical and error values: not at all). - fn converged(&self, max_change: f64) -> bool { - self.members.iter().all(|k| { - let Some(new) = self.results.get(k) else { return true }; - match (new, &self.previous(*k)) { - (Value::Number(a), Value::Number(b)) => { - let d = (a - b).abs(); - d < max_change || d == 0.0 - } - (new, old) => new == old, - } - }) - } -} - -/// A legacy (Ctrl+Shift+Enter) array formula's result fitted to the range it was entered in, as -/// Excel does: a single row or column repeats across the range, a single value fills it, cells -/// past the result show `#N/A`, and a result larger than the range is cut off. -fn fit_to_range(v: Value, range: RangeRef) -> Value { - if range.count() > crate::eval::MAX_CELLS { - return Value::Error(CellError::Num); - } - let (h, w) = (range.height() as usize, range.width() as usize); - let Value::Array(a) = v else { - return if h * w == 1 { v } else { Array::new(h, w, vec![v; h * w]).map(Value::from).unwrap_or(Value::Error(CellError::Value)) }; - }; - if h * w == 1 { - return a.data.first().cloned().unwrap_or_default(); - } - let mut data = Vec::with_capacity(h * w); - for r in 0..h { - for c in 0..w { - let (r, c) = (if a.rows == 1 { 0 } else { r }, if a.cols == 1 { 0 } else { c }); - data.push(a.get(r, c).cloned().unwrap_or(Value::Error(CellError::NA))); - } - } - Array::new(h, w, data).map(Value::from).unwrap_or(Value::Error(CellError::Value)) -} - -impl Host for PassHost<'_> { - fn workbook(&self) -> &Workbook { - self.wb - } - fn stack_top(&self) -> Option { - (self.depth > 1).then_some(self.stack_top) - } - fn stack_exhausted(&mut self) { - self.out_of_stack = true; - } - fn spill_range(&mut self, sheet: usize, anchor: CellRef) -> Option { - let k = (sheet, anchor); - if !(self.pending.contains(&k) || self.results.contains_key(&k)) { - return self.wb.sheet(sheet)?.spill_ranges.get(&anchor).copied(); - } - // Recalculated in this pass: its new array, unless something blocks it (#SPILL!). - self.compute(k); - let arr = self.spills.get(&k)?; - let end = CellRef::new( - anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), - anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)), - ); - let range = RangeRef::new(anchor, end); - let sh = self.wb.sheet(sheet)?; - let blocked = end.row >= gridcraft_core::MAX_ROWS - || end.col >= gridcraft_core::MAX_COLS - || sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (cell.formula.is_some() || !cell.value.is_empty())) - || sh.merges.iter().any(|m| m.intersects(&range)); - (!blocked).then_some(range) - } - fn cell_value(&mut self, sheet: usize, c: CellRef) -> Value { - let k = (sheet, c); - if self.pending.contains(&k) || self.results.contains_key(&k) { - return self.compute(k); - } - // A cell covered by a spill computed in this pass. - for (anchor, arr) in &self.spills { - if anchor.0 == sheet && c.row >= anchor.1.row && c.col >= anchor.1.col { - let (dr, dc) = ((c.row - anchor.1.row) as usize, (c.col - anchor.1.col) as usize); - if dr < arr.rows && dc < arr.cols { - if self.iterate && self.tainted.contains(anchor) { - self.taint = true; - } - return arr.get(dr, dc).cloned().unwrap_or_default(); - } - } - } - self.wb.sheet(sheet).map(|s| s.value(c)).unwrap_or_default() - } - fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec { - let (h, w) = (range.height() as usize, range.width() as usize); - let mut out = vec![Value::Empty; h * w]; - let Some(sh) = self.wb.sheet(sheet) else { return out }; - // Sparse walk: only stored cells; formula cells that are (or were) dirty go through - // `compute`, constants are copied straight from the store. - let mut formulas: Vec<(usize, CellRef)> = Vec::new(); - for (c, cell) in sh.cells.iter_range(range) { - let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; - if cell.formula.is_some() { - formulas.push((i, c)); - } else if let Some(slot) = out.get_mut(i) { - *slot = cell.value.clone(); - } - } - for (c, v) in sh.spill.range(range.start..=range.end) { - if range.contains(*c) { - let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; - if let Some(slot) = out.get_mut(i) - && slot.is_empty() - { - *slot = v.clone(); - } - } - } - for (i, c) in formulas { - let v = self.cell_value(sheet, c); - if let Some(slot) = out.get_mut(i) { - *slot = v; - } - } - if !self.spills.is_empty() { - let new: Vec<(usize, Value)> = self - .spills - .iter() - .filter(|(a, _)| a.0 == sheet) - .flat_map(|(a, arr)| { - let mut v = Vec::new(); - for r in 0..arr.rows { - for cc in 0..arr.cols { - let c = CellRef::new(a.1.row.saturating_add(r as u32), a.1.col.saturating_add(cc as u32)); - if c != a.1 && range.contains(c) { - v.push(( - (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize, - arr.get(r, cc).cloned().unwrap_or_default(), - )); - } - } - } - v - }) - .collect(); - // Iterating: an array spilled by a formula that read a previous value. - if self.iterate - && self.spills.iter().any(|(a, arr)| { - let end = CellRef::new( - a.1.row.saturating_add((arr.rows as u32).saturating_sub(1)), - a.1.col.saturating_add((arr.cols as u32).saturating_sub(1)), - ); - a.0 == sheet && self.tainted.contains(a) && RangeRef::new(a.1, end).intersects(&range) - }) - { - self.taint = true; - } - for (i, v) in new { - if let Some(slot) = out.get_mut(i) { - *slot = v; - } - } - } - out - } - fn visit_range(&mut self, sheet: usize, range: RangeRef, f: &mut dyn FnMut(&Value) -> bool) -> bool { - let wb = self.wb; - let Some(sh) = wb.sheet(sheet) else { return false }; - // Formula cells first, in row-major order like `range_values`: reading one calculates it - // and the pass remembers the value, so the walk below gets the same value again without - // this method holding any. - for (c, cell) in sh.cells.iter_range(range) { - if cell.formula.is_some() { - let _ = self.cell_value(sheet, c); - } - } - // Spilled values sit between the stored cells (and the formulas just calculated may have - // produced some): leave such blocks to `range_values`. - if self.spills.keys().any(|a| a.0 == sheet) || sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c)) { - return false; - } - for (c, cell) in sh.cells.iter_range(range) { - let go = if cell.formula.is_some() { f(&self.cell_value(sheet, c)) } else { f(&cell.value) }; - if !go { - break; - } - } - true - } - fn used_range(&mut self, sheet: usize) -> Option { - let wb = self.wb; - *self.used.entry(sheet).or_insert_with(|| wb.sheet(sheet).and_then(|s| s.used_range())) - } - fn now_serial(&self) -> f64 { - self.now - } - fn random(&mut self) -> f64 { - // xorshift64* - let mut x = *self.rng; - x ^= x >> 12; - x ^= x << 25; - x ^= x >> 27; - *self.rng = x; - (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64 - } -} - /// Pops one finished component off Tarjan's stack, labelling its nodes with `comp_index`. The /// component is everything up to and including `root`. fn pop_component(stack: &mut Vec, on_stack: &mut [bool], comp: &mut [usize], comp_index: usize, root: usize) { @@ -1017,6 +135,10 @@ impl Calc { if cell.value == Value::Error(CellError::Circ) { circ.push((si, c)); } + } else if cell.py.is_some() { + // A Python cell lays out its kept result, so it is calculated like a formula + // that reads nothing: its spill is blocked and unblocked like a formula's. + self.graph.insert((si, c), Node { areas: Vec::new(), dynamic: false }); } } } @@ -1088,11 +210,29 @@ impl Calc { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); + let py = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.py.as_ref()); + let python = py.is_some(); + // A Python cell whose result (if any) is not an array spills nothing. + let spills = py.and_then(|p| p.result_value()).is_some_and(|v| matches!(v, Value::Array(_))); match formula.and_then(|f| f.expr()) { Some(e) => { let (areas, dynamic) = precedents(wb, k.0, &e); self.graph.insert(k, Node { areas, dynamic }); } + // See `rebuild`: its spill is laid out again from its result when it is calculated. + None if python => { + self.graph.insert(k, Node { areas: Vec::new(), dynamic: false }); + // New code has no result yet: the spill the cell had (its old result's, or a + // formula's) goes, and what read it is recalculated, as for a formula + // replaced by a constant. + if !spills + && let Some(sh) = wb.sheet_mut(k.0) + && let Some(r) = sh.spill_ranges.remove(&k.1) + { + sh.clear_spill(r); + cleared.push((k.0, r)); + } + } None => { self.graph.remove(k); // A formula replaced by a constant (or cleared) takes its spilled values with it. @@ -1220,11 +360,15 @@ impl Calc { exprs.insert(*k, e); } } + let python: HashMap = dirty + .iter() + .filter_map(|k| wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.py.as_ref()).and_then(|p| p.result_value()).map(|v| (*k, v))) + .collect(); let now = self.now(); let mut rng = self.rng; let tp = prof_now(); let (results, spills, cycles) = { - let mut host = PassHost::new(wb, &exprs, &mut rng, now); + let mut host = PassHost::new(wb, &exprs, &mut rng, now).with_python(python); host.iterate = wb.calc.iterative; for k in &dirty { host.calculate(*k); @@ -1249,105 +393,13 @@ impl Calc { self.circular.retain(|k| !evaluated.contains(k)); } self.circular.extend(cycles); - // Write back. - let mut spill_changes: Vec = Vec::new(); - let mut freed: Vec<(usize, RangeRef)> = Vec::new(); - for (k, v) in results { - let Some(sheet) = wb.sheet_mut(k.0) else { continue }; - if let Some(cell) = sheet.cells.get_mut(k.1) - && cell.value != v - { - cell.value = v; - } - } - for k in &dirty { - let new = spills.get(k); - let Some(sheet) = wb.sheet_mut(k.0) else { continue }; - let old = sheet.spill_ranges.get(&k.1).copied(); - if old.is_none() && new.is_none() { - continue; - } - // An array that spills exactly as before changes nothing its dependents read, so - // they aren't queued again. Otherwise two arrays that read each other's spill areas - // queue each other in every round, up to the round limit. - if let (Some(r), Some(arr)) = (old, new) - && spills_as_before(sheet, k.1, r, arr) - { - continue; - } - if let Some(r) = old { - for c in r.iter() { - sheet.spill.remove(&c); - } - sheet.spill_ranges.remove(&k.1); - } - let mut changed_range = old; - if let Some(arr) = new { - let end = CellRef::new(k.1.row.saturating_add(arr.rows as u32 - 1), k.1.col.saturating_add(arr.cols as u32 - 1)); - let range = RangeRef::new(k.1, end); - let blocked = end.row >= gridcraft_core::MAX_ROWS - || end.col >= gridcraft_core::MAX_COLS - || range.iter().any(|c| c != k.1 && (sheet.cells.has(c) || sheet.spill.contains_key(&c))) - || sheet.merges.iter().any(|m| m.intersects(&range)) - || sheet.tables.iter().any(|t| t.range.contains(k.1)); - if blocked { - if let Some(cell) = sheet.cells.get_mut(k.1) { - cell.value = Value::Error(CellError::Spill); - } - // Not blocked while the pass ran (it would have been #SPILL! there), so - // blocked by another array of this pass: the formulas that read this one, - // at its anchor or over the area it would have spilled into, read #SPILL! - // or empty cells now. - let mut deps = Vec::new(); - self.graph.dependents_of_range(k.0, range, &mut deps); - spill_changes.extend(deps.into_iter().filter(|d| d != k)); - } else { - for (i, c) in range.iter().enumerate() { - if c != k.1 { - sheet.spill.insert(c, arr.data.get(i).cloned().unwrap_or_default()); - } - } - sheet.spill_ranges.insert(k.1, range); - changed_range = Some(changed_range.map_or(range, |o| o.union(&range))); - } - } - if let Some(r) = changed_range { - let mut deps = Vec::new(); - self.graph.dependents_of_range(k.0, r, &mut deps); - // Not the anchor itself (that would read its own array), unless its old array - // is gone or partly freed: its new formula may have read the old values, still - // laid out while it was evaluated. - let freed = match (old, sheet.spill_ranges.get(&k.1)) { - (Some(o), Some(n)) => !(n.contains(o.start) && n.contains(o.end)), - (_, None) => true, - (None, Some(_)) => false, - }; - spill_changes.extend(deps.into_iter().filter(|d| d != k || freed)); - } - if let Some(o) = old - && !sheet.spill_ranges.get(&k.1).is_some_and(|n| n.contains(o.start) && n.contains(o.end)) - { - freed.push((k.0, o)); - } - } + let mut spill_changes = self.write_back(wb, &dirty, results, &spills); // Formulas with references only known while evaluating (INDIRECT, OFFSET) may have read // a spill area before it was laid out: they are evaluated once more. if dynamic_again && !spills.is_empty() { dynamic_again = false; spill_changes.extend(self.graph.dynamic.iter().copied()); } - // An area a formula no longer spills over may unblock another formula's array. - for (si, o) in freed { - for &(s, c) in self.graph.nodes.keys() { - if s == si - && c.row <= o.end.row - && c.col <= o.end.col - && wb.sheet(s).is_some_and(|sh| sh.value(c) == Value::Error(CellError::Spill)) - { - spill_changes.push((s, c)); - } - } - } if full { // Everything was already evaluated once; spill dependents need another pass. } @@ -1369,6 +421,105 @@ impl Calc { self.circular.retain(|k| self.graph.nodes.contains_key(k)); } } + + fn write_back( + &mut self, + wb: &mut Workbook, + dirty: &[Key], + results: HashMap, + spills: &HashMap>, + ) -> Vec { + let mut spill_changes = Vec::new(); + let mut freed = Vec::new(); + for (key, value) in results { + let Some(sheet) = wb.sheet_mut(key.0) else { continue }; + if let Some(cell) = sheet.cells.get_mut(key.1) + && cell.value != value + { + cell.value = value; + } + } + for key in dirty { + let new = spills.get(key); + let Some(sheet) = wb.sheet_mut(key.0) else { continue }; + let old = sheet.spill_ranges.get(&key.1).copied(); + if old.is_none() && new.is_none() { + continue; + } + // An unchanged spill does not alter any values its dependents read. + if let (Some(range), Some(array)) = (old, new) + && spills_as_before(sheet, key.1, range, array) + { + continue; + } + if let Some(range) = old { + for cell in range.iter() { + sheet.spill.remove(&cell); + } + sheet.spill_ranges.remove(&key.1); + } + let mut changed_range = old; + if let Some(array) = new { + let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1)); + let range = RangeRef::new(key.1, end); + let blocked = spill_is_blocked(sheet, key.1, range, end); + if blocked { + if let Some(cell) = sheet.cells.get_mut(key.1) { + cell.value = Value::Error(CellError::Spill); + } + let mut blocked_dependents = Vec::new(); + self.graph.dependents_of_range(key.0, range, &mut blocked_dependents); + spill_changes.extend(blocked_dependents.into_iter().filter(|dependent| dependent != key)); + } else { + fill_spill(sheet, key.1, range, array); + changed_range = Some(changed_range.map_or(range, |previous| previous.union(&range))); + } + } + if let Some(range) = changed_range { + let mut dependents = Vec::new(); + self.graph.dependents_of_range(key.0, range, &mut dependents); + let freed_old_range = match (old, sheet.spill_ranges.get(&key.1)) { + (Some(previous), Some(current)) => !(current.contains(previous.start) && current.contains(previous.end)), + (_, None) => true, + (None, Some(_)) => false, + }; + spill_changes.extend(dependents.into_iter().filter(|dependent| dependent != key || freed_old_range)); + } + if let Some(previous) = old + && !sheet.spill_ranges.get(&key.1).is_some_and(|current| current.contains(previous.start) && current.contains(previous.end)) + { + freed.push((key.0, previous)); + } + } + for (sheet_index, range) in freed { + for &(sheet, cell) in self.graph.nodes.keys() { + let was_blocked_cell = cell.row <= range.end.row + && cell.col <= range.end.col + && wb.sheet(sheet).is_some_and(|sheet| sheet.value(cell) == Value::Error(CellError::Spill)); + if sheet == sheet_index && was_blocked_cell { + spill_changes.push((sheet, cell)); + } + } + } + spill_changes + } +} + +fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, end: CellRef) -> bool { + end.row >= gridcraft_core::MAX_ROWS + || end.col >= gridcraft_core::MAX_COLS + || range.iter().any(|cell| cell != anchor && (sheet.cells.has(cell) || sheet.spill.contains_key(&cell))) + || sheet.merges.iter().any(|merge| merge.intersects(&range)) + || sheet.tables.iter().any(|table| table.range.contains(anchor)) +} + +fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) { + for (index, cell) in range.iter().enumerate() { + if cell != anchor { + sheet.spill.insert(cell, array.data.get(index).cloned().unwrap_or_default()); + } + } + sheet.spill_ranges.insert(anchor, range); } /// Current date-time as a serial (1900 system), from the system clock (browser clock on wasm). @@ -1394,21 +545,13 @@ pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> V ev.value(expr) } -#[allow(clippy::disallowed_methods)] // the clock is read only off wasm fn prof_now() -> f64 { - #[cfg(not(target_arch = "wasm32"))] - { - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0) - } - #[cfg(target_arch = "wasm32")] - { - 0.0 - } + gridcraft_core::date::unix_now_ms().unwrap_or(0.0) } #[cfg(test)] pub(crate) mod tests { - use std::time::{Duration, Instant}; + use std::time::Duration; use gridcraft_core::{CellRef, RangeRef, Value}; use gridcraft_model::{Cell, Formula, Workbook}; @@ -1430,6 +573,48 @@ pub(crate) mod tests { v } + /// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already + /// spilled on the sheet from the last calculation, as a full recalculation finds them. + fn big_python_spill() -> (Workbook, HashMap) { + let n = 1_000usize; + let data: Vec = (0..n * n).map(|i| Value::Number(i as f64)).collect(); + let array = gridcraft_core::Array::new(n, n, data.clone()).unwrap(); + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + let anchor = CellRef::new(0, 0); + let py = gridcraft_model::PyCode::new("big"); + sh.set_cell(anchor, Cell { value: Value::Number(0.0), py: Some(std::sync::Arc::new(py)), ..Cell::default() }); + let area = RangeRef::new(anchor, CellRef::new(n as u32 - 1, n as u32 - 1)); + sh.spill_ranges.insert(anchor, area); + for (i, c) in area.iter().enumerate().skip(1) { + sh.spill.insert(c, data[i].clone()); + } + let mut python = HashMap::default(); + python.insert((0, anchor), Value::Array(std::sync::Arc::new(array))); + (wb, python) + } + + #[test] + fn a_read_beside_a_large_spill_walks_none_of_it() { + let (wb, python) = big_python_spill(); + let exprs = HashMap::default(); + let mut rng = 1u64; + let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0).with_python(python); + assert_eq!(host.cell_value(0, CellRef::new(0, 0)), Value::Number(0.0)); + // Beside the spill (column ALM, the 1,001st), over the rows it covers. + let beside = RangeRef::parse("ALM1:ALM1000").unwrap(); + host.spill_visits = 0; + assert!(host.range_values(0, beside).iter().all(Value::is_empty)); + assert!(host.visit_range(0, beside, &mut |_| true), "a disjoint read takes the fast path"); + assert_eq!(host.spill_visits, 0, "nothing of the spill is walked"); + // A read inside it still sees the spilled values, walking only the cells it reads. + let inside = RangeRef::parse("B2:C3").unwrap(); + host.spill_visits = 0; + assert_eq!(host.range_values(0, inside), [1_001.0, 1_002.0, 2_001.0, 2_002.0].map(Value::Number).to_vec()); + assert!(host.spill_visits <= 8, "{}", host.spill_visits); + assert!(!host.visit_range(0, inside, &mut |_| true), "an overlapping read leaves the block to range_values"); + } + #[test] fn intervals_match_a_linear_scan() { let mut iv: Intervals = Intervals::default(); @@ -1521,11 +706,10 @@ pub(crate) mod tests { } /// Opening (full recalc), changing every value of a column, and re-entering every formula. - #[allow(clippy::disallowed_methods)] // a native-only timing test: the clock is read off wasm fn open_and_bulk_edit(rows: u32) -> Duration { let mut wb = sum_rows(rows); let mut calc = Calc::new(); - let t = Instant::now(); + let started = gridcraft_core::date::unix_now_ms().unwrap_or(0.0); calc.recalc_all(&mut wb); let values: Vec = (0..rows).map(|r| (0, CellRef::new(r, 4))).collect(); if let Some(sh) = wb.sheet_mut(0) { @@ -1536,7 +720,8 @@ pub(crate) mod tests { calc.cells_changed(&mut wb, &values); let formulas: Vec = (0..rows).map(|r| (0, CellRef::new(r, 10))).collect(); calc.cells_changed(&mut wb, &formulas); - let elapsed = t.elapsed(); + let ended = gridcraft_core::date::unix_now_ms().unwrap_or(started); + let elapsed = Duration::from_secs_f64((ended - started).max(0.0) / 1000.0); let last = wb.sheet(0).map(|s| s.value(CellRef::new(rows - 1, 10))); let r = rows - 1; assert_eq!(last, Some(Value::Number(f64::from(1 + (5..10).map(|c| r % 97 + c).sum::())))); @@ -1551,7 +736,6 @@ pub(crate) mod tests { #[test] #[ignore = "timing-sensitive; run with --ignored in release"] - #[allow(clippy::disallowed_methods)] fn recalc_with_range_formulas_scales_linearly() { // Each row's SUM reads a range in the same columns. Recalculating on open used to walk // every row per range read (the used range), and finding a cell's dependents scanned diff --git a/crates/calc/src/recalc/graph.rs b/crates/calc/src/recalc/graph.rs new file mode 100644 index 0000000000..ab034f8cc1 --- /dev/null +++ b/crates/calc/src/recalc/graph.rs @@ -0,0 +1,347 @@ +use super::RangeRef; +use crate::eval::Area; +use gridcraft_core::CellRef; +use std::collections::BTreeSet; +use std::hash::{BuildHasherDefault, Hasher}; + +/// A fast, non-cryptographic hasher for cell keys (FxHash-style multiply-rotate). +#[derive(Default, Clone, Copy)] +pub struct FxHasher(u64); + +impl Hasher for FxHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.write_u64(*b as u64); + } + } + fn write_u64(&mut self, i: u64) { + self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); + } + fn write_u32(&mut self, i: u32) { + self.write_u64(i as u64); + } + fn write_usize(&mut self, i: usize) { + self.write_u64(i as u64); + } +} + +pub(super) type HashMap = std::collections::HashMap>; + +pub(super) type HashSet = std::collections::HashSet>; + +pub type Key = (usize, CellRef); + +#[derive(Clone, Debug, Default)] +pub(super) struct Node { + pub(super) areas: Vec, + pub(super) dynamic: bool, +} + +/// Ranges wider than this many columns go to the per-sheet wide index instead of per-column ones. +const WIDE: u32 = 64; + +/// Insertions an [`Intervals`] keeps aside (scanned by every query) before merging them in. +const PENDING: usize = 32; + +/// Row intervals `[r0, r1]`, each with a payload, answering "which intervals overlap rows +/// `a..=b`?" in O(log n + k). +/// +/// The intervals are sorted by start with an implicit segment tree of their largest end, so a query +/// only descends into subtrees that hold a match. Removals mark entries dead (re-inserting one +/// revives it); insertions wait in a small sorted set. [`Intervals::settle`] merges them and drops +/// dead entries once either grows, so mutations cost O(log n) amortised. +#[derive(Clone, Debug)] +pub(super) struct Intervals { + /// Sorted, without duplicates. + items: Vec<(u32, u32, T)>, + dead: Vec, + dead_count: usize, + /// Segment tree over `items`: node `i` has children `2i` and `2i + 1`, leaves start at + /// `max_end.len() / 2`. Each node holds the largest end below it (dead entries included). + max_end: Vec, + /// Inserted since the last merge. + pending: BTreeSet<(u32, u32, T)>, +} + +impl Default for Intervals { + fn default() -> Self { + Intervals { items: Vec::new(), dead: Vec::new(), dead_count: 0, max_end: Vec::new(), pending: BTreeSet::new() } + } +} + +impl Intervals { + pub(super) fn is_empty(&self) -> bool { + self.items.len() == self.dead_count && self.pending.is_empty() + } + + pub(super) fn insert(&mut self, r0: u32, r1: u32, t: T) { + let it = (r0, r1, t); + if let Ok(i) = self.items.binary_search(&it) { + if let Some(d) = self.dead.get_mut(i) + && *d + { + *d = false; + self.dead_count -= 1; + } + return; + } + self.pending.insert(it); + } + + pub(super) fn remove(&mut self, r0: u32, r1: u32, t: T) { + let it = (r0, r1, t); + if let Ok(i) = self.items.binary_search(&it) { + if let Some(d) = self.dead.get_mut(i) + && !*d + { + *d = true; + self.dead_count += 1; + } + return; + } + self.pending.remove(&it); + } + + /// Merges pending insertions and drops dead entries when there are enough of them. + pub(super) fn settle(&mut self) { + if self.pending.len() <= PENDING && self.dead_count <= (self.items.len() / 2).max(PENDING) { + return; + } + let mut all: Vec<(u32, u32, T)> = Vec::with_capacity(self.items.len() - self.dead_count + self.pending.len()); + all.extend(self.items.iter().zip(&self.dead).filter(|(_, d)| !**d).map(|(it, _)| *it)); + all.extend(std::mem::take(&mut self.pending)); + // Two sorted runs: the stable sort merges them in linear time. + all.sort(); + all.dedup(); + let size = all.len().next_power_of_two(); + let mut max_end = vec![0; 2 * size]; + if let Some(leaves) = max_end.get_mut(size..) { + for (slot, it) in leaves.iter_mut().zip(&all) { + *slot = it.1; + } + } + for i in (1..size).rev() { + let m = max_end.get(2 * i).copied().unwrap_or(0).max(max_end.get(2 * i + 1).copied().unwrap_or(0)); + if let Some(slot) = max_end.get_mut(i) { + *slot = m; + } + } + self.dead = vec![false; all.len()]; + self.dead_count = 0; + self.items = all; + self.max_end = max_end; + } + + /// Calls `f` for every interval overlapping rows `a..=b` (`r0 <= b && r1 >= a`). Returns the + /// number of tree nodes visited. + pub(super) fn query(&self, a: u32, b: u32, f: &mut dyn FnMut(&T)) -> usize { + for it in &self.pending { + if it.0 <= b && it.1 >= a { + f(&it.2); + } + } + // Entries before `p` start at or before row `b`. + let p = self.items.partition_point(|it| it.0 <= b); + if p == 0 { + return 0; + } + self.walk(1, 0, self.max_end.len() / 2, p, a, f) + } + + fn walk(&self, node: usize, lo: usize, hi: usize, p: usize, a: u32, f: &mut dyn FnMut(&T)) -> usize { + if lo >= p || self.max_end.get(node).is_none_or(|m| *m < a) { + return 1; + } + if hi - lo <= 1 { + if let (Some(it), Some(false)) = (self.items.get(lo), self.dead.get(lo)) + && it.1 >= a + { + f(&it.2); + } + return 1; + } + let mid = lo + (hi - lo) / 2; + 1 + self.walk(2 * node, lo, mid, p, a, f) + self.walk(2 * node + 1, mid, hi, p, a, f) + } +} + +#[derive(Clone, Debug, Default)] +pub struct Graph { + pub(super) nodes: HashMap, + /// single cell → dependents + cell_deps: HashMap>, + /// (sheet, col) → row intervals of the ranges (up to `WIDE` columns) that cover the column + col_deps: HashMap<(usize, u32), Intervals>, + /// sheet → row intervals of wider ranges, with their columns: (first, last, dependent) + wide_deps: HashMap>, + pub(super) dynamic: HashSet, + /// Range indexes changed since the last [`Graph::settle`]. + unsettled_cols: HashSet<(usize, u32)>, + unsettled_wide: HashSet, +} + +/// A formula's precedents split by shape: single cells, column intervals and wide ranges. +type Entries = (Vec, Vec<(usize, u32, u32, u32)>, Vec<(usize, RangeRef)>); + +impl Graph { + pub fn len(&self) -> usize { + self.nodes.len() + } + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// Index entries of a formula's precedents, without duplicates: single cells, column + /// intervals and wide ranges. + fn entries(areas: &[Area]) -> Entries { + let (mut cells, mut cols, mut wide) = (Vec::new(), Vec::new(), Vec::new()); + for a in areas { + if a.range.is_single() { + cells.push((a.sheet, a.range.start)); + } else if a.range.width() > WIDE { + wide.push((a.sheet, a.range)); + } else { + for c in a.range.start.col..=a.range.end.col { + cols.push((a.sheet, c, a.range.start.row, a.range.end.row)); + } + } + } + cells.sort_unstable(); + cells.dedup(); + cols.sort_unstable(); + cols.dedup(); + wide.sort_unstable_by_key(|(s, r)| (*s, r.start, r.end)); + wide.dedup(); + (cells, cols, wide) + } + + pub(super) fn insert(&mut self, k: Key, node: Node) { + self.remove(k); + let (cells, cols, wide) = Self::entries(&node.areas); + for c in cells { + self.cell_deps.entry(c).or_default().insert(k); + } + for (s, c, r0, r1) in cols { + self.col_deps.entry((s, c)).or_default().insert(r0, r1, k); + self.unsettled_cols.insert((s, c)); + } + for (s, r) in wide { + self.wide_deps.entry(s).or_default().insert(r.start.row, r.end.row, (r.start.col, r.end.col, k)); + self.unsettled_wide.insert(s); + } + if node.dynamic { + self.dynamic.insert(k); + } + self.nodes.insert(k, node); + } + + pub(super) fn remove(&mut self, k: Key) { + let Some(old) = self.nodes.remove(&k) else { return }; + let (cells, cols, wide) = Self::entries(&old.areas); + for c in cells { + if let Some(v) = self.cell_deps.get_mut(&c) { + v.remove(&k); + if v.is_empty() { + self.cell_deps.remove(&c); + } + } + } + for (s, c, r0, r1) in cols { + if let Some(v) = self.col_deps.get_mut(&(s, c)) { + v.remove(r0, r1, k); + self.unsettled_cols.insert((s, c)); + } + } + for (s, r) in wide { + if let Some(v) = self.wide_deps.get_mut(&s) { + v.remove(r.start.row, r.end.row, (r.start.col, r.end.col, k)); + self.unsettled_wide.insert(s); + } + } + self.dynamic.remove(&k); + } + + /// Tidies the range indexes changed by `insert`/`remove` (queries stay correct without it, + /// just slower). + pub(super) fn settle(&mut self) { + for key in std::mem::take(&mut self.unsettled_cols) { + if let Some(v) = self.col_deps.get_mut(&key) { + v.settle(); + if v.is_empty() { + self.col_deps.remove(&key); + } + } + } + for key in std::mem::take(&mut self.unsettled_wide) { + if let Some(v) = self.wide_deps.get_mut(&key) { + v.settle(); + if v.is_empty() { + self.wide_deps.remove(&key); + } + } + } + } + + /// Formulas that read cell `c` of `sheet`. + pub fn dependents(&self, sheet: usize, c: CellRef, out: &mut Vec) { + if let Some(v) = self.cell_deps.get(&(sheet, c)) { + out.extend(v.iter().copied()); + } + if let Some(v) = self.col_deps.get(&(sheet, c.col)) { + v.query(c.row, c.row, &mut |k| out.push(*k)); + } + if let Some(v) = self.wide_deps.get(&sheet) { + v.query(c.row, c.row, &mut |(c0, c1, k)| { + if *c0 <= c.col && c.col <= *c1 { + out.push(*k); + } + }); + } + } + + /// Formulas that read any cell of `range` (a formula can be listed more than once). + pub fn dependents_of_range(&self, sheet: usize, range: RangeRef, out: &mut Vec) { + if range.count() <= 4096 { + for c in range.iter() { + if let Some(v) = self.cell_deps.get(&(sheet, c)) { + out.extend(v.iter().copied()); + } + } + } else { + for ((s, c), v) in &self.cell_deps { + if *s == sheet && range.contains(*c) { + out.extend(v.iter().copied()); + } + } + } + let (r0, r1) = (range.start.row, range.end.row); + if (range.width() as usize) <= self.col_deps.len() { + for col in range.start.col..=range.end.col { + if let Some(v) = self.col_deps.get(&(sheet, col)) { + v.query(r0, r1, &mut |k| out.push(*k)); + } + } + } else { + for ((s, col), v) in &self.col_deps { + if *s == sheet && range.start.col <= *col && *col <= range.end.col { + v.query(r0, r1, &mut |k| out.push(*k)); + } + } + } + if let Some(v) = self.wide_deps.get(&sheet) { + v.query(r0, r1, &mut |(c0, c1, k)| { + if *c0 <= range.end.col && range.start.col <= *c1 { + out.push(*k); + } + }); + } + } + + /// Precedent areas of a formula cell (for Trace Precedents). + pub fn precedents_of(&self, k: Key) -> Vec { + self.nodes.get(&k).map(|n| n.areas.clone()).unwrap_or_default() + } +} diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs new file mode 100644 index 0000000000..5909369fda --- /dev/null +++ b/crates/calc/src/recalc/pass_host.rs @@ -0,0 +1,665 @@ +use super::graph::{HashMap, HashSet, Key}; +use super::{Evaluator, Host, Workbook, stack_position}; +use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; +use gridcraft_formula::Expr; + +/// Formulas a formula may calculate on demand one inside the other (each needing one another's +/// value before it is done). Each level takes stack, so a chain deeper than this is suspended and +/// calculated from the top instead (see [`PassHost::calculate`]): long dependency chains calculate +/// whatever order they come in, with bounded stack. +const MAX_NESTED: usize = 64; + +/// Formula evaluations iterative calculation may spend on one recalculation (passes × formulas +/// evaluated again), however high Maximum Iterations is. +const MAX_ITERATION_WORK: usize = 10_000_000; + +pub(super) struct PassHost<'a> { + wb: &'a Workbook, + exprs: &'a HashMap>, + pub(super) results: HashMap, + pending: HashSet, + in_progress: HashSet, + /// New spills found during the pass: anchor → array. + pub(super) spills: HashMap>, + /// Used range per sheet: the workbook doesn't change during a pass, and working it out walks + /// every row, so once per sheet rather than once per range read. + used: HashMap>, + rng: &'a mut u64, + now: f64, + cycle: bool, + pub(super) cycles: Vec, + depth: usize, + /// A formula needed at [`MAX_NESTED`] levels deep: the evaluations in progress are abandoned + /// and it is calculated first. + suspend: Option, + /// Formulas whose evaluation was abandoned for another one, to be calculated again after it. + /// They all need it, so reading one of them while it is calculated is a circular reference, + /// as reading a formula in progress is. + waiting: HashSet, + /// The formulas abandoned since the last suspension. + abandoned: Vec, + /// Other formulas read at [`MAX_NESTED`] levels deep by the evaluations being abandoned. They + /// are calculated along with the suspended one, rather than one per restart (a wide range + /// read at the limit would restart the abandoned evaluations once per cell in it). + also: Vec, + /// Suspensions so far (tests check that a wide read at the limit needs one, not one per cell). + #[cfg(test)] + pub(super) suspensions: usize, + /// Spilled values looked at by range reads (tests check that a read outside a large spill + /// looks at none of it). + #[cfg(test)] + pub(super) spill_visits: usize, + /// The formulas in `cycles`. + cycle_seen: HashSet, + /// Iterative calculation: a circular reference reads the cell's previous value instead of + /// giving `#CIRC!`. + pub(super) iterate: bool, + /// Values from the previous iteration; cells not in it read their stored value. + prev: HashMap, + /// Formulas being evaluated, innermost last (kept only when iterating). + stack: Vec, + /// Formulas found on a circular reference (when iterating). + pub(super) members: HashSet, + /// Results that read a previous value, directly or through other formulas. + pub(super) tainted: HashSet, + /// Whether the formula being evaluated has read a previous value. + taint: bool, + /// `stack_position()` where the outermost formula being calculated started. + stack_top: usize, + /// Whether an evaluation ran past the stack budget since the innermost formula started. + out_of_stack: bool, + /// The kept results of the Python cells in the pass: a Python cell isn't evaluated, its + /// result is laid out (an array spills from the cell, as a formula's does). Each one is in + /// `pending` until it is laid out, so a formula that reads it first gets its new value. + python: HashMap, +} + +impl<'a> PassHost<'a> { + pub(super) fn new(wb: &'a Workbook, exprs: &'a HashMap>, rng: &'a mut u64, now: f64) -> Self { + PassHost { + wb, + exprs, + results: HashMap::with_capacity_and_hasher(exprs.len(), Default::default()), + pending: exprs.keys().copied().collect(), + in_progress: HashSet::default(), + spills: HashMap::default(), + used: HashMap::default(), + rng, + now, + cycle: false, + cycles: vec![], + depth: 0, + suspend: None, + waiting: HashSet::default(), + abandoned: Vec::new(), + also: Vec::new(), + #[cfg(test)] + suspensions: 0, + #[cfg(test)] + spill_visits: 0, + cycle_seen: HashSet::default(), + iterate: false, + prev: HashMap::default(), + stack: Vec::new(), + members: HashSet::default(), + tainted: HashSet::default(), + taint: false, + stack_top: 0, + out_of_stack: false, + python: HashMap::default(), + } + } + + /// Adds the dirty Python cells of the pass and their kept results: like the formulas, they + /// are pending until laid out, so every read path calculates them before reading them. + pub(super) fn with_python(mut self, python: HashMap) -> Self { + self.pending.extend(python.keys().copied()); + self.python = python; + self + } +} + +/// 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 another formula's spill (unless that formula is +/// recalculated in this pass, and so may spill elsewhere now). +fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool { + let Some(sh) = host.wb.sheet(sheet) else { return false }; + let end = + CellRef::new(anchor.row.saturating_add((a.rows as u32).saturating_sub(1)), anchor.col.saturating_add((a.cols as u32).saturating_sub(1))); + let range = RangeRef::new(anchor, end); + let own = sh.spill_ranges.get(&anchor); + let spilled_over = |c: CellRef| { + !own.is_some_and(|o| o.contains(c)) + && sh.spill_ranges.iter().any(|(o, r)| { + // A formula or Python cell recalculated in this pass lays its array out again. + *o != anchor && r.contains(c) && !host.exprs.contains_key(&(sheet, *o)) && !host.python.contains_key(&(sheet, *o)) + }) + }; + end.row >= gridcraft_core::MAX_ROWS + || end.col >= gridcraft_core::MAX_COLS + || sh.merges.iter().any(|m| m.intersects(&range)) + || 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)) +} + +/// Whether `arr`, anchored at `anchor`, would spill exactly what the sheet already holds over +/// `range`: the same area, nothing new in the way, and the same values. +pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, arr: &Array) -> bool { + let end = + 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)) + && !sheet.tables.iter().any(|t| t.range.contains(anchor)) + && range + .iter() + .enumerate() + .all(|(i, c)| c == anchor || (!sheet.cells.has(c) && sheet.spill.get(&c) == Some(arr.data.get(i).unwrap_or(&Value::Empty)))) +} + +/// The area an array anchored at `anchor` covers. +fn array_area(anchor: CellRef, a: &Array) -> RangeRef { + let end = + CellRef::new(anchor.row.saturating_add((a.rows as u32).saturating_sub(1)), anchor.col.saturating_add((a.cols as u32).saturating_sub(1))); + RangeRef::new(anchor, end) +} + +/// The spilled values `sheet` stores inside `range`, passed to `f` until it returns false. Values +/// outside the range are not walked: with fewer rows in the range than spilled values, each row +/// is looked up on its own; otherwise one ordered scan visits each spilled value at most once. +/// Returns how many values were looked at. +fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &mut dyn FnMut(CellRef, &'s Value) -> bool) -> usize { + let mut seen = 0usize; + if sheet.spill.is_empty() { + return 0; + } + if (range.height() as usize) < sheet.spill.len() { + for row in range.start.row..=range.end.row { + for (c, v) in sheet.spill.range(CellRef::new(row, range.start.col)..=CellRef::new(row, range.end.col)) { + seen += 1; + if !f(*c, v) { + return seen; + } + } + } + } else { + for (c, v) in sheet.spill.range(range.start..=range.end) { + seen += 1; + if range.contains(*c) && !f(*c, v) { + return seen; + } + } + } + seen +} + +impl PassHost<'_> { + /// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would + /// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is + /// calculated from here, then the suspended ones again (reading the results kept so far). + pub(super) fn calculate(&mut self, k: Key) { + // Formulas to calculate, innermost last, each with the ones abandoned to calculate the + // next. + let mut work: Vec<(Key, Vec)> = vec![(k, Vec::new())]; + while let Some(&(top, _)) = work.last() { + self.compute(top); + match self.suspend.take() { + Some(next) => { + #[cfg(test)] + { + self.suspensions += 1; + } + let held = std::mem::take(&mut self.abandoned); + self.waiting.extend(held.iter().copied()); + if let Some(entry) = work.last_mut() { + entry.1 = held; + } + // The other formulas read at the limit are calculated after `next`, before the + // held evaluations restart. Each has nothing held of its own, so the held ones + // are released only when the last of them is done. + let mut seen: HashSet = HashSet::default(); + seen.insert(next); + for s in std::mem::take(&mut self.also) { + if seen.insert(s) { + work.push((s, Vec::new())); + } + } + work.push((next, Vec::new())); + } + None => { + work.pop(); + if let Some(entry) = work.last_mut() { + for a in entry.1.drain(..) { + self.waiting.remove(&a); + } + } + } + } + } + } + + fn compute(&mut self, k: Key) -> Value { + if let Some(v) = self.results.get(&k) { + let v = v.clone(); + if self.iterate && self.tainted.contains(&k) { + self.taint = true; + } + return v; + } + if let Some(result) = self.python.get(&k).cloned() { + return self.python_result(k, result); + } + let Some(expr) = self.exprs.get(&k) else { + return self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(); + }; + if self.suspend.is_some() { + // Unwinding to `calculate`: the value is thrown away. A formula read at the limit is + // calculated with the suspended one, so the evaluations are not restarted for each. + if self.depth >= MAX_NESTED && !self.in_progress.contains(&k) && !self.waiting.contains(&k) { + self.also.push(k); + } + return Value::Error(CellError::Calc); + } + if self.in_progress.contains(&k) || self.waiting.contains(&k) { + self.cycle = true; + if self.iterate { + return self.circular_read(k); + } + // Once each, though a suspended evaluation meets it again. + if self.cycle_seen.insert(k) { + self.cycles.push(k); + } + return Value::Error(CellError::Circ); + } + if self.depth >= MAX_NESTED { + self.suspend = Some(k); + return Value::Error(CellError::Calc); + } + if self.depth == 0 { + self.stack_top = stack_position(); + } + self.in_progress.insert(k); + self.depth += 1; + let outer_taint = std::mem::replace(&mut self.taint, false); + if self.iterate { + self.stack.push(k); + } + let expr = std::sync::Arc::clone(expr); + let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false); + let v = { + let mut ev = Evaluator::new(self, k.0, k.1); + ev.value(&expr) + }; + let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack); + if out_of_stack && self.depth > 1 && self.suspend.is_none() { + // It ran out of the stack left below the formulas that read it: it is calculated + // from the top instead, as a formula needed at `MAX_NESTED` levels deep is. + self.suspend = Some(k); + self.depth -= 1; + self.in_progress.remove(&k); + if self.iterate { + self.stack.pop(); + } + self.taint = outer_taint; + return Value::Error(CellError::Calc); + } + if self.suspend.is_some() { + // Abandoned: `calculate` evaluates this formula again once the one it needs is done. + self.depth -= 1; + self.in_progress.remove(&k); + self.abandoned.push(k); + if self.iterate { + self.stack.pop(); + } + self.taint = outer_taint; + return Value::Error(CellError::Calc); + } + // A legacy array formula fills the range it was entered in. + let legacy = self.wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.as_ref()).and_then(|f| f.array); + let v = match legacy { + Some(range) => fit_to_range(v, range), + None => v, + }; + self.depth -= 1; + self.in_progress.remove(&k); + self.pending.remove(&k); + if self.iterate { + self.stack.pop(); + if self.taint { + self.tainted.insert(k); + } else { + self.tainted.remove(&k); + } + } + self.taint |= outer_taint; + // A blank cell shows as 0 in a formula's result, inside an array as well (`=A1:A3`, + // FILTER or SORT of a range with blanks). GROUPBY and PIVOTBY lay out blank cells + // of their own, which stay blank. + let keep_blanks = matches!(&*expr, Expr::Call(n, _) if matches!(n.as_str(), "GROUPBY" | "PIVOTBY")); + let v = match v { + Value::Array(a) => { + let a = if keep_blanks || !a.data.iter().any(|x| matches!(x, Value::Empty)) { + a + } else { + let data = a.data.iter().map(|x| if matches!(x, Value::Empty) { Value::Number(0.0) } else { x.clone() }).collect(); + Array::new(a.rows, a.cols, data).map(std::sync::Arc::new).unwrap_or(a) + }; + // A dynamic-array formula anchors a spill range even while its result is one + // value -- a FILTER matching one row, a SORT or UNIQUE over one item -- so `C1#` + // is the 1 x 1 range and `ROWS(C1#)` is 1, as in Excel (#1491). A formula that + // returns a scalar never reaches this arm, so it does not become an anchor. + self.spills.insert(k, a.clone()); + a.data.first().cloned().unwrap_or_default() + } + Value::Empty => Value::Number(0.0), + v => v, + }; + // An array that can't spill is #SPILL! for the formulas evaluated after it in this pass too. + let v = match self.spills.get(&k) { + Some(a) if spill_blocked(self, k, a) => { + self.spills.remove(&k); + Value::Error(CellError::Spill) + } + _ => v, + }; + self.results.insert(k, v.clone()); + v + } + + /// A Python cell's kept result as its value: an array spills from the cell unless it is + /// blocked, malformed or larger than [`gridcraft_model::python::MAX_RESULT_CELLS`] (only a + /// crafted file holds one), which shows `#SPILL!`. + fn python_result(&mut self, k: Key, result: Value) -> Value { + self.pending.remove(&k); + let v = match result { + Value::Array(a) => { + let sane = a.rows >= 1 + && a.cols >= 1 + && a.rows.checked_mul(a.cols).is_some_and(|n| n == a.data.len() && n <= gridcraft_model::python::MAX_RESULT_CELLS); + if sane { + self.spills.insert(k, a.clone()); + a.data.first().cloned().unwrap_or_default() + } else { + Value::Error(CellError::Spill) + } + } + v => v, + }; + let v = match self.spills.get(&k) { + Some(a) if spill_blocked(self, k, a) => { + self.spills.remove(&k); + Value::Error(CellError::Spill) + } + _ => v, + }; + self.results.insert(k, v.clone()); + v + } + + /// A formula's previous value for iterative calculation: from the last iteration, else the + /// value it shows. Blank, and the `#CIRC!` of a loop calculated with iteration off, are 0. + fn previous(&self, k: Key) -> Value { + let v = match self.prev.get(&k) { + Some(v) => v.clone(), + None => self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(), + }; + if matches!(v, Value::Empty | Value::Error(CellError::Circ)) { Value::Number(0.0) } else { v } + } + + /// Reading `k` while it is being evaluated, with iterative calculation on: its previous value. + /// The formulas around the loop are the ones whose changes decide when iteration stops. + fn circular_read(&mut self, k: Key) -> Value { + self.taint = true; + match self.stack.iter().rposition(|s| *s == k) { + Some(i) => self.members.extend(self.stack.get(i..).unwrap_or_default().iter().copied()), + // Too deep to follow: the formula itself is watched. + None => { + self.members.insert(k); + } + } + self.previous(k) + } + + /// Iterative calculation, after a first pass over `order` that met circular references. The + /// formulas that read a previous value (the loops and what depends on them) are evaluated + /// again in the same order, each pass starting from the last one's values and reading what it + /// has already produced (Gauss-Seidel), until no formula on a loop changes by `max_change` or + /// more, or after `max_iterations` passes in all. Returns the number of passes. + pub(super) fn iterate_loops(&mut self, order: &[Key], max_iterations: u32, max_change: f64) -> u32 { + let again: Vec = order.iter().copied().filter(|k| self.tainted.contains(k)).collect(); + let set: HashSet = again.iter().copied().collect(); + // Bounds the work whatever Maximum Iterations says. + let max_passes = u32::try_from(MAX_ITERATION_WORK / again.len().max(1)).unwrap_or(u32::MAX).max(1); + let mut passes = 1u32; + while passes < max_iterations.min(max_passes) && !self.converged(max_change) { + self.prev = again.iter().filter_map(|k| self.results.remove(k).map(|v| (*k, v))).collect(); + self.pending = set.clone(); + self.spills.retain(|a, _| !set.contains(a)); + for k in &again { + self.calculate(*k); + } + passes += 1; + } + passes + } + + /// Whether every formula on a loop changed by less than `max_change` in the last pass (text, + /// logical and error values: not at all). + fn converged(&self, max_change: f64) -> bool { + self.members.iter().all(|k| { + let Some(new) = self.results.get(k) else { return true }; + match (new, &self.previous(*k)) { + (Value::Number(a), Value::Number(b)) => { + let d = (a - b).abs(); + d < max_change || d == 0.0 + } + (new, old) => new == old, + } + }) + } +} + +/// A legacy (Ctrl+Shift+Enter) array formula's result fitted to the range it was entered in, as +/// Excel does: a single row or column repeats across the range, a single value fills it, cells +/// past the result show `#N/A`, and a result larger than the range is cut off. +fn fit_to_range(v: Value, range: RangeRef) -> Value { + if range.count() > crate::eval::MAX_CELLS { + return Value::Error(CellError::Num); + } + let (h, w) = (range.height() as usize, range.width() as usize); + let Value::Array(a) = v else { + return if h * w == 1 { v } else { Array::new(h, w, vec![v; h * w]).map(Value::from).unwrap_or(Value::Error(CellError::Value)) }; + }; + if h * w == 1 { + return a.data.first().cloned().unwrap_or_default(); + } + let mut data = Vec::with_capacity(h * w); + for r in 0..h { + for c in 0..w { + let (r, c) = (if a.rows == 1 { 0 } else { r }, if a.cols == 1 { 0 } else { c }); + data.push(a.get(r, c).cloned().unwrap_or(Value::Error(CellError::NA))); + } + } + Array::new(h, w, data).map(Value::from).unwrap_or(Value::Error(CellError::Value)) +} + +impl Host for PassHost<'_> { + fn workbook(&self) -> &Workbook { + self.wb + } + fn stack_top(&self) -> Option { + (self.depth > 1).then_some(self.stack_top) + } + fn stack_exhausted(&mut self) { + self.out_of_stack = true; + } + fn spill_range(&mut self, sheet: usize, anchor: CellRef) -> Option { + let k = (sheet, anchor); + if !(self.pending.contains(&k) || self.results.contains_key(&k)) { + return self.wb.sheet(sheet)?.spill_ranges.get(&anchor).copied(); + } + // Recalculated in this pass: its new array, unless something blocks it (#SPILL!). + self.compute(k); + let arr = self.spills.get(&k)?; + let end = CellRef::new( + anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), + anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)), + ); + let range = RangeRef::new(anchor, end); + let sh = self.wb.sheet(sheet)?; + let blocked = end.row >= gridcraft_core::MAX_ROWS + || end.col >= gridcraft_core::MAX_COLS + || sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (cell.formula.is_some() || !cell.value.is_empty())) + || sh.merges.iter().any(|m| m.intersects(&range)); + (!blocked).then_some(range) + } + fn cell_value(&mut self, sheet: usize, c: CellRef) -> Value { + let k = (sheet, c); + if self.pending.contains(&k) || self.results.contains_key(&k) { + return self.compute(k); + } + // A cell covered by a spill computed in this pass. + for (anchor, arr) in &self.spills { + if anchor.0 == sheet && c.row >= anchor.1.row && c.col >= anchor.1.col { + let (dr, dc) = ((c.row - anchor.1.row) as usize, (c.col - anchor.1.col) as usize); + if dr < arr.rows && dc < arr.cols { + if self.iterate && self.tainted.contains(anchor) { + self.taint = true; + } + return arr.get(dr, dc).cloned().unwrap_or_default(); + } + } + } + self.wb.sheet(sheet).map(|s| s.value(c)).unwrap_or_default() + } + fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec { + let (h, w) = (range.height() as usize, range.width() as usize); + let mut out = vec![Value::Empty; h * w]; + let Some(sh) = self.wb.sheet(sheet) else { return out }; + // Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go + // through `compute`, constants are copied straight from the store. + let mut formulas: Vec<(usize, CellRef)> = Vec::new(); + for (c, cell) in sh.cells.iter_range(range) { + let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; + if cell.formula.is_some() || cell.py.is_some() { + formulas.push((i, c)); + } else if let Some(slot) = out.get_mut(i) { + *slot = cell.value.clone(); + } + } + let _seen = stored_spill_in(sh, range, &mut |c, v| { + let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; + if let Some(slot) = out.get_mut(i) + && slot.is_empty() + { + *slot = v.clone(); + } + true + }); + #[cfg(test)] + { + self.spill_visits += _seen; + } + for (i, c) in formulas { + let v = self.cell_value(sheet, c); + if let Some(slot) = out.get_mut(i) { + *slot = v; + } + } + if !self.spills.is_empty() { + // Only the part of each array inside the range is walked: a large array beside a small + // read costs nothing. + let mut new: Vec<(usize, Value)> = Vec::new(); + for (a, arr) in self.spills.iter().filter(|(a, _)| a.0 == sheet) { + let area = array_area(a.1, arr); + if !area.intersects(&range) { + continue; + } + let (r0, r1) = (area.start.row.max(range.start.row), area.end.row.min(range.end.row)); + let (c0, c1) = (area.start.col.max(range.start.col), area.end.col.min(range.end.col)); + for row in r0..=r1 { + for col in c0..=c1 { + let c = CellRef::new(row, col); + if c == a.1 { + continue; + } + let v = arr.get((row - a.1.row) as usize, (col - a.1.col) as usize).cloned().unwrap_or_default(); + new.push(((row - range.start.row) as usize * w + (col - range.start.col) as usize, v)); + } + } + } + #[cfg(test)] + { + self.spill_visits += new.len(); + } + // Iterating: an array spilled by a formula that read a previous value. + if self.iterate + && self.spills.iter().any(|(a, arr)| { + let end = CellRef::new( + a.1.row.saturating_add((arr.rows as u32).saturating_sub(1)), + a.1.col.saturating_add((arr.cols as u32).saturating_sub(1)), + ); + a.0 == sheet && self.tainted.contains(a) && RangeRef::new(a.1, end).intersects(&range) + }) + { + self.taint = true; + } + for (i, v) in new { + if let Some(slot) = out.get_mut(i) { + *slot = v; + } + } + } + out + } + fn visit_range(&mut self, sheet: usize, range: RangeRef, f: &mut dyn FnMut(&Value) -> bool) -> bool { + let wb = self.wb; + let Some(sh) = wb.sheet(sheet) else { return false }; + // Formula and Python cells first, in row-major order like `range_values`: reading one + // calculates it (a Python cell lays out its result) and the pass remembers the value, so + // the walk below gets the same value again without this method holding any. + for (c, cell) in sh.cells.iter_range(range) { + if cell.formula.is_some() || cell.py.is_some() { + let _ = self.cell_value(sheet, c); + } + } + // Spilled values sit between the stored cells (and the formulas just calculated may have + // produced some): leave such blocks to `range_values`. + let arrays = self.spills.iter().any(|(a, arr)| a.0 == sheet && array_area(a.1, arr).intersects(&range)); + let mut stored = false; + let _seen = stored_spill_in(sh, range, &mut |_, _| { + stored = true; + false + }); + #[cfg(test)] + { + self.spill_visits += _seen; + } + if arrays || stored { + return false; + } + for (c, cell) in sh.cells.iter_range(range) { + let go = if cell.formula.is_some() || cell.py.is_some() { f(&self.cell_value(sheet, c)) } else { f(&cell.value) }; + if !go { + break; + } + } + true + } + fn used_range(&mut self, sheet: usize) -> Option { + let wb = self.wb; + *self.used.entry(sheet).or_insert_with(|| wb.sheet(sheet).and_then(|s| s.used_range())) + } + fn now_serial(&self) -> f64 { + self.now + } + fn random(&mut self) -> f64 { + // xorshift64* + let mut x = *self.rng; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *self.rng = x; + (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64 + } +} diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..d635907370 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -614,6 +614,25 @@ fn lambda_calls_spend_one_work_budget_per_cell() { assert_eq!(t.num("A2"), 4000.0 * 4001.0 / 2.0); } +#[test] +fn lifted_lookups_stop_past_their_work_budget() { + // Security: each needle searched the whole lookup vector, so this one cell ran for hours + // (about 1.1e12 compares) and hung opening the file that held it. It is #NUM! at once now. + let mut t = T::new(); + t.set("A1", "=ROWS(XMATCH(SEQUENCE(1048576),-SEQUENCE(1048576)))"); + assert_eq!(t.get("A1"), Value::Error(CellError::Num)); + // Ordinary lifted lookups are unaffected. + for (i, k) in [10, 20, 30, 40, 50].into_iter().enumerate() { + t.set(&format!("B{}", i + 1), &k.to_string()); + t.set(&format!("C{}", i + 1), &(i + 1).to_string()); + } + t.set("D1", "=SUM(XMATCH({30;50;10},B1:B5))"); + t.set("D2", "=SUM(XLOOKUP({20;40},B1:B5,C1:C5))"); + t.set("D3", "=SUM(VLOOKUP({30,10},B1:C5,2,FALSE))"); + t.set("D4", "=SUM(MATCH({25,50},B1:B5))"); + assert_eq!([t.num("D1"), t.num("D2"), t.num("D3"), t.num("D4")], [9.0, 6.0, 4.0, 7.0]); +} + #[test] fn accounting_negative_text_coerces() { let mut t = T::new(); @@ -1232,6 +1251,25 @@ fn array_broadcast_result_is_capped() { assert_eq!(t.num("C3"), 5.0); } +/// MAP refuses a result past `MAX_CELLS` by its checked product, before allocating it (the +/// 2^32-cell wrap that a 32-bit `usize` product would turn into 0 is pinned in +/// `broadcast_len_rejects_a_product_that_wraps_to_zero_on_32_bits`; `SEQUENCE` tops out at +/// 16384 columns, so the widest product it can build is 16384 squared). +#[test] +fn map_caps_its_result_size() { + let mut t = T::new(); + for (at, formula) in + [("A1", "=MAP(SEQUENCE(4001),SEQUENCE(1,4000),LAMBDA(a,b,a))"), ("A2", "=MAP(SEQUENCE(16384),SEQUENCE(1,16384),LAMBDA(a,b,a))")] + { + t.set(at, formula); + assert_eq!(t.get(at), Value::Error(CellError::Num), "{formula}"); + } + // Within the cap the broadcast shape is unchanged. + t.set("A3", "=ROWS(MAP(SEQUENCE(3),SEQUENCE(1,2),LAMBDA(a,b,a+b)))"); + t.set("A4", "=COLUMNS(MAP(SEQUENCE(3),SEQUENCE(1,2),LAMBDA(a,b,a+b)))"); + assert_eq!((t.num("A3"), t.num("A4")), (3.0, 2.0)); +} + #[test] fn text_function() { let mut t = T::new(); @@ -2274,3 +2312,63 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +/// Makes `at` a Python cell showing `cached` (its value before this calculation), with `result` +/// as its kept result, and returns the cell's key for `Calc::cells_changed`. +fn plant_python(t: &mut T, at: &str, cached: Value, result: Value) -> (usize, CellRef) { + use gridcraft_model::python::{PyCode, PyOutput}; + let output = PyOutput { value: result, type_name: "list".into(), preview: String::new(), convertible: true }; + let py = PyCode { output: Some(output), ..PyCode::new("[5, 6]") }; + let cell = Cell { value: cached, formula: None, style: gridcraft_model::StyleId::default(), py: Some(std::sync::Arc::new(py)) }; + t.wb.sheet_mut(0).unwrap().cells.set(c(at), cell); + (0, c(at)) +} + +fn column(values: &[f64]) -> Value { + let data = values.iter().map(|v| Value::Number(*v)).collect(); + Value::Array(std::sync::Arc::new(gridcraft_core::Array::new(values.len(), 1, data).unwrap())) +} + +#[test] +fn formulas_read_a_dirty_python_cell_after_it_is_laid_out() { + // B1's result can't spill (B2 holds a value), so it is #SPILL!. A1, A2 and A3 come before + // it in the pass; each must lay it out first rather than read its old value, 1. + let build = |t: &mut T| { + t.set("B2", "10"); + t.set("B3", "100"); + t.set("A1", "=B1"); + t.set("A2", "=MAX(B1:B3)"); + t.set("A3", "=SUM(B1:B3)"); + t.set("A4", "=COUNTA(B1:B3)"); + t.set("A5", "=SUMPRODUCT(--ISERROR(B1:B3))"); + }; + let check = |t: &T, how: &str| { + assert_eq!(t.get("B1"), Value::Error(CellError::Spill), "{how}"); + assert_eq!(t.get("A1"), Value::Error(CellError::Spill), "{how}: a reference"); + assert_eq!(t.get("A2"), Value::Error(CellError::Spill), "{how}: a range read"); + assert_eq!(t.get("A3"), Value::Error(CellError::Spill), "{how}: a range walked cell by cell"); + assert_eq!(t.num("A4"), 3.0, "{how}"); + assert_eq!(t.num("A5"), 1.0, "{how}: the error is seen in the range"); + }; + + // A full recalculation. + let mut t = T::new(); + build(&mut t); + plant_python(&mut t, "B1", Value::Number(1.0), column(&[5.0, 6.0])); + t.calc.recalc_all(&mut t.wb); + check(&t, "full"); + + // An incremental one: B1 becomes a Python cell after its readers. + let mut t = T::new(); + t.set("B1", "1"); + build(&mut t); + assert_eq!((t.num("A1"), t.num("A3")), (1.0, 111.0)); + let k = plant_python(&mut t, "B1", Value::Number(1.0), column(&[5.0, 6.0])); + t.calc.cells_changed(&mut t.wb, &[k]); + check(&t, "incremental"); + + // Unblocked, the readers see the new array. + t.set("B2", ""); + assert_eq!((t.num("B1"), t.num("B2")), (5.0, 6.0)); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (5.0, 100.0, 111.0)); +} diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 3257082bb7..7e50e78f62 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -1,15 +1,29 @@ //! Chart layout: title, legend, axes and every chart kind, drawn into [`Prim`]s. -use std::collections::HashSet; use std::f32::consts::{PI, TAU}; -use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, QuartileMethod, Theme, TrendlineKind}; +use gridcraft_model::{Chart, ChartKind, LineDash, QuartileMethod, Theme, TrendlineKind}; use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale}; use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color}; use crate::trend::{auto_name, fit_trendline, moving_average}; use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign}; +mod cartesian; +mod frame; +mod kinds; +mod legend; +mod lines; +mod table; +mod trend; + +use cartesian::{cartesian, scatter}; +use frame::{Bx, axis_titles, chart_title}; +use kinds::{box_whisker, funnel, histogram, pie, radar, stock, treemap, waterfall}; +use legend::draw_legend; +pub use legend::{Swatch, legend_entries}; +pub use trend::supports_trendline; + pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF]; const DARK_TEXT: Rgba = [0x26, 0x26, 0x26, 0xFF]; const GRID: Rgba = [0xD9, 0xD9, 0xD9, 0xFF]; @@ -31,32 +45,6 @@ const MAX_MARKERS: usize = 5000; /// Data labels are skipped when a series has more points than this. const MAX_LABELS: usize = 200; -#[derive(Clone, Copy, Debug)] -struct Bx { - x: f32, - y: f32, - w: f32, - h: f32, -} - -impl Bx { - fn right(&self) -> f32 { - self.x + self.w - } - fn bottom(&self) -> f32 { - self.y + self.h - } - fn ok(&self) -> bool { - self.w.is_finite() && self.h.is_finite() && self.w > 4.0 && self.h > 4.0 - } - fn cx(&self) -> f32 { - self.x + self.w / 2.0 - } - fn cy(&self) -> f32 { - self.y + self.h / 2.0 - } -} - struct Ctx<'a> { out: Vec, m: &'a dyn Measure, @@ -82,8 +70,7 @@ impl Ctx<'_> { } String::new() } - #[allow(clippy::too_many_arguments)] - fn text(&mut self, x: f32, y: f32, s: &str, size: f32, color: Rgba, align: HAlign, valign: VAlign) { + fn text(&mut self, x: f32, y: f32, s: &str, size: f32, color: Rgba, (align, valign): (HAlign, VAlign)) { if s.is_empty() { return; } @@ -105,85 +92,6 @@ impl Ctx<'_> { } } -/// Text colour readable on `fill`. -fn on(fill: Rgba) -> Rgba { - let l = 0.299 * fill[0] as f32 + 0.587 * fill[1] as f32 + 0.114 * fill[2] as f32; - if l < 150.0 { WHITE } else { DARK_TEXT } -} - -/// How a legend entry's swatch is drawn. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Swatch { - Box, - Line, - LineMarker, - Marker, -} - -/// The kind a series is drawn as (per-series kinds only apply to combo charts). -fn plot_kind(chart: &Chart, s: &SeriesData) -> ChartKind { - if chart.kind == ChartKind::Combo { if s.kind == ChartKind::Combo { ChartKind::Line } else { s.kind } } else { chart.kind } -} - -/// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). -fn point_color(data: &ChartData, j: usize) -> Rgba { - match (j, data.series.first()) { - (0, Some(s)) => s.color, - _ => j.checked_rem(data.palette.len()).and_then(|k| data.palette.get(k)).copied().unwrap_or_else(|| series_color(&Theme::default(), j)), - } -} - -fn first_len(data: &ChartData) -> usize { - data.series.first().map(|s| s.values.len()).unwrap_or(0) -} - -fn cat_label(data: &ChartData, j: usize) -> String { - data.categories.get(j).cloned().unwrap_or_else(|| (j + 1).to_string()) -} - -/// Legend entries (text, colour, swatch) `render` draws for this chart; empty when hidden. -pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swatch)> { - if chart.legend == LegendPos::None { - return vec![]; - } - match chart.kind { - ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst => { - let n = first_len(data).min(MAX_CATS); - (0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect() - } - ChartKind::Histogram | ChartKind::Funnel | ChartKind::Stock => vec![], - ChartKind::Waterfall => { - if data.series.is_empty() { - return vec![]; - } - let total = data.series.first().map(|s| s.color).unwrap_or(TEXT); - vec![("Increase".into(), UP, Swatch::Box), ("Decrease".into(), DOWN, Swatch::Box), ("Total".into(), total, Swatch::Box)] - } - _ => { - let series = data.series.iter().take(MAX_SERIES); - let mut out: Vec<(String, Rgba, Swatch)> = series - .clone() - .map(|s| { - let sw = match plot_kind(chart, s) { - ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, - ChartKind::LineMarkers => Swatch::LineMarker, - ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, - _ => Swatch::Box, - }; - (s.name.clone(), s.color, sw) - }) - .collect(); - // Trendlines follow the series, named "Linear (Sales)" unless given a name. - for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) { - for t in s.trendlines.iter().take(MAX_TRENDLINES) { - out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); - } - } - out - } - } -} - fn sanitize_vals(v: &[Option]) -> Vec> { v.iter().take(MAX_POINTS).map(|x| x.filter(|n| n.is_finite()).map(clean)).collect() } @@ -213,14 +121,6 @@ fn sanitize(d: &ChartData) -> ChartData { } } -fn chart_title(chart: &Chart, data: &ChartData) -> Option { - match &chart.title { - Some(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()), - None if data.series.len() == 1 => data.series.first().map(|s| s.name.clone()).filter(|t| !t.is_empty()), - None => None, - } -} - /// Lays out and draws a chart into a `w`×`h` box at the origin. Empty for a degenerate box. pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) -> Vec { if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e7 || h > 1e7 { @@ -234,7 +134,7 @@ pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) if let Some(t) = chart_title(chart, &data) { let size = TITLE_SIZE.min(h * 0.12).max(4.0); let t = ctx.fit(&t, size, area.w); - ctx.text(w / 2.0, area.y, &t, size, TEXT, HAlign::Center, VAlign::Top); + ctx.text(w / 2.0, area.y, &t, size, TEXT, (HAlign::Center, VAlign::Top)); let used = size * 1.3 + 4.0; area.y += used; area.h -= used; @@ -276,1483 +176,6 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { } } -fn axis_titles(ctx: &mut Ctx, chart: &Chart, mut area: Bx) -> Bx { - let lh = AXIS_TITLE_SIZE * 1.4 + 2.0; - if let Some(t) = chart.x_title.as_deref().map(str::trim).filter(|t| !t.is_empty()) { - let t = ctx.fit(t, AXIS_TITLE_SIZE, area.w); - ctx.text(area.cx(), area.bottom(), &t, AXIS_TITLE_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - area.h -= lh; - } - if let Some(t) = chart.y_title.as_deref().map(str::trim).filter(|t| !t.is_empty()) { - let t = ctx.fit(t, AXIS_TITLE_SIZE, area.h); - if !t.is_empty() { - ctx.out.push(Prim::Text { - x: area.x, - y: area.cy(), - text: t, - size: AXIS_TITLE_SIZE, - color: TEXT, - bold: false, - align: HAlign::Center, - valign: VAlign::Top, - rotation: -PI / 2.0, - }); - } - area.x += lh; - area.w -= lh; - } - area -} - -// ---------------------------------------------------------------- legend - -fn swatch_w(sw: Swatch, s: f32) -> f32 { - if sw == Swatch::Box { s } else { s * 2.0 } -} - -fn draw_swatch(ctx: &mut Ctx, sw: Swatch, x: f32, yc: f32, s: f32, color: Rgba) { - match sw { - Swatch::Box => ctx.rect(x, yc - s / 2.0, s, s, color, None), - Swatch::Line => ctx.hline(x, x + 2.0 * s, yc, color, 2.0), - Swatch::LineMarker => { - ctx.hline(x, x + 2.0 * s, yc, color, 2.0); - ctx.out.push(Prim::Circle { cx: x + s, cy: yc, r: s * 0.35, fill: Some(color), stroke: None }); - } - Swatch::Marker => ctx.out.push(Prim::Circle { cx: x + s, cy: yc, r: s * 0.4, fill: Some(color), stroke: None }), - } -} - -fn draw_legend(ctx: &mut Ctx, entries: &[(String, Rgba, Swatch)], pos: LegendPos, area: Bx) -> Bx { - let size = LABEL_SIZE; - let row_h = size * 1.6; - let s = size * 0.8; - let gap = 4.0; - let spacing = size * 1.3; - let item_w = |ctx: &Ctx, e: &(String, Rgba, Swatch)| swatch_w(e.2, s) + gap + ctx.tw(&e.0, size); - match pos { - LegendPos::None => area, - LegendPos::Top | LegendPos::Bottom => { - let max_rows = ((area.h * 0.3 / row_h).floor() as usize).max(1); - let mut rows: Vec> = vec![vec![]]; - let mut cur = 0.0f32; - for (i, e) in entries.iter().enumerate() { - let iw = item_w(ctx, e).min(area.w); - let need = if cur > 0.0 { spacing + iw } else { iw }; - if cur > 0.0 && cur + need > area.w { - if rows.len() >= max_rows { - break; - } - rows.push(vec![]); - cur = 0.0; - } - cur += if cur > 0.0 { spacing + iw } else { iw }; - if let Some(r) = rows.last_mut() { - r.push((i, iw)); - } - } - let lh = rows.len() as f32 * row_h; - let y0 = if pos == LegendPos::Bottom { area.bottom() - lh } else { area.y }; - for (ri, row) in rows.iter().enumerate() { - let total: f32 = row.iter().map(|(_, w)| w).sum::() + spacing * row.len().saturating_sub(1) as f32; - let mut x = area.x + (area.w - total).max(0.0) / 2.0; - let yc = y0 + ri as f32 * row_h + row_h / 2.0; - for &(i, iw) in row { - if let Some(e) = entries.get(i) { - draw_swatch(ctx, e.2, x, yc, s, e.1); - let sx = swatch_w(e.2, s) + gap; - let t = ctx.fit(&e.0, size, (iw - sx).max(0.0) + 0.5); - ctx.text(x + sx, yc, &t, size, TEXT, HAlign::Left, VAlign::Middle); - } - x += iw + spacing; - } - } - let used = lh + 4.0; - if pos == LegendPos::Bottom { Bx { h: area.h - used, ..area } } else { Bx { y: area.y + used, h: area.h - used, ..area } } - } - LegendPos::Left | LegendPos::Right => { - let colw = entries.iter().map(|e| item_w(ctx, e)).fold(0.0f32, f32::max).min(area.w * 0.35); - let max_rows = ((area.h / row_h).floor() as usize).max(1); - let n = entries.len().min(max_rows); - let lh = n as f32 * row_h; - let y0 = area.y + (area.h - lh).max(0.0) / 2.0; - let x0 = if pos == LegendPos::Right { area.right() - colw } else { area.x }; - for (i, e) in entries.iter().take(n).enumerate() { - let yc = y0 + i as f32 * row_h + row_h / 2.0; - draw_swatch(ctx, e.2, x0, yc, s, e.1); - let sx = swatch_w(e.2, s) + gap; - let t = ctx.fit(&e.0, size, (colw - sx).max(0.0) + 0.5); - ctx.text(x0 + sx, yc, &t, size, TEXT, HAlign::Left, VAlign::Middle); - } - let used = colw + 8.0; - if pos == LegendPos::Right { Bx { w: area.w - used, ..area } } else { Bx { x: area.x + used, w: area.w - used, ..area } } - } - } -} - -// ---------------------------------------------------------------- axes frame - -enum CatAxis<'a> { - /// Category labels and, for a multi-level axis, the outer levels (nearest the labels first; - /// one entry per category, non-empty where a group starts). - Labels(&'a [String], &'a [Vec]), - Numeric(Scale, &'a Fmt), -} - -/// Groups of an outer category level: `(first, end)` index pairs, a group starting at every -/// non-empty entry (and at the first category). -fn level_groups(level: &[String], n: usize) -> Vec<(usize, usize)> { - let mut starts: Vec = (0..n).filter(|&j| j == 0 || level.get(j).is_some_and(|t| !t.is_empty())).collect(); - starts.push(n); - starts.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() -} - -struct ValAxis<'a> { - scale: Scale, - fmt: &'a Fmt, -} - -impl ValAxis<'_> { - fn labels(&self) -> Vec<(f64, String)> { - self.scale.ticks().into_iter().map(|v| (v, self.fmt.format(v, Some(self.scale.step)))).collect() - } -} - -/// Draws gridlines, axis labels and the category axis line; returns the plot rectangle. -fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Option<&ValAxis>, horizontal: bool, grid: bool) -> Bx { - let ls = LABEL_SIZE; - let lh = ls * 1.4; - let ylabels = y.labels(); - let maxw = |ctx: &Ctx, l: &[(f64, String)]| l.iter().map(|(_, t)| ctx.tw(t, ls)).fold(0.0f32, f32::max); - if !horizontal { - let left = (maxw(ctx, &ylabels) + 6.0).min(area.w * 0.4); - let y2labels = y2.map(ValAxis::labels); - let right = match (&y2labels, &cat) { - (Some(l), _) => (maxw(ctx, l) + 6.0).min(area.w * 0.3), - (None, CatAxis::Numeric(s, f)) => (ctx.tw(&f.format(s.max, Some(s.step)), ls) / 2.0).min(area.w * 0.2), - _ => 4.0, - }; - let levels = match &cat { - CatAxis::Labels(_, o) => o.len() as f32, - CatAxis::Numeric(..) => 0.0, - }; - let plot = Bx { x: area.x + left, y: area.y + lh * 0.5, w: area.w - left - right, h: area.h - lh * 1.5 - 4.0 - lh * levels }; - if !plot.ok() { - return plot; - } - for (v, t) in &ylabels { - let yy = plot.bottom() - y.scale.frac(*v) * plot.h; - if grid { - ctx.hline(plot.x, plot.right(), yy, GRID, 0.75); - } - ctx.text(plot.x - 4.0, yy, t, ls, TEXT, HAlign::Right, VAlign::Middle); - } - if let (Some(a), Some(l)) = (y2, &y2labels) { - for (v, t) in l { - let yy = plot.bottom() - a.scale.frac(*v) * plot.h; - ctx.text(plot.right() + 4.0, yy, t, ls, TEXT, HAlign::Left, VAlign::Middle); - } - } - let zero = if y.scale.min <= 0.0 && y.scale.max >= 0.0 { 0.0 } else { y.scale.min }; - let y0 = plot.bottom() - y.scale.frac(zero) * plot.h; - ctx.hline(plot.x, plot.right(), y0, AXIS, 0.75); - match cat { - CatAxis::Labels(l, outer) => { - let n = l.len().max(1); - let cw = plot.w / n as f32; - let lw = l.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max); - let k = (((lw + 6.0) / cw.max(1e-3)).ceil() as usize).clamp(1, n); - for (j, t) in l.iter().enumerate().step_by(k) { - let t = ctx.fit(t, ls, cw * k as f32 - 2.0); - ctx.text(plot.x + (j as f32 + 0.5) * cw, plot.bottom() + 3.0, &t, ls, TEXT, HAlign::Center, VAlign::Top); - } - // Outer levels, one row each below the labels: a group's name centred under its - // categories, and a separator at each group boundary down through the rows. - for (i, level) in outer.iter().enumerate() { - let top = plot.bottom() + 3.0 + lh * (i as f32 + 1.0); - for (first, end) in level_groups(level, n) { - let (x0, x1) = (plot.x + first as f32 * cw, plot.x + end as f32 * cw); - if let Some(t) = level.get(first).filter(|t| !t.is_empty()) { - let t = ctx.fit(t, ls, x1 - x0 - 2.0); - ctx.text((x0 + x1) / 2.0, top, &t, ls, TEXT, HAlign::Center, VAlign::Top); - } - if first > 0 { - ctx.vline(x0, plot.bottom(), top + lh - 2.0, AXIS, 0.75); - } - } - ctx.vline(plot.right(), plot.bottom(), top + lh - 2.0, AXIS, 0.75); - } - } - CatAxis::Numeric(s, f) => { - let ticks = s.ticks(); - let labels: Vec = ticks.iter().map(|v| f.format(*v, Some(s.step))).collect(); - let lw = labels.iter().map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max); - let slot = plot.w / ticks.len().max(1) as f32; - let k = (((lw + 6.0) / slot.max(1e-3)).ceil() as usize).max(1); - for (v, t) in ticks.iter().zip(&labels).step_by(k) { - let xx = plot.x + s.frac(*v) * plot.w; - ctx.text(xx, plot.bottom() + 3.0, t, ls, TEXT, HAlign::Center, VAlign::Top); - } - if s.min <= 0.0 && s.max >= 0.0 { - let xx = plot.x + s.frac(0.0) * plot.w; - ctx.vline(xx, plot.y, plot.bottom(), AXIS, 0.75); - } - } - } - plot - } else { - let (labels, outer): (Vec, &[Vec]) = match cat { - CatAxis::Labels(l, o) => (l.to_vec(), o), - CatAxis::Numeric(..) => (vec![], &[]), - }; - let lw = (labels.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.35); - // Outer levels stand in columns left of the labels, each as wide as its longest name. - let level_w: Vec = - outer.iter().map(|l| (l.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.15)).collect(); - let levels_w: f32 = level_w.iter().sum(); - let right = ylabels.last().map(|(_, t)| ctx.tw(t, ls) / 2.0).unwrap_or(0.0).min(area.w * 0.2) + 2.0; - let plot = Bx { x: area.x + lw + levels_w, y: area.y + 2.0, w: area.w - lw - levels_w - right, h: area.h - lh - 6.0 }; - if !plot.ok() { - return plot; - } - let vw = maxw(ctx, &ylabels); - let slot = plot.w / ylabels.len().max(1) as f32; - let k = (((vw + 6.0) / slot.max(1e-3)).ceil() as usize).max(1); - for (i, (v, t)) in ylabels.iter().enumerate() { - let xx = plot.x + y.scale.frac(*v) * plot.w; - if grid { - ctx.vline(xx, plot.y, plot.bottom(), GRID, 0.75); - } - if i % k == 0 { - ctx.text(xx, plot.bottom() + 3.0, t, ls, TEXT, HAlign::Center, VAlign::Top); - } - } - let zero = if y.scale.min <= 0.0 && y.scale.max >= 0.0 { 0.0 } else { y.scale.min }; - let x0 = plot.x + y.scale.frac(zero) * plot.w; - ctx.vline(x0, plot.y, plot.bottom(), AXIS, 0.75); - let n = labels.len().max(1); - let ch = plot.h / n as f32; - let k = ((lh / ch.max(1e-3)).ceil() as usize).clamp(1, n); - for (j, t) in labels.iter().enumerate().step_by(k) { - let t = ctx.fit(t, ls, lw - 6.0); - ctx.text(plot.x - 4.0, plot.bottom() - (j as f32 + 0.5) * ch, &t, ls, TEXT, HAlign::Right, VAlign::Middle); - } - // Outer levels: a group's name centred beside its categories, separators at the - // boundaries running right to the axis. - let mut x1 = plot.x - lw; - for (level, w) in outer.iter().zip(&level_w) { - let x0 = x1 - w; - for (first, end) in level_groups(level, n) { - let (y0, y1) = (plot.bottom() - end as f32 * ch, plot.bottom() - first as f32 * ch); - if let Some(t) = level.get(first).filter(|t| !t.is_empty()) { - let t = ctx.fit(t, ls, w - 4.0); - ctx.text((x0 + x1) / 2.0, (y0 + y1) / 2.0, &t, ls, TEXT, HAlign::Center, VAlign::Middle); - } - if first > 0 { - ctx.hline(x0, plot.x, y1, AXIS, 0.75); - } - } - ctx.hline(x0, plot.x, plot.y, AXIS, 0.75); - x1 = x0; - } - plot - } -} - -// ---------------------------------------------------------------- helpers - -/// Reduces a long polyline to first/min/max/last per pixel column. -fn decimate(pts: Vec<[f32; 2]>, max: usize) -> Vec<[f32; 2]> { - if pts.len() <= max { - return pts; - } - let mut out = Vec::with_capacity(max * 2); - let mut i = 0; - while let Some(p) = pts.get(i) { - let col = p[0].floor(); - let (start, mut mn, mut mx) = (i, i, i); - let mut k = i + 1; - while let Some(q) = pts.get(k) { - if q[0].floor() != col { - break; - } - if pts.get(mn).is_some_and(|m| q[1] < m[1]) { - mn = k; - } - if pts.get(mx).is_some_and(|m| q[1] > m[1]) { - mx = k; - } - k += 1; - } - let mut idx = [start, mn, mx, k - 1]; - idx.sort_unstable(); - let mut last = usize::MAX; - for ix in idx { - if ix != last - && let Some(q) = pts.get(ix) - { - out.push(*q); - last = ix; - } - } - i = k; - } - if out.len() > max * 4 { - let step = out.len() / (max * 2) + 1; - let last = out.last().copied(); - let mut s: Vec<[f32; 2]> = out.into_iter().step_by(step).collect(); - if let Some(l) = last - && s.last() != Some(&l) - { - s.push(l); - } - return s; - } - out -} - -/// Draws a polyline split at gaps (`None`), decimated when long. With `smooth` (the plot box), -/// each run is interpolated with a Catmull-Rom spline so the line curves through the data points. -fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32, smooth: Option) { - let mut run: Vec<[f32; 2]> = Vec::new(); - for p in pts.iter().chain(std::iter::once(&None)) { - match p { - Some(p) => run.push(*p), - None => { - if run.len() >= 2 { - let r = decimate(std::mem::take(&mut run), MAX_LINE_PTS); - let r = match smooth { - Some(plot) => smooth_run(r, plot), - None => r, - }; - ctx.line(r, color, width); - } else { - run.clear(); - } - } - } - } -} - -/// Catmull-Rom spline through `pts`: every segment gets the same number of sub-segments (up to -/// 100), chosen so the whole curve stays within `MAX_LINE_PTS * 2` points. Endpoints are -/// duplicated so the curve passes through the first and last points, and the curve is clamped -/// to the `plot` box (a spline overshoots its data near sharp turns). -fn smooth_run(pts: Vec<[f32; 2]>, plot: Bx) -> Vec<[f32; 2]> { - let n = pts.len(); - if n < 3 { - return pts; - } - let cap = MAX_LINE_PTS * 2; - let steps = (cap / n).clamp(1, 100); - let mut out: Vec<[f32; 2]> = Vec::with_capacity(n.saturating_mul(steps).min(cap) + 1); - let at = |i: isize| -> [f32; 2] { - let j = i.clamp(0, n as isize - 1) as usize; - pts.get(j).copied().unwrap_or([0.0, 0.0]) - }; - let (x0, x1) = (plot.x.min(plot.right()), plot.x.max(plot.right())); - let (y0, y1) = (plot.y.min(plot.bottom()), plot.y.max(plot.bottom())); - let clip = |p: [f32; 2]| [p[0].clamp(x0, x1), p[1].clamp(y0, y1)]; - for i in 0..n.saturating_sub(1) { - let (p0, p1, p2, p3) = (at(i as isize - 1), at(i as isize), at(i as isize + 1), at(i as isize + 2)); - for s in 0..steps { - let t = s as f32 / steps as f32; - out.push(clip(catmull(p0, p1, p2, p3, t))); - } - } - out.push(clip(at(n as isize - 1))); - out -} - -/// One Catmull-Rom point between `p1` and `p2` (uniform parameterisation), tangent-scaled by 0.5. -fn catmull(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] { - let t2 = t * t; - let t3 = t2 * t; - let mut o = [0.0f32; 2]; - for k in 0..2 { - let (a0, a1, a2, a3) = (p0[k], p1[k], p2[k], p3[k]); - o[k] = 0.5 * ((2.0 * a1) + (-a0 + a2) * t + (2.0 * a0 - 5.0 * a1 + 4.0 * a2 - a3) * t2 + (-a0 + 3.0 * a1 - 3.0 * a2 + a3) * t3); - } - o -} - -fn draw_markers(ctx: &mut Ctx, pts: impl Iterator, r: f32, color: Rgba) { - let mut seen = HashSet::new(); - for p in pts { - if seen.len() >= MAX_MARKERS { - break; - } - if seen.insert(((p[0] * 0.5) as i32, (p[1] * 0.5) as i32)) { - ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(color), stroke: Some((WHITE, 0.75)) }); - } - } -} - -fn value_range(it: impl Iterator) -> Option<(f64, f64)> { - it.fold(None, |acc, v| match acc { - None => Some((v, v)), - Some((a, b)) => Some((a.min(v), b.max(v))), - }) -} - -// ---------------------------------------------------------------- trendlines - -/// Samples along a regression trendline. -const TREND_STEPS: usize = 200; - -/// Whether series drawn as `k` show trendlines (Excel offers them on 2-D unstacked column, -/// bar, line, area, scatter and bubble charts). -pub fn supports_trendline(k: ChartKind) -> bool { - use ChartKind::*; - matches!(k, ColumnClustered | BarClustered | Line | LineMarkers | Area | Scatter | ScatterLines | Bubble) -} - -/// A forecast distance as drawn: finite, non-negative and bounded. -fn forecast(v: f64) -> f64 { - if v.is_finite() && v > 0.0 { v.min(1e9) } else { 0.0 } -} - -/// Most empty category slots a forward forecast may add after `ncat` categories: four times the -/// data (at least 32), and never past `MAX_CATS` in total. A larger forecast would shrink every -/// column to nothing. -fn max_forward_slots(ncat: usize) -> f64 { - (ncat.saturating_mul(4).max(32)).min(MAX_CATS.saturating_sub(ncat)) as f64 -} - -/// Longest forward forecast among `s`'s regression trendlines. -fn max_forward(s: &SeriesData) -> f64 { - s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.forward)).fold(0.0, f64::max) -} - -/// Longest backward forecast among `s`'s regression trendlines. -fn max_backward(s: &SeriesData) -> f64 { - s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.backward)).fold(0.0, f64::max) -} - -/// Liang–Barsky: the part of segment `a`–`b` inside the unit square, with whether the start and -/// end were cut. -#[allow(clippy::type_complexity)] -fn clip_segment(a: (f64, f64), b: (f64, f64)) -> Option<((f64, f64), (f64, f64), bool, bool)> { - let (dx, dy) = (b.0 - a.0, b.1 - a.1); - let (mut t0, mut t1) = (0.0f64, 1.0f64); - for (p, q) in [(-dx, a.0), (dx, 1.0 - a.0), (-dy, a.1), (dy, 1.0 - a.1)] { - if p == 0.0 { - if q < 0.0 { - return None; - } - } else { - let r = q / p; - if p < 0.0 { - if r > t1 { - return None; - } - t0 = t0.max(r); - } else { - if r < t0 { - return None; - } - t1 = t1.min(r); - } - } - } - Some(((a.0 + t0 * dx, a.1 + t0 * dy), (a.0 + t1 * dx, a.1 + t1 * dy), t0 > 0.0, t1 < 1.0)) -} - -/// Clips a sampled polyline in plot fractions (`None` = gap) to the plot box (the unit -/// square), returning the visible runs. -fn clip_unit(pts: &[Option<(f64, f64)>]) -> Vec> { - const LIM: f64 = 1e9; - let ok = |p: &(f64, f64)| p.0.is_finite() && p.1.is_finite(); - let cl = |p: (f64, f64)| (p.0.clamp(-LIM, LIM), p.1.clamp(-LIM, LIM)); - let mut runs: Vec> = Vec::new(); - let mut run: Vec<(f64, f64)> = Vec::new(); - for w in pts.windows(2) { - let seg = match w { - [Some(a), Some(b)] if ok(a) && ok(b) => clip_segment(cl(*a), cl(*b)), - _ => None, - }; - match seg { - Some((p, q, cut_start, cut_end)) => { - if cut_start || run.is_empty() { - if run.len() >= 2 { - runs.push(std::mem::take(&mut run)); - } - run.clear(); - run.push(p); - } - run.push(q); - if cut_end { - runs.push(std::mem::take(&mut run)); - } - } - None => { - if run.len() >= 2 { - runs.push(std::mem::take(&mut run)); - } - run.clear(); - } - } - } - if run.len() >= 2 { - runs.push(run); - } - runs -} - -/// Draws `s`'s trendlines fitted to its plotted points `pts` (data x, y). `frac` maps data to -/// fractions of the plot box (0..1 inside, along the x and y axes), `px` fractions to pixels. -/// Equation and R² label lines are appended to `labels`. Degenerate fits draw nothing. -fn draw_trendlines( - ctx: &mut Ctx, - s: &SeriesData, - pts: &[(f64, f64)], - frac: &dyn Fn(f64, f64) -> (f64, f64), - px: &dyn Fn((f64, f64)) -> [f32; 2], - labels: &mut Vec, - window: (f64, f64), -) { - let Some((xlo, xhi)) = value_range(pts.iter().map(|p| p.0)) else { return }; - for t in s.trendlines.iter().take(MAX_TRENDLINES) { - let spec = &t.spec; - let samples: Vec> = match spec.kind { - TrendlineKind::MovingAverage(p) => moving_average(pts, p).into_iter().map(|(x, y)| Some(frac(x, y))).collect(), - _ => { - let Some(fit) = fit_trendline(spec, pts) else { continue }; - // Sample only the part of the forecast that is on the plot. - let (lo, hi) = ((xlo - forecast(spec.backward)).max(window.0), (xhi + forecast(spec.forward)).min(window.1)); - if spec.display_equation { - labels.push(fit.equation()); - } - if spec.display_r_squared { - labels.push(fit.r_squared()); - } - (0..=TREND_STEPS) - .map(|i| { - let x = lo + (hi - lo) * i as f64 / TREND_STEPS as f64; - fit.eval(x).map(|y| frac(x, y)) - }) - .collect() - } - }; - let width = spec.width.filter(|w| w.is_finite()).unwrap_or(1.5).clamp(0.25, 12.0); - let dash = spec.dash != Some(LineDash::Solid); - for run in clip_unit(&samples) { - let line = decimate(run.into_iter().map(px).collect(), MAX_LINE_PTS); - if line.len() >= 2 { - ctx.out.push(Prim::Line { pts: line, color: t.color, width, dash }); - } - } - } -} - -/// Trendline equation / R² labels, stacked in the plot's top-right corner. -fn draw_trend_labels(ctx: &mut Ctx, plot: Bx, labels: &[String]) { - let lh = LABEL_SIZE * 1.3; - for (i, t) in labels.iter().enumerate() { - let y = plot.y + 4.0 + i as f32 * lh; - if y + lh > plot.bottom() { - break; - } - let t = ctx.fit(t, LABEL_SIZE, plot.w - 8.0); - ctx.text(plot.right() - 4.0, y, &t, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Top); - } -} - -// ---------------------------------------------------------------- cartesian (column/bar/line/area/combo) - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Fam { - Col, - ColStack, - Col100, - Line, - LineStack, - Area, - AreaStack, - Area100, -} - -fn family(k: ChartKind) -> Fam { - use ChartKind::*; - match k { - ColumnStacked | BarStacked => Fam::ColStack, - ColumnStacked100 | BarStacked100 => Fam::Col100, - Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line, - LineStacked => Fam::LineStack, - Area => Fam::Area, - AreaStacked => Fam::AreaStack, - AreaStacked100 => Fam::Area100, - _ => Fam::Col, - } -} - -/// Families stacked to 100%: each category's values are shares of its total. -fn is_100(f: Fam) -> bool { - matches!(f, Fam::Col100 | Fam::Area100) -} - -fn is_col(f: Fam) -> bool { - matches!(f, Fam::Col | Fam::ColStack | Fam::Col100) -} -fn is_line(f: Fam) -> bool { - matches!(f, Fam::Line | Fam::LineStack) -} - -fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { - let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); - if ncat == 0 { - return; - } - let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { plot_kind(chart, s) }).collect(); - let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); - let any_primary = data.series.iter().any(|s| !s.secondary); - let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); - - // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). - let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); - for (i, s) in data.series.iter().enumerate() { - let fam = fams.get(i).copied().unwrap_or(Fam::Col); - if is_100(fam) { - let key = (sec.get(i).copied().unwrap_or(false), fam); - let p = match totals.iter().position(|(k, _)| *k == key) { - Some(p) => p, - None => { - totals.push((key, vec![0.0; ncat])); - totals.len() - 1 - } - }; - for (j, v) in s.values.iter().take(ncat).enumerate() { - if let (Some(v), Some(t)) = (v, totals.get_mut(p).and_then(|(_, t)| t.get_mut(j))) { - *t += v.abs(); - } - } - } - } - // A value's share of its category's total, for the 100% families. - let share = |key: (bool, Fam), j: usize, v: f64| { - let t = totals.iter().find(|(k, _)| *k == key).and_then(|(_, t)| t.get(j)).copied().unwrap_or(0.0); - if t > 0.0 { v / t } else { 0.0 } - }; - // Stack accumulators keyed by (axis, family): positive and negative running sums. - let mut stacks: Vec<((bool, Fam), Vec, Vec)> = Vec::new(); - let mut spans: Vec>> = Vec::with_capacity(data.series.len()); - for (i, s) in data.series.iter().enumerate() { - let fam = fams.get(i).copied().unwrap_or(Fam::Col); - let a = sec.get(i).copied().unwrap_or(false); - let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100); - let key = (a, fam); - let si = if stacked { - match stacks.iter().position(|(k, _, _)| *k == key) { - Some(p) => Some(p), - None => { - stacks.push((key, vec![0.0; ncat], vec![0.0; ncat])); - Some(stacks.len() - 1) - } - } - } else { - None - }; - let mut row = Vec::with_capacity(ncat); - for j in 0..ncat { - let v = s.values.get(j).copied().flatten(); - let span = match (si.and_then(|p| stacks.get_mut(p)), fam) { - (Some((_, pos, neg)), Fam::ColStack | Fam::Col100) => v.and_then(|v| { - let v = if fam == Fam::Col100 { share(key, j, v) } else { v }; - let acc = if v >= 0.0 { pos.get_mut(j) } else { neg.get_mut(j) }?; - let base = *acc; - *acc += v; - Some((base, *acc)) - }), - (Some((_, pos, _)), _) => { - let v = v.unwrap_or(0.0); - 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); - (base, *acc) - }) - } - (None, _) => v.map(|v| (0.0, v)), - }; - row.push(span); - } - spans.push(row); - } - - // Axis scales. - let mut axes: Vec<(Scale, Fmt)> = Vec::new(); - for axis in [false, true] { - let members: Vec = (0..data.series.len()).filter(|i| sec.get(*i).copied().unwrap_or(false) == axis).collect(); - if members.is_empty() { - continue; - } - let force_zero = members.iter().any(|i| fams.get(*i).is_some_and(|f| !is_line(*f))); - let all100 = members.iter().all(|i| fams.get(*i).is_some_and(|f| is_100(*f))); - let range = value_range(members.iter().flat_map(|i| { - let line = fams.get(*i).is_some_and(|f| is_line(*f)); - spans.get(*i).into_iter().flatten().flatten().flat_map(move |(b, t)| if line { vec![*t] } else { vec![*b, *t] }) - })); - let (lo, hi) = range.unwrap_or((0.0, 0.0)); - let (scale, fmt) = if all100 { - (fixed_scale(if lo < -1e-9 { -1.0 } else { 0.0 }, if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, 0.2), Fmt::new("0%")) - } else { - let code = members.first().and_then(|i| data.series.get(*i)).map(|s| s.number_format.as_str()).unwrap_or("General"); - (nice_scale(lo, hi, force_zero), Fmt::new(code)) - }; - axes.push((scale, fmt)); - if !axis && sec.iter().all(|s| !s) { - break; - } - } - let Some((s1, f1)) = axes.first() else { return }; - let y1 = ValAxis { scale: *s1, fmt: f1 }; - let y2 = axes.get(1).map(|(s, f)| ValAxis { scale: *s, fmt: f }); - // A forward forecast on a category axis adds empty category slots after the data. - let fwd = data - .series - .iter() - .enumerate() - .filter(|(i, _)| kinds.get(*i).is_some_and(|k| supports_trendline(*k))) - .map(|(_, s)| max_forward(s)) - .fold(0.0, f64::max); - let ncat_slots = ncat.saturating_add(fwd.min(max_forward_slots(ncat)).ceil() as usize).min(MAX_CATS.max(ncat)); - let labels: Vec = (0..ncat_slots).map(|j| if j < ncat { cat_label(data, j) } else { String::new() }).collect(); - // Outer levels padded to the slots (forecast slots stay in the last group). - let outer: Vec> = - data.category_levels.iter().map(|l| (0..ncat_slots).map(|j| l.get(j).cloned().unwrap_or_default()).collect()).collect(); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &outer), &y1, y2.as_ref(), horizontal, chart.gridlines); - if !plot.ok() { - return; - } - let scale_of = |i: usize| -> Scale { if sec.get(i).copied().unwrap_or(false) { y2.as_ref().map(|a| a.scale).unwrap_or(*s1) } else { *s1 } }; - let cat_len = if horizontal { plot.h } else { plot.w }; - let cw = cat_len / ncat_slots as f32; - let center = |j: usize| if horizontal { plot.bottom() - (j as f32 + 0.5) * cw } else { plot.x + (j as f32 + 0.5) * cw }; - let vpos = |v: f64, sc: &Scale| if horizontal { plot.x + sc.frac(v) * plot.w } else { plot.bottom() - sc.frac(v) * plot.h }; - - // Column slots: each clustered series gets one, each stack group shares one. - let mut slot_keys: Vec<(bool, Fam, usize)> = Vec::new(); - let mut slot_of = vec![0usize; data.series.len()]; - for (i, f) in fams.iter().enumerate() { - if !is_col(*f) { - continue; - } - let a = sec.get(i).copied().unwrap_or(false); - let key = if *f == Fam::Col { (a, *f, i) } else { (a, *f, usize::MAX) }; - let k = match slot_keys.iter().position(|k| *k == key) { - Some(p) => p, - None => { - slot_keys.push(key); - slot_keys.len() - 1 - } - }; - if let Some(s) = slot_of.get_mut(i) { - *s = k; - } - } - let nslots = slot_keys.len().max(1) as f32; - let bw = cw / (nslots + 1.5); - let labels_on = chart.data_labels && ncat <= MAX_LABELS; - // Area labels wait until every area is filled, so a later (stacked) area can't paint over them. - let mut area_labels = Vec::new(); - - // Areas first, then columns, then lines on top. - for pass in 0..3 { - for (i, s) in data.series.iter().enumerate() { - let fam = fams.get(i).copied().unwrap_or(Fam::Col); - let want = match pass { - 0 => matches!(fam, Fam::Area | Fam::AreaStack | Fam::Area100), - 1 => is_col(fam), - _ => is_line(fam), - }; - if !want { - continue; - } - let sc = scale_of(i); - let fmt = Fmt::new(&s.number_format); - let row = match spans.get(i) { - Some(r) => r, - None => continue, - }; - match pass { - 0 => { - let mut top = Vec::with_capacity(ncat * 2); - let mut base = Vec::with_capacity(ncat); - for (j, sp) in row.iter().enumerate() { - let (b, t) = sp.unwrap_or((0.0, 0.0)); - let c = center(j); - top.push([c, vpos(t, &sc)]); - base.push([c, vpos(b, &sc)]); - // Source values (not stack totals), just above the top edge like the line labels. - if labels_on - && sp.is_some() - && let Some(v) = s.values.get(j).copied().flatten() - { - area_labels.push((c, vpos(t, &sc) - 5.0, fmt.format(v, None))); - } - } - if top.len() == 1 { - // A single point: give it some width. - if let (Some(t), Some(b)) = (top.first().copied(), base.first().copied()) { - top = vec![[t[0] - cw * 0.3, t[1]], [t[0] + cw * 0.3, t[1]]]; - base = vec![[b[0] - cw * 0.3, b[1]], [b[0] + cw * 0.3, b[1]]]; - } - } - let top = decimate(top, MAX_LINE_PTS * 2); - let base = decimate(base, MAX_LINE_PTS * 2); - let mut poly = top; - poly.extend(base.into_iter().rev()); - if poly.len() >= 3 { - ctx.out.push(Prim::Polygon { pts: poly, fill: s.color, stroke: None }); - } - } - 1 => { - let k = slot_of.get(i).copied().unwrap_or(0) as f32; - for (j, sp) in row.iter().enumerate() { - let Some((b, t)) = sp else { continue }; - let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc)); - let c = center(j); - let lo = pb.min(pt); - let len = (pb - pt).abs(); - if horizontal { - let y = c + nslots * bw / 2.0 - (k + 1.0) * bw; - ctx.rect(lo, y, len, bw, s.color, None); - } else { - let x = c - nslots * bw / 2.0 + k * bw; - ctx.rect(x, lo, bw, len, s.color, None); - } - if labels_on && let Some(v) = s.values.get(j).copied().flatten() { - let t = fmt.format(v, None); - let stacked = fam != Fam::Col; - let mid = (pb + pt) / 2.0; - if horizontal { - let y = c + nslots * bw / 2.0 - (k + 0.5) * bw; - if stacked { - ctx.text(mid, y, &t, LABEL_SIZE, on(s.color), HAlign::Center, VAlign::Middle); - } else if v >= 0.0 { - ctx.text(pb.max(pt) + 3.0, y, &t, LABEL_SIZE, TEXT, HAlign::Left, VAlign::Middle); - } else { - ctx.text(lo - 3.0, y, &t, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Middle); - } - } else { - let x = c - nslots * bw / 2.0 + (k + 0.5) * bw; - if stacked { - ctx.text(x, mid, &t, LABEL_SIZE, on(s.color), HAlign::Center, VAlign::Middle); - } else if v >= 0.0 { - ctx.text(x, lo - 2.0, &t, LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } else { - ctx.text(x, lo + len + 2.0, &t, LABEL_SIZE, TEXT, HAlign::Center, VAlign::Top); - } - } - } - } - } - _ => { - let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); - draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); - let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); - if k == ChartKind::LineMarkers && cw >= 3.0 { - draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); - } - if labels_on { - for (j, p) in pts.iter().enumerate() { - if let (Some(p), Some(v)) = (p, s.values.get(j).copied().flatten()) { - ctx.text(p[0], p[1] - 5.0, &fmt.format(v, None), LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } - } - } - } - } - } - for (x, y, t) in area_labels.drain(..) { - ctx.text(x, y, &t, LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } - } - // Trendlines on top: x is the category number 1..n. - let mut trend_labels = Vec::new(); - for (i, s) in data.series.iter().enumerate() { - if s.trendlines.is_empty() || !kinds.get(i).is_some_and(|k| supports_trendline(*k)) { - continue; - } - let sc = scale_of(i); - let pts: Vec<(f64, f64)> = s.values.iter().take(ncat).enumerate().filter_map(|(j, v)| v.map(|v| ((j + 1) as f64, v))).collect(); - let frac = |x: f64, y: f64| ((x - 0.5) / ncat_slots as f64, (y - sc.min) / (sc.max - sc.min)); - let px = |(fx, fy): (f64, f64)| { - if horizontal { - [plot.x + fy as f32 * plot.w, plot.bottom() - fx as f32 * plot.h] - } else { - [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h] - } - }; - draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels, (0.5, ncat_slots as f64 + 0.5)); - } - draw_trend_labels(ctx, plot, &trend_labels); -} - -// ---------------------------------------------------------------- scatter & bubble - -fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let pts_of = |s: &SeriesData| -> Vec> { - s.values - .iter() - .enumerate() - .map(|(j, v)| { - let x = match &s.x { - Some(xs) => xs.get(j).copied().flatten(), - None => Some((j + 1) as f64), - }; - match (x, v) { - (Some(x), Some(y)) => Some((x, *y)), - _ => None, - } - }) - .collect() - }; - let all: Vec>> = data.series.iter().map(pts_of).collect(); - let Some((mut xlo, mut xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return }; - // Forecasts extend the x axis to the trendline's ends. - for (s, pts) in data.series.iter().zip(&all) { - if let Some((lo, hi)) = value_range(pts.iter().flatten().map(|p| p.0)).filter(|_| !s.trendlines.is_empty()) { - xlo = xlo.min(lo - max_backward(s)); - xhi = xhi.max(hi + max_forward(s)); - } - } - let Some((ylo, yhi)) = value_range(all.iter().flatten().flatten().map(|p| p.1)) else { return }; - let xs = nice_scale(xlo, xhi, false); - let ys = nice_scale(ylo, yhi, false); - let fx = Fmt::new("General"); - let fy = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); - let plot = frame(ctx, area, CatAxis::Numeric(xs, &fx), &ValAxis { scale: ys, fmt: &fy }, None, false, chart.gridlines); - if !plot.ok() { - return; - } - let map = |(x, y): (f64, f64)| [plot.x + xs.frac(x) * plot.w, plot.bottom() - ys.frac(y) * plot.h]; - let bubble = chart.kind == ChartKind::Bubble; - let rmax = plot.w.min(plot.h) * 0.12; - for (s, pts) in data.series.iter().zip(&all) { - let px: Vec> = pts.iter().map(|p| p.map(map)).collect(); - if bubble { - let sizes = s.sizes.as_deref().unwrap_or(&[]); - let smax = sizes.iter().flatten().fold(0.0f64, |a, b| a.max(*b)); - let mut bubbles: Vec<([f32; 2], f64)> = px - .iter() - .enumerate() - .filter_map(|(j, p)| { - let sz = if sizes.is_empty() { Some(1.0) } else { sizes.get(j).copied().flatten() }; - match (p, sz) { - (Some(p), Some(sz)) if sz > 0.0 => Some((*p, sz)), - _ => None, - } - }) - .take(MAX_MARKERS) - .collect(); - bubbles.sort_by(|a, b| b.1.total_cmp(&a.1)); - let smax = if sizes.is_empty() { 1.0 } else { smax }; - let fill = [s.color[0], s.color[1], s.color[2], 0xC0]; - for (p, sz) in bubbles { - let r = ((sz / smax).sqrt() as f32 * rmax).max(1.0); - ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(fill), stroke: Some((WHITE, 0.75)) }); - } - } else { - let lines = chart.kind == ChartKind::ScatterLines || s.kind == ChartKind::ScatterLines; - if lines { - draw_runs(ctx, &px, s.color, 2.0, s.smooth.then_some(plot)); - } - if !lines || px.len() <= 500 { - draw_markers(ctx, px.iter().flatten().copied(), 3.5, s.color); - } - } - if chart.data_labels && pts.len() <= MAX_LABELS { - for (p, raw) in px.iter().zip(pts) { - if let (Some(p), Some((_, y))) = (p, raw) { - ctx.text(p[0], p[1] - 6.0, &fy.format(*y, None), LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } - } - } - } - let mut trend_labels = Vec::new(); - for (s, pts) in data.series.iter().zip(&all) { - if s.trendlines.is_empty() { - continue; - } - let pts: Vec<(f64, f64)> = pts.iter().flatten().copied().collect(); - let frac = |x: f64, y: f64| ((x - xs.min) / (xs.max - xs.min), (y - ys.min) / (ys.max - ys.min)); - let px = |(fx, fy): (f64, f64)| [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h]; - draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels, (xs.min, xs.max)); - } - draw_trend_labels(ctx, plot, &trend_labels); -} - -// ---------------------------------------------------------------- histogram - -fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let Some(s) = data.series.first() else { return }; - let vals: Vec = s.values.iter().flatten().copied().collect(); - let Some((lo, hi)) = value_range(vals.iter().copied()) else { return }; - let n = vals.len(); - let span = hi - lo; - let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100); - if !(span.is_finite() && span > 0.0) { - bins = 1; - } - let width = if bins == 1 && span.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { 1.0 } else { span / bins as f64 }; - // Upper edge of each bin, exactly as shown in the labels below. Bins are right-inclusive (the first is closed on both sides), so a value - // equal to an edge belongs to the bin that ends there. - let edges: Vec = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect(); - let mut counts = vec![0usize; bins]; - for v in &vals { - let b = edges.partition_point(|e| e < v).min(bins - 1); - if let Some(c) = counts.get_mut(b) { - *c += 1; - } - } - let f = Fmt::new(&s.number_format); - let labels: Vec = (0..bins) - .map(|b| { - let a = lo + b as f64 * width; - let e = edges.get(b).copied().unwrap_or(a); - let open = if b == 0 { '[' } else { '(' }; - format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0))) - }) - .collect(); - let maxc = counts.iter().copied().max().unwrap_or(0) as f64; - let ys = nice_scale(0.0, maxc, true); - let fc = Fmt::new("General"); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &fc }, None, false, chart.gridlines); - if !plot.ok() { - return; - } - let cw = plot.w / bins as f32; - for (b, c) in counts.iter().enumerate() { - let top = plot.bottom() - ys.frac(*c as f64) * plot.h; - let x = plot.x + b as f32 * cw; - ctx.rect(x, top, cw, plot.bottom() - top, s.color, Some((WHITE, 0.75))); - if chart.data_labels { - ctx.text(x + cw / 2.0, top - 2.0, &c.to_string(), LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } - } -} - -// ---------------------------------------------------------------- waterfall - -fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let Some(s) = data.series.first() else { return }; - let mut ncat = data.categories.len().max(s.values.len()).min(MAX_CATS); - if ncat == 0 { - return; - } - let mut labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); - let mut vals: Vec = (0..ncat).map(|j| s.values.get(j).copied().flatten().unwrap_or(0.0)).collect(); - let mut is_total = vec![false; ncat]; - let last_total = labels.last().is_some_and(|l| l.to_lowercase().contains("total")); - if let Some(t) = is_total.last_mut() { - *t = last_total; - } - if !last_total { - labels.push("Total".into()); - vals.push(0.0); - is_total.push(true); - ncat += 1; - } - let mut bars = Vec::with_capacity(ncat); - let mut cum = 0.0f64; - for (j, v) in vals.iter().enumerate() { - if is_total.get(j).copied().unwrap_or(false) { - let total = if last_total && j + 1 == ncat && *v != 0.0 { *v } else { cum }; - bars.push((0.0, total, 0u8)); - cum = total; - } else { - let top = clean(cum + v); - bars.push((cum, top, if *v >= 0.0 { 1 } else { 2 })); - cum = top; - } - } - let (lo, hi) = value_range(bars.iter().flat_map(|(b, t, _)| [*b, *t])).unwrap_or((0.0, 0.0)); - let ys = nice_scale(lo, hi, true); - let f = Fmt::new(&s.number_format); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); - if !plot.ok() { - return; - } - let cw = plot.w / ncat as f32; - let bw = cw / 1.5; - let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; - for (j, (b, t, kind)) in bars.iter().enumerate() { - let color = match kind { - 1 => UP, - 2 => DOWN, - _ => s.color, - }; - let x = plot.x + (j as f32 + 0.5) * cw - bw / 2.0; - let (yb, yt) = (vy(*b), vy(*t)); - ctx.rect(x, yb.min(yt), bw, (yb - yt).abs().max(0.5), color, None); - if j + 1 < bars.len() && ncat <= 500 { - ctx.out.push(Prim::Line { pts: vec![[x + bw, yt], [x + cw, yt]], color: AXIS, width: 0.75, dash: true }); - } - if chart.data_labels && ncat <= MAX_LABELS { - let v = if *kind == 0 { *t } else { t - b }; - ctx.text(x + bw / 2.0, yb.min(yt) - 2.0, &f.format(v, None), LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom); - } - } -} - -// ---------------------------------------------------------------- funnel - -fn funnel(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let Some(s) = data.series.first() else { return }; - let n = data.categories.len().max(s.values.len()).min(MAX_CATS); - if n == 0 { - return; - } - let vals: Vec = (0..n).map(|j| s.values.get(j).copied().flatten().unwrap_or(0.0).abs()).collect(); - let max = vals.iter().copied().fold(0.0f64, f64::max); - if max.is_nan() || max <= 0.0 { - return; - } - let labels: Vec = (0..n).map(|j| cat_label(data, j)).collect(); - let lw = (labels.iter().take(2000).map(|t| ctx.tw(t, LABEL_SIZE)).fold(0.0f32, f32::max) + 8.0).min(area.w * 0.35); - let plot = Bx { x: area.x + lw, w: area.w - lw, ..area }; - if !plot.ok() { - return; - } - let slot = plot.h / n as f32; - let bh = slot * 0.85; - let f = Fmt::new(&s.number_format); - let show = slot >= LABEL_SIZE * 0.9; - for (j, v) in vals.iter().enumerate() { - let bw = (*v / max) as f32 * plot.w; - let x = plot.x + (plot.w - bw) / 2.0; - let y = plot.y + j as f32 * slot + (slot - bh) / 2.0; - if bw > 0.0 { - ctx.rect(x, y, bw, bh, s.color, None); - } - if show { - let yc = y + bh / 2.0; - if chart.data_labels { - let t = f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None); - let color = if ctx.tw(&t, LABEL_SIZE) + 4.0 <= bw { on(s.color) } else { TEXT }; - ctx.text(plot.cx(), yc, &t, LABEL_SIZE, color, HAlign::Center, VAlign::Middle); - } - let l = ctx.fit(labels.get(j).map(String::as_str).unwrap_or(""), LABEL_SIZE, lw - 8.0); - ctx.text(plot.x - 6.0, yc, &l, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Middle); - } - } -} - -// ---------------------------------------------------------------- pie, doughnut, sunburst - -fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inner: f32, names: bool) { - let Some(s) = data.series.first() else { return }; - let vals: Vec = s.values.iter().take(MAX_CATS).map(|v| v.map(f64::abs).unwrap_or(0.0)).collect(); - let total: f64 = vals.iter().sum(); - if !(total.is_finite() && total > 0.0) { - return; - } - let (cx, cy) = (area.cx(), area.cy()); - let r = area.w.min(area.h) / 2.0 * 0.92; - if r < 2.0 { - return; - } - let ri = r * inner; - let f = Fmt::new(&s.number_format); - let mut a = 0.0f32; - let mut labels = Vec::new(); - for (j, v) in vals.iter().enumerate() { - let sweep = (*v / total) as f32 * TAU; - if sweep > 1e-4 { - let fill = point_color(data, j); - ctx.out.push(Prim::Wedge { cx, cy, r_outer: r, r_inner: ri, a0: a, a1: (a + sweep).min(TAU), fill, stroke: Some((WHITE, 1.5)) }); - if (chart.data_labels || names) && vals.len() <= MAX_LABELS { - let t = if names { cat_label(data, j) } else { f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None) }; - let mid = a + sweep / 2.0; - let rr = if ri > 0.0 { (r + ri) / 2.0 } else { r * 0.65 }; - let room = sweep * rr; - if ctx.tw(&t, LABEL_SIZE) <= room.max(r - ri) && room >= LABEL_SIZE { - labels.push((cx + rr * mid.sin(), cy - rr * mid.cos(), t, on(fill))); - } - } - } - a += sweep; - } - for (x, y, t, c) in labels { - ctx.text(x, y, &t, LABEL_SIZE, c, HAlign::Center, VAlign::Middle); - } -} - -// ---------------------------------------------------------------- treemap - -fn worst(row: &[f64], side: f64) -> f64 { - let s: f64 = row.iter().sum(); - if s <= 0.0 || side <= 0.0 { - return f64::INFINITY; - } - let (mn, mx) = row.iter().fold((f64::INFINITY, 0.0f64), |(a, b), v| (a.min(*v), b.max(*v))); - let s2 = s * s; - let w2 = side * side; - (w2 * mx / s2).max(s2 / (w2 * mn)) -} - -/// Squarified treemap layout of (index, area) items, sorted descending, into `r`. -fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { - let total: f64 = items.iter().map(|i| i.1).sum(); - let area = (r.w as f64) * (r.h as f64); - if !(total > 0.0 && area > 0.0) { - return vec![]; - } - let scale = area / total; - let mut out = Vec::with_capacity(items.len()); - let mut rem = r; - let mut row: Vec<(usize, f64)> = Vec::new(); - let mut i = 0; - let layout = |row: &[(usize, f64)], rem: &mut Bx, out: &mut Vec<(usize, Bx)>| { - let s: f64 = row.iter().map(|x| x.1).sum(); - if s <= 0.0 { - return; - } - if rem.w >= rem.h { - let cw = (s / rem.h.max(1e-6) as f64) as f32; - let mut y = rem.y; - for (j, a) in row { - let h = (*a / cw.max(1e-6) as f64) as f32; - out.push((*j, Bx { x: rem.x, y, w: cw, h })); - y += h; - } - rem.x += cw; - rem.w = (rem.w - cw).max(0.0); - } else { - let rh = (s / rem.w.max(1e-6) as f64) as f32; - let mut x = rem.x; - for (j, a) in row { - let w = (*a / rh.max(1e-6) as f64) as f32; - out.push((*j, Bx { x, y: rem.y, w, h: rh })); - x += w; - } - rem.y += rh; - rem.h = (rem.h - rh).max(0.0); - } - }; - while let Some(&(j, v)) = items.get(i) { - let a = v * scale; - let side = rem.w.min(rem.h) as f64; - let cur: Vec = row.iter().map(|x| x.1).collect(); - let mut with = cur.clone(); - with.push(a); - if row.is_empty() || worst(&with, side) <= worst(&cur, side) { - row.push((j, a)); - i += 1; - } else { - layout(&row, &mut rem, &mut out); - row.clear(); - } - } - if !row.is_empty() { - layout(&row, &mut rem, &mut out); - } - out -} - -fn treemap(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let Some(s) = data.series.first() else { return }; - let mut items: Vec<(usize, f64)> = - s.values.iter().take(MAX_MARKERS).enumerate().filter_map(|(j, v)| v.filter(|v| *v > 0.0).map(|v| (j, v))).collect(); - items.sort_by(|a, b| b.1.total_cmp(&a.1)); - let f = Fmt::new(&s.number_format); - for (j, b) in squarify(&items, area) { - let fill = point_color(data, j); - ctx.rect(b.x, b.y, b.w, b.h, fill, Some((WHITE, 1.5))); - if b.w > 24.0 && b.h > LABEL_SIZE * 1.6 { - let name = ctx.fit(&cat_label(data, j), LABEL_SIZE, b.w - 8.0); - ctx.text(b.x + 4.0, b.y + 4.0, &name, LABEL_SIZE, on(fill), HAlign::Left, VAlign::Top); - if chart.data_labels && b.h > LABEL_SIZE * 3.2 { - let v = items.iter().find(|x| x.0 == j).map(|x| x.1).unwrap_or(0.0); - let t = ctx.fit(&f.format(v, None), LABEL_SIZE, b.w - 8.0); - ctx.text(b.x + 4.0, b.y + 4.0 + LABEL_SIZE * 1.4, &t, LABEL_SIZE, on(fill), HAlign::Left, VAlign::Top); - } - } - } -} - -// ---------------------------------------------------------------- radar - -fn radar(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(1000); - if ncat == 0 { - return; - } - let labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); - let lw = labels.iter().map(|t| ctx.tw(t, LABEL_SIZE)).fold(0.0f32, f32::max).min(area.w * 0.2); - let r = ((area.w - 2.0 * (lw + 8.0)).min(area.h - 2.0 * (LABEL_SIZE * 1.4 + 6.0)) / 2.0).max(0.0); - if r < 5.0 { - return; - } - let (cx, cy) = (area.cx(), area.cy()); - let (lo, hi) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())).unwrap_or((0.0, 0.0)); - let sc = nice_scale(lo, hi, true); - let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); - let ang = |j: usize| j as f32 / ncat as f32 * TAU; - let pt = |a: f32, rr: f32| [cx + rr * a.sin(), cy - rr * a.cos()]; - let ticks = sc.ticks(); - let spacing = r / ticks.len().saturating_sub(1).max(1) as f32; - let every = ((LABEL_SIZE * 1.3 / spacing.max(1e-3)).ceil() as usize).max(1); - for (ti, t) in ticks.into_iter().enumerate() { - let rr = sc.frac(t) * r; - if rr > 0.5 && chart.gridlines { - let mut ring: Vec<[f32; 2]> = (0..ncat).map(|j| pt(ang(j), rr)).collect(); - if ncat < 3 { - ring = (0..=48).map(|k| pt(k as f32 / 48.0 * TAU, rr)).collect(); - } else if let Some(p) = ring.first().copied() { - ring.push(p); - } - ctx.line(ring, GRID, 0.75); - } - if ti % every == 0 { - ctx.text(cx - 3.0, cy - rr, &f.format(t, Some(sc.step)), LABEL_SIZE * 0.9, TEXT, HAlign::Right, VAlign::Middle); - } - } - let step = ncat.div_ceil(72).max(1); - for j in (0..ncat).step_by(step) { - let a = ang(j); - ctx.line(vec![[cx, cy], pt(a, r)], GRID, 0.75); - let p = pt(a, r + 6.0); - let (sa, ca) = (a.sin(), a.cos()); - let align = if sa > 0.1 { - HAlign::Left - } else if sa < -0.1 { - HAlign::Right - } else { - HAlign::Center - }; - let valign = if ca > 0.1 { - VAlign::Bottom - } else if ca < -0.1 { - VAlign::Top - } else { - VAlign::Middle - }; - let t = ctx.fit(labels.get(j).map(String::as_str).unwrap_or(""), LABEL_SIZE, lw.max(20.0)); - ctx.text(p[0], p[1], &t, LABEL_SIZE, TEXT, align, valign); - } - for s in &data.series { - let mut pts: Vec<[f32; 2]> = (0..ncat).map(|j| pt(ang(j), sc.frac(s.values.get(j).copied().flatten().unwrap_or(sc.min)) * r)).collect(); - if let Some(p) = pts.first().copied() { - pts.push(p); - } - ctx.line(pts, s.color, 2.0); - } -} - -// ---------------------------------------------------------------- box & whisker - -fn quantile(sorted: &[f64], q: f64, method: QuartileMethod) -> f64 { - let n = sorted.len(); - if n == 0 { - return 0.0; - } - // Clamp exclusive ranks for short samples so one or two points remain drawable. - let pos = match method { - QuartileMethod::Inclusive => q * (n - 1) as f64, - QuartileMethod::Exclusive => (q * (n as f64 + 1.0) - 1.0).clamp(0.0, (n - 1) as f64), - }; - let i = pos.floor() as usize; - let frac = pos - i as f64; - let a = sorted.get(i).copied().unwrap_or(0.0); - let b = sorted.get(i + 1).copied().unwrap_or(a); - a + (b - a) * frac -} - -fn box_whisker(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let labels: Vec = data.series.iter().map(|s| s.name.clone()).collect(); - let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return }; - let ys = nice_scale(lo, hi, false); - let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); - if !plot.ok() { - return; - } - let n = data.series.len().max(1); - let cw = plot.w / n as f32; - let bw = (cw * 0.4).min(80.0); - let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; - for (i, s) in data.series.iter().enumerate() { - let mut v: Vec = s.values.iter().flatten().copied().collect(); - if v.is_empty() { - continue; - } - v.sort_by(f64::total_cmp); - let method = chart.series.get(i).map(|s| s.quartiles).unwrap_or_default(); - let (q1, med, q3) = (quantile(&v, 0.25, method), quantile(&v, 0.5, method), quantile(&v, 0.75, method)); - let iqr = q3 - q1; - let (flo, fhi) = (q1 - 1.5 * iqr, q3 + 1.5 * iqr); - let wlo = v.iter().copied().find(|x| *x >= flo).unwrap_or(q1); - let whi = v.iter().rev().copied().find(|x| *x <= fhi).unwrap_or(q3); - let mean = v.iter().sum::() / v.len() as f64; - let c = plot.x + (i as f32 + 0.5) * cw; - ctx.vline(c, vy(whi), vy(q3), s.color, 1.25); - ctx.vline(c, vy(q1), vy(wlo), s.color, 1.25); - ctx.hline(c - bw / 4.0, c + bw / 4.0, vy(whi), s.color, 1.25); - ctx.hline(c - bw / 4.0, c + bw / 4.0, vy(wlo), s.color, 1.25); - let (yt, yb) = (vy(q3), vy(q1)); - ctx.rect(c - bw / 2.0, yt, bw, (yb - yt).max(0.5), s.color, None); - ctx.hline(c - bw / 2.0, c + bw / 2.0, vy(med), WHITE, 1.5); - let (mx, my, d) = (c, vy(mean), 3.0); - ctx.line(vec![[mx - d, my - d], [mx + d, my + d]], WHITE, 1.25); - ctx.line(vec![[mx - d, my + d], [mx + d, my - d]], WHITE, 1.25); - for o in v.iter().filter(|x| **x < flo || **x > fhi).take(MAX_MARKERS) { - ctx.out.push(Prim::Circle { cx: c, cy: vy(*o), r: 2.5, fill: None, stroke: Some((s.color, 1.0)) }); - } - } -} - -// ---------------------------------------------------------------- stock - -fn stock(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { - let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); - if ncat == 0 { - return; - } - let labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); - let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return }; - let ys = nice_scale(lo, hi, false); - let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); - if !plot.ok() { - return; - } - let ser = |k: usize| data.series.get(k); - let (open, high, low, close) = match data.series.len() { - 0 => return, - 1 => (None, None, None, ser(0)), - 2 => (None, ser(0), ser(1), None), - 3 => (None, ser(0), ser(1), ser(2)), - _ => (ser(0), ser(1), ser(2), ser(3)), - }; - let get = |s: Option<&SeriesData>, j: usize| s.and_then(|s| s.values.get(j).copied().flatten()); - let cw = plot.w / ncat as f32; - let tick = (cw * 0.25).max(1.0); - let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; - for j in 0..ncat { - let c = plot.x + (j as f32 + 0.5) * cw; - if let (Some(h), Some(l)) = (get(high, j), get(low, j)) { - ctx.vline(c, vy(h), vy(l), STOCK, 1.25); - } - match (get(open, j), get(close, j)) { - (Some(o), Some(cl)) => { - let (yo, yc) = (vy(o), vy(cl)); - let bw = (cw * 0.5).max(1.0); - let fill = if cl >= o { WHITE } else { STOCK }; - ctx.rect(c - bw / 2.0, yo.min(yc), bw, (yo - yc).abs().max(0.75), fill, Some((STOCK, 1.0))); - } - (None, Some(cl)) => { - if high.is_some() { - ctx.hline(c, c + tick, vy(cl), STOCK, 1.25); - } else { - ctx.out.push(Prim::Circle { cx: c, cy: vy(cl), r: 2.5, fill: Some(STOCK), stroke: None }); - } - } - _ => {} - } - } -} - // ---------------------------------------------------------------- final safety pass fn fin(v: f32) -> bool { @@ -1829,60 +252,3 @@ pub(crate) fn finalize(prims: Vec, w: f32, h: f32) -> Vec { }) .collect() } - -#[cfg(test)] -mod smooth_tests { - use super::*; - - #[test] - fn long_runs_are_smoothed_uniformly_within_the_cap() { - let plot = Bx { x: 0.0, y: 0.0, w: 3000.0, h: 100.0 }; - let pts: Vec<[f32; 2]> = (0..1500).map(|i| [i as f32 * 2.0, if i % 2 == 0 { 20.0 } else { 80.0 }]).collect(); - let out = smooth_run(pts, plot); - assert!(out.len() <= MAX_LINE_PTS * 2 + 1, "{}", out.len()); - // Two sub-segments per segment all the way to the end, not 100 each and then a straight tail. - assert_eq!(out.len(), 1499 * 2 + 1); - assert_eq!(out.last().copied(), Some([2998.0, 80.0])); - } - - #[test] - fn spline_overshoot_is_clamped_to_the_plot() { - let plot = Bx { x: 0.0, y: 10.0, w: 300.0, h: 100.0 }; - // A step right at the plot edges: Catmull-Rom overshoots past both. - let pts = vec![[0.0, 110.0], [100.0, 110.0], [110.0, 10.0], [200.0, 10.0], [300.0, 10.0]]; - let out = smooth_run(pts, plot); - assert!(out.len() > 5); - assert!(out.iter().all(|p| (0.0..=300.0).contains(&p[0]) && (10.0..=110.0).contains(&p[1]))); - } -} - -#[cfg(test)] -mod quartile_tests { - use super::*; - - #[test] - fn box_whisker_default_quartiles_are_exclusive() { - let values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; - assert_eq!(quantile(&values, 0.25, QuartileMethod::default()), 1.75); - assert_eq!(quantile(&values, 0.5, QuartileMethod::default()), 3.5); - assert_eq!(quantile(&values, 0.75, QuartileMethod::default()), 5.25); - } - - #[test] - fn quartile_methods_and_short_samples() { - for (values, exclusive, inclusive) in [ - (vec![1., 2., 3.], (1., 3.), (1.5, 2.5)), - (vec![1., 2., 3., 4.], (1.25, 3.75), (1.75, 3.25)), - (vec![1., 2., 3., 4., 5.], (1.5, 4.5), (2., 4.)), - (vec![1., 2., 3., 4., 5., 6., 7.], (2., 6.), (2.5, 5.5)), - (vec![1., 1., 2., 3., 5., 8.], (1., 5.75), (1.25, 4.5)), - (vec![1., 2.], (1., 2.), (1.25, 1.75)), - (vec![1.], (1., 1.), (1., 1.)), - (vec![], (0., 0.), (0., 0.)), - ] { - for (method, expected) in [(QuartileMethod::Exclusive, exclusive), (QuartileMethod::Inclusive, inclusive)] { - assert_eq!((quantile(&values, 0.25, method), quantile(&values, 0.75, method)), expected); - } - } - } -} diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs new file mode 100644 index 0000000000..05105dbf47 --- /dev/null +++ b/crates/chart/src/render/cartesian.rs @@ -0,0 +1,452 @@ +use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range}; +use super::legend::{cat_label, plot_kind}; +use super::lines::{decimate_area, draw_markers, draw_runs}; +use super::trend::{draw_trend_labels, draw_trendlines, max_backward, max_forward, max_forward_slots, supports_trendline}; +use super::{ + Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, Prim, Scale, SeriesData, TEXT, + VAlign, WHITE, clean, fixed_scale, nice_scale, +}; + +// ---------------------------------------------------------------- cartesian (column/bar/line/area/combo) + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Fam { + Col, + ColStack, + Col100, + Line, + LineStack, + Area, + AreaStack, + Area100, +} + +/// Stack accumulator: (axis, family) key with positive and negative running sums. +type Stack = ((bool, Fam), Vec, Vec); + +fn family(k: ChartKind) -> Fam { + use ChartKind::*; + match k { + ColumnStacked | BarStacked => Fam::ColStack, + ColumnStacked100 | BarStacked100 => Fam::Col100, + Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line, + LineStacked => Fam::LineStack, + Area => Fam::Area, + AreaStacked => Fam::AreaStack, + AreaStacked100 => Fam::Area100, + _ => Fam::Col, + } +} + +/// Families stacked to 100%: each category's values are shares of its total. +fn is_100(f: Fam) -> bool { + matches!(f, Fam::Col100 | Fam::Area100) +} + +fn is_col(f: Fam) -> bool { + matches!(f, Fam::Col | Fam::ColStack | Fam::Col100) +} + +fn is_line(f: Fam) -> bool { + matches!(f, Fam::Line | Fam::LineStack) +} + +fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { + // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). + let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); + for (i, s) in data.series.iter().enumerate() { + let fam = fams.get(i).copied().unwrap_or(Fam::Col); + if is_100(fam) { + let key = (sec.get(i).copied().unwrap_or(false), fam); + let p = match totals.iter().position(|(k, _)| *k == key) { + Some(p) => p, + None => { + totals.push((key, vec![0.0; ncat])); + totals.len() - 1 + } + }; + for (j, v) in s.values.iter().take(ncat).enumerate() { + if let (Some(v), Some(t)) = (v, totals.get_mut(p).and_then(|(_, t)| t.get_mut(j))) { + *t += v.abs(); + } + } + } + } + // A value's share of its category's total, for the 100% families. + let share = |key: (bool, Fam), j: usize, v: f64| { + let t = totals.iter().find(|(k, _)| *k == key).and_then(|(_, t)| t.get(j)).copied().unwrap_or(0.0); + if t > 0.0 { v / t } else { 0.0 } + }; + // Stack accumulators keyed by (axis, family): positive and negative running sums. + let mut stacks: Vec = Vec::new(); + let mut spans: Vec>> = Vec::with_capacity(data.series.len()); + for (i, s) in data.series.iter().enumerate() { + let fam = fams.get(i).copied().unwrap_or(Fam::Col); + let a = sec.get(i).copied().unwrap_or(false); + let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100); + let key = (a, fam); + let si = if stacked { + match stacks.iter().position(|(k, _, _)| *k == key) { + Some(p) => Some(p), + None => { + stacks.push((key, vec![0.0; ncat], vec![0.0; ncat])); + Some(stacks.len() - 1) + } + } + } else { + None + }; + let mut row = Vec::with_capacity(ncat); + for j in 0..ncat { + let v = s.values.get(j).copied().flatten(); + let span = match (si.and_then(|p| stacks.get_mut(p)), fam) { + (Some((_, pos, neg)), Fam::ColStack | Fam::Col100) => v.and_then(|v| { + let v = if fam == Fam::Col100 { share(key, j, v) } else { v }; + let acc = if v >= 0.0 { pos.get_mut(j) } else { neg.get_mut(j) }?; + let base = *acc; + *acc += v; + Some((base, *acc)) + }), + (Some((_, pos, _)), _) => { + let v = v.unwrap_or(0.0); + 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); + (base, *acc) + }) + } + (None, _) => v.map(|v| (0.0, v)), + }; + row.push(span); + } + spans.push(row); + } + + spans +} + +fn axis_scales(data: &ChartData, fams: &[Fam], sec: &[bool], spans: &[Vec>]) -> Vec<(Scale, Fmt)> { + // Axis scales. + let mut axes: Vec<(Scale, Fmt)> = Vec::new(); + for axis in [false, true] { + let members: Vec = (0..data.series.len()).filter(|i| sec.get(*i).copied().unwrap_or(false) == axis).collect(); + if members.is_empty() { + continue; + } + let force_zero = members.iter().any(|i| fams.get(*i).is_some_and(|f| !is_line(*f))); + let all100 = members.iter().all(|i| fams.get(*i).is_some_and(|f| is_100(*f))); + let range = value_range(members.iter().flat_map(|i| { + let line = fams.get(*i).is_some_and(|f| is_line(*f)); + spans.get(*i).into_iter().flatten().flatten().flat_map(move |(b, t)| if line { vec![*t] } else { vec![*b, *t] }) + })); + let (lo, hi) = range.unwrap_or((0.0, 0.0)); + let (scale, fmt) = if all100 { + (fixed_scale(if lo < -1e-9 { -1.0 } else { 0.0 }, if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, 0.2), Fmt::new("0%")) + } else { + let code = members.first().and_then(|i| data.series.get(*i)).map(|s| s.number_format.as_str()).unwrap_or("General"); + (nice_scale(lo, hi, force_zero), Fmt::new(code)) + }; + axes.push((scale, fmt)); + if !axis && sec.iter().all(|s| !s) { + break; + } + } + axes +} + +fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec, f32) { + // Column slots: each clustered series gets one, each stack group shares one. + let mut slot_keys: Vec<(bool, Fam, usize)> = Vec::new(); + let mut slot_of = vec![0usize; fams.len()]; + for (i, f) in fams.iter().enumerate() { + if !is_col(*f) { + continue; + } + let a = sec.get(i).copied().unwrap_or(false); + let key = if *f == Fam::Col { (a, *f, i) } else { (a, *f, usize::MAX) }; + let k = match slot_keys.iter().position(|k| *k == key) { + Some(p) => p, + None => { + slot_keys.push(key); + slot_keys.len() - 1 + } + }; + if let Some(s) = slot_of.get_mut(i) { + *s = k; + } + } + (slot_of, slot_keys.len().max(1) as f32) +} + +pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { + let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); + if ncat == 0 { + return; + } + let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { plot_kind(chart, s) }).collect(); + let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); + let any_primary = data.series.iter().any(|s| !s.secondary); + let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); + + let spans = series_spans(data, &fams, &sec, ncat); + + let axes = axis_scales(data, &fams, &sec, &spans); + let Some((s1, f1)) = axes.first() else { return }; + let y1 = ValAxis { scale: *s1, fmt: f1 }; + let y2 = axes.get(1).map(|(s, f)| ValAxis { scale: *s, fmt: f }); + // A forward forecast on a category axis adds empty category slots after the data. + let fwd = data + .series + .iter() + .enumerate() + .filter(|(i, _)| kinds.get(*i).is_some_and(|k| supports_trendline(*k))) + .map(|(_, s)| max_forward(s)) + .fold(0.0, f64::max); + let ncat_slots = ncat.saturating_add(fwd.min(max_forward_slots(ncat)).ceil() as usize).min(MAX_CATS.max(ncat)); + let labels: Vec = (0..ncat_slots).map(|j| if j < ncat { cat_label(data, j) } else { String::new() }).collect(); + // Outer levels padded to the slots (forecast slots stay in the last group). + let outer: Vec> = + data.category_levels.iter().map(|l| (0..ncat_slots).map(|j| l.get(j).cloned().unwrap_or_default()).collect()).collect(); + let (area, table) = super::table::reserve(ctx, chart, data, area, ncat_slots); + let category_axis = super::table::category_axis(&table, &labels, &outer); + let plot = frame(ctx, area, category_axis, &y1, y2.as_ref(), horizontal, chart.gridlines); + if !plot.ok() { + return; + } + let scale_of = |i: usize| -> Scale { if sec.get(i).copied().unwrap_or(false) { y2.as_ref().map(|a| a.scale).unwrap_or(*s1) } else { *s1 } }; + let cat_len = if horizontal { plot.h } else { plot.w }; + let cw = cat_len / ncat_slots as f32; + let center = |j: usize| if horizontal { plot.bottom() - (j as f32 + 0.5) * cw } else { plot.x + (j as f32 + 0.5) * cw }; + let vpos = |v: f64, sc: &Scale| if horizontal { plot.x + sc.frac(v) * plot.w } else { plot.bottom() - sc.frac(v) * plot.h }; + + let (slot_of, nslots) = column_slots(&fams, &sec); + let bw = cw / (nslots + 1.5); + let labels_on = chart.data_labels && ncat <= MAX_LABELS; + // Area labels wait until every area is filled, so a later (stacked) area can't paint over them. + let mut area_labels = Vec::new(); + + // Areas first, then columns, then lines on top. + for pass in 0..3 { + for (i, s) in data.series.iter().enumerate() { + let fam = fams.get(i).copied().unwrap_or(Fam::Col); + let want = match pass { + 0 => matches!(fam, Fam::Area | Fam::AreaStack | Fam::Area100), + 1 => is_col(fam), + _ => is_line(fam), + }; + if !want { + continue; + } + let sc = scale_of(i); + let fmt = Fmt::new(&s.number_format); + let row = match spans.get(i) { + Some(r) => r, + None => continue, + }; + match pass { + 0 => { + let mut top = Vec::with_capacity(ncat * 2); + let mut base = Vec::with_capacity(ncat); + for (j, sp) in row.iter().enumerate() { + let (b, t) = sp.unwrap_or((0.0, 0.0)); + let c = center(j); + top.push([c, vpos(t, &sc)]); + base.push([c, vpos(b, &sc)]); + // Source values (not stack totals), just above the top edge like the line labels. + if labels_on + && sp.is_some() + && let Some(v) = s.values.get(j).copied().flatten() + { + area_labels.push((c, vpos(t, &sc) - 5.0, fmt.format(v, None))); + } + } + if top.len() == 1 { + // A single point: give it some width. + if let (Some(t), Some(b)) = (top.first().copied(), base.first().copied()) { + top = vec![[t[0] - cw * 0.3, t[1]], [t[0] + cw * 0.3, t[1]]]; + base = vec![[b[0] - cw * 0.3, b[1]], [b[0] + cw * 0.3, b[1]]]; + } + } + let poly = decimate_area(top, base, MAX_LINE_PTS * 2); + if poly.len() >= 3 { + ctx.out.push(Prim::Polygon { pts: poly, fill: s.color, stroke: None }); + } + } + 1 => { + let k = slot_of.get(i).copied().unwrap_or(0) as f32; + for (j, sp) in row.iter().enumerate() { + let Some((b, t)) = sp else { continue }; + let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc)); + let c = center(j); + let lo = pb.min(pt); + let len = (pb - pt).abs(); + if horizontal { + let y = c + nslots * bw / 2.0 - (k + 1.0) * bw; + ctx.rect(lo, y, len, bw, s.color, None); + } else { + let x = c - nslots * bw / 2.0 + k * bw; + ctx.rect(x, lo, bw, len, s.color, None); + } + if labels_on && let Some(v) = s.values.get(j).copied().flatten() { + let t = fmt.format(v, None); + let stacked = fam != Fam::Col; + let mid = (pb + pt) / 2.0; + if horizontal { + let y = c + nslots * bw / 2.0 - (k + 0.5) * bw; + if stacked { + ctx.text(mid, y, &t, LABEL_SIZE, on(s.color), (HAlign::Center, VAlign::Middle)); + } else if v >= 0.0 { + ctx.text(pb.max(pt) + 3.0, y, &t, LABEL_SIZE, TEXT, (HAlign::Left, VAlign::Middle)); + } else { + ctx.text(lo - 3.0, y, &t, LABEL_SIZE, TEXT, (HAlign::Right, VAlign::Middle)); + } + } else { + let x = c - nslots * bw / 2.0 + (k + 0.5) * bw; + if stacked { + ctx.text(x, mid, &t, LABEL_SIZE, on(s.color), (HAlign::Center, VAlign::Middle)); + } else if v >= 0.0 { + ctx.text(x, lo - 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } else { + ctx.text(x, lo + len + 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Top)); + } + } + } + } + } + _ => { + let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); + draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); + let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); + if k == ChartKind::LineMarkers && cw >= 3.0 { + draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); + } + if labels_on { + for (j, p) in pts.iter().enumerate() { + if let (Some(p), Some(v)) = (p, s.values.get(j).copied().flatten()) { + ctx.text(p[0], p[1] - 5.0, &fmt.format(v, None), LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } + } + } + } + } + } + for (x, y, t) in area_labels.drain(..) { + ctx.text(x, y, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } + } + // Trendlines on top: x is the category number 1..n. + let mut trend_labels = Vec::new(); + for (i, s) in data.series.iter().enumerate() { + if s.trendlines.is_empty() || !kinds.get(i).is_some_and(|k| supports_trendline(*k)) { + continue; + } + let sc = scale_of(i); + let pts: Vec<(f64, f64)> = s.values.iter().take(ncat).enumerate().filter_map(|(j, v)| v.map(|v| ((j + 1) as f64, v))).collect(); + let frac = |x: f64, y: f64| ((x - 0.5) / ncat_slots as f64, (y - sc.min) / (sc.max - sc.min)); + let px = |(fx, fy): (f64, f64)| { + if horizontal { + [plot.x + fy as f32 * plot.w, plot.bottom() - fx as f32 * plot.h] + } else { + [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h] + } + }; + draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels, (0.5, ncat_slots as f64 + 0.5)); + } + draw_trend_labels(ctx, plot, &trend_labels); + super::table::draw(ctx, chart, data, plot, table.as_ref()); +} + +// ---------------------------------------------------------------- scatter & bubble + +pub(super) fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let pts_of = |s: &SeriesData| -> Vec> { + s.values + .iter() + .enumerate() + .map(|(j, v)| { + let x = match &s.x { + Some(xs) => xs.get(j).copied().flatten(), + None => Some((j + 1) as f64), + }; + match (x, v) { + (Some(x), Some(y)) => Some((x, *y)), + _ => None, + } + }) + .collect() + }; + let all: Vec>> = data.series.iter().map(pts_of).collect(); + let Some((mut xlo, mut xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return }; + // Forecasts extend the x axis to the trendline's ends. + for (s, pts) in data.series.iter().zip(&all) { + if let Some((lo, hi)) = value_range(pts.iter().flatten().map(|p| p.0)).filter(|_| !s.trendlines.is_empty()) { + xlo = xlo.min(lo - max_backward(s)); + xhi = xhi.max(hi + max_forward(s)); + } + } + let Some((ylo, yhi)) = value_range(all.iter().flatten().flatten().map(|p| p.1)) else { return }; + let xs = nice_scale(xlo, xhi, false); + let ys = nice_scale(ylo, yhi, false); + let fx = Fmt::new("General"); + let fy = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); + let plot = frame(ctx, area, CatAxis::Numeric(xs, &fx), &ValAxis { scale: ys, fmt: &fy }, None, false, chart.gridlines); + if !plot.ok() { + return; + } + let map = |(x, y): (f64, f64)| [plot.x + xs.frac(x) * plot.w, plot.bottom() - ys.frac(y) * plot.h]; + let bubble = chart.kind == ChartKind::Bubble; + let rmax = plot.w.min(plot.h) * 0.12; + for (s, pts) in data.series.iter().zip(&all) { + let px: Vec> = pts.iter().map(|p| p.map(map)).collect(); + if bubble { + let sizes = s.sizes.as_deref().unwrap_or(&[]); + let smax = sizes.iter().flatten().fold(0.0f64, |a, b| a.max(*b)); + let mut bubbles: Vec<([f32; 2], f64)> = px + .iter() + .enumerate() + .filter_map(|(j, p)| { + let sz = if sizes.is_empty() { Some(1.0) } else { sizes.get(j).copied().flatten() }; + match (p, sz) { + (Some(p), Some(sz)) if sz > 0.0 => Some((*p, sz)), + _ => None, + } + }) + .take(MAX_MARKERS) + .collect(); + bubbles.sort_by(|a, b| b.1.total_cmp(&a.1)); + let smax = if sizes.is_empty() { 1.0 } else { smax }; + let fill = [s.color[0], s.color[1], s.color[2], 0xC0]; + for (p, sz) in bubbles { + let r = ((sz / smax).sqrt() as f32 * rmax).max(1.0); + ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(fill), stroke: Some((WHITE, 0.75)) }); + } + } else { + let lines = chart.kind == ChartKind::ScatterLines || s.kind == ChartKind::ScatterLines; + if lines { + draw_runs(ctx, &px, s.color, 2.0, s.smooth.then_some(plot)); + } + if !lines || px.len() <= 500 { + draw_markers(ctx, px.iter().flatten().copied(), 3.5, s.color); + } + } + if chart.data_labels && pts.len() <= MAX_LABELS { + for (p, raw) in px.iter().zip(pts) { + if let (Some(p), Some((_, y))) = (p, raw) { + ctx.text(p[0], p[1] - 6.0, &fy.format(*y, None), LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } + } + } + } + let mut trend_labels = Vec::new(); + for (s, pts) in data.series.iter().zip(&all) { + if s.trendlines.is_empty() { + continue; + } + let pts: Vec<(f64, f64)> = pts.iter().flatten().copied().collect(); + let frac = |x: f64, y: f64| ((x - xs.min) / (xs.max - xs.min), (y - ys.min) / (ys.max - ys.min)); + let px = |(fx, fy): (f64, f64)| [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h]; + draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels, (xs.min, xs.max)); + } + draw_trend_labels(ctx, plot, &trend_labels); +} diff --git a/crates/chart/src/render/frame.rs b/crates/chart/src/render/frame.rs new file mode 100644 index 0000000000..92d8dd9e35 --- /dev/null +++ b/crates/chart/src/render/frame.rs @@ -0,0 +1,254 @@ +use super::{AXIS, AXIS_TITLE_SIZE, Chart, ChartData, Ctx, DARK_TEXT, Fmt, GRID, HAlign, LABEL_SIZE, PI, Prim, Rgba, Scale, TEXT, VAlign, WHITE}; + +#[derive(Clone, Copy, Debug)] +pub(super) struct Bx { + pub(super) x: f32, + pub(super) y: f32, + pub(super) w: f32, + pub(super) h: f32, +} + +impl Bx { + pub(super) fn right(&self) -> f32 { + self.x + self.w + } + pub(super) fn bottom(&self) -> f32 { + self.y + self.h + } + pub(super) fn ok(&self) -> bool { + self.w.is_finite() && self.h.is_finite() && self.w > 4.0 && self.h > 4.0 + } + pub(super) fn cx(&self) -> f32 { + self.x + self.w / 2.0 + } + pub(super) fn cy(&self) -> f32 { + self.y + self.h / 2.0 + } +} + +/// Text colour readable on `fill`. +pub(super) fn on(fill: Rgba) -> Rgba { + let l = 0.299 * fill[0] as f32 + 0.587 * fill[1] as f32 + 0.114 * fill[2] as f32; + if l < 150.0 { WHITE } else { DARK_TEXT } +} + +pub(super) fn chart_title(chart: &Chart, data: &ChartData) -> Option { + match &chart.title { + Some(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()), + None if data.series.len() == 1 => data.series.first().map(|s| s.name.clone()).filter(|t| !t.is_empty()), + None => None, + } +} + +pub(super) fn axis_titles(ctx: &mut Ctx, chart: &Chart, mut area: Bx) -> Bx { + let lh = AXIS_TITLE_SIZE * 1.4 + 2.0; + if let Some(t) = chart.x_title.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + let t = ctx.fit(t, AXIS_TITLE_SIZE, area.w); + ctx.text(area.cx(), area.bottom(), &t, AXIS_TITLE_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + area.h -= lh; + } + if let Some(t) = chart.y_title.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + let t = ctx.fit(t, AXIS_TITLE_SIZE, area.h); + if !t.is_empty() { + ctx.out.push(Prim::Text { + x: area.x, + y: area.cy(), + text: t, + size: AXIS_TITLE_SIZE, + color: TEXT, + bold: false, + align: HAlign::Center, + valign: VAlign::Top, + rotation: -PI / 2.0, + }); + } + area.x += lh; + area.w -= lh; + } + area +} + +// ---------------------------------------------------------------- axes frame + +pub(super) enum CatAxis<'a> { + /// Category labels and, for a multi-level axis, the outer levels (nearest the labels first; + /// one entry per category, non-empty where a group starts). + Labels(&'a [String], &'a [Vec]), + /// A data table supplies the labels below a vertical chart. Its stub must clear the plot. + Table(&'a [String], f32), + Numeric(Scale, &'a Fmt), +} + +/// Groups of an outer category level: `(first, end)` index pairs, a group starting at every +/// non-empty entry (and at the first category). +pub(super) fn level_groups(level: &[String], n: usize) -> Vec<(usize, usize)> { + let mut starts: Vec = (0..n).filter(|&j| j == 0 || level.get(j).is_some_and(|t| !t.is_empty())).collect(); + starts.push(n); + starts.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() +} + +pub(super) struct ValAxis<'a> { + pub(super) scale: Scale, + pub(super) fmt: &'a Fmt, +} + +impl ValAxis<'_> { + fn labels(&self) -> Vec<(f64, String)> { + self.scale.ticks().into_iter().map(|v| (v, self.fmt.format(v, Some(self.scale.step)))).collect() + } +} + +/// Draws gridlines, axis labels and the category axis line; returns the plot rectangle. +pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Option<&ValAxis>, horizontal: bool, grid: bool) -> Bx { + let ls = LABEL_SIZE; + let lh = ls * 1.4; + let ylabels = y.labels(); + let stub = match &cat { + CatAxis::Table(_, width) => *width, + _ => 0.0, + }; + let maxw = |ctx: &Ctx, l: &[(f64, String)]| l.iter().map(|(_, t)| ctx.tw(t, ls)).fold(0.0f32, f32::max); + if !horizontal { + let left = (maxw(ctx, &ylabels) + 6.0).min(area.w * 0.4).max(stub); + let y2labels = y2.map(ValAxis::labels); + let right = match (&y2labels, &cat) { + (Some(l), _) => (maxw(ctx, l) + 6.0).min(area.w * 0.3), + (None, CatAxis::Numeric(s, f)) => (ctx.tw(&f.format(s.max, Some(s.step)), ls) / 2.0).min(area.w * 0.2), + _ => 4.0, + }; + let levels = match &cat { + CatAxis::Labels(_, o) => o.len() as f32, + CatAxis::Numeric(..) | CatAxis::Table(..) => 0.0, + }; + let plot = Bx { x: area.x + left, y: area.y + lh * 0.5, w: area.w - left - right, h: area.h - lh * 1.5 - 4.0 - lh * levels }; + if !plot.ok() { + return plot; + } + for (v, t) in &ylabels { + let yy = plot.bottom() - y.scale.frac(*v) * plot.h; + if grid { + ctx.hline(plot.x, plot.right(), yy, GRID, 0.75); + } + ctx.text(plot.x - 4.0, yy, t, ls, TEXT, (HAlign::Right, VAlign::Middle)); + } + if let (Some(a), Some(l)) = (y2, &y2labels) { + for (v, t) in l { + let yy = plot.bottom() - a.scale.frac(*v) * plot.h; + ctx.text(plot.right() + 4.0, yy, t, ls, TEXT, (HAlign::Left, VAlign::Middle)); + } + } + let zero = if y.scale.min <= 0.0 && y.scale.max >= 0.0 { 0.0 } else { y.scale.min }; + let y0 = plot.bottom() - y.scale.frac(zero) * plot.h; + ctx.hline(plot.x, plot.right(), y0, AXIS, 0.75); + match cat { + CatAxis::Table(..) => {} + CatAxis::Labels(l, outer) => { + let n = l.len().max(1); + let cw = plot.w / n as f32; + let lw = l.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max); + let k = (((lw + 6.0) / cw.max(1e-3)).ceil() as usize).clamp(1, n); + for (j, t) in l.iter().enumerate().step_by(k) { + let t = ctx.fit(t, ls, cw * k as f32 - 2.0); + ctx.text(plot.x + (j as f32 + 0.5) * cw, plot.bottom() + 3.0, &t, ls, TEXT, (HAlign::Center, VAlign::Top)); + } + // Outer levels, one row each below the labels: a group's name centred under its + // categories, and a separator at each group boundary down through the rows. + for (i, level) in outer.iter().enumerate() { + let top = plot.bottom() + 3.0 + lh * (i as f32 + 1.0); + for (first, end) in level_groups(level, n) { + let (x0, x1) = (plot.x + first as f32 * cw, plot.x + end as f32 * cw); + if let Some(t) = level.get(first).filter(|t| !t.is_empty()) { + let t = ctx.fit(t, ls, x1 - x0 - 2.0); + ctx.text((x0 + x1) / 2.0, top, &t, ls, TEXT, (HAlign::Center, VAlign::Top)); + } + if first > 0 { + ctx.vline(x0, plot.bottom(), top + lh - 2.0, AXIS, 0.75); + } + } + ctx.vline(plot.right(), plot.bottom(), top + lh - 2.0, AXIS, 0.75); + } + } + CatAxis::Numeric(s, f) => { + let ticks = s.ticks(); + let labels: Vec = ticks.iter().map(|v| f.format(*v, Some(s.step))).collect(); + let lw = labels.iter().map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max); + let slot = plot.w / ticks.len().max(1) as f32; + let k = (((lw + 6.0) / slot.max(1e-3)).ceil() as usize).max(1); + for (v, t) in ticks.iter().zip(&labels).step_by(k) { + let xx = plot.x + s.frac(*v) * plot.w; + ctx.text(xx, plot.bottom() + 3.0, t, ls, TEXT, (HAlign::Center, VAlign::Top)); + } + if s.min <= 0.0 && s.max >= 0.0 { + let xx = plot.x + s.frac(0.0) * plot.w; + ctx.vline(xx, plot.y, plot.bottom(), AXIS, 0.75); + } + } + } + plot + } else { + let (labels, outer): (Vec, &[Vec]) = match cat { + CatAxis::Labels(l, o) => (l.to_vec(), o), + CatAxis::Table(l, _) => (l.to_vec(), &[]), + CatAxis::Numeric(..) => (vec![], &[]), + }; + let lw = (labels.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.35); + // Outer levels stand in columns left of the labels, each as wide as its longest name. + let level_w: Vec = + outer.iter().map(|l| (l.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.15)).collect(); + let levels_w: f32 = level_w.iter().sum(); + let right = ylabels.last().map(|(_, t)| ctx.tw(t, ls) / 2.0).unwrap_or(0.0).min(area.w * 0.2) + 2.0; + let left = (lw + levels_w).max(stub); + let plot = Bx { x: area.x + left, y: area.y + 2.0, w: area.w - left - right, h: area.h - lh - 6.0 }; + if !plot.ok() { + return plot; + } + let vw = maxw(ctx, &ylabels); + let slot = plot.w / ylabels.len().max(1) as f32; + let k = (((vw + 6.0) / slot.max(1e-3)).ceil() as usize).max(1); + for (i, (v, t)) in ylabels.iter().enumerate() { + let xx = plot.x + y.scale.frac(*v) * plot.w; + if grid { + ctx.vline(xx, plot.y, plot.bottom(), GRID, 0.75); + } + if i % k == 0 { + ctx.text(xx, plot.bottom() + 3.0, t, ls, TEXT, (HAlign::Center, VAlign::Top)); + } + } + let zero = if y.scale.min <= 0.0 && y.scale.max >= 0.0 { 0.0 } else { y.scale.min }; + let x0 = plot.x + y.scale.frac(zero) * plot.w; + ctx.vline(x0, plot.y, plot.bottom(), AXIS, 0.75); + let n = labels.len().max(1); + let ch = plot.h / n as f32; + let k = ((lh / ch.max(1e-3)).ceil() as usize).clamp(1, n); + for (j, t) in labels.iter().enumerate().step_by(k) { + let t = ctx.fit(t, ls, lw - 6.0); + ctx.text(plot.x - 4.0, plot.bottom() - (j as f32 + 0.5) * ch, &t, ls, TEXT, (HAlign::Right, VAlign::Middle)); + } + // Outer levels: a group's name centred beside its categories, separators at the + // boundaries running right to the axis. + let mut x1 = plot.x - lw; + for (level, w) in outer.iter().zip(&level_w) { + let x0 = x1 - w; + for (first, end) in level_groups(level, n) { + let (y0, y1) = (plot.bottom() - end as f32 * ch, plot.bottom() - first as f32 * ch); + if let Some(t) = level.get(first).filter(|t| !t.is_empty()) { + let t = ctx.fit(t, ls, w - 4.0); + ctx.text((x0 + x1) / 2.0, (y0 + y1) / 2.0, &t, ls, TEXT, (HAlign::Center, VAlign::Middle)); + } + if first > 0 { + ctx.hline(x0, plot.x, y1, AXIS, 0.75); + } + } + ctx.hline(x0, plot.x, plot.y, AXIS, 0.75); + x1 = x0; + } + plot + } +} + +pub(super) fn value_range(it: impl Iterator) -> Option<(f64, f64)> { + it.fold(None, |acc, v| match acc { + None => Some((v, v)), + Some((a, b)) => Some((a.min(v), b.max(v))), + }) +} diff --git a/crates/chart/src/render/kinds.rs b/crates/chart/src/render/kinds.rs new file mode 100644 index 0000000000..54ce6bec82 --- /dev/null +++ b/crates/chart/src/render/kinds.rs @@ -0,0 +1,508 @@ +use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range}; +use super::legend::{cat_label, point_color}; +use super::{ + AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, Prim, QuartileMethod, STOCK, SeriesData, + TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale, +}; + +// ---------------------------------------------------------------- histogram + +pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let Some(s) = data.series.first() else { return }; + let vals: Vec = s.values.iter().flatten().copied().collect(); + let Some((lo, hi)) = value_range(vals.iter().copied()) else { return }; + let n = vals.len(); + let span = hi - lo; + let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100); + if !(span.is_finite() && span > 0.0) { + bins = 1; + } + let width = if bins == 1 && span.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { 1.0 } else { span / bins as f64 }; + // Upper edge of each bin, exactly as shown in the labels below. Bins are right-inclusive (the first is closed on both sides), so a value + // equal to an edge belongs to the bin that ends there. + let edges: Vec = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect(); + let mut counts = vec![0usize; bins]; + for v in &vals { + let b = edges.partition_point(|e| e < v).min(bins - 1); + if let Some(c) = counts.get_mut(b) { + *c += 1; + } + } + let f = Fmt::new(&s.number_format); + let labels: Vec = (0..bins) + .map(|b| { + let a = lo + b as f64 * width; + let e = edges.get(b).copied().unwrap_or(a); + let open = if b == 0 { '[' } else { '(' }; + format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0))) + }) + .collect(); + let maxc = counts.iter().copied().max().unwrap_or(0) as f64; + let ys = nice_scale(0.0, maxc, true); + let fc = Fmt::new("General"); + let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &fc }, None, false, chart.gridlines); + if !plot.ok() { + return; + } + let cw = plot.w / bins as f32; + for (b, c) in counts.iter().enumerate() { + let top = plot.bottom() - ys.frac(*c as f64) * plot.h; + let x = plot.x + b as f32 * cw; + ctx.rect(x, top, cw, plot.bottom() - top, s.color, Some((WHITE, 0.75))); + if chart.data_labels { + ctx.text(x + cw / 2.0, top - 2.0, &c.to_string(), LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } + } +} + +// ---------------------------------------------------------------- waterfall + +pub(super) fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let Some(s) = data.series.first() else { return }; + let mut ncat = data.categories.len().max(s.values.len()).min(MAX_CATS); + if ncat == 0 { + return; + } + let mut labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); + let mut vals: Vec = (0..ncat).map(|j| s.values.get(j).copied().flatten().unwrap_or(0.0)).collect(); + let mut is_total = vec![false; ncat]; + let last_total = labels.last().is_some_and(|l| l.to_lowercase().contains("total")); + if let Some(t) = is_total.last_mut() { + *t = last_total; + } + if !last_total { + labels.push("Total".into()); + vals.push(0.0); + is_total.push(true); + ncat += 1; + } + let mut bars = Vec::with_capacity(ncat); + let mut cum = 0.0f64; + for (j, v) in vals.iter().enumerate() { + if is_total.get(j).copied().unwrap_or(false) { + let total = if last_total && j + 1 == ncat && *v != 0.0 { *v } else { cum }; + bars.push((0.0, total, 0u8)); + cum = total; + } else { + let top = clean(cum + v); + bars.push((cum, top, if *v >= 0.0 { 1 } else { 2 })); + cum = top; + } + } + let (lo, hi) = value_range(bars.iter().flat_map(|(b, t, _)| [*b, *t])).unwrap_or((0.0, 0.0)); + let ys = nice_scale(lo, hi, true); + let f = Fmt::new(&s.number_format); + let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); + if !plot.ok() { + return; + } + let cw = plot.w / ncat as f32; + let bw = cw / 1.5; + let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; + for (j, (b, t, kind)) in bars.iter().enumerate() { + let color = match kind { + 1 => UP, + 2 => DOWN, + _ => s.color, + }; + let x = plot.x + (j as f32 + 0.5) * cw - bw / 2.0; + let (yb, yt) = (vy(*b), vy(*t)); + ctx.rect(x, yb.min(yt), bw, (yb - yt).abs().max(0.5), color, None); + if j + 1 < bars.len() && ncat <= 500 { + ctx.out.push(Prim::Line { pts: vec![[x + bw, yt], [x + cw, yt]], color: AXIS, width: 0.75, dash: true }); + } + if chart.data_labels && ncat <= MAX_LABELS { + let v = if *kind == 0 { *t } else { t - b }; + ctx.text(x + bw / 2.0, yb.min(yt) - 2.0, &f.format(v, None), LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + } + } +} + +// ---------------------------------------------------------------- funnel + +pub(super) fn funnel(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let Some(s) = data.series.first() else { return }; + let n = data.categories.len().max(s.values.len()).min(MAX_CATS); + if n == 0 { + return; + } + let vals: Vec = (0..n).map(|j| s.values.get(j).copied().flatten().unwrap_or(0.0).abs()).collect(); + let max = vals.iter().copied().fold(0.0f64, f64::max); + if max.is_nan() || max <= 0.0 { + return; + } + let labels: Vec = (0..n).map(|j| cat_label(data, j)).collect(); + let lw = (labels.iter().take(2000).map(|t| ctx.tw(t, LABEL_SIZE)).fold(0.0f32, f32::max) + 8.0).min(area.w * 0.35); + let plot = Bx { x: area.x + lw, w: area.w - lw, ..area }; + if !plot.ok() { + return; + } + let slot = plot.h / n as f32; + let bh = slot * 0.85; + let f = Fmt::new(&s.number_format); + let show = slot >= LABEL_SIZE * 0.9; + for (j, v) in vals.iter().enumerate() { + let bw = (*v / max) as f32 * plot.w; + let x = plot.x + (plot.w - bw) / 2.0; + let y = plot.y + j as f32 * slot + (slot - bh) / 2.0; + if bw > 0.0 { + ctx.rect(x, y, bw, bh, s.color, None); + } + if show { + let yc = y + bh / 2.0; + if chart.data_labels { + let t = f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None); + let color = if ctx.tw(&t, LABEL_SIZE) + 4.0 <= bw { on(s.color) } else { TEXT }; + ctx.text(plot.cx(), yc, &t, LABEL_SIZE, color, (HAlign::Center, VAlign::Middle)); + } + let l = ctx.fit(labels.get(j).map(String::as_str).unwrap_or(""), LABEL_SIZE, lw - 8.0); + ctx.text(plot.x - 6.0, yc, &l, LABEL_SIZE, TEXT, (HAlign::Right, VAlign::Middle)); + } + } +} + +// ---------------------------------------------------------------- pie, doughnut, sunburst + +pub(super) fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inner: f32, names: bool) { + let Some(s) = data.series.first() else { return }; + let vals: Vec = s.values.iter().take(MAX_CATS).map(|v| v.map(f64::abs).unwrap_or(0.0)).collect(); + let total: f64 = vals.iter().sum(); + if !(total.is_finite() && total > 0.0) { + return; + } + let (cx, cy) = (area.cx(), area.cy()); + let r = area.w.min(area.h) / 2.0 * 0.92; + if r < 2.0 { + return; + } + let ri = r * inner; + let f = Fmt::new(&s.number_format); + let mut a = 0.0f32; + let mut labels = Vec::new(); + for (j, v) in vals.iter().enumerate() { + let sweep = (*v / total) as f32 * TAU; + if sweep > 1e-4 { + let fill = point_color(data, j); + ctx.out.push(Prim::Wedge { cx, cy, r_outer: r, r_inner: ri, a0: a, a1: (a + sweep).min(TAU), fill, stroke: Some((WHITE, 1.5)) }); + if (chart.data_labels || names) && vals.len() <= MAX_LABELS { + let t = if names { cat_label(data, j) } else { f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None) }; + let mid = a + sweep / 2.0; + let rr = if ri > 0.0 { (r + ri) / 2.0 } else { r * 0.65 }; + let room = sweep * rr; + if ctx.tw(&t, LABEL_SIZE) <= room.max(r - ri) && room >= LABEL_SIZE { + labels.push((cx + rr * mid.sin(), cy - rr * mid.cos(), t, on(fill))); + } + } + } + a += sweep; + } + for (x, y, t, c) in labels { + ctx.text(x, y, &t, LABEL_SIZE, c, (HAlign::Center, VAlign::Middle)); + } +} + +// ---------------------------------------------------------------- treemap + +fn worst(row: &[f64], side: f64) -> f64 { + let s: f64 = row.iter().sum(); + if s <= 0.0 || side <= 0.0 { + return f64::INFINITY; + } + let (mn, mx) = row.iter().fold((f64::INFINITY, 0.0f64), |(a, b), v| (a.min(*v), b.max(*v))); + let s2 = s * s; + let w2 = side * side; + (w2 * mx / s2).max(s2 / (w2 * mn)) +} + +/// Squarified treemap layout of (index, area) items, sorted descending, into `r`. +fn squarify(items: &[(usize, f64)], r: Bx) -> Vec<(usize, Bx)> { + let total: f64 = items.iter().map(|i| i.1).sum(); + let area = (r.w as f64) * (r.h as f64); + if !(total > 0.0 && area > 0.0) { + return vec![]; + } + let scale = area / total; + let mut out = Vec::with_capacity(items.len()); + let mut rem = r; + let mut row: Vec<(usize, f64)> = Vec::new(); + let mut i = 0; + let layout = |row: &[(usize, f64)], rem: &mut Bx, out: &mut Vec<(usize, Bx)>| { + let s: f64 = row.iter().map(|x| x.1).sum(); + if s <= 0.0 { + return; + } + if rem.w >= rem.h { + let cw = (s / rem.h.max(1e-6) as f64) as f32; + let mut y = rem.y; + for (j, a) in row { + let h = (*a / cw.max(1e-6) as f64) as f32; + out.push((*j, Bx { x: rem.x, y, w: cw, h })); + y += h; + } + rem.x += cw; + rem.w = (rem.w - cw).max(0.0); + } else { + let rh = (s / rem.w.max(1e-6) as f64) as f32; + let mut x = rem.x; + for (j, a) in row { + let w = (*a / rh.max(1e-6) as f64) as f32; + out.push((*j, Bx { x, y: rem.y, w, h: rh })); + x += w; + } + rem.y += rh; + rem.h = (rem.h - rh).max(0.0); + } + }; + while let Some(&(j, v)) = items.get(i) { + let a = v * scale; + let side = rem.w.min(rem.h) as f64; + let cur: Vec = row.iter().map(|x| x.1).collect(); + let mut with = cur.clone(); + with.push(a); + if row.is_empty() || worst(&with, side) <= worst(&cur, side) { + row.push((j, a)); + i += 1; + } else { + layout(&row, &mut rem, &mut out); + row.clear(); + } + } + if !row.is_empty() { + layout(&row, &mut rem, &mut out); + } + out +} + +pub(super) fn treemap(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let Some(s) = data.series.first() else { return }; + let mut items: Vec<(usize, f64)> = + s.values.iter().take(MAX_MARKERS).enumerate().filter_map(|(j, v)| v.filter(|v| *v > 0.0).map(|v| (j, v))).collect(); + items.sort_by(|a, b| b.1.total_cmp(&a.1)); + let f = Fmt::new(&s.number_format); + for (j, b) in squarify(&items, area) { + let fill = point_color(data, j); + ctx.rect(b.x, b.y, b.w, b.h, fill, Some((WHITE, 1.5))); + if b.w > 24.0 && b.h > LABEL_SIZE * 1.6 { + let name = ctx.fit(&cat_label(data, j), LABEL_SIZE, b.w - 8.0); + ctx.text(b.x + 4.0, b.y + 4.0, &name, LABEL_SIZE, on(fill), (HAlign::Left, VAlign::Top)); + if chart.data_labels && b.h > LABEL_SIZE * 3.2 { + let v = items.iter().find(|x| x.0 == j).map(|x| x.1).unwrap_or(0.0); + let t = ctx.fit(&f.format(v, None), LABEL_SIZE, b.w - 8.0); + ctx.text(b.x + 4.0, b.y + 4.0 + LABEL_SIZE * 1.4, &t, LABEL_SIZE, on(fill), (HAlign::Left, VAlign::Top)); + } + } + } +} + +// ---------------------------------------------------------------- radar + +pub(super) fn radar(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(1000); + if ncat == 0 { + return; + } + let labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); + let lw = labels.iter().map(|t| ctx.tw(t, LABEL_SIZE)).fold(0.0f32, f32::max).min(area.w * 0.2); + let r = ((area.w - 2.0 * (lw + 8.0)).min(area.h - 2.0 * (LABEL_SIZE * 1.4 + 6.0)) / 2.0).max(0.0); + if r < 5.0 { + return; + } + let (cx, cy) = (area.cx(), area.cy()); + let (lo, hi) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())).unwrap_or((0.0, 0.0)); + let sc = nice_scale(lo, hi, true); + let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); + let ang = |j: usize| j as f32 / ncat as f32 * TAU; + let pt = |a: f32, rr: f32| [cx + rr * a.sin(), cy - rr * a.cos()]; + let ticks = sc.ticks(); + let spacing = r / ticks.len().saturating_sub(1).max(1) as f32; + let every = ((LABEL_SIZE * 1.3 / spacing.max(1e-3)).ceil() as usize).max(1); + for (ti, t) in ticks.into_iter().enumerate() { + let rr = sc.frac(t) * r; + if rr > 0.5 && chart.gridlines { + let mut ring: Vec<[f32; 2]> = (0..ncat).map(|j| pt(ang(j), rr)).collect(); + if ncat < 3 { + ring = (0..=48).map(|k| pt(k as f32 / 48.0 * TAU, rr)).collect(); + } else if let Some(p) = ring.first().copied() { + ring.push(p); + } + ctx.line(ring, GRID, 0.75); + } + if ti % every == 0 { + ctx.text(cx - 3.0, cy - rr, &f.format(t, Some(sc.step)), LABEL_SIZE * 0.9, TEXT, (HAlign::Right, VAlign::Middle)); + } + } + let step = ncat.div_ceil(72).max(1); + for j in (0..ncat).step_by(step) { + let a = ang(j); + ctx.line(vec![[cx, cy], pt(a, r)], GRID, 0.75); + let p = pt(a, r + 6.0); + let (sa, ca) = (a.sin(), a.cos()); + let align = if sa > 0.1 { + HAlign::Left + } else if sa < -0.1 { + HAlign::Right + } else { + HAlign::Center + }; + let valign = if ca > 0.1 { + VAlign::Bottom + } else if ca < -0.1 { + VAlign::Top + } else { + VAlign::Middle + }; + let t = ctx.fit(labels.get(j).map(String::as_str).unwrap_or(""), LABEL_SIZE, lw.max(20.0)); + ctx.text(p[0], p[1], &t, LABEL_SIZE, TEXT, (align, valign)); + } + for s in &data.series { + let mut pts: Vec<[f32; 2]> = (0..ncat).map(|j| pt(ang(j), sc.frac(s.values.get(j).copied().flatten().unwrap_or(sc.min)) * r)).collect(); + if let Some(p) = pts.first().copied() { + pts.push(p); + } + ctx.line(pts, s.color, 2.0); + } +} + +// ---------------------------------------------------------------- box & whisker + +fn quantile(sorted: &[f64], q: f64, method: QuartileMethod) -> f64 { + let n = sorted.len(); + if n == 0 { + return 0.0; + } + // Clamp exclusive ranks for short samples so one or two points remain drawable. + let pos = match method { + QuartileMethod::Inclusive => q * (n - 1) as f64, + QuartileMethod::Exclusive => (q * (n as f64 + 1.0) - 1.0).clamp(0.0, (n - 1) as f64), + }; + let i = pos.floor() as usize; + let frac = pos - i as f64; + let a = sorted.get(i).copied().unwrap_or(0.0); + let b = sorted.get(i + 1).copied().unwrap_or(a); + a + (b - a) * frac +} + +pub(super) fn box_whisker(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let labels: Vec = data.series.iter().map(|s| s.name.clone()).collect(); + let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return }; + let ys = nice_scale(lo, hi, false); + let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); + let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); + if !plot.ok() { + return; + } + let n = data.series.len().max(1); + let cw = plot.w / n as f32; + let bw = (cw * 0.4).min(80.0); + let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; + for (i, s) in data.series.iter().enumerate() { + let mut v: Vec = s.values.iter().flatten().copied().collect(); + if v.is_empty() { + continue; + } + v.sort_by(f64::total_cmp); + let method = chart.series.get(i).map(|s| s.quartiles).unwrap_or_default(); + let (q1, med, q3) = (quantile(&v, 0.25, method), quantile(&v, 0.5, method), quantile(&v, 0.75, method)); + let iqr = q3 - q1; + let (flo, fhi) = (q1 - 1.5 * iqr, q3 + 1.5 * iqr); + let wlo = v.iter().copied().find(|x| *x >= flo).unwrap_or(q1); + let whi = v.iter().rev().copied().find(|x| *x <= fhi).unwrap_or(q3); + let mean = v.iter().sum::() / v.len() as f64; + let c = plot.x + (i as f32 + 0.5) * cw; + ctx.vline(c, vy(whi), vy(q3), s.color, 1.25); + ctx.vline(c, vy(q1), vy(wlo), s.color, 1.25); + ctx.hline(c - bw / 4.0, c + bw / 4.0, vy(whi), s.color, 1.25); + ctx.hline(c - bw / 4.0, c + bw / 4.0, vy(wlo), s.color, 1.25); + let (yt, yb) = (vy(q3), vy(q1)); + ctx.rect(c - bw / 2.0, yt, bw, (yb - yt).max(0.5), s.color, None); + ctx.hline(c - bw / 2.0, c + bw / 2.0, vy(med), WHITE, 1.5); + let (mx, my, d) = (c, vy(mean), 3.0); + ctx.line(vec![[mx - d, my - d], [mx + d, my + d]], WHITE, 1.25); + ctx.line(vec![[mx - d, my + d], [mx + d, my - d]], WHITE, 1.25); + for o in v.iter().filter(|x| **x < flo || **x > fhi).take(MAX_MARKERS) { + ctx.out.push(Prim::Circle { cx: c, cy: vy(*o), r: 2.5, fill: None, stroke: Some((s.color, 1.0)) }); + } + } +} + +// ---------------------------------------------------------------- stock + +pub(super) fn stock(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS); + if ncat == 0 { + return; + } + let labels: Vec = (0..ncat).map(|j| cat_label(data, j)).collect(); + let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return }; + let ys = nice_scale(lo, hi, false); + let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General")); + let plot = frame(ctx, area, CatAxis::Labels(&labels, &[]), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines); + if !plot.ok() { + return; + } + let ser = |k: usize| data.series.get(k); + let (open, high, low, close) = match data.series.len() { + 0 => return, + 1 => (None, None, None, ser(0)), + 2 => (None, ser(0), ser(1), None), + 3 => (None, ser(0), ser(1), ser(2)), + _ => (ser(0), ser(1), ser(2), ser(3)), + }; + let get = |s: Option<&SeriesData>, j: usize| s.and_then(|s| s.values.get(j).copied().flatten()); + let cw = plot.w / ncat as f32; + let tick = (cw * 0.25).max(1.0); + let vy = |v: f64| plot.bottom() - ys.frac(v) * plot.h; + for j in 0..ncat { + let c = plot.x + (j as f32 + 0.5) * cw; + if let (Some(h), Some(l)) = (get(high, j), get(low, j)) { + ctx.vline(c, vy(h), vy(l), STOCK, 1.25); + } + match (get(open, j), get(close, j)) { + (Some(o), Some(cl)) => { + let (yo, yc) = (vy(o), vy(cl)); + let bw = (cw * 0.5).max(1.0); + let fill = if cl >= o { WHITE } else { STOCK }; + ctx.rect(c - bw / 2.0, yo.min(yc), bw, (yo - yc).abs().max(0.75), fill, Some((STOCK, 1.0))); + } + (None, Some(cl)) => { + if high.is_some() { + ctx.hline(c, c + tick, vy(cl), STOCK, 1.25); + } else { + ctx.out.push(Prim::Circle { cx: c, cy: vy(cl), r: 2.5, fill: Some(STOCK), stroke: None }); + } + } + _ => {} + } + } +} + +#[cfg(test)] +mod quartile_tests { + use super::*; + + #[test] + fn box_whisker_default_quartiles_are_exclusive() { + let values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; + assert_eq!(quantile(&values, 0.25, QuartileMethod::default()), 1.75); + assert_eq!(quantile(&values, 0.5, QuartileMethod::default()), 3.5); + assert_eq!(quantile(&values, 0.75, QuartileMethod::default()), 5.25); + } + + #[test] + fn quartile_methods_and_short_samples() { + for (values, exclusive, inclusive) in [ + (vec![1., 2., 3.], (1., 3.), (1.5, 2.5)), + (vec![1., 2., 3., 4.], (1.25, 3.75), (1.75, 3.25)), + (vec![1., 2., 3., 4., 5.], (1.5, 4.5), (2., 4.)), + (vec![1., 2., 3., 4., 5., 6., 7.], (2., 6.), (2.5, 5.5)), + (vec![1., 1., 2., 3., 5., 8.], (1., 5.75), (1.25, 4.5)), + (vec![1., 2.], (1., 2.), (1.25, 1.75)), + (vec![1.], (1., 1.), (1., 1.)), + (vec![], (0., 0.), (0., 0.)), + ] { + for (method, expected) in [(QuartileMethod::Exclusive, exclusive), (QuartileMethod::Inclusive, inclusive)] { + assert_eq!((quantile(&values, 0.25, method), quantile(&values, 0.75, method)), expected); + } + } + } +} diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs new file mode 100644 index 0000000000..5ddb5a3cd3 --- /dev/null +++ b/crates/chart/src/render/legend.rs @@ -0,0 +1,165 @@ +use super::frame::Bx; +use super::trend::supports_trendline; +use super::{ + Chart, ChartData, ChartKind, Ctx, DOWN, HAlign, LABEL_SIZE, MAX_CATS, MAX_SERIES, MAX_TRENDLINES, Prim, Rgba, SeriesData, TEXT, Theme, UP, + VAlign, auto_name, series_color, +}; +use gridcraft_model::LegendPos; + +/// How a legend entry's swatch is drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Swatch { + Box, + Line, + LineMarker, + Marker, +} + +/// The kind a series is drawn as (per-series kinds only apply to combo charts). +pub(super) fn plot_kind(chart: &Chart, s: &SeriesData) -> ChartKind { + if chart.kind == ChartKind::Combo { if s.kind == ChartKind::Combo { ChartKind::Line } else { s.kind } } else { chart.kind } +} + +/// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). +pub(super) fn point_color(data: &ChartData, j: usize) -> Rgba { + match (j, data.series.first()) { + (0, Some(s)) => s.color, + _ => j.checked_rem(data.palette.len()).and_then(|k| data.palette.get(k)).copied().unwrap_or_else(|| series_color(&Theme::default(), j)), + } +} + +fn first_len(data: &ChartData) -> usize { + data.series.first().map(|s| s.values.len()).unwrap_or(0) +} + +pub(super) fn cat_label(data: &ChartData, j: usize) -> String { + data.categories.get(j).cloned().unwrap_or_else(|| (j + 1).to_string()) +} + +/// Legend entries (text, colour, swatch) `render` draws for this chart; empty when hidden. +pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swatch)> { + if chart.legend == LegendPos::None { + return vec![]; + } + match chart.kind { + ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst => { + let n = first_len(data).min(MAX_CATS); + (0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect() + } + ChartKind::Histogram | ChartKind::Funnel | ChartKind::Stock => vec![], + ChartKind::Waterfall => { + if data.series.is_empty() { + return vec![]; + } + let total = data.series.first().map(|s| s.color).unwrap_or(TEXT); + vec![("Increase".into(), UP, Swatch::Box), ("Decrease".into(), DOWN, Swatch::Box), ("Total".into(), total, Swatch::Box)] + } + _ => { + let series = data.series.iter().take(MAX_SERIES); + let mut out: Vec<(String, Rgba, Swatch)> = series + .clone() + .map(|s| { + let sw = match plot_kind(chart, s) { + ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, + ChartKind::LineMarkers => Swatch::LineMarker, + ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, + _ => Swatch::Box, + }; + (s.name.clone(), s.color, sw) + }) + .collect(); + // Trendlines follow the series, named "Linear (Sales)" unless given a name. + for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) { + for t in s.trendlines.iter().take(MAX_TRENDLINES) { + out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); + } + } + out + } + } +} + +// ---------------------------------------------------------------- legend + +fn swatch_w(sw: Swatch, s: f32) -> f32 { + if sw == Swatch::Box { s } else { s * 2.0 } +} + +pub(super) fn draw_swatch(ctx: &mut Ctx, sw: Swatch, x: f32, yc: f32, s: f32, color: Rgba) { + match sw { + Swatch::Box => ctx.rect(x, yc - s / 2.0, s, s, color, None), + Swatch::Line => ctx.hline(x, x + 2.0 * s, yc, color, 2.0), + Swatch::LineMarker => { + ctx.hline(x, x + 2.0 * s, yc, color, 2.0); + ctx.out.push(Prim::Circle { cx: x + s, cy: yc, r: s * 0.35, fill: Some(color), stroke: None }); + } + Swatch::Marker => ctx.out.push(Prim::Circle { cx: x + s, cy: yc, r: s * 0.4, fill: Some(color), stroke: None }), + } +} + +pub(super) fn draw_legend(ctx: &mut Ctx, entries: &[(String, Rgba, Swatch)], pos: LegendPos, area: Bx) -> Bx { + let size = LABEL_SIZE; + let row_h = size * 1.6; + let s = size * 0.8; + let gap = 4.0; + let spacing = size * 1.3; + let item_w = |ctx: &Ctx, e: &(String, Rgba, Swatch)| swatch_w(e.2, s) + gap + ctx.tw(&e.0, size); + match pos { + LegendPos::None => area, + LegendPos::Top | LegendPos::Bottom => { + let max_rows = ((area.h * 0.3 / row_h).floor() as usize).max(1); + let mut rows: Vec> = vec![vec![]]; + let mut cur = 0.0f32; + for (i, e) in entries.iter().enumerate() { + let iw = item_w(ctx, e).min(area.w); + let need = if cur > 0.0 { spacing + iw } else { iw }; + if cur > 0.0 && cur + need > area.w { + if rows.len() >= max_rows { + break; + } + rows.push(vec![]); + cur = 0.0; + } + cur += if cur > 0.0 { spacing + iw } else { iw }; + if let Some(r) = rows.last_mut() { + r.push((i, iw)); + } + } + let lh = rows.len() as f32 * row_h; + let y0 = if pos == LegendPos::Bottom { area.bottom() - lh } else { area.y }; + for (ri, row) in rows.iter().enumerate() { + let total: f32 = row.iter().map(|(_, w)| w).sum::() + spacing * row.len().saturating_sub(1) as f32; + let mut x = area.x + (area.w - total).max(0.0) / 2.0; + let yc = y0 + ri as f32 * row_h + row_h / 2.0; + for &(i, iw) in row { + if let Some(e) = entries.get(i) { + draw_swatch(ctx, e.2, x, yc, s, e.1); + let sx = swatch_w(e.2, s) + gap; + let t = ctx.fit(&e.0, size, (iw - sx).max(0.0) + 0.5); + ctx.text(x + sx, yc, &t, size, TEXT, (HAlign::Left, VAlign::Middle)); + } + x += iw + spacing; + } + } + let used = lh + 4.0; + if pos == LegendPos::Bottom { Bx { h: area.h - used, ..area } } else { Bx { y: area.y + used, h: area.h - used, ..area } } + } + LegendPos::Left | LegendPos::Right => { + let colw = entries.iter().map(|e| item_w(ctx, e)).fold(0.0f32, f32::max).min(area.w * 0.35); + let max_rows = ((area.h / row_h).floor() as usize).max(1); + let n = entries.len().min(max_rows); + let lh = n as f32 * row_h; + let y0 = area.y + (area.h - lh).max(0.0) / 2.0; + let x0 = if pos == LegendPos::Right { area.right() - colw } else { area.x }; + for (i, e) in entries.iter().take(n).enumerate() { + let yc = y0 + i as f32 * row_h + row_h / 2.0; + draw_swatch(ctx, e.2, x0, yc, s, e.1); + let sx = swatch_w(e.2, s) + gap; + let t = ctx.fit(&e.0, size, (colw - sx).max(0.0) + 0.5); + ctx.text(x0 + sx, yc, &t, size, TEXT, (HAlign::Left, VAlign::Middle)); + } + let used = colw + 8.0; + if pos == LegendPos::Right { Bx { w: area.w - used, ..area } } else { Bx { x: area.x + used, w: area.w - used, ..area } } + } + } +} diff --git a/crates/chart/src/render/lines.rs b/crates/chart/src/render/lines.rs new file mode 100644 index 0000000000..770aabe02b --- /dev/null +++ b/crates/chart/src/render/lines.rs @@ -0,0 +1,291 @@ +use super::frame::Bx; +use super::{Ctx, MAX_LINE_PTS, MAX_MARKERS, Prim, Rgba, WHITE}; +use std::collections::HashSet; + +// ---------------------------------------------------------------- helpers + +/// Reduces a long polyline to first/min/max/last per pixel column. +pub(super) fn decimate(pts: Vec<[f32; 2]>, max: usize) -> Vec<[f32; 2]> { + if pts.len() <= max { + return pts; + } + let mut out = Vec::with_capacity(max * 2); + let mut i = 0; + while let Some(p) = pts.get(i) { + let col = p[0].floor(); + let (start, mut mn, mut mx) = (i, i, i); + let mut k = i + 1; + while let Some(q) = pts.get(k) { + if q[0].floor() != col { + break; + } + if pts.get(mn).is_some_and(|m| q[1] < m[1]) { + mn = k; + } + if pts.get(mx).is_some_and(|m| q[1] > m[1]) { + mx = k; + } + k += 1; + } + let mut idx = [start, mn, mx, k - 1]; + idx.sort_unstable(); + let mut last = usize::MAX; + for ix in idx { + if ix != last + && let Some(q) = pts.get(ix) + { + out.push(*q); + last = ix; + } + } + i = k; + } + if out.len() > max * 4 { + let step = out.len() / (max * 2) + 1; + let last = out.last().copied(); + let mut s: Vec<[f32; 2]> = out.into_iter().step_by(step).collect(); + if let Some(l) = last + && s.last() != Some(&l) + { + s.push(l); + } + return s; + } + out +} + +/// Decimates the top and baseline of an area chart together at the same horizontal indices so +/// `area_mesh`'s paired vertical-strip topology (`pts[i]` ↔ `pts[2n - 1 - i]`) is preserved. +pub(super) fn decimate_area(top: Vec<[f32; 2]>, base: Vec<[f32; 2]>, max: usize) -> Vec<[f32; 2]> { + let n = top.len().min(base.len()); + if n == 0 { + return Vec::new(); + } + if n <= max { + let mut poly = top; + poly.truncate(n); + poly.extend(base.into_iter().take(n).rev()); + return poly; + } + let mut cols: Vec<[usize; 6]> = Vec::new(); + let mut keep = Vec::with_capacity(max * 2); + let mut i = 0; + while i < n { + let col = top[i][0].floor(); + let (start, mut t_mn, mut t_mx, mut b_mn, mut b_mx) = (i, i, i, i, i); + let mut k = i + 1; + while k < n && top[k][0].floor() == col { + if top[k][1] < top[t_mn][1] { + t_mn = k; + } + if top[k][1] > top[t_mx][1] { + t_mx = k; + } + if base[k][1] < base[b_mn][1] { + b_mn = k; + } + if base[k][1] > base[b_mx][1] { + b_mx = k; + } + k += 1; + } + let entry = [start, t_mn, t_mx, b_mn, b_mx, k - 1]; + cols.push(entry); + let mut idx = entry; + idx.sort_unstable(); + let mut last = usize::MAX; + for ix in idx { + if ix != last { + keep.push(ix); + last = ix; + } + } + i = k; + } + if keep.len() > max * 4 { + let max_groups = (max * 4 / 6).max(1); + let group_size = cols.len().div_ceil(max_groups); + keep.clear(); + for ch in cols.chunks(group_size) { + let start = ch[0][0]; + let end = ch.last().map_or(start, |c| c[5]); + let t_mn = ch.iter().map(|c| c[1]).min_by(|&a, &b| top[a][1].total_cmp(&top[b][1])).unwrap_or(start); + let t_mx = ch.iter().map(|c| c[2]).max_by(|&a, &b| top[a][1].total_cmp(&top[b][1])).unwrap_or(start); + let b_mn = ch.iter().map(|c| c[3]).min_by(|&a, &b| base[a][1].total_cmp(&base[b][1])).unwrap_or(start); + let b_mx = ch.iter().map(|c| c[4]).max_by(|&a, &b| base[a][1].total_cmp(&base[b][1])).unwrap_or(start); + let mut idx = [start, t_mn, t_mx, b_mn, b_mx, end]; + idx.sort_unstable(); + let mut last = usize::MAX; + for ix in idx { + if ix != last { + keep.push(ix); + last = ix; + } + } + } + } + let mut poly = Vec::with_capacity(keep.len() * 2); + for &ix in &keep { + poly.push(top[ix]); + } + for &ix in keep.iter().rev() { + poly.push(base[ix]); + } + poly +} + +/// Draws a polyline split at gaps (`None`), decimated when long. With `smooth` (the plot box), +/// each run is interpolated with a Catmull-Rom spline so the line curves through the data points. +pub(super) fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32, smooth: Option) { + let mut run: Vec<[f32; 2]> = Vec::new(); + for p in pts.iter().chain(std::iter::once(&None)) { + match p { + Some(p) => run.push(*p), + None => { + if run.len() >= 2 { + let r = decimate(std::mem::take(&mut run), MAX_LINE_PTS); + let r = match smooth { + Some(plot) => smooth_run(r, plot), + None => r, + }; + ctx.line(r, color, width); + } else { + run.clear(); + } + } + } + } +} + +/// Catmull-Rom spline through `pts`: every segment gets the same number of sub-segments (up to +/// 100), chosen so the whole curve stays within `MAX_LINE_PTS * 2` points. Endpoints are +/// duplicated so the curve passes through the first and last points, and the curve is clamped +/// to the `plot` box (a spline overshoots its data near sharp turns). +fn smooth_run(pts: Vec<[f32; 2]>, plot: Bx) -> Vec<[f32; 2]> { + let n = pts.len(); + if n < 3 { + return pts; + } + let cap = MAX_LINE_PTS * 2; + let steps = (cap / n).clamp(1, 100); + let mut out: Vec<[f32; 2]> = Vec::with_capacity(n.saturating_mul(steps).min(cap) + 1); + let at = |i: isize| -> [f32; 2] { + let j = i.clamp(0, n as isize - 1) as usize; + pts.get(j).copied().unwrap_or([0.0, 0.0]) + }; + let (x0, x1) = (plot.x.min(plot.right()), plot.x.max(plot.right())); + let (y0, y1) = (plot.y.min(plot.bottom()), plot.y.max(plot.bottom())); + let clip = |p: [f32; 2]| [p[0].clamp(x0, x1), p[1].clamp(y0, y1)]; + for i in 0..n.saturating_sub(1) { + let (p0, p1, p2, p3) = (at(i as isize - 1), at(i as isize), at(i as isize + 1), at(i as isize + 2)); + for s in 0..steps { + let t = s as f32 / steps as f32; + out.push(clip(catmull(p0, p1, p2, p3, t))); + } + } + out.push(clip(at(n as isize - 1))); + out +} + +/// One Catmull-Rom point between `p1` and `p2` (uniform parameterisation), tangent-scaled by 0.5. +fn catmull(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] { + let t2 = t * t; + let t3 = t2 * t; + let mut o = [0.0f32; 2]; + for k in 0..2 { + let (a0, a1, a2, a3) = (p0[k], p1[k], p2[k], p3[k]); + o[k] = 0.5 * ((2.0 * a1) + (-a0 + a2) * t + (2.0 * a0 - 5.0 * a1 + 4.0 * a2 - a3) * t2 + (-a0 + 3.0 * a1 - 3.0 * a2 + a3) * t3); + } + o +} + +pub(super) fn draw_markers(ctx: &mut Ctx, pts: impl Iterator, r: f32, color: Rgba) { + let mut seen = HashSet::new(); + for p in pts { + if seen.len() >= MAX_MARKERS { + break; + } + if seen.insert(((p[0] * 0.5) as i32, (p[1] * 0.5) as i32)) { + ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r, fill: Some(color), stroke: Some((WHITE, 0.75)) }); + } + } +} + +#[cfg(test)] +mod smooth_tests { + use super::*; + + #[test] + fn long_runs_are_smoothed_uniformly_within_the_cap() { + let plot = Bx { x: 0.0, y: 0.0, w: 3000.0, h: 100.0 }; + let pts: Vec<[f32; 2]> = (0..1500).map(|i| [i as f32 * 2.0, if i % 2 == 0 { 20.0 } else { 80.0 }]).collect(); + let out = smooth_run(pts, plot); + assert!(out.len() <= MAX_LINE_PTS * 2 + 1, "{}", out.len()); + // Two sub-segments per segment all the way to the end, not 100 each and then a straight tail. + assert_eq!(out.len(), 1499 * 2 + 1); + assert_eq!(out.last().copied(), Some([2998.0, 80.0])); + } + + #[test] + fn spline_overshoot_is_clamped_to_the_plot() { + let plot = Bx { x: 0.0, y: 10.0, w: 300.0, h: 100.0 }; + // A step right at the plot edges: Catmull-Rom overshoots past both. + let pts = vec![[0.0, 110.0], [100.0, 110.0], [110.0, 10.0], [200.0, 10.0], [300.0, 10.0]]; + let out = smooth_run(pts, plot); + assert!(out.len() > 5); + assert!(out.iter().all(|p| (0.0..=300.0).contains(&p[0]) && (10.0..=110.0).contains(&p[1]))); + } + + #[test] + fn decimate_area_preserves_paired_vertical_strips() { + let top: Vec<[f32; 2]> = (0..1000).map(|i| [i as f32 * 0.25, ((i * 37) % 100) as f32]).collect(); + let base: Vec<[f32; 2]> = (0..1000).map(|i| [i as f32 * 0.25, 100.0]).collect(); + let poly = decimate_area(top, base, 64); + assert_eq!(poly.len() % 2, 0); + let half = poly.len() / 2; + for i in 0..half { + assert_eq!(poly[i][0], poly[poly.len() - 1 - i][0]); + assert_eq!(poly[poly.len() - 1 - i][1], 100.0); + } + } + + #[test] + fn decimate_area_preserves_extrema_across_3000_columns() { + // 3,000 occupied pixel columns with 6 points per column (18,000 points total), + // where each column has distinct top and baseline extrema so the initial per-column + // index list exceeds `MAX_LINE_PTS * 2 * 4` (6,400). + let max = MAX_LINE_PTS * 2; + let mut top = Vec::with_capacity(18_000); + let mut base = Vec::with_capacity(18_000); + for col in 0..3_000 { + let y_top = [50.0, 20.0, 80.0, 50.0, 50.0, 50.0]; + let y_base = [150.0, 150.0, 150.0, 120.0, 180.0, 150.0]; + for s in 0..6 { + let x = col as f32 + s as f32 * 0.1; + top.push([x, y_top[s]]); + base.push([x, y_base[s]]); + } + } + // Plant sharp spikes on both top and baseline in interior columns. + top[777 * 6 + 1][1] = 1.0; + top[1999 * 6 + 2][1] = 99.0; + base[1234 * 6 + 3][1] = 101.0; + base[2501 * 6 + 4][1] = 199.0; + + let poly = decimate_area(top, base, max); + assert_eq!(poly.len() % 2, 0); + let half = poly.len() / 2; + assert!(half <= max * 4, "retained {half} paired vertices, limit is {}", max * 4); + for i in 0..half { + assert_eq!(poly[i][0], poly[poly.len() - 1 - i][0]); + } + let top_kept = &poly[..half]; + let base_kept = &poly[half..]; + assert_eq!(top_kept.first().map(|p| p[0]), Some(0.0)); + assert_eq!(top_kept.last().map(|p| p[0]), Some(2999.5)); + assert!(top_kept.iter().any(|p| p[1] == 1.0), "top min spike preserved"); + assert!(top_kept.iter().any(|p| p[1] == 99.0), "top max spike preserved"); + assert!(base_kept.iter().any(|p| p[1] == 101.0), "base min spike preserved"); + assert!(base_kept.iter().any(|p| p[1] == 199.0), "base max spike preserved"); + } +} diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs new file mode 100644 index 0000000000..f0839dcfef --- /dev/null +++ b/crates/chart/src/render/table.rs @@ -0,0 +1,107 @@ +//! The chart data table uses the same primitives as the plot, including in print/PDF output. + +use super::frame::{Bx, CatAxis, level_groups}; +use super::legend::{Swatch, cat_label, draw_swatch, plot_kind}; +use super::{AXIS, Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, TEXT, VAlign}; + +pub(super) struct Layout { + top: f32, + row_height: f32, + headers: usize, + stub: f32, + columns: usize, +} + +pub(super) fn category_axis<'a>(layout: &Option, labels: &'a [String], outer: &'a [Vec]) -> CatAxis<'a> { + match layout { + Some(t) => CatAxis::Table(labels, t.stub), + None => CatAxis::Labels(labels, outer), + } +} + +/// Reserve at most half the available height. A table that cannot fit is explicitly labelled +/// instead of dropping rows or allocating a series × point-sized matrix. +pub(super) fn reserve(ctx: &mut Ctx, chart: &Chart, data: &ChartData, mut area: Bx, columns: usize) -> (Bx, Option) { + if chart.data_table.is_none() || !chart.supports_data_table() { + return (area, None); + } + let headers = data.category_levels.len() + 1; + let rows = headers + data.series.len(); + let row_height = LABEL_SIZE * 1.4 + 4.0; + let height = row_height * rows as f32; + let key_width = if chart.data_table.as_ref().is_some_and(|t| t.show_keys) { 22.0 } else { 0.0 }; + let names = data.series.iter().take(32).map(|s| ctx.tw(&s.name, LABEL_SIZE)).fold(0.0f32, f32::max); + let stub = (names + key_width + 10.0).clamp(24.0, (area.w * 0.3).max(24.0)); + if columns == 0 || columns > 128 || data.series.len() > 32 || height > area.h * 0.5 || (area.w * 0.6) / (columns as f32) < 18.0 { + let message = ctx.fit("Data table needs more space", LABEL_SIZE, area.w); + ctx.text(area.cx(), area.bottom(), &message, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + area.h -= row_height; + return (area, None); + } + area.h -= height; + (area, Some(Layout { top: area.bottom(), row_height, headers, stub, columns })) +} + +pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, layout: Option<&Layout>) { + let Some(layout) = layout else { return }; + let Some(settings) = &chart.data_table else { return }; + let x0 = plot.x - layout.stub; + let top = layout.top; + let rows = layout.headers + data.series.len(); + let bottom = top + layout.row_height * rows as f32; + let cw = plot.w / layout.columns as f32; + // Outermost category level first, then the individual categories. + for (i, level) in data.category_levels.iter().rev().enumerate() { + for (first, end) in level_groups(level, layout.columns) { + let text = level.get(first).map(String::as_str).unwrap_or(""); + let text = ctx.fit(text, LABEL_SIZE, (end - first) as f32 * cw - 4.0); + let x = plot.x + (first + end) as f32 * cw / 2.0; + ctx.text(x, top + (i as f32 + 0.5) * layout.row_height, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + } + let header_y = top + (layout.headers as f32 - 0.5) * layout.row_height; + let n = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)); + for j in 0..layout.columns { + let text = if j < n { cat_label(data, j) } else { String::new() }; + let text = ctx.fit(&text, LABEL_SIZE, cw - 4.0); + ctx.text(plot.x + (j as f32 + 0.5) * cw, header_y, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + for (i, series) in data.series.iter().enumerate() { + let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; + let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; + if settings.show_keys { + let swatch = match plot_kind(chart, series) { + ChartKind::Line | ChartKind::LineStacked => Swatch::Line, + ChartKind::LineMarkers => Swatch::LineMarker, + _ => Swatch::Box, + }; + draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color); + } + let name = ctx.fit(&series.name, LABEL_SIZE, plot.x - name_x - 4.0); + ctx.text(name_x, y, &name, LABEL_SIZE, TEXT, (HAlign::Left, VAlign::Middle)); + let fmt = Fmt::new(&series.number_format); + for j in 0..layout.columns { + let value = series.values.get(j).copied().flatten().map(|v| fmt.format(v, None)).unwrap_or_default(); + let text = ctx.fit(&value, LABEL_SIZE, cw - 4.0); + ctx.text(plot.x + (j as f32 + 0.5) * cw, y, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + } + if settings.horizontal_border { + for row in 1..rows { + ctx.hline(x0, plot.right(), top + row as f32 * layout.row_height, AXIS, 0.75); + } + } + if settings.vertical_border { + ctx.vline(plot.x, top, bottom, AXIS, 0.75); + // The outer headers span groups; category dividers begin at the innermost header. + for j in 1..layout.columns { + ctx.vline(plot.x + j as f32 * cw, top + (layout.headers - 1) as f32 * layout.row_height, bottom, AXIS, 0.75); + } + } + if settings.outline { + ctx.hline(x0, plot.right(), top, AXIS, 0.75); + ctx.hline(x0, plot.right(), bottom, AXIS, 0.75); + ctx.vline(x0, top, bottom, AXIS, 0.75); + ctx.vline(plot.right(), top, bottom, AXIS, 0.75); + } +} diff --git a/crates/chart/src/render/trend.rs b/crates/chart/src/render/trend.rs new file mode 100644 index 0000000000..b642df2623 --- /dev/null +++ b/crates/chart/src/render/trend.rs @@ -0,0 +1,170 @@ +use super::frame::{Bx, value_range}; +use super::lines::decimate; +use super::{ + ChartKind, Ctx, HAlign, LABEL_SIZE, LineDash, MAX_CATS, MAX_LINE_PTS, MAX_TRENDLINES, Prim, SeriesData, TEXT, TrendlineKind, VAlign, + fit_trendline, moving_average, +}; + +// ---------------------------------------------------------------- trendlines + +/// Samples along a regression trendline. +const TREND_STEPS: usize = 200; + +/// Whether series drawn as `k` show trendlines (Excel offers them on 2-D unstacked column, +/// bar, line, area, scatter and bubble charts). +pub fn supports_trendline(k: ChartKind) -> bool { + use ChartKind::*; + matches!(k, ColumnClustered | BarClustered | Line | LineMarkers | Area | Scatter | ScatterLines | Bubble) +} + +/// A forecast distance as drawn: finite, non-negative and bounded. +fn forecast(v: f64) -> f64 { + if v.is_finite() && v > 0.0 { v.min(1e9) } else { 0.0 } +} + +/// Most empty category slots a forward forecast may add after `ncat` categories: four times the +/// data (at least 32), and never past `MAX_CATS` in total. A larger forecast would shrink every +/// column to nothing. +pub(super) fn max_forward_slots(ncat: usize) -> f64 { + (ncat.saturating_mul(4).max(32)).min(MAX_CATS.saturating_sub(ncat)) as f64 +} + +/// Longest forward forecast among `s`'s regression trendlines. +pub(super) fn max_forward(s: &SeriesData) -> f64 { + s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.forward)).fold(0.0, f64::max) +} + +/// Longest backward forecast among `s`'s regression trendlines. +pub(super) fn max_backward(s: &SeriesData) -> f64 { + s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.backward)).fold(0.0, f64::max) +} + +type ClippedSegment = ((f64, f64), (f64, f64), bool, bool); + +/// Liang–Barsky: the part of segment `a`–`b` inside the unit square, with whether the start and +/// end were cut. +fn clip_segment(a: (f64, f64), b: (f64, f64)) -> Option { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [(-dx, a.0), (dx, 1.0 - a.0), (-dy, a.1), (dy, 1.0 - a.1)] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else { + let r = q / p; + if p < 0.0 { + if r > t1 { + return None; + } + t0 = t0.max(r); + } else { + if r < t0 { + return None; + } + t1 = t1.min(r); + } + } + } + Some(((a.0 + t0 * dx, a.1 + t0 * dy), (a.0 + t1 * dx, a.1 + t1 * dy), t0 > 0.0, t1 < 1.0)) +} + +/// Clips a sampled polyline in plot fractions (`None` = gap) to the plot box (the unit +/// square), returning the visible runs. +fn clip_unit(pts: &[Option<(f64, f64)>]) -> Vec> { + const LIM: f64 = 1e9; + let ok = |p: &(f64, f64)| p.0.is_finite() && p.1.is_finite(); + let cl = |p: (f64, f64)| (p.0.clamp(-LIM, LIM), p.1.clamp(-LIM, LIM)); + let mut runs: Vec> = Vec::new(); + let mut run: Vec<(f64, f64)> = Vec::new(); + for w in pts.windows(2) { + let seg = match w { + [Some(a), Some(b)] if ok(a) && ok(b) => clip_segment(cl(*a), cl(*b)), + _ => None, + }; + match seg { + Some((p, q, cut_start, cut_end)) => { + if cut_start || run.is_empty() { + if run.len() >= 2 { + runs.push(std::mem::take(&mut run)); + } + run.clear(); + run.push(p); + } + run.push(q); + if cut_end { + runs.push(std::mem::take(&mut run)); + } + } + None => { + if run.len() >= 2 { + runs.push(std::mem::take(&mut run)); + } + run.clear(); + } + } + } + if run.len() >= 2 { + runs.push(run); + } + runs +} + +/// Draws `s`'s trendlines fitted to its plotted points `pts` (data x, y). `frac` maps data to +/// fractions of the plot box (0..1 inside, along the x and y axes), `px` fractions to pixels. +/// Equation and R² label lines are appended to `labels`. Degenerate fits draw nothing. +pub(super) fn draw_trendlines( + ctx: &mut Ctx, + s: &SeriesData, + pts: &[(f64, f64)], + frac: &dyn Fn(f64, f64) -> (f64, f64), + px: &dyn Fn((f64, f64)) -> [f32; 2], + labels: &mut Vec, + window: (f64, f64), +) { + let Some((xlo, xhi)) = value_range(pts.iter().map(|p| p.0)) else { return }; + for t in s.trendlines.iter().take(MAX_TRENDLINES) { + let spec = &t.spec; + let samples: Vec> = match spec.kind { + TrendlineKind::MovingAverage(p) => moving_average(pts, p).into_iter().map(|(x, y)| Some(frac(x, y))).collect(), + _ => { + let Some(fit) = fit_trendline(spec, pts) else { continue }; + // Sample only the part of the forecast that is on the plot. + let (lo, hi) = ((xlo - forecast(spec.backward)).max(window.0), (xhi + forecast(spec.forward)).min(window.1)); + if spec.display_equation { + labels.push(fit.equation()); + } + if spec.display_r_squared { + labels.push(fit.r_squared()); + } + (0..=TREND_STEPS) + .map(|i| { + let x = lo + (hi - lo) * i as f64 / TREND_STEPS as f64; + fit.eval(x).map(|y| frac(x, y)) + }) + .collect() + } + }; + let width = spec.width.filter(|w| w.is_finite()).unwrap_or(1.5).clamp(0.25, 12.0); + let dash = spec.dash != Some(LineDash::Solid); + for run in clip_unit(&samples) { + let line = decimate(run.into_iter().map(px).collect(), MAX_LINE_PTS); + if line.len() >= 2 { + ctx.out.push(Prim::Line { pts: line, color: t.color, width, dash }); + } + } + } +} + +/// Trendline equation / R² labels, stacked in the plot's top-right corner. +pub(super) fn draw_trend_labels(ctx: &mut Ctx, plot: Bx, labels: &[String]) { + let lh = LABEL_SIZE * 1.3; + for (i, t) in labels.iter().enumerate() { + let y = plot.y + 4.0 + i as f32 * lh; + if y + lh > plot.bottom() { + break; + } + let t = ctx.fit(t, LABEL_SIZE, plot.w - 8.0); + ctx.text(plot.right() - 4.0, y, &t, LABEL_SIZE, TEXT, (HAlign::Right, VAlign::Top)); + } +} diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index 6eee201ae1..de3cdef1b3 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -179,9 +179,10 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str) -> ( /// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on /// that sheet), the way the evaluator looks names up. fn is_defined_name(wb: &Workbook, sheet: usize, t: &str) -> bool { - match t.split_once('!') { - Some((s, bare)) => wb.sheet_index(s.trim_matches('\'')).is_some_and(|i| wb.name(bare, i).is_some()), - None => wb.name(t, sheet).is_some(), + // `'Bob''s'!Name`: the sheet is unquoted as everywhere else (#2012). + match gridcraft_core::split_sheet(t) { + (Some(s), bare) => wb.sheet_index(&s).is_some_and(|i| wb.name(bare, i).is_some()), + (None, _) => wb.name(t, sheet).is_some(), } } diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 3f1a068a23..6e423802cb 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -5,6 +5,8 @@ use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, Sparkl use crate::*; +mod data_table; + const ALL_KINDS: [ChartKind; 26] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, @@ -43,6 +45,7 @@ fn chart(kind: ChartKind) -> Chart { series: vec![], legend: LegendPos::Bottom, data_labels: true, + data_table: None, gridlines: true, style: 0, x_title: Some("Quarter".into()), @@ -1255,3 +1258,75 @@ fn box_whisker_draws_each_series_quartile_method() { // The boxes span 3.5 and 2.5 data units on the same value axis. assert!((heights[0] / heights[1] - 1.4).abs() < 0.001); } + +#[test] +fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() { + // #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series + // was named by the literal text. + let mut wb = Workbook::new(); + { + let s = wb.sheet_mut(0).unwrap(); + s.name = "Bob's".into(); + s.set_value(CellRef::new(0, 0), Value::from("Takings")); + s.set_value(CellRef::new(1, 0), Value::Number(4.0)); + s.set_value(CellRef::new(2, 0), Value::Number(9.0)); + } + wb.names.push(gridcraft_model::DefinedName { + name: "Title".into(), + scope: Some(0), + formula: "'Bob''s'!$A$1".into(), + comment: String::new(), + hidden: false, + }); + let mut c = chart(ChartKind::ColumnClustered); + c.series = vec![Series { + name: Some("'Bob''s'!Title".into()), + categories: None, + values: "'Bob''s'!$A$2:$A$3".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }]; + let d = resolve(&wb, 0, &c); + assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings")); +} + +#[test] +fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() { + // `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at + // the last one, not the first. + let mut wb = Workbook::new(); + { + let s = wb.sheet_mut(0).unwrap(); + s.name = "a!b".into(); + s.set_value(CellRef::new(0, 0), Value::from("Takings")); + s.set_value(CellRef::new(1, 0), Value::Number(4.0)); + s.set_value(CellRef::new(2, 0), Value::Number(9.0)); + } + wb.names.push(gridcraft_model::DefinedName { + name: "Title".into(), + scope: Some(0), + formula: "'a!b'!$A$1".into(), + comment: String::new(), + hidden: false, + }); + let mut c = chart(ChartKind::ColumnClustered); + c.series = vec![Series { + name: Some("'a!b'!Title".into()), + categories: None, + values: "'a!b'!$A$2:$A$3".into(), + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }]; + let d = resolve(&wb, 0, &c); + assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings")); +} diff --git a/crates/chart/src/tests/data_table.rs b/crates/chart/src/tests/data_table.rs new file mode 100644 index 0000000000..13e2baf6c9 --- /dev/null +++ b/crates/chart/src/tests/data_table.rs @@ -0,0 +1,121 @@ +use super::*; +use gridcraft_model::ChartDataTable; + +#[test] +fn tables_draw_source_values_for_every_supported_chart_kind() { + for kind in ALL_KINDS { + let mut c = chart(kind); + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let supported = c.supports_data_table(); + let d = sample(kind); + let prims = render(&c, &d, 900.0, 500.0, &ApproxMeasure); + assert_sane(&prims, 900.0, 500.0); + let labels = texts(&prims); + // Source amounts, including on 100% stacked charts, not shares or running totals. + if supported { + for value in ["$12,000", "-$4,000", "$38,000", "$61,870"] { + assert!(labels.contains(&value), "{kind:?}: missing {value}"); + } + } else { + c.data_table = None; + assert_eq!(prims, render(&c, &d, 900.0, 500.0, &ApproxMeasure)); + } + } +} + +#[test] +fn table_columns_align_with_plot_and_keep_missing_values_blank() { + let mut c = chart(ChartKind::ColumnClustered); + c.title = Some(String::new()); + c.x_title = None; + c.y_title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let color = [1, 2, 3, 255]; + let mut s = series("Rate", &[0.25, 0.0, 0.75], color, c.kind); + s.values[1] = None; + s.number_format = "0.0%".into(); + let d = ChartData { categories: ["Jan", "Feb", "Mar"].map(String::from).to_vec(), series: vec![s], ..Default::default() }; + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + let at = |text: &str| -> (f32, f32) { + p.iter() + .find_map(|p| match p { + Prim::Text { text: t, x, y, .. } if t == text => Some((*x, *y)), + _ => None, + }) + .unwrap() + }; + let (x1, y1) = at("25.0%"); + let (x3, y3) = at("75.0%"); + let header_y = at("Jan").1; + assert!(y1 > header_y && (y1 - y3).abs() < 0.01); + assert_eq!(at("Jan").0, x1); + assert_eq!(at("Mar").0, x3); + assert_eq!(texts(&p).iter().filter(|t| **t == "Jan").count(), 1, "the table replaces category-axis labels"); + let centers: Vec = p + .iter() + .filter_map(|p| match p { + Prim::Rect { x, y, w, fill: Some(f), .. } if *f == color && *y < header_y => Some(x + w / 2.0), + _ => None, + }) + .collect(); + assert_eq!(centers.len(), 2); + assert!((centers[0] - x1).abs() < 0.01 && (centers[1] - x3).abs() < 0.01); + let cells: Vec<&str> = p + .iter() + .filter_map(|p| match p { + Prim::Text { y, text, .. } if (*y - y1).abs() < 0.01 => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(cells, ["Rate", "25.0%", "75.0%"], "blank cells are not zeroes"); + assert!( + p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y)), + "legend key independent of hidden chart legend" + ); + c.data_table = Some(ChartDataTable { show_keys: false, ..Default::default() }); + let off = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + assert!(!off.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y))); +} + +#[test] +fn table_borders_are_independent_and_multilevel_headers_are_kept() { + let mut c = chart(ChartKind::Line); + c.legend = LegendPos::None; + c.data_labels = false; + let mut d = sample(c.kind); + d.category_levels = vec![vec!["2025".into(), "".into(), "".into(), "2026".into(), "".into(), "".into()]]; + for (h, v, outline, want) in [(false, false, false, 0), (true, false, false, 4), (false, true, false, 6), (false, false, true, 4)] { + c.data_table = Some(ChartDataTable { horizontal_border: h, vertical_border: v, outline, show_keys: false }); + let p = render(&c, &d, 900.0, 600.0, &ApproxMeasure); + let year_y = p + .iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == "2025" => Some(*y), + _ => None, + }) + .unwrap(); + assert!(texts(&p).contains(&"2026")); + let lines = p.iter().filter(|p| matches!(p, Prim::Line { pts, .. } if pts.iter().all(|p| p[1] > year_y - 9.0))).count(); + assert_eq!(lines, want, "{h} {v} {outline}"); + assert_sane(&p, 900.0, 600.0); + } +} + +#[test] +fn dense_and_tiny_tables_are_bounded_and_explicit() { + let mut c = chart(ChartKind::ColumnClustered); + c.data_table = Some(ChartDataTable::default()); + let mut d = sample(c.kind); + d.categories = (0..20_000).map(|i| i.to_string()).collect(); + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + assert!(texts(&p).contains(&"Data table needs more space")); + assert_sane(&p, 600.0, 400.0); + d.categories.clear(); + for (w, h) in [(1.0, 1.0), (10.0, 10.0), (40.0, 35.0), (200.0, 100.0)] { + assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h); + } +} diff --git a/crates/core/src/addr.rs b/crates/core/src/addr.rs index fd8ffec115..c8ddf74601 100644 --- a/crates/core/src/addr.rs +++ b/crates/core/src/addr.rs @@ -188,6 +188,12 @@ impl RangeRef { end: CellRef::new(self.end.row.max(o.end.row), self.end.col.max(o.end.col)), } } + /// The top-left cell of a list of areas: the lowest row and the lowest column across all of + /// them, whatever order they are listed in. Excel writes the relative formulas of a + /// multi-area validation or conditional format for this cell. `None` for no areas. + pub fn top_left(ranges: &[RangeRef]) -> Option { + ranges.iter().copied().reduce(|a, b| a.union(&b)).map(|r| r.start) + } /// Row-major iterator over the cells. Callers must bound huge ranges themselves. pub fn iter(&self) -> impl Iterator + '_ { let (r0, r1, c0, c1) = (self.start.row, self.end.row, self.start.col, self.end.col); @@ -295,15 +301,26 @@ mod tests { use super::*; #[test] - fn range_parse_rejects_signed_rows() { + fn range_parse_rejects_signed_rows() -> Result<(), std::io::Error> { assert!(RangeRef::parse("+1:+3").is_none()); assert!(RangeRef::parse("-1:3").is_none()); assert!(RangeRef::parse("$$1:3").is_none()); assert!(RangeRef::parse(":3").is_none()); assert!(RangeRef::parse("$$A:$$C").is_none()); assert!(RangeRef::parse("$A:$C").is_some()); - let r = RangeRef::parse("$1:$3").unwrap(); + let r = RangeRef::parse("$1:$3").ok_or_else(|| std::io::Error::other("valid row range"))?; assert_eq!((r.start.row, r.end.row), (0, 2)); + Ok(()) + } + + #[test] + fn top_left_spans_every_area_in_any_order() { + let areas: Vec = ["H62:H68", "H26:H27", "H93:H95"].iter().filter_map(|a| RangeRef::parse(a)).collect(); + assert_eq!(RangeRef::top_left(&areas), CellRef::parse("H26")); + // Lowest row and lowest column, even when they come from different areas. + let areas: Vec = ["C5:D6", "E2", "B9"].iter().filter_map(|a| RangeRef::parse(a)).collect(); + assert_eq!(RangeRef::top_left(&areas), CellRef::parse("B2")); + assert_eq!(RangeRef::top_left(&[]), None); } #[test] @@ -389,18 +406,20 @@ mod tests { } #[test] - fn ranges() { - let r = RangeRef::parse("C3:A1").unwrap(); + fn ranges() -> Result<(), std::io::Error> { + let parse = |s| RangeRef::parse(s).ok_or_else(|| std::io::Error::other("valid range")); + let r = parse("C3:A1")?; assert_eq!(r.a1(), "A1:C3"); assert_eq!(r.count(), 9); - assert_eq!(RangeRef::parse("A:C").unwrap().a1(), "A:C"); - assert_eq!(RangeRef::parse("3:5").unwrap().a1(), "3:5"); + assert_eq!(parse("A:C")?.a1(), "A:C"); + assert_eq!(parse("3:5")?.a1(), "3:5"); assert!(RangeRef::parse("0:5").is_none()); - let a = RangeRef::parse("A1:C3").unwrap(); - let b = RangeRef::parse("B2:D4").unwrap(); - assert_eq!(a.intersection(&b).unwrap().a1(), "B2:C3"); + let a = parse("A1:C3")?; + let b = parse("B2:D4")?; + assert_eq!(a.intersection(&b).ok_or_else(|| std::io::Error::other("overlap expected"))?.a1(), "B2:C3"); assert_eq!(a.union(&b).a1(), "A1:D4"); assert_eq!(a.iter().count(), 9); + Ok(()) } #[test] @@ -458,18 +477,19 @@ mod category_level_tests { use super::*; #[test] - fn a_wide_range_beside_a_column_of_values_is_a_multi_level_axis() { - let r = |s: &str| RangeRef::parse(s).unwrap(); - assert_eq!(category_levels(&r("A4:B39"), Some(&r("C4:C39"))), Some(CategoryLevels { by_columns: true, outer: 1 })); - assert_eq!(category_levels(&r("A4:D39"), Some(&r("C4:C39"))), Some(CategoryLevels { by_columns: true, outer: 3 })); - assert_eq!(category_levels(&r("A4:F39"), Some(&r("C4:C39"))).map(|l| l.outer), Some(3), "capped"); - assert_eq!(category_levels(&r("A4:A39"), Some(&r("C4:C39"))), None, "one column: a plain list"); + fn a_wide_range_beside_a_column_of_values_is_a_multi_level_axis() -> Result<(), std::io::Error> { + let r = |s| RangeRef::parse(s).ok_or_else(|| std::io::Error::other("valid test range")); + assert_eq!(category_levels(&r("A4:B39")?, Some(&r("C4:C39")?)), Some(CategoryLevels { by_columns: true, outer: 1 })); + assert_eq!(category_levels(&r("A4:D39")?, Some(&r("C4:C39")?)), Some(CategoryLevels { by_columns: true, outer: 3 })); + assert_eq!(category_levels(&r("A4:F39")?, Some(&r("C4:C39")?)).map(|l| l.outer), Some(3), "capped"); + assert_eq!(category_levels(&r("A4:A39")?, Some(&r("C4:C39")?)), None, "one column: a plain list"); // A row of values: levels are rows. - assert_eq!(category_levels(&r("B2:M3"), Some(&r("B4:M4"))), Some(CategoryLevels { by_columns: false, outer: 1 })); - assert_eq!(category_levels(&r("B3:M3"), Some(&r("B4:M4"))), None); + assert_eq!(category_levels(&r("B2:M3")?, Some(&r("B4:M4")?)), Some(CategoryLevels { by_columns: false, outer: 1 })); + assert_eq!(category_levels(&r("B3:M3")?, Some(&r("B4:M4")?)), None); // Literal values: the categories' own shape decides. - assert_eq!(category_levels(&r("A1:B6"), None), Some(CategoryLevels { by_columns: true, outer: 1 })); - assert_eq!(category_levels(&r("A1:F2"), None), Some(CategoryLevels { by_columns: false, outer: 1 })); - assert_eq!(category_levels(&r("A:B"), Some(&r("C:C"))), None, "whole columns"); + assert_eq!(category_levels(&r("A1:B6")?, None), Some(CategoryLevels { by_columns: true, outer: 1 })); + assert_eq!(category_levels(&r("A1:F2")?, None), Some(CategoryLevels { by_columns: false, outer: 1 })); + assert_eq!(category_levels(&r("A:B")?, Some(&r("C:C")?)), None, "whole columns"); + Ok(()) } } diff --git a/crates/core/src/date.rs b/crates/core/src/date.rs index 8e68695f1a..606d3dacf3 100644 --- a/crates/core/src/date.rs +++ b/crates/core/src/date.rs @@ -47,13 +47,11 @@ pub fn days_from_civil(y: i32, m: u32, d: u32) -> i64 { } /// Milliseconds since the Unix epoch (UTC) from the system clock; `None` when the clock is unavailable. -/// On wasm32 `std::time::SystemTime::now` traps, so the browser clock is read through `Date.now()`. -#[allow(clippy::disallowed_methods)] // the std clock is read only off wasm +/// Chrono uses the browser clock on wasm32, where the standard library clock methods trap. pub fn unix_now_ms() -> Option { #[cfg(not(target_arch = "wasm32"))] { - let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?; - Some(d.as_secs_f64() * 1000.0) + Some(chrono::Utc::now().timestamp_millis() as f64) } #[cfg(target_arch = "wasm32")] { @@ -323,7 +321,7 @@ mod tests { } #[test] - fn fictitious_1900_02_29() { + fn fictitious_1900_02_29() -> Result<(), std::io::Error> { // Excel's 1900 calendar has a 29 February 1900 (serial 60); day and month overflow count // through it. let s = DateSystem::D1900; @@ -345,7 +343,7 @@ mod tests { assert_eq!(serial_from_ymd(s, 1904, 2, 29), Some(1521.0)); // Every serial up to 1900-12-31 comes back from its own year, month and day. for serial in 0..=366 { - let d = datetime_from_serial(s, serial as f64).unwrap(); + let d = datetime_from_serial(s, serial as f64).ok_or_else(|| std::io::Error::other("serial should convert"))?; assert_eq!(serial_from_ymd(s, d.year as i64, d.month as i64, d.day as i64), Some(serial as f64), "{d:?}"); } assert_eq!(days_in_month_in(s, 1900, 2), 29); @@ -358,6 +356,7 @@ mod tests { assert_eq!(serial_from_ymd(s, 1904, 3, 1), Some(60.0)); assert_eq!(serial_from_ymd(s, 1904, 1, 0), None); assert_eq!(serial_from_ymd(s, 1900, 2, 29), None); + Ok(()) } #[test] @@ -371,17 +370,18 @@ mod tests { } #[test] - fn roundtrip() { + fn roundtrip() -> Result<(), std::io::Error> { let s = DateSystem::D1900; for serial in [1.0, 59.0, 60.0, 61.0, 36526.0, 46302.0, 2958465.0] { - let d = datetime_from_serial(s, serial).unwrap(); + let d = datetime_from_serial(s, serial).ok_or_else(|| std::io::Error::other("serial should convert"))?; assert_eq!(serial_from_ymd(s, d.year as i64, d.month as i64, d.day as i64), Some(serial)); } - let d = datetime_from_serial(s, 60.0).unwrap(); + let d = datetime_from_serial(s, 60.0).ok_or_else(|| std::io::Error::other("leap-day serial should convert"))?; assert_eq!((d.year, d.month, d.day), (1900, 2, 29)); - let d = datetime_from_serial(s, 46302.75).unwrap(); + let d = datetime_from_serial(s, 46302.75).ok_or_else(|| std::io::Error::other("time serial should convert"))?; assert_eq!((d.hour, d.minute, d.weekday), (18, 0, 3)); // 2026-10-07 is a Wednesday - let d = datetime_from_serial(s, 1.0).unwrap(); + let d = datetime_from_serial(s, 1.0).ok_or_else(|| std::io::Error::other("first serial should convert"))?; assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar + Ok(()) } } diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index c531de4dc1..0000028e93 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -21,10 +21,18 @@ pub enum CellError { Calc, /// Circular reference that could not be resolved (shown as 0 by Excel; we keep it explicit). Circ, + /// A Python cell's code raised an error, or Python stopped. + Python, + /// A Python cell is waiting to run. + Busy, + /// A Python cell ran longer than the time limit. + Timeout, + /// Python can't run here: the workbook's content isn't enabled, or this build has no Python. + Blocked, } impl CellError { - pub const ALL: [CellError; 10] = [ + pub const ALL: [CellError; 14] = [ CellError::Null, CellError::Div0, CellError::Value, @@ -35,6 +43,10 @@ impl CellError { CellError::GettingData, CellError::Spill, CellError::Calc, + CellError::Python, + CellError::Busy, + CellError::Timeout, + CellError::Blocked, ]; pub fn as_str(&self) -> &'static str { match self { @@ -49,9 +61,16 @@ impl CellError { CellError::Spill => "#SPILL!", CellError::Calc => "#CALC!", CellError::Circ => "#CIRC!", + CellError::Python => "#PYTHON!", + CellError::Busy => "#BUSY!", + CellError::Timeout => "#TIMEOUT!", + CellError::Blocked => "#BLOCKED!", } } - /// `ERROR.TYPE` number. + /// `ERROR.TYPE` number. Microsoft documents 1 to 8; 9 (#SPILL!), 11 (#BLOCKED!) and 14 (#CALC!) + /// are the numbers Excel returns. Microsoft documents no number for #PYTHON!, #BUSY! or + /// #TIMEOUT!: 19, 20 and 21 are GridCraft's own choice, after the numbers Excel is known to use, + /// and may change if Excel's numbers become known. pub fn code(&self) -> u32 { match self { CellError::Null => 1, @@ -65,6 +84,10 @@ impl CellError { CellError::Spill => 9, CellError::Calc => 14, CellError::Circ => 15, + CellError::Blocked => 11, + CellError::Python => 19, + CellError::Busy => 20, + CellError::Timeout => 21, } } pub fn parse(s: &str) -> Option { @@ -454,11 +477,12 @@ mod tests { } #[test] - fn arrays() { - let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).unwrap(); + 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"))?; assert_eq!(a.transpose().get(0, 1), Some(&Value::Number(3.0))); assert!(Array::new(2, 2, vec![]).is_none()); let row = Array::row(vec![1.0.into(), 2.0.into()]); assert_eq!(row.get_broadcast(5, 1), Value::Number(2.0)); + Ok(()) } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index e8ea91c26d..341d1b35c0 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,11 +17,13 @@ gridcraft-model = { workspace = true } gridcraft-calc = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +web-time = { workspace = true } thiserror = { workspace = true } log = { workspace = true } gridcraft-xlsx = { workspace = true } gridcraft-chart = { workspace = true } gridcraft-pdf = { workspace = true } +gridcraft-math = { workspace = true } image = { workspace = true } [dev-dependencies] diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 007cbf4bc0..45455e00b5 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -269,6 +269,7 @@ pub const CATALOG: &[(&str, &str, &str, &str)] = &[ ("view.unhideWindow", "View", "Window", "Unhide"), ("view.switchWindows", "View", "Window", "Switch Windows"), ("view.macros", "View", "Macros", "Macros"), + ("macro.record", "View", "Macros", "Record Macro"), // Automate ("automate.newScript", "Automate", "Scripting Tools", "New Script"), ("automate.allScripts", "Automate", "Scripting Tools", "All Scripts"), diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index 0c0f9683ea..38f5bb1fe8 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -136,6 +136,95 @@ fn lerp(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { pub use gridcraft_model::icon_count; +struct RuleEval<'a> { + wb: &'a Workbook, + sheet: usize, + cell: CellRef, + first: CellRef, + value: &'a Value, + text: &'a str, + stats: &'a RuleStats, +} + +fn simple_rule_style<'a>(ctx: &RuleEval<'_>, rule: &'a CfRule) -> Option<&'a Style> { + let RuleEval { wb, sheet, cell, first, value, text, stats } = ctx; + match rule { + CfRule::CellIs { op, a, b, style } => { + let eval = |f: &str| gridcraft_calc::evaluate(wb, *sheet, *cell, &relative(f, *first, *cell)); + let av = eval(a); + let matches = match op { + CfOperator::Between | CfOperator::NotBetween => { + let bv = b.as_deref().map(eval).unwrap_or_default(); + let (lo, hi) = if compare(&av, &bv) == std::cmp::Ordering::Greater { (bv, av) } else { (av, bv) }; + let within = compare(value, &lo) != std::cmp::Ordering::Less && compare(value, &hi) != std::cmp::Ordering::Greater; + if *op == CfOperator::Between { within } else { !within } + } + CfOperator::Equal => compare(value, &av) == std::cmp::Ordering::Equal, + CfOperator::NotEqual => compare(value, &av) != std::cmp::Ordering::Equal, + CfOperator::Greater => compare(value, &av) == std::cmp::Ordering::Greater, + CfOperator::Less => compare(value, &av) == std::cmp::Ordering::Less, + CfOperator::GreaterOrEqual => compare(value, &av) != std::cmp::Ordering::Less, + CfOperator::LessOrEqual => compare(value, &av) != std::cmp::Ordering::Greater, + }; + (matches && !value.is_error()).then_some(style.as_ref()) + } + CfRule::Expression { formula, style } => { + gridcraft_calc::evaluate(wb, *sheet, *cell, &relative(formula, *first, *cell)).to_bool().unwrap_or(false).then_some(style.as_ref()) + } + CfRule::ContainsText { text: needle, style } => { + (!value.is_error() && text.to_lowercase().contains(&needle.to_lowercase())).then_some(style.as_ref()) + } + CfRule::NotContainsText { text: needle, style } => { + (value.is_error() || !text.to_lowercase().contains(&needle.to_lowercase())).then_some(style.as_ref()) + } + CfRule::BeginsWith { text: needle, style } => { + (!value.is_error() && text.to_lowercase().starts_with(&needle.to_lowercase())).then_some(style.as_ref()) + } + CfRule::EndsWith { text: needle, style } => { + (!value.is_error() && text.to_lowercase().ends_with(&needle.to_lowercase())).then_some(style.as_ref()) + } + CfRule::Blanks { style } => (value.is_empty() || text.trim().is_empty()).then_some(style.as_ref()), + CfRule::NoBlanks { style } => (!value.is_empty() && !text.trim().is_empty()).then_some(style.as_ref()), + CfRule::Errors { style } => value.is_error().then_some(style.as_ref()), + CfRule::NoErrors { style } => (!value.is_error()).then_some(style.as_ref()), + CfRule::Duplicate { style } => { + (!value.is_empty() && stats.counts.get(&text.to_lowercase()).copied().unwrap_or(0) > 1).then_some(style.as_ref()) + } + CfRule::Unique { style } => { + (!value.is_empty() && stats.counts.get(&text.to_lowercase()).copied().unwrap_or(0) == 1).then_some(style.as_ref()) + } + _ => None, + } +} + +fn time_period_matches(wb: &Workbook, period: &str, serial: f64) -> bool { + let today = gridcraft_core::date::serial_in_system(wb.date_system, gridcraft_calc::now_serial()).floor(); + let day = serial.floor(); + let date = |serial| gridcraft_core::date::datetime_from_serial(wb.date_system, serial); + let week_start = today - date(today).map(|value| value.weekday as f64).unwrap_or(0.0); + let (year, month) = date(today).map(|value| (value.year, value.month)).unwrap_or((2026, 1)); + let year_month = date(day).map(|value| (value.year, value.month)); + let month_matches = |offset: i32| { + let shifted_month = month as i32 + offset; + let shifted_year = year + (shifted_month - 1).div_euclid(12); + let shifted_month = (shifted_month - 1).rem_euclid(12) + 1; + year_month == Some((shifted_year, shifted_month as u32)) + }; + match period { + "yesterday" => day == today - 1.0, + "today" => day == today, + "tomorrow" => day == today + 1.0, + "last7Days" => day > today - 7.0 && day <= today, + "lastWeek" => day >= week_start - 7.0 && day < week_start, + "thisWeek" => day >= week_start && day < week_start + 7.0, + "nextWeek" => day >= week_start + 7.0 && day < week_start + 14.0, + "lastMonth" => month_matches(-1), + "thisMonth" => month_matches(0), + "nextMonth" => month_matches(1), + _ => false, + } +} + impl CfCache { pub fn new() -> Self { Self::default() @@ -155,58 +244,14 @@ impl CfCache { let v = sh.value(c); let no_stats = RuleStats::default(); for (idx, cf) in rules { - let first = cf.ranges.first().map(|r| r.start).unwrap_or(c); + let first = RangeRef::top_left(&cf.ranges).unwrap_or(c); let st: &RuleStats = match stats_need(&cf.rule) { Some(need) => &*self.stats.entry(idx).or_insert_with(|| RuleStats::build(sh, &cf.ranges, need)), None => &no_stats, }; let text = v.display(); - let matched_style: Option<&Style> = match &cf.rule { - CfRule::CellIs { op, a, b, style } => { - let eval = |f: &str| gridcraft_calc::evaluate(wb, sheet, c, &relative(f, first, c)); - let av = eval(a); - let ok = match op { - CfOperator::Between | CfOperator::NotBetween => { - let bv = b.as_deref().map(eval).unwrap_or_default(); - let (lo, hi) = if compare(&av, &bv) == std::cmp::Ordering::Greater { (bv, av) } else { (av, bv) }; - let inside = compare(&v, &lo) != std::cmp::Ordering::Less && compare(&v, &hi) != std::cmp::Ordering::Greater; - if *op == CfOperator::Between { inside } else { !inside } - } - CfOperator::Equal => compare(&v, &av) == std::cmp::Ordering::Equal, - CfOperator::NotEqual => compare(&v, &av) != std::cmp::Ordering::Equal, - CfOperator::Greater => compare(&v, &av) == std::cmp::Ordering::Greater, - CfOperator::Less => compare(&v, &av) == std::cmp::Ordering::Less, - CfOperator::GreaterOrEqual => compare(&v, &av) != std::cmp::Ordering::Less, - CfOperator::LessOrEqual => compare(&v, &av) != std::cmp::Ordering::Greater, - }; - // As in Excel, a blank cell compares as 0 (or ""), and an error never matches. - (ok && !v.is_error()).then_some(style.as_ref()) - } - CfRule::Expression { formula, style } => { - gridcraft_calc::evaluate(wb, sheet, c, &relative(formula, first, c)).to_bool().unwrap_or(false).then_some(style.as_ref()) - } - // As in Excel, an error value never contains, begins or ends with anything (its rule - // formulas SEARCH/LEFT/RIGHT fail on it), so it always "does not contain" (#1162). - CfRule::ContainsText { text: t, style } => { - (!v.is_error() && text.to_lowercase().contains(&t.to_lowercase())).then_some(style.as_ref()) - } - CfRule::NotContainsText { text: t, style } => { - (v.is_error() || !text.to_lowercase().contains(&t.to_lowercase())).then_some(style.as_ref()) - } - CfRule::BeginsWith { text: t, style } => { - (!v.is_error() && text.to_lowercase().starts_with(&t.to_lowercase())).then_some(style.as_ref()) - } - CfRule::EndsWith { text: t, style } => (!v.is_error() && text.to_lowercase().ends_with(&t.to_lowercase())).then_some(style.as_ref()), - CfRule::Blanks { style } => (v.is_empty() || text.trim().is_empty()).then_some(style.as_ref()), - CfRule::NoBlanks { style } => (!v.is_empty() && !text.trim().is_empty()).then_some(style.as_ref()), - CfRule::Errors { style } => v.is_error().then_some(style.as_ref()), - CfRule::NoErrors { style } => (!v.is_error()).then_some(style.as_ref()), - CfRule::Duplicate { style } => { - (!v.is_empty() && st.counts.get(&text.to_lowercase()).copied().unwrap_or(0) > 1).then_some(style.as_ref()) - } - CfRule::Unique { style } => { - (!v.is_empty() && st.counts.get(&text.to_lowercase()).copied().unwrap_or(0) == 1).then_some(style.as_ref()) - } + let context = RuleEval { wb, sheet, cell: c, first, value: &v, text: &text, stats: st }; + let matched_style = simple_rule_style(&context, &cf.rule).or_else(|| match &cf.rule { CfRule::Top10 { bottom, percent, rank, style } => match v.as_f64() { Some(n) if !st.sorted.is_empty() => { let k = if *percent { ((st.sorted.len() as f64) * (*rank as f64) / 100.0).floor().max(1.0) as usize } else { *rank as usize }; @@ -229,36 +274,8 @@ impl CfCache { None => None, }, CfRule::TimePeriod { period, style } => match v.as_f64() { - Some(n) => { - let today = gridcraft_core::date::serial_in_system(wb.date_system, gridcraft_calc::now_serial()).floor(); - let d = n.floor(); - let wd = gridcraft_core::date::datetime_from_serial(wb.date_system, today).map(|x| x.weekday as f64).unwrap_or(0.0); - let week_start = today - wd; - let (ty, tm) = - gridcraft_core::date::datetime_from_serial(wb.date_system, today).map(|x| (x.year, x.month)).unwrap_or((2026, 1)); - let ym = gridcraft_core::date::datetime_from_serial(wb.date_system, d).map(|x| (x.year, x.month)); - let month_off = |k: i32| { - let m = tm as i32 + k; - let y = ty + (m - 1).div_euclid(12); - let m = (m - 1).rem_euclid(12) + 1; - ym == Some((y, m as u32)) - }; - let ok = match period.as_str() { - "yesterday" => d == today - 1.0, - "today" => d == today, - "tomorrow" => d == today + 1.0, - "last7Days" => d > today - 7.0 && d <= today, - "lastWeek" => d >= week_start - 7.0 && d < week_start, - "thisWeek" => d >= week_start && d < week_start + 7.0, - "nextWeek" => d >= week_start + 7.0 && d < week_start + 14.0, - "lastMonth" => month_off(-1), - "thisMonth" => month_off(0), - "nextMonth" => month_off(1), - _ => false, - }; - ok.then_some(style.as_ref()) - } - None => None, + Some(n) if time_period_matches(wb, period, n) => Some(style.as_ref()), + _ => None, }, CfRule::ColorScale { stops } => { if let Some(n) = v.as_f64() { @@ -329,7 +346,8 @@ impl CfCache { } None } - }; + _ => None, + }); if let Some(st) = matched_style { any = true; // Every matching rule applies; where two set the same part, the rule with the diff --git a/crates/engine/src/clip_html.rs b/crates/engine/src/clip_html.rs index e1d217c9ca..fa9822390e 100644 --- a/crates/engine/src/clip_html.rs +++ b/crates/engine/src/clip_html.rs @@ -17,11 +17,13 @@ const MAX_ROW_SPAN: usize = gridcraft_core::MAX_ROWS as usize; /// table is ignored: the HTML only refines cells of the tab-separated text, which stays the source. const MAX_HTML_CELLS: usize = 1_000_000; -/// One table cell: its visible text and the number the source recorded for it, if any. +/// One table cell: its visible text, the number the source recorded for it, if any, and whether +/// it is a header cell (``). #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct HtmlCell { pub text: String, pub num: Option, + pub header: bool, } /// The cells of the first table in `html`, row by row, read no further than `max_rows` rows of @@ -88,7 +90,7 @@ pub(crate) fn table_cells(html: &str, max_rows: usize, max_cols: usize) -> Vec().ok()).filter(|n| n.is_finite()); let colspan = span(attrs, "colspan", MAX_SPAN); let rowspan = span(attrs, "rowspan", MAX_ROW_SPAN); - cell = Some(OpenCell { cell: HtmlCell { text: String::new(), num }, colspan, rowspan }); + cell = Some(OpenCell { cell: HtmlCell { text: String::new(), num, header: name == "th" }, colspan, rowspan }); } ("td" | "th", true) | ("tr", true) => grid.finish(&mut cell), ("br", _) => { @@ -376,18 +378,18 @@ mod tests {
2.50 & upx
"#; let rows = table_cells(excel, 2, 3); assert_eq!(rows.len(), 2); - assert_eq!(rows[0][0], HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) }); - assert_eq!(rows[0][1], HtmlCell { text: "Name".into(), num: None }); + assert_eq!(rows[0][0], HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0), ..HtmlCell::default() }); + assert_eq!(rows[0][1], HtmlCell { text: "Name".into(), num: None, ..HtmlCell::default() }); assert_eq!(rows[1].len(), 3, "colspan keeps the next cell in its column"); assert_eq!(rows[1][0].text, "2.50 & up"); assert_eq!(rows[1][2].text, "x"); let calc = r#"
Rp10,000.00
"#; - assert_eq!(table_cells(calc, 1, 1), vec![vec![HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) }]]); + assert_eq!(table_cells(calc, 1, 1), vec![vec![HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0), ..HtmlCell::default() }]]); let quoted_gt = r#"
1500
"#; - assert_eq!(table_cells(quoted_gt, 1, 1), vec![vec![HtmlCell { text: "1500".into(), num: Some(1500.0) }]]); + assert_eq!(table_cells(quoted_gt, 1, 1), vec![vec![HtmlCell { text: "1500".into(), num: Some(1500.0), ..HtmlCell::default() }]]); } #[test] @@ -434,7 +436,7 @@ mod tests { assert!(cells <= MAX_HTML_CELLS, "{cells} cells"); assert!(rows.iter().all(|r| r.len() <= MAX_SPAN)); assert_eq!(rows[0].len(), MAX_SPAN, "the first span fills the sheet's width"); - assert_eq!(rows[0][0], HtmlCell { text: "1".into(), num: Some(1.0) }); + assert_eq!(rows[0][0], HtmlCell { text: "1".into(), num: Some(1.0), ..HtmlCell::default() }); // Bounded by the pasted text's shape, the same markup yields just that shape. let rows = table_cells(&html, 3, 2); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd.rs similarity index 83% rename from crates/engine/src/cmd/mod.rs rename to crates/engine/src/cmd.rs index ef6714eea2..1148a6b6ee 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd.rs @@ -5,6 +5,7 @@ pub mod analysis; pub mod data; pub mod draw; pub mod edit; +pub mod equation; pub mod extra; pub mod file; pub mod forecast; @@ -12,8 +13,10 @@ pub mod format; pub mod formulas; pub mod insert; pub mod inspect; +pub mod macros; pub mod pivot; pub mod print; +pub mod python; pub mod review; pub mod sheet; pub mod slicer; @@ -39,7 +42,11 @@ pub struct CommandSpec { pub label: &'static str, /// Ribbon/menu placement, e.g. `["Home", "Font"]`. Empty = not in menus. pub menu: &'static [&'static str], + /// Portable notation: `Cmd` is ⌘ on macOS and Ctrl elsewhere. pub shortcut: Option<&'static str>, + /// macOS override when its key differs. Equal to `shortcut` marks a Mac-only shortcut + /// (Align Left/Center): other platforms show none. See [`CommandInfo::shortcut_for_platform`]. + pub shortcut_mac: Option<&'static str>, pub params: &'static str, pub enabled: Enabled, pub run: Run, @@ -53,12 +60,32 @@ pub struct CommandInfo { pub label: &'static str, pub menu: Vec<&'static str>, pub shortcut: Option<&'static str>, + pub shortcut_mac: Option<&'static str>, pub params: &'static str, pub enabled: bool, #[serde(skip_serializing_if = "Option::is_none")] pub disabled_reason: Option, } +impl CommandInfo { + /// Format the portable shortcut notation for the runtime operating system. + pub fn shortcut_for_platform(&self, mac: bool) -> Option { + let keys = if mac { + self.shortcut_mac.or(self.shortcut) + } else if self.shortcut_mac.is_some() && self.shortcut_mac == self.shortcut { + // An identical Mac override marks a Mac-only display shortcut. + // The portable field remains unchanged for legacy CLI consumers. + None + } else { + self.shortcut + }?; + if mac { + return Some(keys.to_owned()); + } + Some(keys.split('+').map(|part| if part == "Cmd" { "Ctrl" } else { part }).collect::>().join("+")) + } +} + impl CommandSpec { pub fn info(&self, s: &Session) -> CommandInfo { let e = (self.enabled)(s); @@ -67,6 +94,7 @@ impl CommandSpec { label: self.label, menu: self.menu.to_vec(), shortcut: self.shortcut, + shortcut_mac: self.shortcut_mac, params: self.params, enabled: e.is_ok(), disabled_reason: e.err(), @@ -117,13 +145,13 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> { macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: true, undoable: true } }; (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: false, undoable: false } }; (noundo $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: true, undoable: false } }; } pub(crate) use cmd; @@ -137,16 +165,19 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(format::specs()); v.extend(sheet::specs()); v.extend(insert::specs()); + v.extend(equation::specs()); v.extend(data::specs()); v.extend(formulas::specs()); v.extend(review::specs()); v.extend(view::specs()); v.extend(inspect::specs()); v.extend(extra::specs()); + v.extend(macros::specs()); v.extend(draw::specs()); v.extend(spelling::specs()); v.extend(solver::specs()); v.extend(pivot::specs()); + v.extend(python::specs()); v.extend(slicer::specs()); v.extend(whatif::specs()); v.extend(forecast::specs()); @@ -178,6 +209,7 @@ pub fn register_test_command(id: &'static str, run: Run) { label: id, menu: &[], shortcut: None, + shortcut_mac: None, params: "", enabled: |_| Ok(()), run, @@ -195,6 +227,7 @@ pub(crate) fn register_undoable_test_command(id: &'static str, run: Run) { label: id, menu: &[], shortcut: None, + shortcut_mac: None, params: "", enabled: |_| Ok(()), run, @@ -205,7 +238,6 @@ pub(crate) fn register_undoable_test_command(id: &'static str, run: Run) { } fn test_commands() -> std::sync::MutexGuard<'static, Vec<&'static CommandSpec>> { - #[allow(clippy::unwrap_used)] // a poisoned test registry has no meaningful recovery match TEST_COMMANDS.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), @@ -338,6 +370,9 @@ pub struct Ctx<'a> { /// The command applied sheet protection itself (row/column inserts and deletes the /// protection allows), so cells it shifts aren't refused as edits of locked cells. pub protection_checked: bool, + /// The structural edits the command made, in order (the sheet's name, the edit), as + /// references were rewritten for them. + pub edits: Vec<(String, gridcraft_formula::adjust::Edit)>, } pub(crate) fn edit(s: &mut Session, f: impl FnOnce(&mut Ctx) -> Result) -> Result { @@ -349,26 +384,51 @@ pub(crate) fn edit(s: &mut Session, f: impl FnOnce(&mut Ctx) -> Result) -> }) } +fn wall_clock() -> std::time::Duration { + std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap_or_default() +} + pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) -> Result { - // `GRIDCRAFT_PROFILE` timing. Read the clock only when profiling, and never on wasm: there - // `Instant::now` traps (`RuntimeError: unreachable`), which broke every edit in the web app. - #[allow(clippy::disallowed_methods)] - let t0 = if cfg!(target_arch = "wasm32") { None } else { std::env::var_os("GRIDCRAFT_PROFILE").map(|_| std::time::Instant::now()) }; + // `GRIDCRAFT_PROFILE` timing, never on wasm where the clock traps. `elapsed` on the epoch + // reads the wall clock without the (disallowed) `now`. + let t0 = if cfg!(target_arch = "wasm32") { None } else { std::env::var_os("GRIDCRAFT_PROFILE").map(|_| wall_clock()) }; + let since = |t0: std::time::Duration| wall_clock().saturating_sub(t0); let mut sel = d.selection.clone(); - let mut ctx = Ctx { wb: (*d.wb).clone(), changed: Vec::new(), structural: false, sel: &mut sel, fit_rows: Vec::new(), protection_checked: false }; + let mut ctx = Ctx { + wb: (*d.wb).clone(), + changed: Vec::new(), + structural: false, + sel: &mut sel, + fit_rows: Vec::new(), + protection_checked: false, + edits: Vec::new(), + }; let r = f(&mut ctx)?; - let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, .. } = ctx; + let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, edits, .. } = ctx; + // Equations whose source changed (or that arrived without a layout, as from a paste) are + // laid out here, so painting only ever reads the cache. + wb.refresh_equations(); if !protection_checked { check_protection(&d.wb, &wb, &d.unlocked_ranges)?; } if !structural { check_arrays(&d.wb, &wb)?; } + if let Some(log) = d.touched.as_mut() { + for (si, c) in changed.iter().take(TOUCH_LOG_LIMIT.saturating_sub(log.len())) { + if let Some(sh) = wb.sheet(*si) { + log.push((sh.name.clone(), *c)); + } + } + } + if let Some(log) = d.edits.as_mut() { + log.extend(edits); + } if changed.len() <= 200_000 { fit_rows.extend(changed.iter().map(|(s, c)| (*s, c.row))); } if let Some(t0) = t0 { - eprintln!("commit: edit {:?}, {} changed", t0.elapsed(), changed.len()); + eprintln!("commit: edit {:?}, {} changed", since(t0), changed.len()); } if structural { d.calc.recalc_all(&mut wb); @@ -376,7 +436,7 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) d.calc.cells_changed(&mut wb, &changed); } if let Some(t0) = t0 { - eprintln!("commit: + recalc {:?}", t0.elapsed()); + eprintln!("commit: + recalc {:?}", since(t0)); } fit_rows.sort_unstable(); fit_rows.dedup(); @@ -384,19 +444,26 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) auto_row_height(&mut wb, si, row); } if let Some(t0) = t0 { - eprintln!("commit: + rows {:?}", t0.elapsed()); + eprintln!("commit: + rows {:?}", since(t0)); } d.wb = std::sync::Arc::new(wb); d.selection = sel; Ok(r) } +/// The most cells a dry run's touch log keeps; a footprint whose log is full may be missing writes +/// that kept a cell's value, so a shift is refused then. +pub(crate) const TOUCH_LOG_LIMIT: usize = 1_000_000; + /// Excel's message for an edit of a locked cell on a protected sheet. pub(crate) const PROTECTED: &str = "The cell or chart you're trying to change is on a protected sheet."; /// Refuses an edit that changed what a locked cell on a protected sheet holds (its value or -/// formula), whichever command made it. Sheets are matched by name, so moving, renaming or -/// deleting a sheet isn't an edit of its cells. +/// formula), or that unlocked it, whichever command made it. Sheets are matched by name, so +/// moving, renaming or deleting a sheet isn't an edit of its cells. A sort or duplicate removal +/// that moves an unlocked cell with equal content onto a locked one changes no content but would +/// leave the cell editable, so the effective lock (row and column formats included) is compared +/// as well. fn check_protection(old: &Workbook, new: &Workbook, unlocked: &[(String, String)]) -> Result<()> { for sh in &old.sheets { if !sh.is_protected() { @@ -407,7 +474,8 @@ fn check_protection(old: &Workbook, new: &Workbook, unlocked: &[(String, String) continue; } for c in sh.cells.diff(&after.cells) { - if !same_content(sh.cell(c), after.cell(c)) + let unlocked_now = !new.styles.get(after.style_id(c)).protection.locked; + if (unlocked_now || !same_content(sh.cell(c), after.cell(c))) && old.styles.get(sh.style_id(c)).protection.locked && let Some(m) = locked_cell_error(sh, c, unlocked) { @@ -460,7 +528,7 @@ fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> { continue; } for c in sh.cells.diff(&after.cells) { - let filled = after.cell(c).is_some_and(|x| x.formula.is_some() || !x.value.is_empty()); + let filled = after.cell(c).is_some_and(gridcraft_model::Cell::has_content); if !filled || !sh.spill.contains_key(&c) || same_content(sh.cell(c), after.cell(c)) { continue; } @@ -476,13 +544,18 @@ fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> { Ok(()) } -/// Two cells hold the same value or formula (formats aside). +/// Two cells hold the same value, formula or Python code (formats aside; a Python cell's result +/// is not something the person edits). fn same_content(a: Option<&gridcraft_model::Cell>, b: Option<&gridcraft_model::Cell>) -> bool { - let empty = |c: Option<&gridcraft_model::Cell>| c.is_none_or(|c| c.formula.is_none() && c.value.is_empty()); + let empty = |c: Option<&gridcraft_model::Cell>| c.is_none_or(|c| !c.has_content()); match (a, b) { (Some(a), Some(b)) => match (&a.formula, &b.formula) { (Some(x), Some(y)) => x.text == y.text && x.array == y.array, - (None, None) => a.value == b.value, + (None, None) => match (&a.py, &b.py) { + (Some(x), Some(y)) => x.code == y.code && x.object == y.object, + (None, None) => a.value == b.value, + _ => false, + }, _ => false, }, _ => empty(a) && empty(b), diff --git a/crates/engine/src/cmd/analysis.rs b/crates/engine/src/cmd/analysis.rs index 6225b4934a..9cd10e50fb 100644 --- a/crates/engine/src/cmd/analysis.rs +++ b/crates/engine/src/cmd/analysis.rs @@ -14,7 +14,7 @@ use gridcraft_model::{Cell, NumFmt, Sheet}; use serde_json::{Value as Json, json}; use super::whatif::parse_range; -use super::*; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, edit, has_doc, str_param}; const CMD: &str = "data.analysisToolPak"; /// Most input cells a tool reads. @@ -27,6 +27,14 @@ const MAX_MATRIX_VARS: usize = 256; const MAX_REGRESSORS: usize = 16; /// Most histogram bins. const MAX_BINS: usize = 100_000; +/// Excel's limit on Fourier Analysis input values. +const MAX_FOURIER: usize = 4096; +/// Most numbers Random Number Generation or Sampling writes in one run. +const MAX_RANDOM: usize = 1_000_000; +/// Most trials of a binomial draw, and the farthest Poisson outcome considered. +const MAX_OUTCOMES: f64 = 1_000_000.0; +/// Largest seed: seeds are whole numbers that a JSON number holds exactly. +const MAX_SEED: u64 = (1 << 53) - 1; /// Part of the error a programmatic call gets when the output range already holds data; the /// dialog recognises it and asks before running again with `overwrite: true`. @@ -35,18 +43,24 @@ pub const OVERWRITE_ERROR: &str = "already holds data"; /// (id, label) of every tool, in the order of Excel's Analysis Tools list. pub const TOOLS: &[(&str, &str)] = &[ ("anovaSingle", "Anova: Single Factor"), + ("anovaTwoFactorWith", "Anova: Two-Factor With Replication"), + ("anovaTwoFactorWithout", "Anova: Two-Factor Without Replication"), ("correlation", "Correlation"), ("covariance", "Covariance"), ("descriptive", "Descriptive Statistics"), ("exponentialSmoothing", "Exponential Smoothing"), ("fTest", "F-Test Two-Sample for Variances"), + ("fourierAnalysis", "Fourier Analysis"), ("histogram", "Histogram"), ("movingAverage", "Moving Average"), + ("randomNumberGeneration", "Random Number Generation"), ("rankPercentile", "Rank and Percentile"), ("regression", "Regression"), + ("sampling", "Sampling"), ("tTestPaired", "t-Test: Paired Two Sample for Means"), ("tTestEqual", "t-Test: Two-Sample Assuming Equal Variances"), ("tTestUnequal", "t-Test: Two-Sample Assuming Unequal Variances"), + ("zTest", "z-Test: Two Sample for Means"), ]; pub fn specs() -> Vec { @@ -55,7 +69,7 @@ pub fn specs() -> Vec { "Data Analysis…", ["Data", "Analysis"], None, - "{tool: anovaSingle|correlation|covariance|descriptive|exponentialSmoothing|fTest|histogram|movingAverage|rankPercentile|regression|tTestPaired|tTestEqual|tTestUnequal (or the tool's label), output?: \"E1\" (top-left of the report; default a new sheet), newSheet?: name, outputTo?: range|newSheet (picks between the two), overwrite?: bool (else non-empty output cells are refused), labels?: bool (first row/column holds names), groupedBy?: columns|rows, …tool params} — range tools take `range`; descriptive: summary? (default true), confidence?: 95, kthLargest?, kthSmallest?; histogram: bins?: range (default evenly spaced), pareto?, cumulative?; regression: inputY, inputX, constantZero?, confidence?: 95, residuals?, standardizedResiduals?, normalProbability?; movingAverage: interval? (3), standardErrors?; exponentialSmoothing: damping? (0.3), standardErrors?; t-tests and fTest: range1, range2, alpha? (0.05), hypothesizedDifference? (0); anovaSingle: alpha?. Writes static values. No `tool` → {tools} (the menu opens the dialog).", + "{tool: anovaSingle|anovaTwoFactorWith|anovaTwoFactorWithout|correlation|covariance|descriptive|exponentialSmoothing|fTest|fourierAnalysis|histogram|movingAverage|randomNumberGeneration|rankPercentile|regression|sampling|tTestPaired|tTestEqual|tTestUnequal|zTest (or the tool's label), output?: \"E1\" (top-left of the report; default a new sheet), newSheet?: name, outputTo?: range|newSheet (picks between the two), overwrite?: bool (else non-empty output cells are refused), labels?: bool (first row/column holds names), groupedBy?: columns|rows, …tool params} — range tools take `range`; descriptive: summary? (default true), confidence?: 95, kthLargest?, kthSmallest?; histogram: bins?: range (default evenly spaced), pareto?, cumulative?; regression: inputY, inputX, constantZero?, confidence?: 95, residuals?, standardizedResiduals?, normalProbability?; movingAverage: interval? (3), standardErrors?; exponentialSmoothing: damping? (0.3), standardErrors?; t-tests and fTest: range1, range2, alpha? (0.05), hypothesizedDifference? (0); anovaSingle: alpha?; anovaTwoFactorWithout: range, labels? (the first row holds column names and the first column row names), alpha?; anovaTwoFactorWith: range (first row and column hold labels), rowsPerSample, alpha?; zTest: range1, range2, variance1, variance2 (known variances), alpha?, hypothesizedDifference?; fourierAnalysis: range (one row or column of 2^k numbers or complex text, at most 4096), inverse?; randomNumberGeneration: variables? (1), count (per variable; not for patterned), distribution: uniform{from, to} | normal{mean, standardDeviation} | bernoulli{p} | binomial{p, trials} | poisson{lambda} | patterned{from, to, step, repeatEach, repeatSequence} | discrete{valueRange: two columns of value and probability}, seed? (whole number, not for patterned; the same seed repeats the numbers; the result reports the seed used), at most 1,000,000 numbers; sampling: range, method?: periodic|random, period (periodic), samples (random, with replacement), seed?. Writes static values. No `tool` → {tools} (the menu opens the dialog).", has_doc, run )] @@ -107,7 +121,7 @@ fn confidence(p: &Json, key: &str) -> Result> { } fn alpha(p: &Json) -> Result { - match num(p, "alpha") { + match opt_num(p, "alpha")? { None => Ok(0.05), Some(a) if a > 0.0 && a < 1.0 => Ok(a), Some(_) => Err(bad(CMD, "alpha must be between 0 and 1")), @@ -1050,6 +1064,684 @@ fn anova_single(s: &Session, p: &Json) -> Result { Ok(g) } +// ---------------------------------------------------------------- two-factor anova and z-test + +/// Count, Sum, Average and Variance of a group, as the Anova summaries list them. +fn group_summary(x: &[f64]) -> [Value; 4] { + [Value::number(x.len() as f64), Value::number(x.iter().sum()), n_or_div0(mean(x)), n_or_div0(var_s(x))] +} + +const ANOVA_HEAD: [&str; 7] = ["Source of Variation", "SS", "df", "MS", "F", "P-value", "F crit"]; + +/// One line of an Anova table. A factor line, tested against the error term `err` (its MS and +/// df), adds F, the P-value and the critical F. +fn anova_line(g: &mut Grid, row: u32, label: &str, ss: f64, df: f64, err: Option<(f64, f64)>, alpha: f64) { + g.txt(row, 0, label); + g.num(row, 1, ss); + g.num(row, 2, df); + g.put(row, 3, ratio(ss, df)); + if let Some((mse, dfe)) = err { + let f = ss / df / mse; + g.put(row, 4, n_or_div0(f)); + g.put(row, 5, if f.is_finite() && dfe > 0.0 { callf("F.DIST.RT", &[f, df, dfe]) } else { div0() }); + g.put(row, 6, if df > 0.0 && dfe > 0.0 { callf("F.INV.RT", &[alpha, df, dfe]) } else { div0() }); + } +} + +/// The cells of a two-factor input range, row by row. +fn input_rows(s: &Session, p: &Json) -> Result>> { + let (si, r) = input_range(s, p, &["range", "input"])?; + Ok(variables(s, si, r, true, false, &|_| String::new())?.into_iter().map(|v| v.vals).collect()) +} + +/// The values of column `j` of a table of numbers. +fn column(data: &[Vec], j: usize) -> Vec { + data.iter().filter_map(|r| r.get(j).copied()).collect() +} + +/// Anova: Two-Factor Without Replication: one observation for each pair of levels (rows × +/// columns), the error term being the residual after both main effects. +fn anova_two_factor_without(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let labels = flag(p, "labels"); + let mut rows = input_rows(s, p)?; + let head = if labels && !rows.is_empty() { Some(rows.remove(0)) } else { None }; + let mut row_names = Vec::with_capacity(rows.len()); + let mut data: Vec> = Vec::with_capacity(rows.len()); + for (i, mut row) in rows.into_iter().enumerate() { + let name = if labels && !row.is_empty() { row.remove(0).display() } else { format!("Row {}", i + 1) }; + row_names.push(name); + data.push(numbers(&row, false)?); + } + let (a, b) = (data.len(), data.first().map_or(0, Vec::len)); + if a < 2 || b < 2 { + return Err(EngineError::Other("Anova needs at least two rows and two columns of numbers.".into())); + } + let col_names: Vec = match head { + Some(h) => h.iter().skip(1).map(Value::display).collect(), + None => (1..=b).map(|j| format!("Column {j}")).collect(), + }; + let cols: Vec> = (0..b).map(|j| column(&data, j)).collect(); + let all: Vec = data.iter().flatten().copied().collect(); + let grand = mean(&all); + let row_means: Vec = data.iter().map(|r| mean(r)).collect(); + let col_means: Vec = cols.iter().map(|c| mean(c)).collect(); + let ss_rows: f64 = row_means.iter().map(|m| b as f64 * (m - grand).powi(2)).sum(); + let ss_cols: f64 = col_means.iter().map(|m| a as f64 * (m - grand).powi(2)).sum(); + // The residual of each observation after removing both main effects. + let ss_err: f64 = + data.iter().zip(&row_means).flat_map(|(r, rm)| r.iter().zip(&col_means).map(move |(x, cm)| (x - rm - cm + grand).powi(2))).sum(); + let (df_rows, df_cols) = ((a - 1) as f64, (b - 1) as f64); + let df_err = df_rows * df_cols; + let mut g = Grid::default(); + g.txt(0, 0, "Anova: Two-Factor Without Replication"); + g.labels(2, 0, &["SUMMARY", "Count", "Sum", "Average", "Variance"]); + let summary = |g: &mut Grid, row: u32, name: &str, x: &[f64]| { + g.txt(row, 0, name); + for (k, v) in group_summary(x).into_iter().enumerate() { + g.put(row, 1 + idx(k), v); + } + }; + for (i, (name, x)) in row_names.iter().zip(&data).enumerate() { + summary(&mut g, 3 + idx(i), name, x); + } + let first_col = 3 + idx(a) + 1; + for (j, (name, x)) in col_names.iter().zip(&cols).enumerate() { + summary(&mut g, first_col + idx(j), name, x); + } + let row = first_col + idx(b) + 2; + g.txt(row, 0, "ANOVA"); + g.labels(row + 1, 0, &ANOVA_HEAD); + let err = Some((ss_err / df_err, df_err)); + anova_line(&mut g, row + 2, "Rows", ss_rows, df_rows, err, alpha); + anova_line(&mut g, row + 3, "Columns", ss_cols, df_cols, err, alpha); + anova_line(&mut g, row + 4, "Error", ss_err, df_err, None, alpha); + g.txt(row + 6, 0, "Total"); + g.num(row + 6, 1, ss(&all)); + g.num(row + 6, 2, (all.len() - 1) as f64); + Ok(g) +} + +/// The number of rows in each sample of a two-factor Anova with replication. +fn rows_per_sample(p: &Json, data_rows: usize) -> Result { + let per = num(p, "rowsPerSample").ok_or_else(|| bad(CMD, "missing `rowsPerSample` (the number of rows in each sample)"))?; + if per < 2.0 || per.fract() != 0.0 || per > data_rows as f64 || !data_rows.is_multiple_of(per as usize) { + return Err(EngineError::Other("Rows per sample must be a whole number of at least 2 that divides the number of data rows.".into())); + } + Ok(per as usize) +} + +/// Anova: Two-Factor With Replication. The input range holds column labels in its first row and +/// sample labels in its first column; each sample (a level of the row factor) spans +/// `rowsPerSample` consecutive rows, so every cell of the design holds that many observations. +fn anova_two_factor_with(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let mut rows = input_rows(s, p)?; + if rows.len() < 3 { + return Err(EngineError::Other("The input range must hold a row of labels and at least two samples.".into())); + } + let head = rows.remove(0); + let col_names: Vec = head.iter().skip(1).map(Value::display).collect(); + let per = rows_per_sample(p, rows.len())?; + let mut sample_names = Vec::new(); + let mut data: Vec> = Vec::with_capacity(rows.len()); + for (i, mut row) in rows.into_iter().enumerate() { + let name = if row.is_empty() { Value::Empty } else { row.remove(0) }; + if i.is_multiple_of(per) { + sample_names.push(name.display()); + } + data.push(numbers(&row, false)?); + } + let (a, b) = (sample_names.len(), col_names.len()); + if a < 2 || b < 2 { + return Err(EngineError::Other("Anova needs at least two samples and two columns of numbers.".into())); + } + // cells[i][j]: the observations of sample i in column j. + let cells: Vec>> = data.chunks(per).map(|block| (0..b).map(|j| column(block, j)).collect()).collect(); + let all: Vec = data.iter().flatten().copied().collect(); + let grand = mean(&all); + let sample_all: Vec> = data.chunks(per).map(|block| block.iter().flatten().copied().collect()).collect(); + let cols: Vec> = (0..b).map(|j| column(&data, j)).collect(); + let (sm, cm): (Vec, Vec) = (sample_all.iter().map(|x| mean(x)).collect(), cols.iter().map(|x| mean(x)).collect()); + let n = per as f64; + let ss_sample: f64 = sm.iter().map(|m| n * b as f64 * (m - grand).powi(2)).sum(); + let ss_cols: f64 = cm.iter().map(|m| n * a as f64 * (m - grand).powi(2)).sum(); + let mut ss_inter = 0.0; + let mut ss_within = 0.0; + for (i, row) in cells.iter().enumerate() { + for (j, cell) in row.iter().enumerate() { + let (si, cj) = (sm.get(i).copied().unwrap_or(f64::NAN), cm.get(j).copied().unwrap_or(f64::NAN)); + ss_inter += n * (mean(cell) - si - cj + grand).powi(2); + ss_within += ss(cell); + } + } + let (df_sample, df_cols) = ((a - 1) as f64, (b - 1) as f64); + let df_within = (a * b * (per - 1)) as f64; + let mut g = Grid::default(); + g.txt(0, 0, "Anova: Two-Factor With Replication"); + g.txt(2, 0, "SUMMARY"); + for (j, name) in col_names.iter().enumerate() { + g.txt(2, 1 + idx(j), name); + } + g.txt(2, 1 + idx(b), "Total"); + let stats = ["Count", "Sum", "Average", "Variance"]; + let mut row = 3u32; + let block = |g: &mut Grid, row: &mut u32, name: &str, groups: Vec<&[f64]>| { + g.txt(*row, 0, name); + let sums: Vec<[Value; 4]> = groups.iter().map(|x| group_summary(x)).collect(); + for (k, label) in stats.iter().enumerate() { + let r = *row + 1 + idx(k); + g.txt(r, 0, label); + for (j, sm) in sums.iter().enumerate() { + g.put(r, 1 + idx(j), sm.get(k).cloned().unwrap_or(Value::Empty)); + } + } + *row += 6; + }; + for ((name, row_cells), whole) in sample_names.iter().zip(&cells).zip(&sample_all) { + let mut groups: Vec<&[f64]> = row_cells.iter().map(Vec::as_slice).collect(); + groups.push(whole); + block(&mut g, &mut row, name, groups); + } + block(&mut g, &mut row, "Total", cols.iter().map(Vec::as_slice).collect()); + row += 1; + g.txt(row, 0, "ANOVA"); + g.labels(row + 1, 0, &ANOVA_HEAD); + let err = Some((ss_within / df_within, df_within)); + anova_line(&mut g, row + 2, "Sample", ss_sample, df_sample, err, alpha); + anova_line(&mut g, row + 3, "Columns", ss_cols, df_cols, err, alpha); + anova_line(&mut g, row + 4, "Interaction", ss_inter, df_sample * df_cols, err, alpha); + anova_line(&mut g, row + 5, "Within", ss_within, df_within, None, alpha); + g.txt(row + 7, 0, "Total"); + g.num(row + 7, 1, ss(&all)); + g.num(row + 7, 2, (all.len() - 1) as f64); + Ok(g) +} + +/// A known variance parameter: a positive number. +fn known_variance(p: &Json, key: &str) -> Result { + match num(p, key) { + Some(v) if v > 0.0 => Ok(v), + _ => Err(EngineError::Other(format!("Enter the known variance `{key}` (a positive number)."))), + } +} + +/// z-Test: Two Sample for Means, for two samples whose population variances are known. +fn z_test(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let hmd = match opt_num(p, "hypothesizedDifference")? { + Some(d) => d, + None => num_or(p, "difference", 0.0)?, + }; + let (v1, v2) = (known_variance(p, "variance1")?, known_variance(p, "variance2")?); + let a = single(s, p, "range1", "Variable 1")?; + let b = single(s, p, "range2", "Variable 2")?; + let (x, y) = (numbers(&a.vals, true)?, numbers(&b.vals, true)?); + if x.is_empty() || y.is_empty() { + return Err(EngineError::Other("Each input range needs at least one number.".into())); + } + let (n1, n2) = (x.len() as f64, y.len() as f64); + let (m1, m2) = (mean(&x), mean(&y)); + let z = (m1 - m2 - hmd) / (v1 / n1 + v2 / n2).sqrt(); + let mut g = Grid::default(); + let row = test_head(&mut g, "z-Test: Two Sample for Means", &a.name, &b.name); + pair_row(&mut g, row, "Mean", Value::number(m1), Value::number(m2)); + pair_row(&mut g, row + 1, "Known Variance", Value::number(v1), Value::number(v2)); + pair_row(&mut g, row + 2, "Observations", Value::number(n1), Value::number(n2)); + pair_row(&mut g, row + 3, "Hypothesized Mean Difference", Value::number(hmd), Value::Empty); + pair_row(&mut g, row + 4, "z", n_or_div0(z), Value::Empty); + // The tail beyond |z|: 1 − Φ(|z|). + let tail = call("NORM.S.DIST", &[Value::Number(z.abs()), Value::Bool(true)]).as_f64().map(|c| 1.0 - c); + let lines: [(&str, Value); 4] = [ + ("P(Z<=z) one-tail", tail.map_or_else(div0, Value::number)), + ("z Critical one-tail", callf("NORM.S.INV", &[1.0 - alpha])), + ("P(Z<=z) two-tail", tail.map_or_else(div0, |t| Value::number(2.0 * t))), + ("z Critical two-tail", callf("NORM.S.INV", &[1.0 - alpha / 2.0])), + ]; + for (k, (label, v)) in lines.into_iter().enumerate() { + pair_row(&mut g, row + 5 + idx(k), label, v, Value::Empty); + } + Ok(g) +} + +// ---------------------------------------------------------------- fourier analysis + +/// Radix-2 fast Fourier transform (iterative Cooley–Tukey) in place, for a power-of-two number of +/// complex values (re, im). The forward transform is unscaled, X[k] = Σ x[n]·e^(−2πikn/N); the +/// inverse uses e^(+2πikn/N) and divides by N, so it returns the values the forward one took. +fn fft(a: &mut [(f64, f64)], inverse: bool) { + let n = a.len(); + if n < 2 || !n.is_power_of_two() { + return; + } + let bits = n.trailing_zeros(); + for i in 0..n { + let j = i.reverse_bits() >> (usize::BITS - bits); + if i < j { + a.swap(i, j); + } + } + let sign = if inverse { 1.0 } else { -1.0 }; + let mut len = 2; + while len <= n { + let ang = sign * 2.0 * std::f64::consts::PI / len as f64; + for start in (0..n).step_by(len) { + for k in 0..len / 2 { + // Each twiddle factor is computed directly, not by repeated multiplication. + let (wr, wi) = ((ang * k as f64).cos(), (ang * k as f64).sin()); + let (i, j) = (start + k, start + k + len / 2); + let (Some(&(ur, ui)), Some(&(xr, xi))) = (a.get(i), a.get(j)) else { continue }; + let (vr, vi) = (xr * wr - xi * wi, xr * wi + xi * wr); + if let Some(u) = a.get_mut(i) { + *u = (ur + vr, ui + vi); + } + if let Some(x) = a.get_mut(j) { + *x = (ur - vr, ui - vi); + } + } + } + len <<= 1; + } + if inverse { + let nf = n as f64; + a.iter_mut().for_each(|v| *v = (v.0 / nf, v.1 / nf)); + } +} + +/// Fourier Analysis: the discrete Fourier transform (or with `inverse` its inverse) of one row or +/// column of 2^k values, read and written as complex numbers the way IMREAL, IMAGINARY and +/// COMPLEX read and write them. +fn fourier_analysis(s: &Session, p: &Json) -> Result { + let v = single(s, p, "range", "")?; + let n = v.vals.len(); + if n == 0 || n > MAX_FOURIER || !n.is_power_of_two() { + return Err(EngineError::Other(format!("Fourier Analysis needs 1, 2, 4, 8 … {MAX_FOURIER} input values (a power of two)."))); + } + let mut a = Vec::with_capacity(n); + for x in &v.vals { + let part = |f: &str| call(f, std::slice::from_ref(x)).as_f64(); + match (x, part("IMREAL"), part("IMAGINARY")) { + (Value::Empty, ..) => return Err(non_numeric()), + (_, Some(re), Some(im)) => a.push((re, im)), + _ => return Err(EngineError::Other("Input range must hold numbers or complex numbers such as 3+4i.".into())), + } + } + let total: f64 = a.iter().map(|(re, im)| re.abs() + im.abs()).sum(); + let inverse = flag(p, "inverse"); + fft(&mut a, inverse); + // Parts that can only be rounding noise of the transform are written as 0. Each of the + // log2(N) butterfly stages adds at most a few units of f64::EPSILON times the magnitude of + // the values it combines, so the computed transform differs from the exact one by at most + // about log2(N) · ε · Σ|x_n| times a small constant (Higham, Accuracy and Stability of + // Numerical Algorithms, 2nd ed., chapter 24, The Fast Fourier Transform). The bound comes + // from the input and N, never from the largest output, so a small part beside a large one + // (an imaginary part of 1 beside a real part of 1e14, a harmonic of 4e-7 beside a DC term of + // 8e6) is kept. With N = 1 the transform is the identity and log2(N) = 0: nothing is zeroed. + // The inverse divides its outputs by N, so its noise is divided by N as well. An input sum + // that overflows gives no finite bound; then nothing is cleaned up. + let mut noise = 8.0 * f64::EPSILON * f64::from(n.trailing_zeros()) * total; + if inverse { + noise /= n as f64; + } + let noise = if noise.is_finite() { noise } else { 0.0 }; + let clean = |x: f64| if x.abs() <= noise { 0.0 } else { x }; + let mut g = Grid::default(); + let first = u32::from(flag(p, "labels")); + if first == 1 { + g.txt(0, 0, &v.name); + } + for (i, (re, im)) in a.into_iter().enumerate() { + g.put(first + idx(i), 0, callf("COMPLEX", &[clean(re), clean(im)])); + } + Ok(g) +} + +// ---------------------------------------------------------------- random numbers and sampling + +/// A seeded generator: xoshiro256** (Blackman and Vigna, a public-domain algorithm) with its +/// state filled by SplitMix64. The same seed gives the same numbers in GridCraft; they are not +/// Excel's numbers, whose generator is not documented. +struct Rng([u64; 4]); + +impl Rng { + fn new(seed: u64) -> Rng { + let mut x = seed; + let mut next = || { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = x; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + }; + Rng([next(), next(), next(), next()]) + } + + fn next_u64(&mut self) -> u64 { + let [s0, s1, s2, s3] = self.0; + let out = s1.wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let (s2, s3) = (s2 ^ s0, s3 ^ s1); + self.0 = [s0 ^ s3, s1 ^ s2, s2 ^ (s1 << 17), s3.rotate_left(45)]; + out + } + + /// Uniform in [0, 1), with 53 random bits. + fn uniform(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } + + /// Uniform whole number in [0, n), without modulo bias. + fn below(&mut self, n: u64) -> u64 { + if n <= 1 { + return 0; + } + let zone = u64::MAX - u64::MAX % n; + loop { + let v = self.next_u64(); + if v < zone { + return v % n; + } + } + } + + /// Standard normal by the Box–Muller transform. + fn normal(&mut self) -> f64 { + let (u1, u2) = (1.0 - self.uniform(), self.uniform()); + (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos() + } +} + +/// The `seed` parameter, or a seed taken from the clock when there is none. +fn seed_of(p: &Json) -> Result { + let given = p.get("seed").is_some_and(|v| match v { + Json::Null => false, + Json::String(t) => !t.trim().is_empty(), + _ => true, + }); + if !given { + let ms = gridcraft_core::date::unix_now_ms().unwrap_or(0.0); + return Ok((ms * 1000.0) as u64 & MAX_SEED); + } + match num(p, "seed") { + Some(x) if x >= 0.0 && x.fract() == 0.0 && x <= MAX_SEED as f64 => Ok(x as u64), + _ => Err(EngineError::Other("The random seed must be a whole number from 0.".into())), + } +} + +/// A number parameter: `None` when absent, null or blank; an error when present but not a +/// finite number (a typed "0,3" or "abc" must not quietly become the default). +fn opt_num(p: &Json, key: &str) -> Result> { + match p.get(key) { + None | Some(Json::Null) => Ok(None), + Some(Json::String(t)) if t.trim().is_empty() => Ok(None), + Some(_) => num(p, key).map(Some).ok_or_else(|| EngineError::Other(format!("`{key}` must be a number."))), + } +} + +/// A number parameter, `default` when absent or blank. +fn num_or(p: &Json, key: &str, default: f64) -> Result { + Ok(opt_num(p, key)?.unwrap_or(default)) +} + +/// A whole-number parameter of at least `min`, `default` when absent. +fn whole(p: &Json, key: &str, default: Option, min: f64) -> Result { + match opt_num(p, key)?.or(default) { + Some(x) if x >= min && x.fract() == 0.0 => Ok(x), + Some(_) => Err(EngineError::Other(format!("`{key}` must be a whole number of at least {min}."))), + None => Err(bad(CMD, format!("missing `{key}`"))), + } +} + +/// A probability parameter in [0, 1]. +fn probability(p: &Json) -> Result { + match num_or(p, "p", 0.5)? { + x if (0.0..=1.0).contains(&x) => Ok(x), + _ => Err(EngineError::Other("The p value must be between 0 and 1.".into())), + } +} + +/// The probabilities of a distribution on 0, 1, 2 … `last`, as (first outcome, probabilities of +/// first, first + 1, …), from its probability `at_mode` at `mode`, its most likely outcome, and +/// `ratio`(k) = pmf(k + 1) / pmf(k). Each term is one multiplication of its neighbour towards the +/// mode, so no worksheet function runs per outcome, and the terms only shrink away from the mode, +/// so nothing underflows before the terms that matter. The left tail ends where its terms vanish, +/// the right tail once the cumulative probability reaches 1 within f64 resolution (every later +/// draw would map to the last outcome). The table is as wide as the distribution's effective +/// support, not as `last`: Binomial(1,000,000, 0.5) takes about 23,000 entries, not 1,000,001. +fn pmf_table(last: f64, mode: f64, at_mode: f64, ratio: impl Fn(f64) -> f64) -> Result<(f64, Vec)> { + if !at_mode.is_finite() || at_mode <= 0.0 || !(0.0..=last).contains(&mode) || mode.fract() != 0.0 { + return Err(EngineError::Other("The distribution could not be tabulated.".into())); + } + let mut left = Vec::new(); + let (mut k, mut v) = (mode, at_mode); + while k > 0.0 { + v /= ratio(k - 1.0); + if v.is_nan() || v < f64::MIN_POSITIVE { + break; + } + left.push(v); + k -= 1.0; + } + let first = k; + let mut pmf: Vec = left.into_iter().rev().collect(); + let mut acc = pmf.iter().sum::() + at_mode; + pmf.push(at_mode); + let (mut k, mut v) = (mode, at_mode); + while k < last && acc < 1.0 - 1e-15 { + v *= ratio(k); + if v.is_nan() || v < f64::MIN_POSITIVE { + break; + } + pmf.push(v); + acc += v; + k += 1.0; + } + Ok((first, pmf)) +} + +/// A distribution on whole numbers tabulated for inversion sampling: the cumulative +/// probabilities of `first`, `first + 1`, … up to the last outcome that matters. +struct Table { + first: f64, + cdf: Vec, +} + +impl Table { + /// The distribution on 0, 1, 2 … `last` that `pmf_table` describes. + fn from_mode(last: f64, mode: f64, at_mode: f64, ratio: impl Fn(f64) -> f64) -> Result { + let (first, pmf) = pmf_table(last, mode, at_mode, ratio)?; + let mut acc = 0.0; + let cdf = pmf + .into_iter() + .map(|p| { + acc += p; + acc + }) + .collect(); + Ok(Table { first, cdf }) + } + + /// All the probability on one outcome. + fn point(value: f64) -> Table { + Table { first: value, cdf: vec![1.0] } + } + + /// A draw: the first outcome whose cumulative probability exceeds a uniform number (inversion). + fn draw(&self, r: &mut Rng) -> f64 { + let u = r.uniform() * self.cdf.last().copied().unwrap_or(1.0); + self.first + self.cdf.partition_point(|c| *c <= u).min(self.cdf.len().saturating_sub(1)) as f64 + } +} + +/// The numbers of a patterned sequence: `from` to `to` in steps, each number repeated, the whole +/// sequence repeated. +fn pattern(p: &Json) -> Result> { + let (from, to, step) = (num_or(p, "from", 1.0)?, num_or(p, "to", 1.0)?, num_or(p, "step", 1.0)?); + let (each, times) = (whole(p, "repeatEach", Some(1.0), 1.0)?, whole(p, "repeatSequence", Some(1.0), 1.0)?); + if step <= 0.0 || to < from { + return Err(EngineError::Other("The pattern must run from a smaller number to a larger one in positive steps.".into())); + } + let steps = ((to - from) / step + 1e-9).floor() + 1.0; + if steps * each * times > MAX_RANDOM as f64 { + return Err(EngineError::Other(format!("Random Number Generation writes at most {MAX_RANDOM} numbers."))); + } + let base: Vec = (0..steps as usize).map(|k| from + step * k as f64).collect(); + let one: Vec = base.iter().flat_map(|v| std::iter::repeat_n(*v, each as usize)).collect(); + Ok(one.repeat(times as usize)) +} + +/// Random Number Generation: `count` numbers from a distribution in each of `variables` +/// columns, drawn row by row. +fn random_numbers(s: &Session, p: &Json, seed: u64) -> Result { + let vars = whole(p, "variables", Some(1.0), 1.0)?; + let dist = text(p, &["distribution"]).map(norm).unwrap_or_else(|| "uniform".into()); + let cells = |rows: f64| { + if rows * vars > MAX_RANDOM as f64 { + Err(EngineError::Other(format!("Random Number Generation writes at most {MAX_RANDOM} numbers."))) + } else { + Ok(rows as usize) + } + }; + let mut g = Grid::default(); + let cols = vars as usize; + if dist == "patterned" { + let seq = pattern(p)?; + cells(seq.len() as f64)?; + for (i, x) in seq.iter().enumerate() { + for c in 0..cols { + g.num(idx(i), idx(c), *x); + } + } + return Ok(g); + } + let count = cells(whole(p, "count", None, 1.0)?)?; + let mut draw: Box f64> = match dist.as_str() { + "uniform" => { + let (a, b) = (num_or(p, "from", 0.0)?, num_or(p, "to", 1.0)?); + Box::new(move |r| a + (b - a) * r.uniform()) + } + "normal" => { + let (m, sd) = (num_or(p, "mean", 0.0)?, num_or(p, "standardDeviation", 1.0)?); + if sd < 0.0 { + return Err(EngineError::Other("The standard deviation must not be negative.".into())); + } + Box::new(move |r| m + sd * r.normal()) + } + "bernoulli" => { + let pr = probability(p)?; + Box::new(move |r| if r.uniform() < pr { 1.0 } else { 0.0 }) + } + "binomial" => { + let (pr, n) = (probability(p)?, whole(p, "trials", Some(1.0), 1.0)?); + if n > MAX_OUTCOMES { + return Err(EngineError::Other(format!("The number of trials must be at most {MAX_OUTCOMES}."))); + } + // p = 0 and p = 1 are exact: every draw is 0 or n. Otherwise one BINOM.DIST value at + // the mode ⌊(n + 1)p⌋ anchors pmf(k + 1) = pmf(k) · (n − k)/(k + 1) · p/(1 − p). + let table = if pr == 0.0 { + Table::point(0.0) + } else if pr == 1.0 { + Table::point(n) + } else { + let mode = ((n + 1.0) * pr).floor().min(n); + let at_mode = f64_of(&call("BINOM.DIST", &[Value::Number(mode), Value::Number(n), Value::Number(pr), Value::Bool(false)])); + let odds = pr / (1.0 - pr); + Table::from_mode(n, mode, at_mode, |k| (n - k) / (k + 1.0) * odds)? + }; + Box::new(move |r| table.draw(r)) + } + "poisson" => { + let lambda = num_or(p, "lambda", 1.0)?; + if lambda <= 0.0 || lambda > 100_000.0 { + return Err(EngineError::Other("Lambda must be greater than 0 and at most 100000.".into())); + } + // One POISSON.DIST value at the mode ⌊λ⌋ anchors pmf(k + 1) = pmf(k) · λ/(k + 1). + let last = (lambda + 40.0 * lambda.sqrt() + 100.0).min(MAX_OUTCOMES); + let mode = lambda.floor(); + let at_mode = f64_of(&call("POISSON.DIST", &[Value::Number(mode), Value::Number(lambda), Value::Bool(false)])); + let table = Table::from_mode(last, mode, at_mode, |k| lambda / (k + 1.0))?; + Box::new(move |r| table.draw(r)) + } + "discrete" => { + let (si, r) = input_range(s, p, &["valueRange", "values"])?; + if r.width() != 2 { + return Err(EngineError::Other("The value and probability input range must have two columns.".into())); + } + let v = variables(s, si, r, false, false, &|_| String::new())?; + let (values, probs) = match v.as_slice() { + [a, b] => (numbers(&a.vals, false)?, numbers(&b.vals, false)?), + _ => return Err(non_numeric()), + }; + if probs.iter().any(|x| !(0.0..=1.0).contains(x)) || (probs.iter().sum::() - 1.0).abs() > 1e-9 { + return Err(EngineError::Other("The probabilities must be between 0 and 1 and add up to 1.".into())); + } + let cdf: Vec = probs + .iter() + .scan(0.0, |acc, x| { + *acc += x; + Some(*acc) + }) + .collect(); + let table = Table { first: 0.0, cdf }; + Box::new(move |r| values.get(table.draw(r) as usize).copied().unwrap_or(f64::NAN)) + } + other => return Err(bad(CMD, format!("unknown distribution `{other}`"))), + }; + let mut rng = Rng::new(seed); + for i in 0..count { + for c in 0..cols { + g.num(idx(i), idx(c), draw(&mut rng)); + } + } + Ok(g) +} + +/// Whether Random Number Generation writes a patterned sequence (which uses no seed). +fn patterned(p: &Json) -> bool { + text(p, &["distribution"]).map(norm).is_some_and(|d| d == "patterned") +} + +fn random_sampling(p: &Json) -> bool { + text(p, &["method"]).is_some_and(|m| m.eq_ignore_ascii_case("random")) +} + +/// Sampling: every `period`-th value of the input, or `samples` values drawn at random with +/// replacement, down one column. The input is read column by column (row by row for a single +/// row); blanks are skipped. +fn sampling(s: &Session, p: &Json, seed: Option) -> Result { + let (si, r) = input_range(s, p, &["range", "input"])?; + let by_rows = r.height() == 1 && r.width() > 1; + let vars = variables(s, si, r, by_rows, flag(p, "labels"), &|_| String::new())?; + let mut x = Vec::new(); + for v in &vars { + x.extend(numbers(&v.vals, true)?); + } + if x.is_empty() { + return Err(EngineError::Other("The input range holds no numbers.".into())); + } + let picked: Vec = match seed { + Some(seed) => { + let k = whole(p, "samples", None, 1.0)?; + if k > MAX_RANDOM as f64 { + return Err(EngineError::Other(format!("Sampling takes at most {MAX_RANDOM} samples."))); + } + let mut rng = Rng::new(seed); + (0..k as usize).filter_map(|_| x.get(rng.below(x.len() as u64) as usize).copied()).collect() + } + None => { + let period = whole(p, "period", None, 1.0)?; + if period > x.len() as f64 { + return Err(EngineError::Other("The period must be at most the number of input values.".into())); + } + x.iter().skip(period as usize - 1).step_by(period as usize).copied().collect() + } + }; + let mut g = Grid::default(); + for (i, v) in picked.iter().enumerate() { + g.num(idx(i), 0, *v); + } + Ok(g) +} + // ---------------------------------------------------------------- output /// Writes the report at `output` (refusing to overwrite data unless `overwrite`) or on a new @@ -1096,7 +1788,7 @@ fn write_report(s: &mut Session, p: &Json, tool: &str, g: Grid) -> Result { for row in rect.start.row..=rect.end.row { for (c, cell) in sh.cells.row(row, rect.start.col, rect.end.col) { - if !cell.value.is_empty() || cell.formula.is_some() { + if cell.has_content() { occupied.push(CellRef::new(row, c)); } } @@ -1124,13 +1816,13 @@ fn write_report(s: &mut Session, p: &Json, tool: &str, g: Grid) -> Result let sh = cx.sheet_mut(si)?; for c in &occupied { let style = sh.style_id(*c); - sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style }); + sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style, py: None }); } let mut touched = occupied.clone(); for ((r, c), v) in &g.cells { let cell = CellRef::new(at.row + r, at.col + c); let style = pct_styles.get(&cell).copied().unwrap_or_else(|| sh.style_id(cell)); - sh.set_cell(cell, Cell { value: v.clone(), formula: None, style }); + sh.set_cell(cell, Cell { value: v.clone(), formula: None, style, py: None }); touched.push(cell); } for c in touched { @@ -1150,6 +1842,7 @@ fn run(s: &mut Session, p: &Json) -> Result { return Ok(json!({"tools": TOOLS.iter().map(|(id, label)| json!({"id": id, "label": label})).collect::>()})); }; let tool = tool_id(t).ok_or_else(|| bad(CMD, format!("unknown tool `{t}`")))?; + let mut seed = None; let g = match tool { "descriptive" => descriptive(s, p)?, "histogram" => histogram(s, p)?, @@ -1162,16 +1855,38 @@ fn run(s: &mut Session, p: &Json) -> Result { "tTestPaired" | "tTestEqual" | "tTestUnequal" => t_test(s, p, tool)?, "fTest" => f_test(s, p)?, "anovaSingle" => anova_single(s, p)?, + "anovaTwoFactorWithout" => anova_two_factor_without(s, p)?, + "anovaTwoFactorWith" => anova_two_factor_with(s, p)?, + "zTest" => z_test(s, p)?, + "fourierAnalysis" => fourier_analysis(s, p)?, + "randomNumberGeneration" => { + // A patterned sequence draws nothing: its seed is neither read nor reported. + if !patterned(p) { + seed = Some(seed_of(p)?); + } + random_numbers(s, p, seed.unwrap_or(0))? + } + "sampling" => { + if random_sampling(p) { + seed = Some(seed_of(p)?); + } + sampling(s, p, seed)? + } _ => return Err(bad(CMD, format!("unknown tool `{t}`"))), }; - write_report(s, p, tool, g) + let mut out = write_report(s, p, tool, g)?; + if let Some(k) = seed { + out["seed"] = json!(k); + } + Ok(out) } #[cfg(test)] mod tests { use gridcraft_core::{CellRef, Value}; - use serde_json::json; + use serde_json::{Value as Json, json}; + use super::{MAX_OUTCOMES, call, f64_of, pmf_table}; use crate::Session; fn s() -> Session { @@ -1375,6 +2090,462 @@ mod tests { assert_eq!(n(&s, "X4"), 0.25, "4 has one value below it among five"); } + #[test] + fn two_factor_anova_without_replication_matches_a_textbook_example() { + // Hardness testing, a randomized complete block design (Montgomery, Design and Analysis + // of Experiments, Example 4.1): four tips (rows) by four coupons (columns). Published: + // SS tips 0.385, SS coupons 0.825, SS error 0.080, SS total 1.290, F tips 14.44. + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["", "Coupon 1", "Coupon 2", "Coupon 3", "Coupon 4"], + ["Tip 1", 9.3, 9.4, 9.6, 10.0], + ["Tip 2", 9.4, 9.3, 9.8, 9.9], + ["Tip 3", 9.2, 9.4, 9.5, 9.7], + ["Tip 4", 9.7, 9.6, 10.0, 10.2], + ]}), + ) + .unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Anova: Two-Factor Without Replication", "range": "A1:E5", "labels": true, "output": "H1"})) + .unwrap(); + assert_eq!(v(&s, "H1"), Value::text("Anova: Two-Factor Without Replication")); + assert_eq!((v(&s, "H4"), n(&s, "I4")), (Value::text("Tip 1"), 4.0)); + assert!(close(n(&s, "J4"), 38.3, 1e-12), "sum of tip 1"); + assert_eq!(v(&s, "H9"), Value::text("Coupon 1")); + assert!(close(n(&s, "K12"), 9.95, 1e-12), "average of coupon 4"); + assert_eq!(v(&s, "H17"), Value::text("Rows")); + assert!(close(n(&s, "I17"), 0.385, 1e-12)); + assert!(close(n(&s, "I18"), 0.825, 1e-12)); + assert!(close(n(&s, "I19"), 0.080, 1e-12)); + assert!(close(n(&s, "I21"), 1.290, 1e-12)); + assert_eq!((n(&s, "J17"), n(&s, "J19"), n(&s, "J21")), (3.0, 9.0, 15.0)); + assert!(close(n(&s, "L17"), 14.4375, 1e-9), "F for tips"); + assert!(close(n(&s, "M17"), eval(&mut s, "=F.DIST.RT(14.4375,3,9)"), 1e-9)); + assert!(close(n(&s, "N17"), eval(&mut s, "=F.INV.RT(0.05,3,9)"), 1e-9)); + assert!(v(&s, "L19").is_empty(), "the error line has no F"); + } + + #[test] + fn two_factor_anova_with_replication_matches_a_textbook_example() { + let mut s = s(); + // Battery life (Montgomery, Example 5.1): three materials (samples of four rows) by three + // temperatures (columns). Published: SS material 10683.72, SS temperature 39118.72, + // SS interaction 9613.78, SS error 18230.75 on 27 df, SS total 77646.97. + s.execute( + "range.setValues", + json!({"range": "A20", "values": [ + ["Material", "15 F", "70 F", "125 F"], + ["Type 1", 130, 34, 20], ["", 155, 40, 70], ["", 74, 80, 82], ["", 180, 75, 58], + ["Type 2", 150, 136, 25], ["", 188, 122, 70], ["", 159, 106, 58], ["", 126, 115, 45], + ["Type 3", 138, 174, 96], ["", 110, 120, 104], ["", 168, 150, 82], ["", 160, 139, 60], + ]}), + ) + .unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "anovaTwoFactorWith", "range": "A20:D32", "rowsPerSample": 4, "newSheet": "Battery"})) + .unwrap(); + assert_eq!(v(&s, "Battery!A3"), Value::text("SUMMARY")); + assert_eq!((v(&s, "Battery!B3"), v(&s, "Battery!E3")), (Value::text("15 F"), Value::text("Total"))); + assert_eq!(v(&s, "Battery!A4"), Value::text("Type 1")); + assert_eq!((n(&s, "Battery!B5"), n(&s, "Battery!B6"), n(&s, "Battery!E5")), (4.0, 539.0, 12.0)); + assert_eq!(v(&s, "Battery!A22"), Value::text("Total")); + assert_eq!(n(&s, "Battery!B24"), 1738.0, "sum of the 15 F column"); + assert_eq!(v(&s, "Battery!A29"), Value::text("ANOVA")); + assert_eq!( + (v(&s, "Battery!A31"), v(&s, "Battery!A34"), v(&s, "Battery!A36")), + (Value::text("Sample"), Value::text("Within"), Value::text("Total")) + ); + assert!(close(n(&s, "Battery!B31"), 10683.72, 0.01)); + assert!(close(n(&s, "Battery!B32"), 39118.72, 0.01)); + assert!(close(n(&s, "Battery!B33"), 9613.78, 0.01)); + assert!(close(n(&s, "Battery!B34"), 18230.75, 0.01)); + assert!(close(n(&s, "Battery!B36"), 77646.97, 0.01)); + assert_eq!((n(&s, "Battery!C33"), n(&s, "Battery!C34"), n(&s, "Battery!C36")), (4.0, 27.0, 35.0)); + assert!(close(n(&s, "Battery!E31"), 7.91, 0.005) && close(n(&s, "Battery!E32"), 28.97, 0.005) && close(n(&s, "Battery!E33"), 3.56, 0.005)); + assert!(close(n(&s, "Battery!F33"), 0.0186, 0.00005), "interaction P-value"); + // Rows per sample must divide the data rows. + let bad = json!({"tool": "anovaTwoFactorWith", "range": "Sheet1!A20:D32", "rowsPerSample": 5, "output": "F60"}); + assert!(s.execute("data.analysisToolPak", bad).is_err()); + } + + #[test] + fn z_test_with_known_variances() { + // x̄ = 3 (n = 5, σ² = 2), ȳ = 4 (n = 3, σ² = 6): z = −1/√2.4. Critical values from the + // standard normal table: 1.644854 (one tail) and 1.959964 (two tails) at α = 0.05. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["x", "y"], [1, 2], [2, 4], [3, 6], [4, null], [5, null]]})).unwrap(); + s.execute( + "data.analysisToolPak", + json!({"tool": "zTest", "range1": "A1:A6", "range2": "B1:B6", "labels": true, "variance1": 2, "variance2": 6, "output": "D1"}), + ) + .unwrap(); + assert_eq!(v(&s, "D1"), Value::text("z-Test: Two Sample for Means")); + assert_eq!((v(&s, "E3"), v(&s, "F3")), (Value::text("x"), Value::text("y"))); + assert_eq!((n(&s, "E4"), n(&s, "F4"), n(&s, "E5"), n(&s, "F6")), (3.0, 4.0, 2.0, 3.0)); + let z = -1.0 / 2.4f64.sqrt(); + assert!(close(n(&s, "E8"), z, 1e-12)); + let tail = 1.0 - eval(&mut s, &format!("=NORM.S.DIST({},TRUE)", -z)); + assert!(close(n(&s, "E9"), tail, 1e-12) && close(n(&s, "E9"), 0.2593, 1e-4)); + assert!(close(n(&s, "E10"), 1.644_853_6, 1e-6)); + assert!(close(n(&s, "E11"), 2.0 * tail, 1e-12)); + assert!(close(n(&s, "E12"), 1.959_964_0, 1e-6)); + // Unknown or non-positive variances are refused. + assert!(s.execute("data.analysisToolPak", json!({"tool": "zTest", "range1": "A2:A6", "range2": "B2:B4", "output": "H1"})).is_err()); + let zero = json!({"tool": "zTest", "range1": "A2:A6", "range2": "B2:B4", "variance1": 0, "variance2": 1, "output": "H1"}); + assert!(s.execute("data.analysisToolPak", zero).is_err()); + } + + #[test] + fn fourier_analysis_matches_known_transforms() { + let mut s = s(); + // DFT of 1, 2, 3, 4: 10, −2+2i, −2, −2−2i. + s.execute("range.setValues", json!({"range": "A1", "values": [["Signal"], [1], [2], [3], [4]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Fourier Analysis", "range": "A1:A5", "labels": true, "output": "C1"})).unwrap(); + let col = |s: &Session, c: &str, rows: std::ops::RangeInclusive| rows.map(|r| v(s, &format!("{c}{r}"))).collect::>(); + assert_eq!(col(&s, "C", 1..=5), ["Signal", "10", "-2+2i", "-2", "-2-2i"].map(Value::text).to_vec()); + // The inverse transform of that output returns the signal. + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C2:C5", "inverse": true, "output": "E1"})).unwrap(); + assert_eq!(col(&s, "E", 1..=4), ["1", "2", "3", "4"].map(Value::text).to_vec()); + // cos(2πn/8) over eight points: N/2 = 4 at the first and last frequencies, 0 elsewhere. + let wave: Vec = (0..8).map(|k| json!([(std::f64::consts::PI * k as f64 / 4.0).cos()])).collect(); + s.execute("range.setValues", json!({"range": "G1", "values": wave})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "G1:G8", "output": "H1"})).unwrap(); + assert_eq!(col(&s, "H", 1..=8), ["0", "4", "0", "0", "0", "0", "0", "4"].map(Value::text).to_vec()); + // Complex text input; a single value is its own transform. + s.execute("range.setValues", json!({"range": "J1", "values": [["3+4i"], ["1-i"]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "J1:J2", "output": "K1"})).unwrap(); + assert_eq!(col(&s, "K", 1..=2), ["4+3i", "2+5i"].map(Value::text).to_vec()); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "J1", "output": "L1"})).unwrap(); + assert_eq!(v(&s, "L1"), Value::text("3+4i")); + // Three values are not a power of two; a word is not a number. + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A2:A4", "output": "N1"})).is_err()); + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A4", "output": "N1"})).is_err()); + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A8192", "output": "N1"})).is_err()); + } + + #[test] + fn fourier_analysis_keeps_a_small_imaginary_part_beside_a_large_real_one() { + let mut s = s(); + // With one value the transform is the identity and performs no arithmetic, so no part of + // the output is rounding noise: 1e14 + 1i comes back as 1e14 + 1i, forward and inverse. + s.execute("range.setValues", json!({"range": "A1", "values": [["100000000000000+1i"]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1", "output": "C1"})).unwrap(); + assert_eq!(eval(&mut s, "=IMREAL(C1)"), 1e14); + assert_eq!(eval(&mut s, "=IMAGINARY(C1)"), 1.0); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C1", "inverse": true, "output": "E1"})).unwrap(); + assert_eq!(eval(&mut s, "=IMREAL(E1)"), 1e14); + assert_eq!(eval(&mut s, "=IMAGINARY(E1)"), 1.0); + } + + #[test] + fn fourier_analysis_round_trip_recovers_small_components_beside_a_large_dc() { + let mut s = s(); + // x_n = 1e6 + 1e-7·cos(2πn/8) for n = 0 … 7. The transform of a constant c over N points is + // N·c at k = 0 and 0 elsewhere; the transform of a·cos(2πn/N) is a·N/2 at k = 1 and + // k = N − 1. So X_0 = 8·1e6 = 8e6, X_1 = X_7 = 1e-7·8/2 = 4e-7 and X_2 … X_6 = 0. The inputs + // are stored to within ulp(1e6)/2 ≈ 6e-11 and the first butterfly stage subtracts nearby + // numbers exactly, so the harmonics carry at most about 5e-10 of noise. The cleanup bound + // 8·ε·log2(8)·Σ|x_n| ≈ 8 · 2.2e-16 · 3 · 8e6 ≈ 4.3e-8 zeroes noise of that size and keeps + // 4e-7; a cutoff relative to the largest output (8e6 · 1e-13 = 8e-7) would zero the + // harmonics. + let x = |k: usize| 1e6 + 1e-7 * (std::f64::consts::PI * k as f64 / 4.0).cos(); + let wave: Vec = (0..8).map(|k| json!([x(k)])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": wave})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A8", "output": "C1"})).unwrap(); + assert!(close(eval(&mut s, "=IMREAL(C1)"), 8e6, 1e-6)); + assert_eq!(eval(&mut s, "=IMAGINARY(C1)"), 0.0); + for cell in ["C2", "C8"] { + assert!(close(eval(&mut s, &format!("=IMREAL({cell})")), 4e-7, 5e-9), "{cell}"); + assert_eq!(eval(&mut s, &format!("=IMAGINARY({cell})")), 0.0, "{cell}"); + } + for r in 3..=7 { + assert_eq!(v(&s, &format!("C{r}")), Value::text("0"), "C{r}"); + } + // The inverse of that output returns each x_n to within 2e-9 (2e-15 relative); without the + // harmonics every value would come back as 1e6, off by up to 1e-7. + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C1:C8", "inverse": true, "output": "E1"})).unwrap(); + for k in 0..8 { + let cell = format!("E{}", k + 1); + assert!(close(eval(&mut s, &format!("=IMREAL({cell})")), x(k), 2e-9), "{cell}"); + assert_eq!(eval(&mut s, &format!("=IMAGINARY({cell})")), 0.0, "{cell}"); + } + } + + /// Column `col` of sheet `sheet`, rows 1 to `rows`, as numbers. + fn numbers_of(s: &Session, sheet: &str, col: &str, rows: u32) -> Vec { + (1..=rows).map(|r| n(s, &format!("{sheet}!{col}{r}"))).collect() + } + fn mean_var(x: &[f64]) -> (f64, f64) { + let m = x.iter().sum::() / x.len() as f64; + (m, x.iter().map(|v| (v - m).powi(2)).sum::() / (x.len() - 1) as f64) + } + + #[test] + fn random_numbers_are_seeded_and_follow_their_distributions() { + let mut s = s(); + let rng = |s: &mut Session, sheet: &str, p: Json| { + let mut p = p; + p["tool"] = json!("randomNumberGeneration"); + p["newSheet"] = json!(sheet); + s.execute("data.analysisToolPak", p).unwrap() + }; + // The same seed repeats the numbers; the result reports the seed. + let r = rng(&mut s, "U1", json!({"variables": 2, "count": 2000, "distribution": "uniform", "from": 2, "to": 4, "seed": 42})); + assert_eq!((r["seed"].as_u64(), r["range"].as_str()), (Some(42), Some("A1:B2000"))); + rng(&mut s, "U2", json!({"variables": 2, "count": 2000, "distribution": "uniform", "from": 2, "to": 4, "seed": 42})); + let (a, b) = (numbers_of(&s, "U1", "B", 2000), numbers_of(&s, "U2", "B", 2000)); + assert_eq!(a, b); + assert!(a.iter().all(|x| (2.0..4.0).contains(x))); + // Uniform on [2, 4]: mean 3, variance 1/3. + let (m, var) = mean_var(&a); + assert!((m - 3.0).abs() < 0.05 && (var - 1.0 / 3.0).abs() < 0.03, "{m} {var}"); + let unseeded = rng(&mut s, "U3", json!({"count": 1})); + assert!(unseeded["seed"].as_u64().is_some(), "a seed is chosen and reported"); + // Normal(10, 2): mean 10, variance 4. + rng(&mut s, "N", json!({"count": 20000, "distribution": "normal", "mean": 10, "standardDeviation": 2, "seed": 7})); + let (m, var) = mean_var(&numbers_of(&s, "N", "A", 20000)); + assert!((m - 10.0).abs() < 0.05 && (var - 4.0).abs() < 0.15, "{m} {var}"); + // Binomial(20, 0.3): mean np = 6, variance np(1 − p) = 4.2. + rng(&mut s, "B", json!({"count": 20000, "distribution": "binomial", "p": 0.3, "trials": 20, "seed": 8})); + let x = numbers_of(&s, "B", "A", 20000); + assert!(x.iter().all(|v| v.fract() == 0.0 && (0.0..=20.0).contains(v))); + let (m, var) = mean_var(&x); + assert!((m - 6.0).abs() < 0.08 && (var - 4.2).abs() < 0.2, "{m} {var}"); + // Poisson(3.5): mean and variance 3.5. + rng(&mut s, "P", json!({"count": 20000, "distribution": "poisson", "lambda": 3.5, "seed": 9})); + let (m, var) = mean_var(&numbers_of(&s, "P", "A", 20000)); + assert!((m - 3.5).abs() < 0.08 && (var - 3.5).abs() < 0.2, "{m} {var}"); + // Bernoulli(0.25) and a discrete distribution on {1, 2} with P(2) = 0.75. + rng(&mut s, "Ber", json!({"count": 4000, "distribution": "bernoulli", "p": 0.25, "seed": 10})); + let ones = numbers_of(&s, "Ber", "A", 4000).iter().filter(|v| **v == 1.0).count(); + assert!((900..1100).contains(&ones), "{ones}"); + s.execute("range.setValues", json!({"range": "Sheet1!A1", "values": [[1, 0.25], [2, 0.75]]})).unwrap(); + rng(&mut s, "D", json!({"count": 4000, "distribution": "discrete", "valueRange": "Sheet1!A1:B2", "seed": 11})); + let x = numbers_of(&s, "D", "A", 4000); + assert!(x.iter().all(|v| *v == 1.0 || *v == 2.0)); + let twos = x.iter().filter(|v| **v == 2.0).count(); + assert!((2900..3100).contains(&twos), "{twos}"); + // Patterned: 1 to 3, each number twice, the sequence twice. + rng(&mut s, "Pat", json!({"distribution": "patterned", "from": 1, "to": 3, "step": 1, "repeatEach": 2, "repeatSequence": 2})); + assert_eq!(numbers_of(&s, "Pat", "A", 12), [1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0]); + assert!(v(&s, "Pat!A13").is_empty()); + // Output is bounded; parameters are checked. + for p in [ + json!({"count": 2_000_000}), + json!({"count": 1000, "variables": 2000}), + json!({"count": 0}), + json!({"count": 1.5}), + json!({"distribution": "uniform"}), + json!({"count": 1, "distribution": "bernoulli", "p": 2}), + json!({"count": 1, "distribution": "binomial", "trials": 1e9}), + json!({"count": 1, "distribution": "poisson", "lambda": -1}), + json!({"count": 1, "distribution": "normal", "standardDeviation": -1}), + json!({"count": 1, "distribution": "discrete", "valueRange": "Sheet1!A1:A2"}), + json!({"count": 1, "distribution": "patterned", "from": 1, "to": 1e9, "step": 1}), + json!({"count": 1, "distribution": "patterned", "from": 3, "to": 1}), + json!({"count": 1, "distribution": "weird"}), + json!({"count": 1, "seed": -1}), + json!({"count": 1, "seed": "abc"}), + ] { + let mut q = p.clone(); + q["tool"] = json!("randomNumberGeneration"); + q["output"] = json!("Sheet1!H1"); + assert!(s.execute("data.analysisToolPak", q).is_err(), "{p}"); + } + s.execute("range.setValues", json!({"range": "Sheet1!A1", "values": [[1, 0.5], [2, 0.6]]})).unwrap(); + let p = + json!({"tool": "randomNumberGeneration", "count": 1, "distribution": "discrete", "valueRange": "Sheet1!A1:B2", "output": "Sheet1!H1"}); + assert!(s.execute("data.analysisToolPak", p).is_err(), "probabilities must add up to 1"); + } + + #[test] + fn binomial_and_poisson_tables_agree_with_the_worksheet_functions() { + // The recurrence outward from the mode reproduces BINOM.DIST and POISSON.DIST at every + // tabulated outcome, the table carries the whole distribution, and it is only as wide as + // the outcomes that matter. The worksheet functions themselves are accurate to about + // n · ε for n trials (their logarithms are of that size), hence the moderate n and λ. + let binom = |k: f64, n: f64, p: f64| f64_of(&call("BINOM.DIST", &[Value::Number(k), Value::Number(n), Value::Number(p), Value::Bool(false)])); + for (n, p) in [(20.0f64, 0.3f64), (100.0, 0.5), (50.0, 0.9), (30.0, 0.01), (7.0, 0.999), (1.0, 0.5)] { + let mode = ((n + 1.0) * p).floor().min(n); + let odds = p / (1.0 - p); + let (first, pmf) = pmf_table(n, mode, binom(mode, n, p), |k| (n - k) / (k + 1.0) * odds).unwrap(); + assert!(first >= 0.0 && first + pmf.len() as f64 - 1.0 <= n, "n={n} p={p}: {first} + {}", pmf.len()); + for (i, got) in pmf.iter().enumerate() { + let k = first + i as f64; + let want = binom(k, n, p); + assert!(((got - want) / want).abs() < 1e-12, "n={n} p={p} k={k}: {got} vs {want}"); + } + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-12, "n={n} p={p}"); + } + let poisson = |k: f64, lambda: f64| f64_of(&call("POISSON.DIST", &[Value::Number(k), Value::Number(lambda), Value::Bool(false)])); + for lambda in [0.2f64, 3.5, 50.0] { + let mode = lambda.floor(); + let (first, pmf) = pmf_table(MAX_OUTCOMES, mode, poisson(mode, lambda), |k| lambda / (k + 1.0)).unwrap(); + assert_eq!(first, 0.0); + for (i, got) in pmf.iter().enumerate() { + let want = poisson(i as f64, lambda); + assert!(((got - want) / want).abs() < 1e-12, "lambda={lambda} k={i}: {got} vs {want}"); + } + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-12, "lambda={lambda}"); + } + // Binomial(1e6, 0.5): standard deviation 500, so the terms vanish within about 38 + // standard deviations below the mode and the sum reaches 1 within about 8 above it: + // roughly 23,000 entries starting near 481,000, not 1,000,001 starting at 0. + let (n, p) = (1_000_000.0, 0.5); + let (first, pmf) = pmf_table(n, 500_000.0, binom(500_000.0, n, p), |k| (n - k) / (k + 1.0)).unwrap(); + assert!((470_000.0..=490_000.0).contains(&first) && pmf.len() < 40_000, "{first} + {}", pmf.len()); + // The anchor BINOM.DIST(500000, 1e6, 0.5) carries that function's error of about n · ε + // (its logarithms are near 7e5), which scales the whole table; draws divide by the total. + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-8); + // A bad anchor or mode is refused rather than tabulated. + assert!(pmf_table(10.0, 5.0, f64::NAN, |_| 1.0).is_err()); + assert!(pmf_table(10.0, 5.0, 0.0, |_| 1.0).is_err()); + assert!(pmf_table(10.0, 11.0, 0.5, |_| 1.0).is_err()); + } + + #[test] + #[allow(clippy::disallowed_methods)] // a native-only timing test: the clock is read off wasm + fn binomial_and_poisson_draws_at_the_limits_are_tabulated_quickly() { + let mut s = s(); + // The tables cover the outcomes around the mode, not every one of the 1,000,001 for a + // million trials, so the largest inputs cost milliseconds. Binomial(1e6, 0.5) has mean + // 500000 and standard deviation 500: 1000 draws put the sample mean within 500/√1000 ≈ 16 + // of it, so 100 is six standard errors. Poisson(1e5) has mean 1e5 and standard deviation + // 316: 1000 draws put the mean within 10, so 60 is six standard errors. With p = 1 every + // draw is exactly 1e6, with p = 0 exactly 0. + let mut draw = |sheet: &str, dist: Json| { + let mut dist = dist; + dist["tool"] = json!("randomNumberGeneration"); + dist["count"] = json!(1000); + dist["seed"] = json!(3); + dist["newSheet"] = json!(sheet); + s.execute("data.analysisToolPak", dist).unwrap(); + }; + let start = std::time::Instant::now(); + draw("Half", json!({"distribution": "binomial", "p": 0.5, "trials": 1_000_000})); + draw("Sure", json!({"distribution": "binomial", "p": 1, "trials": 1_000_000})); + draw("Never", json!({"distribution": "binomial", "p": 0, "trials": 1_000_000})); + draw("Pois", json!({"distribution": "poisson", "lambda": 100_000})); + let elapsed = start.elapsed(); + let (m, _) = mean_var(&numbers_of(&s, "Half", "A", 1000)); + assert!((m - 500_000.0).abs() < 100.0, "{m}"); + assert!(numbers_of(&s, "Sure", "A", 1000).iter().all(|v| *v == 1_000_000.0)); + assert!(numbers_of(&s, "Never", "A", 1000).iter().all(|v| *v == 0.0)); + let (m, _) = mean_var(&numbers_of(&s, "Pois", "A", 1000)); + assert!((m - 100_000.0).abs() < 60.0, "{m}"); + assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}"); + } + + #[test] + fn sampling_periodic_and_random() { + let mut s = s(); + let values: Vec = (1..=10).map(|k| json!([k])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Sampling", "range": "A1:A10", "period": 3, "output": "C1"})).unwrap(); + assert_eq!(numbers_of(&s, "Sheet1", "C", 3), [3.0, 6.0, 9.0]); + assert!(v(&s, "C4").is_empty()); + let r = s + .execute( + "data.analysisToolPak", + json!({"tool": "sampling", "range": "A1:A10", "method": "random", "samples": 20, "seed": 5, "output": "D1"}), + ) + .unwrap(); + assert_eq!(r["seed"], 5); + s.execute( + "data.analysisToolPak", + json!({"tool": "sampling", "range": "A1:A10", "method": "random", "samples": 20, "seed": 5, "output": "E1"}), + ) + .unwrap(); + let (a, b) = (numbers_of(&s, "Sheet1", "D", 20), numbers_of(&s, "Sheet1", "E", 20)); + assert_eq!(a, b, "the same seed repeats the sample"); + assert!(a.iter().all(|x| x.fract() == 0.0 && (1.0..=10.0).contains(x))); + for p in [ + json!({"range": "A1:A10", "period": 11}), + json!({"range": "A1:A10", "period": 0}), + json!({"range": "A1:A10"}), + json!({"range": "A1:A10", "method": "random", "samples": 2_000_000}), + json!({"range": "B1:B10", "period": 1}), + ] { + let mut q = p.clone(); + q["tool"] = json!("sampling"); + q["output"] = json!("G1"); + assert!(s.execute("data.analysisToolPak", q).is_err(), "{p}"); + } + } + + #[test] + fn options_typed_as_text_that_is_not_a_number_are_refused() { + // A form sends its options as text; one that doesn't read as a number (a decimal comma, + // a typo) is an error, not the default, while a blank option takes the default. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2], [2, 4], [3, 6]]})).unwrap(); + let rng = |dist: &str| json!({"tool": "randomNumberGeneration", "count": 3, "distribution": dist, "seed": 1, "outputTo": "newSheet"}); + let z = json!({"tool": "zTest", "range1": "Sheet1!A1:A3", "range2": "Sheet1!B1:B3", "variance1": 1, "variance2": 4, "outputTo": "newSheet"}); + let with = |base: &Json, key: &str, val: &str| { + let mut p = base.clone(); + p[key] = json!(val); + p + }; + let cases = [ + (rng("uniform"), "from"), + (rng("uniform"), "to"), + (rng("normal"), "mean"), + (rng("normal"), "standardDeviation"), + (rng("bernoulli"), "p"), + (rng("binomial"), "p"), + (rng("poisson"), "lambda"), + (rng("patterned"), "step"), + (rng("uniform"), "variables"), + (z.clone(), "hypothesizedDifference"), + ]; + for (base, key) in cases { + let e = s.execute("data.analysisToolPak", with(&base, key, "0,3")).unwrap_err().to_string(); + assert!(e.contains(key), "{key}: {e}"); + s.execute("data.analysisToolPak", with(&base, key, " ")).unwrap_or_else(|e| panic!("{key} blank: {e}")); + } + } + + #[test] + fn an_alpha_that_is_not_a_number_is_refused() { + // A decimal comma or a typo in Alpha must not run the test at 0.05 without a word. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["", "c1", "c2"], ["r1", 1, 2], ["r1", 2, 4], ["r2", 3, 6], ["r2", 5, 9]]})) + .unwrap(); + for base in [ + json!({"tool": "zTest", "range1": "Sheet1!B2:B5", "range2": "Sheet1!C2:C5", "variance1": 1, "variance2": 4}), + json!({"tool": "anovaTwoFactorWithout", "range": "Sheet1!B2:C5"}), + json!({"tool": "anovaTwoFactorWith", "range": "Sheet1!A1:C5", "rowsPerSample": 2}), + json!({"tool": "tTestEqual", "range1": "Sheet1!B2:B5", "range2": "Sheet1!C2:C5"}), + ] { + let mut p = base.clone(); + p["alpha"] = json!("0,01"); + let e = s.execute("data.analysisToolPak", p).unwrap_err().to_string(); + assert!(e.contains("alpha"), "{base}: {e}"); + let mut p = base.clone(); + p["alpha"] = json!(""); + s.execute("data.analysisToolPak", p).unwrap_or_else(|e| panic!("{base} blank alpha: {e}")); + } + } + + #[test] + fn a_patterned_sequence_ignores_the_seed() { + // Patterned generation draws nothing, so a seed left in the form (even one that isn't a + // number) neither blocks the run nor shows up in the result. + let mut s = s(); + for seed in [json!("abc"), json!(7)] { + let r = s + .execute( + "data.analysisToolPak", + json!({"tool": "randomNumberGeneration", "distribution": "patterned", "from": 1, "to": 3, "seed": seed, "outputTo": "newSheet"}), + ) + .unwrap_or_else(|e| panic!("seed {seed}: {e}")); + assert!(r.get("seed").is_none(), "seed {seed}: {r}"); + } + // A random distribution still refuses the bad seed. + let bad = json!({"tool": "randomNumberGeneration", "distribution": "uniform", "count": 2, "seed": "abc", "outputTo": "newSheet"}); + assert!(s.execute("data.analysisToolPak", bad).is_err()); + } + #[test] fn hostile_inputs_are_refused_without_panicking() { let mut s = s(); @@ -1399,6 +2570,11 @@ mod tests { json!({"tool": "anovaSingle", "range": "A1:A2"}), json!({"tool": "correlation", "range": "A1:B2", "alpha": "x", "groupedBy": 5}), json!({"tool": "descriptive", "range": "A1:A2", "confidence": 250}), + json!({"tool": "anovaTwoFactorWithout", "range": "A1:B2"}), + json!({"tool": "anovaTwoFactorWithout", "range": "A1:A2"}), + json!({"tool": "anovaTwoFactorWith", "range": "A1:B2", "rowsPerSample": 2}), + json!({"tool": "anovaTwoFactorWith", "range": "A1:B2", "rowsPerSample": 1e300}), + json!({"tool": "zTest", "range1": "A1", "range2": "A2", "variance1": "x", "variance2": -1}), ] { assert!(s.execute("data.analysisToolPak", p.clone()).is_err(), "{p}"); } diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index fcab9db713..0906f48937 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -4,13 +4,37 @@ use std::cmp::Ordering; use std::sync::Arc; use gridcraft_core::{CellRef, RangeRef, Value, sort_compare}; -use gridcraft_model::*; +use gridcraft_model::{ + Anchor, AnchorMode, AutoFilter, Cell, CfOperator, Comment, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo, Sheet, Validation, + ValidationKind, Workbook, +}; use serde_json::{Value as Json, json}; -use super::*; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_param, cell_param, cell_param_on, cmd, edit, has_doc, ok, parse_lines, split_sheet, + str_param, target_range, target_ranges, target_sheet, +}; use crate::outline; use crate::selection::current_region; +mod filter; +mod grouping; +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}; +use grouping::{detail, group, outline_settings, show_levels, subtotal}; +use sort::{quick_sort, sort}; +#[cfg(test)] +use tools::split_delimited; +use tools::{remove_duplicates, text_to_columns}; +pub use validation::{check_validation, list_items}; +use validation::{circle_invalid, validate_cmd, validation}; +pub(super) use validation::{move_rule_formula, remove_validation_cells}; + pub fn specs() -> Vec { vec![ cmd!("data.sortAscending", "Sort A to Z", ["Data", "Sort & Filter"], None, "{range?, column?: \"B\"}", has_doc, |s, p| quick_sort( @@ -75,18 +99,30 @@ pub fn specs() -> Vec { ), cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd), cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → invalid cells", has_doc, circle_invalid), - cmd!( - "data.group", - "Group", - ["Data", "Outline"], - Some("Alt+Shift+Right"), - "{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default), sheet?}", - has_doc, - |s, p| group(s, p, true) - ), - cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Alt+Shift+Left"), "{rows? | cols? | by?: rows|cols, sheet?}", has_doc, |s, p| { - group(s, p, false) - }), + CommandSpec { + shortcut_mac: Some("Cmd+Shift+K"), + ..cmd!( + "data.group", + "Group", + ["Data", "Outline"], + Some("Alt+Shift+Right"), + "{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default), sheet?}", + has_doc, + |s, p| group(s, p, true) + ) + }, + CommandSpec { + shortcut_mac: Some("Cmd+Shift+J"), + ..cmd!( + "data.ungroup", + "Ungroup", + ["Data", "Outline"], + Some("Alt+Shift+Left"), + "{rows? | cols? | by?: rows|cols, sheet?}", + has_doc, + |s, p| { group(s, p, false) } + ) + }, cmd!( "data.hideDetail", "Hide Detail", @@ -200,1893 +236,5 @@ fn guess_header(wb: &Workbook, sh: &Sheet, r: RangeRef) -> bool { votes > 0 } -#[derive(Clone)] -struct SortKey { - col: u32, - desc: bool, - by: String, - list: Option>, -} - -/// The sheet and range a sort works on: the sheet `sheet` or a `Sheet!` prefix on `range` names, -/// else the active one. The selection belongs to the active sheet, so another sheet needs `range`. -fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> { - let sheet = target_sheet(s, p)?; - let d = s.doc()?; - if let Some(t) = str_param(p, "range") - && let (Some(name), _) = split_sheet(t) - && d.wb.sheet_index(&name) != Some(sheet) - { - return Err(bad("data.sort", format!("`{t}` names a sheet other than `sheet`"))); - } - if sheet != d.wb.active_sheet() && p.get("range").is_none() { - return Err(bad("data.sort", "missing `range`: the selection is on the active sheet")); - } - Ok((sheet, data_range(s, p)?)) -} - -fn quick_sort(s: &mut Session, p: &Json, asc: bool) -> Result { - let (sheet, r) = sort_target(s, p)?; - let col = col_param(p.get("column"), r.start.col).unwrap_or(s.doc()?.selection.active.col).clamp(r.start.col, r.end.col); - let d = s.doc()?; - let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; - let header = guess_header(&d.wb, sh, r); - do_sort(s, sheet, r, header, vec![SortKey { col, desc: !asc, by: "values".into(), list: None }], false, false) -} - -fn sort(s: &mut Session, p: &Json) -> Result { - let (sheet, r) = sort_target(s, p)?; - let d = s.doc()?; - let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; - let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r)); - let by_cols = str_param(p, "orientation") == Some("columns"); - let case = bool_param(p, "matchCase").unwrap_or(false); - let mut keys: Vec = Vec::new(); - for k in p.get("keys").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default() { - let col = if by_cols { - let row = match k.get("row").and_then(Json::as_u64) { - // Worksheet rows are 1-based; 0 (or a value past u32) has no coordinate. - Some(n) => { - let row = u32::try_from(n).ok().and_then(|n| n.checked_sub(1)); - Some(row.ok_or_else(|| bad("data.sort", "sort key row must be 1 or greater"))?) - } - None => None, - }; - row.or_else(|| col_param(k.get("column"), r.start.row)) - } else { - col_param(k.get("column"), r.start.col) - }; - let Some(col) = col else { continue }; - keys.push(SortKey { - col, - desc: k.get("order").and_then(Json::as_str) == Some("desc"), - by: k.get("by").and_then(Json::as_str).unwrap_or("values").to_string(), - list: k.get("customList").and_then(Json::as_array).map(|l| l.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()), - }); - } - if keys.is_empty() { - s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header}))); - return ok(); - } - if keys.len() > 64 { - return Err(bad("data.sort", "too many sort levels (64 max)")); - } - do_sort(s, sheet, r, header, keys, by_cols, case) -} - -fn do_sort(s: &mut Session, sheet: usize, r: RangeRef, header: bool, keys: Vec, by_cols: bool, case: bool) -> Result { - // Protect Sheet ▸ Sort. Both Sort… and the A-to-Z buttons come through here. - super::refuse_unless_allowed(s, sheet, "Sorting", |p| p.sort)?; - let body = if by_cols { - if header && r.width() > 1 { RangeRef::new(CellRef::new(r.start.row, r.start.col + 1), r.end) } else { r } - } else if header && r.height() > 1 { - RangeRef::new(CellRef::new(r.start.row + 1, r.start.col), r.end) - } else { - r - }; - if body.count() > 20_000_000 { - return Err(bad("data.sort", "range too large")); - } - edit(s, |cx| { - let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) }; - if sh.merges.iter().any(|m| m.intersects(&body) && !m.is_single()) { - return Err(EngineError::Other("To do this, all the merged cells need to be the same size.".into())); - } - let n = if by_cols { body.width() } else { body.height() }; - let line = |i: u32, k: u32| if by_cols { CellRef::new(k, body.start.col + i) } else { CellRef::new(body.start.row + i, k) }; - let theme = cx.wb.theme.clone(); - let styles = &cx.wb.styles; - let key_val = |i: u32, k: &SortKey| -> (Value, u32) { - let c = line(i, k.col); - let v = sh.value(c); - let color = match k.by.as_str() { - "cellColor" => { - styles.get(sh.style_id(c)).fill.fg.resolve(&theme).map(|[r, g, b]| u32::from_be_bytes([0, r, g, b])).unwrap_or(u32::MAX) - } - "fontColor" => { - styles.get(sh.style_id(c)).font.color.resolve(&theme).map(|[r, g, b]| u32::from_be_bytes([0, r, g, b])).unwrap_or(u32::MAX) - } - _ => 0, - }; - (v, color) - }; - let mut order: Vec = (0..n).collect(); - let keyed: Vec> = (0..n).map(|i| keys.iter().map(|k| key_val(i, k)).collect()).collect(); - order.sort_by(|&a, &b| { - for (ki, k) in keys.iter().enumerate() { - let (va, ca) = &keyed[a as usize][ki]; - let (vb, cb) = &keyed[b as usize][ki]; - let o = if k.by != "values" { - ca.cmp(cb) - } else if let Some(list) = &k.list { - let pos = |v: &Value| v.as_text().and_then(|t| list.iter().position(|x| x.eq_ignore_ascii_case(t))).unwrap_or(usize::MAX); - pos(va).cmp(&pos(vb)) - } else if case && va.is_text() && vb.is_text() { - sort_compare(va, vb).then_with(|| case_order(va.as_text().unwrap_or(""), vb.as_text().unwrap_or(""))) - } else { - sort_compare(va, vb) - }; - // Blanks always sort last, whatever the order. - let o = if k.desc && !(va.is_empty() || vb.is_empty()) { o.reverse() } else { o }; - if o != Ordering::Equal { - return o; - } - } - Ordering::Equal - }); - if order.iter().enumerate().all(|(i, &o)| i as u32 == o) { - return Ok(Json::Null); - } - // Move whole lines (cells with formulas adjusted for relative references). - let lanes: Vec = if by_cols { (body.start.row..=body.end.row).collect() } else { (body.start.col..=body.end.col).collect() }; - // Notes and hyperlinks hang off a cell, not a row, so they travel with the row they - // describe — the way cell pictures and row heights do. Collect them before inserting, - // so a swap can't resurrect one from a destination that is also a source. - let side: Vec<(CellRef, Comment)> = order - .iter() - .enumerate() - .flat_map(|(dst_i, &src_i)| lanes.iter().map(move |&k| (src_i, dst_i as u32, k))) - .filter_map(|(src_i, dst_i, k)| sh.comments.get(&line(src_i, k)).map(|cm| (line(dst_i, k), cm.clone()))) - .collect(); - let links: Vec<(CellRef, Hyperlink)> = order - .iter() - .enumerate() - .flat_map(|(dst_i, &src_i)| lanes.iter().map(move |&k| (src_i, dst_i as u32, k))) - .filter_map(|(src_i, dst_i, k)| sh.hyperlinks.get(&line(src_i, k)).map(|h| (line(dst_i, k), h.clone()))) - .collect(); - let mut moved: Vec<(CellRef, Option)> = Vec::with_capacity(body.count() as usize); - let mut pictures = Vec::new(); - for (dst_i, &src_i) in order.iter().enumerate() { - for &k in &lanes { - let src = line(src_i, k); - let dst = line(dst_i as u32, k); - let mut cell = sh.cell(src).cloned(); - if let Some(c) = cell.as_mut() - && let Some(f) = &c.formula - && let Some(e) = f.expr() - { - let shifted = gridcraft_formula::adjust::shift_relative(e, dst.row as i64 - src.row as i64, dst.col as i64 - src.col as i64); - c.formula = Some(Arc::new(Formula::from_expr(shifted))); - } - if let Some(picture) = sh.cell_pictures.get(&src) { - pictures.push((dst, picture.clone())); - } - moved.push((dst, cell)); - } - } - // Row heights travel with rows. - let heights: Vec> = - if by_cols { vec![] } else { order.iter().map(|&i| sh.rows.get(&(body.start.row + i)).copied()).collect() }; - // Floating objects anchored inside the sorted body travel with their lines, unless they - // are pinned absolutely ("Don't move or size with cells", `editAs="absolute"`). Reordering - // is the inverse of `order`: `dst_of[src] = dst`. - let dst_of: Vec = { - let mut v = vec![0u32; order.len()]; - for (dst_i, &src_i) in order.iter().enumerate() { - if let Some(slot) = v.get_mut(src_i as usize) { - *slot = dst_i as u32; - } - } - v - }; - // The object's own geometry (its top-left anchor cell, offset and size) is read from the - // pre-sort `sh`; a two-cell object's bottom-right cell is derived from its size here so it - // can be re-fitted to the lines it spans after the sort. - let objs: Vec = - sh.images.iter().map(|o| o.anchor).chain(sh.charts.iter().map(|o| o.anchor)).chain(sh.shapes.iter().map(|o| o.anchor)).collect(); - let descs: Vec<(u32, u32, f32, f32)> = objs - .iter() - .map(|a| { - let x2 = sh.col_left(a.cell.col) + a.dx as f64 + a.width.max(0.0) as f64; - let y2 = sh.row_top(a.cell.row) + a.dy as f64 + a.height.max(0.0) as f64; - let tc = sh.col_at(x2); - let tr = sh.row_at(y2); - (tc, tr, (x2 - sh.col_left(tc)) as f32, (y2 - sh.row_top(tr)) as f32) - }) - .collect(); - let shm = cx.sheet_mut(sheet)?; - for (c, cell) in &moved { - match cell { - Some(x) => shm.set_cell(*c, x.clone()), - None => { - shm.remove_cell(*c); - } - } - } - // Every cell of the body is the destination of exactly one source cell, so clearing the - // body and inserting the permuted entries is the same permutation the cells went through. - for c in body.iter() { - shm.comments.remove(&c); - shm.hyperlinks.remove(&c); - } - for (at, cm) in side { - shm.comments.insert(at, cm); - } - for (at, h) in links { - shm.hyperlinks.insert(at, h); - } - shm.cell_pictures.extend(pictures); - for (i, h) in heights.into_iter().enumerate() { - let row = body.start.row + i as u32; - match h { - Some(info) => { - shm.rows.insert(row, LineInfo { hidden: shm.rows.get(&row).is_some_and(|x| x.hidden), ..info }); - } - None => { - if let Some(e) = shm.rows.get_mut(&row) { - e.size = None; - } - } - } - } - // Re-anchor floating objects now that the row heights are final. `objs` was collected as - // images ++ charts ++ shapes, so the same index maps straight onto each vec. - // Only objects anchored inside the sorted block move: within its lines on the sort axis - // and within its span on the other axis (a picture beside the block stays put). - let (b0, b1) = if by_cols { (body.start.col, body.end.col) } else { (body.start.row, body.end.row) }; - let (o0, o1) = if by_cols { (body.start.row, body.end.row) } else { (body.start.col, body.end.col) }; - let ni = shm.images.len(); - let nch = shm.charts.len(); - for (i, (a, desc)) in objs.into_iter().zip(descs).enumerate() { - let other = if by_cols { a.cell.row } else { a.cell.col }; - if other < o0 || other > o1 { - continue; - } - let na = sorted_anchor(shm, a, desc, by_cols, b0, b1, &dst_of); - if na != a { - if i < ni { - if let Some(o) = shm.images.get_mut(i) { - o.anchor = na; - } - } else if i < ni + nch { - if let Some(o) = shm.charts.get_mut(i - ni) { - o.anchor = na; - } - } else if let Some(o) = shm.shapes.get_mut(i - ni - nch) { - o.anchor = na; - } - } - } - for (c, _) in moved { - cx.changed.push((sheet, c)); - } - cx.structural = true; - Ok(Json::Null) - })?; - Ok(json!({"sorted": body.a1()})) -} - -/// Re-anchor one floating object for a sort. `bottom` is the object's bottom-right line and the -/// offset of that corner inside it, measured before the sort. `map` (via `dst_of`) translates a -/// line index on the moving axis and is the identity outside `b0..=b1`. `sh` is the post-sort -/// grid (row heights already reordered), so re-fitting uses the heights the object lands on. -/// Objects pinned absolutely ("Don't move or size with cells") never move; "move but don't size" -/// keeps its size; "move and size" is re-fitted when its whole extent stays inside the body. -fn sorted_anchor(sh: &Sheet, a: Anchor, bottom: (u32, u32, f32, f32), by_cols: bool, b0: u32, b1: u32, dst_of: &[u32]) -> Anchor { - if a.mode == AnchorMode::Absolute { - return a; - } - let (tc, tr, tdx, tdy) = bottom; - let map = |v: u32| -> u32 { if v >= b0 && v <= b1 { dst_of.get((v - b0) as usize).map_or(v, |&d| b0 + d) } else { v } }; - let (axis_start, axis_end) = if by_cols { (a.cell.col, tc) } else { (a.cell.row, tr) }; - if axis_start < b0 || axis_start > b1 { - return a; - } - let (nr, nc) = if by_cols { (a.cell.row, map(a.cell.col)) } else { (map(a.cell.row), a.cell.col) }; - if a.mode == AnchorMode::MoveAndSize && axis_end >= b0 && axis_end <= b1 { - let (nbr, nbc) = if by_cols { (tr, map(tc)) } else { (map(tr), tc) }; - let x1 = sh.col_left(nc) + a.dx as f64; - let y1 = sh.row_top(nr) + a.dy as f64; - let x2 = sh.col_left(nbc) + tdx as f64; - let y2 = sh.row_top(nbr) + tdy as f64; - Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode: a.mode } - } else { - Anchor { cell: CellRef::new(nr, nc), ..a } - } -} - -// ---------------------------------------------------------------- filter - -fn toggle_filter(s: &mut Session, p: &Json) -> Result { - let (sheet, r) = data_target(s, p, "data.filter")?; - super::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?; - // The active cell belongs to the active sheet: on another sheet the table is the one at `range`. - let at = if sheet == s.doc()?.wb.active_sheet() { s.doc()?.selection.active } else { r.start }; - 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 { - return edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - 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(); - } - } - Ok(Json::Null) - }); - } - if has { - return edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - // Reveal only rows the filter hid; rows hidden by hand or by a collapsed group stay hidden. - let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); - sh.autofilter = None; - for r in filtered { - if let Some(info) = sh.rows.get_mut(&r) { - info.hidden = false; - } - } - cx.structural = true; - Ok(json!({"filter": false})) - }); - } - install_filter(s, p) -} - -/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection. -fn install_filter(s: &mut Session, p: &Json) -> Result { - let (sheet, mut r) = data_target(s, p, "data.filter")?; - // A selected header row filters the data below it (#201). - if p.get("range").is_none() && r.height() == 1 { - let d = s.doc()?; - let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let below = current_region(sh, r.start).end.row; - if below > r.end.row { - r = RangeRef::new(r.start, CellRef::new(below, r.end.col)); - } - } - edit(s, |cx| { - cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] }); - Ok(json!({"filter": true, "range": r.a1()})) - }) -} - -fn filter_by(s: &mut Session, p: &Json) -> Result { - let sheet = s.doc()?.wb.active_sheet(); - super::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?; - let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; - let af = match &sh.autofilter { - Some(a) => a.clone(), - None => { - install_filter(s, &json!({}))?; - s.doc()?.wb.sheet(sheet).and_then(|sh| sh.autofilter.clone()).ok_or_else(|| EngineError::Other("no filter".into()))? - } - }; - let col = match col_param(p.get("column"), af.range.start.col) { - Some(c) => c, - // A number too large to be a column is outside the filter range, not a missing parameter. - None if p.get("column").is_some_and(|v| v.as_u64().is_some()) => return Err(bad("data.filterBy", "column outside the filter range")), - None => return Err(bad("data.filterBy", "missing `column`")), - }; - if col < af.range.start.col || col > af.range.end.col { - return Err(bad("data.filterBy", "column outside the filter range")); - } - let off = col - af.range.start.col; - let crit = if bool_param(p, "clear").unwrap_or(false) { - None - } else if let Some(vals) = p.get("values").and_then(Json::as_array) { - Some(FilterCriterion::Values { - values: vals.iter().map(super::edit::json_to_input).collect(), - blanks: bool_param(p, "blanks").unwrap_or(false), - }) - } else if let Some(c) = p.get("custom") { - let a = (c.get("op").and_then(Json::as_str).unwrap_or("=").to_string(), c.get("value").map(super::edit::json_to_input).unwrap_or_default()); - let b = c.get("op2").and_then(Json::as_str).map(|o| (o.to_string(), c.get("value2").map(super::edit::json_to_input).unwrap_or_default())); - Some(FilterCriterion::Custom { a, b, and: c.get("and").and_then(Json::as_bool).unwrap_or(true) }) - } else if let Some(t) = p.get("top") { - Some(FilterCriterion::Top10 { - bottom: t.get("bottom").and_then(Json::as_bool).unwrap_or(false), - percent: t.get("percent").and_then(Json::as_bool).unwrap_or(false), - count: t.get("count").and_then(Json::as_u64).unwrap_or(10) as u32, - }) - } else { - bool_param(p, "aboveAverage").map(FilterCriterion::AboveAverage) - }; - edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - if let Some(a) = sh.autofilter.as_mut() { - a.criteria.retain(|(o, _)| *o != off); - if let Some(c) = crit.clone() { - a.criteria.push((off, c)); - } - } - apply_filter(&mut cx.wb, sheet); - cx.structural = true; - Ok(Json::Null) - })?; - let hidden = s.doc()?.wb.sheet(sheet).map(|sh| sh.rows.values().filter(|r| r.hidden).count()).unwrap_or(0); - Ok(json!({"hiddenRows": hidden})) -} - -/// Does a value pass a custom comparison (`>`, `=*abc*`, `<>x`…)? -fn custom_ok(v: &Value, text: &str, op: &str, crit: &str) -> bool { - let num = gridcraft_core::parse::parse_number_text(crit); - let cmp = match (v.as_f64(), num) { - (Some(a), Some(b)) => a.partial_cmp(&b), - // A numeric ordering comparison only matches numbers; blanks and text never do. - (None, Some(_)) if matches!(op, "<" | "<=" | ">" | ">=") => None, - _ => Some(gridcraft_core::compare_text(text, crit)), - }; - let wild = || super::edit::wildcard(&text.to_lowercase(), &crit.to_lowercase()); - match op { - "=" => { - if crit.contains(['*', '?']) { - wild() - } else { - cmp == Some(Ordering::Equal) - } - } - "<>" => { - if crit.contains(['*', '?']) { - !wild() - } else { - cmp != Some(Ordering::Equal) - } - } - ">" => cmp == Some(Ordering::Greater), - "<" => cmp == Some(Ordering::Less), - ">=" => matches!(cmp, Some(Ordering::Greater | Ordering::Equal)), - "<=" => matches!(cmp, Some(Ordering::Less | Ordering::Equal)), - "beginsWith" => text.to_lowercase().starts_with(&crit.to_lowercase()), - "endsWith" => text.to_lowercase().ends_with(&crit.to_lowercase()), - "contains" => text.to_lowercase().contains(&crit.to_lowercase()), - "notContains" => !text.to_lowercase().contains(&crit.to_lowercase()), - _ => true, - } -} - -/// The filter's "(Blanks)" group: truly empty cells and zero-length text such as a `=""` result. -fn filter_blank(v: &Value) -> bool { - v.is_empty() || matches!(v, Value::Text(t) if t.is_empty()) -} - -/// Excel grows an AutoFilter range when a value is entered in the row right below it, in one of its columns (#2342). -/// A table's own filter is left to the table, and a row typed after a blank row does not count. -/// A formula counts before it is calculated: this runs inside the edit, ahead of the recalc. -pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { - if !sh.cells.get(at).is_some_and(|c| !filter_blank(&c.value) || c.formula.is_some()) { - return; - } - let Some(af) = sh.autofilter.as_ref() else { return }; - let r = af.range; - if r.end.row.checked_add(1) != Some(at.row) || at.col < r.start.col || at.col > r.end.col || sh.tables.iter().any(|t| t.range == r) { - return; - } - let grown = RangeRef::new(r.start, CellRef::new(at.row, r.end.col)); - if let Some(af) = sh.autofilter.as_mut() { - af.range = grown; - } -} - -/// 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 }; - let r = af.range; - let mut hide = Vec::new(); - // Precompute per-criterion top10 threshold and average once, not per row. - let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); - for (i, (off, c)) in af.criteria.iter().enumerate() { - if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { - let col = r.start.col + off; - let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); - let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::() / nums.len() as f64 }; - let thr = match c { - FilterCriterion::Top10 { bottom, percent, count } => { - nums.sort_by(|a, b| if *bottom { a.partial_cmp(b) } else { b.partial_cmp(a) }.unwrap_or(Ordering::Equal)); - let k = if *percent { ((nums.len() as f64) * (*count as f64) / 100.0).ceil() as usize } else { *count as usize }; - let k = k.clamp(1, nums.len().max(1)); - nums.get(k - 1).copied() - } - _ => None, - }; - col_stats.insert(i, (thr, avg)); - } - } - for row in r.start.row + 1..=r.end.row { - let mut visible = true; - for (i, (off, crit)) in af.criteria.iter().enumerate() { - let c = CellRef::new(row, r.start.col + off); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { - if filter_blank(&v) { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) - } - } - FilterCriterion::Custom { a, b, and } => { - let x = custom_ok(&v, &text, &a.0, &a.1); - match b { - Some(b) => { - let y = custom_ok(&v, &text, &b.0, &b.1); - if *and { x && y } else { x || y } - } - None => x, - } - } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((thr, _))) => { - let thr = thr.unwrap_or(n); - if *bottom { n <= thr } else { n >= thr } - } - _ => false, - }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((_, avg))) => { - if *above { - n > *avg - } else { - n < *avg - } - } - _ => false, - }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, - // Icons are not evaluated here: the row keeps its current visibility. - FilterCriterion::Icon { .. } => !sh.is_row_hidden(row), - }; - if !ok { - visible = false; - break; - } - } - hide.push((row, !visible)); - } - let Some(shm) = wb.sheet_mut(sheet) else { return }; - for (row, h) in hide { - if h { - shm.rows.entry(row).or_default().hidden = true; - } else if let Some(e) = shm.rows.get_mut(&row) { - e.hidden = false; - } - } -} - -fn clear_filter(s: &mut Session, _: &Json) -> Result { - let sheet = s.doc()?.wb.active_sheet(); - edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - if let Some(a) = sh.autofilter.as_mut() { - a.criteria.clear(); - } - apply_filter(&mut cx.wb, sheet); - cx.structural = true; - Ok(Json::Null) - }) -} - -fn reapply(s: &mut Session, _: &Json) -> Result { - let sheet = s.doc()?.wb.active_sheet(); - edit(s, |cx| { - apply_filter(&mut cx.wb, sheet); - cx.structural = true; - Ok(Json::Null) - }) -} - -/// Distinct display values of a filter column (for the dropdown list). -pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> { - let Some(sh) = wb.sheet(sheet) else { return vec![] }; - let Some(af) = &sh.autofilter else { return vec![] }; - let off = col.saturating_sub(af.range.start.col); - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); - let mut seen = std::collections::BTreeMap::new(); - for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) { - let c = CellRef::new(row, col); - let v = sh.value(c); - let blank = filter_blank(&v); - let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; - let on = match selected { - Some(FilterCriterion::Values { values, blanks }) => { - if blank { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&t)) - } - } - _ => true, - }; - let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; - seen.entry((key, t)).or_insert(on); - } - seen.into_iter().map(|((_, t), on)| (t, on)).collect() -} - -/// Case-sensitive tie-break for text that is equal ignoring case: as in Excel, lowercase sorts -/// before uppercase at the first letter that differs in case. -fn case_order(a: &str, b: &str) -> Ordering { - a.chars().zip(b.chars()).find(|(x, y)| x != y).map_or(Ordering::Equal, |(x, y)| y.is_lowercase().cmp(&x.is_lowercase())) -} - -fn sort_key(v: &Value) -> (u8, i64, String) { - match v { - Value::Number(n) => (0, (n * 1e6) as i64, String::new()), - Value::Text(t) => (1, 0, t.to_lowercase()), - Value::Bool(b) => (2, *b as i64, String::new()), - Value::Empty => (9, 0, String::new()), - _ => (3, 0, v.display()), - } -} - -// ---------------------------------------------------------------- tools - -fn remove_duplicates(s: &mut Session, p: &Json) -> Result { - let (sheet, r) = data_target(s, p, "data.removeDuplicates")?; - let d = s.doc()?; - let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; - // Rows and columns past the data are blank: only the part with data is compared (whole - // columns compared a million blank rows and reported them as removed duplicates). - let r = sh.used_range().and_then(|u| r.intersection(&u)).unwrap_or(RangeRef::cell(r.start)); - let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r)); - let cols: Vec = p - .get("columns") - .and_then(Json::as_array) - .map(|a| a.iter().filter_map(|c| col_param(Some(c), r.start.col)).collect()) - .unwrap_or_else(|| (r.start.col..=r.end.col).collect()); - // With no column to compare, every row key is empty: the first row would survive and every - // other row would be deleted as a duplicate. A column outside the range compares data the - // user didn't select. Excel refuses both. - if cols.is_empty() || cols.iter().any(|c| !(r.start.col..=r.end.col).contains(c)) { - return Err(bad("data.removeDuplicates", "`columns` must name at least one column of the range")); - } - let start = r.start.row + header as u32; - let mut removed = 0; - edit(s, |cx| { - let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; - let mut seen = std::collections::HashSet::new(); - let mut keep: Vec = Vec::new(); - // Cells are compared by the text they show, as in Excel: the same date in two formats - // isn't a duplicate, while 1.01 and 1.02 shown as 1.0 are. - let shown = |c: CellRef| crate::display::format(&sh.value(c), cx.wb.styles.get(sh.style_id(c)).num_fmt.as_str(), &cx.wb).text; - for row in start..=r.end.row { - let key: Vec = cols.iter().map(|c| shown(CellRef::new(row, *c)).to_lowercase()).collect(); - if seen.insert(key) { - keep.push(row); - } else { - removed += 1; - } - } - let pictures: Vec<_> = keep - .iter() - .enumerate() - .flat_map(|(i, row)| { - (r.start.col..=r.end.col) - .filter_map(move |col| sh.cell_pictures.get(&CellRef::new(*row, col)).map(|p| (CellRef::new(start + i as u32, col), p.clone()))) - }) - .collect(); - // Rows a filter keeps are compacted to `start + i`, so the notes and hyperlinks that - // describe them move with them; the ones on removed rows are dropped with the row. - let notes: Vec<_> = keep - .iter() - .enumerate() - .flat_map(|(i, row)| { - (r.start.col..=r.end.col) - .filter_map(move |col| sh.comments.get(&CellRef::new(*row, col)).map(|cm| (CellRef::new(start + i as u32, col), cm.clone()))) - }) - .collect(); - let links: Vec<_> = keep - .iter() - .enumerate() - .flat_map(|(i, row)| { - (r.start.col..=r.end.col) - .filter_map(move |col| sh.hyperlinks.get(&CellRef::new(*row, col)).map(|h| (CellRef::new(start + i as u32, col), h.clone()))) - }) - .collect(); - let rows: Vec>> = - keep.iter().map(|row| (r.start.col..=r.end.col).map(|c| sh.cell(CellRef::new(*row, c)).cloned()).collect()).collect(); - let shm = cx.sheet_mut(sheet)?; - for row in start..=r.end.row { - for c in r.start.col..=r.end.col { - shm.remove_cell(CellRef::new(row, c)); - } - } - for row in start..=r.end.row { - for c in r.start.col..=r.end.col { - let at = CellRef::new(row, c); - shm.comments.remove(&at); - shm.hyperlinks.remove(&at); - } - } - for (i, cells) in rows.into_iter().enumerate() { - for (j, cell) in cells.into_iter().enumerate() { - if let Some(cell) = cell { - shm.set_cell(CellRef::new(start + i as u32, r.start.col + j as u32), cell); - } - } - } - shm.cell_pictures.extend(pictures); - for (at, cm) in notes { - shm.comments.insert(at, cm); - } - for (at, h) in links { - shm.hyperlinks.insert(at, h); - } - for c in RangeRef::new(CellRef::new(start, r.start.col), r.end).iter() { - cx.changed.push((sheet, c)); - } - Ok(()) - })?; - let remaining = (r.end.row + 1 - start) as usize - removed; - Ok(json!({"removed": removed, "remaining": remaining})) -} - -fn text_to_columns(s: &mut Session, p: &Json) -> Result { - let r = target_range(s, p)?; - let sheet = target_sheet(s, p)?; - let mut delims: Vec = p - .get("delimiters") - .and_then(Json::as_array) - .map(|a| a.iter().filter_map(|d| d.as_str().and_then(|x| x.chars().next())).collect()) - .unwrap_or_else(|| vec!['\t']); - if let Some(o) = str_param(p, "other").and_then(|o| o.chars().next()) { - delims.push(o); - } - let fixed: Option> = - p.get("fixedWidths").and_then(Json::as_array).map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as usize)).collect()); - let consecutive = bool_param(p, "treatConsecutive").unwrap_or(false); - let quote = str_param(p, "textQualifier").and_then(|q| q.chars().next()).unwrap_or('"'); - let dest = cell_param_on(s, p, "destination", sheet)?.unwrap_or(r.start); - edit(s, |cx| { - let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; - let mut out: Vec<(CellRef, String)> = Vec::new(); - for (i, row) in (r.start.row..=r.end.row).enumerate() { - let text = sh.value(CellRef::new(row, r.start.col)).display(); - let parts: Vec = match &fixed { - Some(w) => { - let chars: Vec = text.chars().collect(); - let mut cuts = vec![0]; - let mut breaks: Vec = w.iter().copied().filter(|x| *x > 0 && *x < chars.len()).collect(); - breaks.sort_unstable(); - breaks.dedup(); - cuts.extend(breaks); - cuts.push(chars.len()); - cuts.windows(2) - .map(|p| chars.get(p[0]..p[1]).map(|s| s.iter().collect::().trim().to_string()).unwrap_or_default()) - .collect() - } - None => split_delimited(&text, &delims, consecutive, quote), - }; - for (j, part) in parts.into_iter().enumerate() { - out.push((CellRef::new(dest.row + i as u32, dest.col + j as u32), part)); - } - } - for (c, t) in out { - let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); - let shm = cx.sheet_mut(sheet)?; - match cell { - Some(x) => shm.set_cell(c, x), - None => { - shm.remove_cell(c); - } - } - cx.changed.push((sheet, c)); - } - Ok(()) - })?; - ok() -} - -fn split_delimited(text: &str, delims: &[char], consecutive: bool, quote: char) -> Vec { - let mut out = Vec::new(); - let mut cur = String::new(); - let mut in_q = false; - let mut last_delim = false; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { - if c == quote { - if in_q && chars.peek() == Some("e) { - cur.push(quote); - chars.next(); - } else { - in_q = !in_q; - } - continue; - } - if !in_q && delims.contains(&c) { - if consecutive && last_delim { - continue; - } - out.push(std::mem::take(&mut cur)); - last_delim = true; - continue; - } - last_delim = false; - cur.push(c); - } - out.push(cur); - out -} - -// ---------------------------------------------------------------- validation - -fn op_param(s: Option<&str>) -> CfOperator { - match s.unwrap_or("between") { - "notBetween" => CfOperator::NotBetween, - "equal" => CfOperator::Equal, - "notEqual" => CfOperator::NotEqual, - "greater" | "greaterThan" => CfOperator::Greater, - "less" | "lessThan" => CfOperator::Less, - "greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual, - "lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual, - _ => CfOperator::Between, - } -} - -/// `r` minus `cut`, as up to four non-overlapping rectangles. -fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec { - let Some(i) = r.intersection(cut) else { return vec![r] }; - let mut out = Vec::new(); - if i.start.row > r.start.row { - out.push(RangeRef::new(r.start, CellRef::new(i.start.row - 1, r.end.col))); - } - if i.end.row < r.end.row { - out.push(RangeRef::new(CellRef::new(i.end.row + 1, r.start.col), r.end)); - } - if i.start.col > r.start.col { - out.push(RangeRef::new(CellRef::new(i.start.row, r.start.col), CellRef::new(i.end.row, i.start.col - 1))); - } - if i.end.col < r.end.col { - out.push(RangeRef::new(CellRef::new(i.start.row, i.end.col + 1), CellRef::new(i.end.row, r.end.col))); - } - out -} - -/// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges. -pub(super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { - for dv in validations.iter_mut() { - for cut in cuts { - dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); - } - } - validations.retain(|d| !d.ranges.is_empty()); -} - -fn validation(s: &mut Session, p: &Json) -> Result { - let ranges = target_ranges(s, p)?; - let sheet = target_sheet(s, p)?; - if bool_param(p, "clear").unwrap_or(false) { - return edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - remove_validation_cells(&mut sh.validations, &ranges); - Ok(Json::Null) - }); - } - let Some(kind) = str_param(p, "type") else { - s.ui_requests.push(crate::UiRequest::Dialog("dataValidation".into(), json!({}))); - return ok(); - }; - let kind = match kind { - "whole" => ValidationKind::Whole, - "decimal" => ValidationKind::Decimal, - "list" => ValidationKind::List, - "date" => ValidationKind::Date, - "time" => ValidationKind::Time, - "textLength" => ValidationKind::TextLength, - "custom" => ValidationKind::Custom, - "any" => ValidationKind::Any, - // An unknown type used to give an "any value" rule, saved as `type="none"`: no validation. - other => return Err(bad("data.validation", format!("unknown type `{other}` (any, whole, decimal, list, date, time, textLength, custom)"))), - }; - if kind == ValidationKind::List && str_param(p, "formula1").is_none_or(|f| f.trim().trim_start_matches('=').is_empty()) { - return Err(bad("data.validation", "a list validation needs `formula1`")); - } - const OPERATORS: [&str; 12] = [ - "between", - "notBetween", - "equal", - "notEqual", - "greater", - "greaterThan", - "less", - "lessThan", - "greaterOrEqual", - "greaterThanOrEqual", - "lessOrEqual", - "lessThanOrEqual", - ]; - if let Some(op) = str_param(p, "operator").filter(|op| !OPERATORS.contains(op)) { - return Err(bad("data.validation", format!("unknown operator `{op}` ({})", OPERATORS.join(", ")))); - } - let error_style = match str_param(p, "errorStyle") { - None | Some("stop") => ErrorStyle::Stop, - Some("warning") => ErrorStyle::Warning, - Some("information") => ErrorStyle::Information, - Some(other) => return Err(bad("data.validation", format!("unknown errorStyle `{other}` (stop, warning, information)"))), - }; - let f1 = str_param(p, "formula1").unwrap_or(""); - let f1 = if kind == ValidationKind::List { list_source(f1) } else { f1.trim_start_matches('=').to_string() }; - let dv = Validation { - ranges: ranges.clone(), - kind, - op: op_param(str_param(p, "operator")), - f1, - f2: str_param(p, "formula2").map(|f| f.trim_start_matches('=').to_string()), - allow_blank: bool_param(p, "ignoreBlank").unwrap_or(true), - in_cell_dropdown: bool_param(p, "dropdown").unwrap_or(true), - input_title: str_param(p, "inputTitle").unwrap_or("").into(), - input_message: str_param(p, "inputMessage").unwrap_or("").into(), - show_input: true, - error_title: str_param(p, "errorTitle").unwrap_or("").into(), - error_message: str_param(p, "errorMessage").unwrap_or("").into(), - error_style, - show_error: true, - }; - edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - remove_validation_cells(&mut sh.validations, &ranges); - sh.validations.push(dv.clone()); - Ok(Json::Null) - }) -} - -/// Whether a list rule's source is a literal list (`"a,b"`, or `a,b` typed without quotes) rather -/// than a reference or a name to evaluate. -fn is_literal_list(f: &str) -> bool { - f.starts_with('"') - || (!f.contains('!') - && gridcraft_formula::parse(f).map(|e| !matches!(e, gridcraft_formula::Expr::Ref(_) | gridcraft_formula::Expr::Name(_))).unwrap_or(true)) -} - -/// A list rule's source as a file stores it. A literal list typed without quotes, as in Excel's -/// Source box (`Open,In progress,Closed`), becomes the quoted string Excel saves -/// (`"Open,In progress,Closed"`, inner quotes doubled); unquoted, the file would read it as a -/// formula. A formula (`=…`), a reference, a name or an already quoted list is kept as before. -fn list_source(f: &str) -> String { - let t = f.trim(); - if t.is_empty() || t.starts_with('=') || t.starts_with('"') || !is_literal_list(t) { - return f.trim_start_matches('=').to_string(); - } - format!("\"{}\"", t.replace('"', "\"\"")) -} - -/// List entries of a list validation (literal or from a range). -pub fn list_items(wb: &Workbook, sheet: usize, dv: &Validation) -> Vec { - let f = dv.f1.trim(); - if is_literal_list(f) { - // A quoted list is a string literal: `""` inside stands for one `"`. - let items = match f.strip_prefix('"').and_then(|x| x.strip_suffix('"')) { - Some(body) => body.replace("\"\"", "\""), - None => f.trim_matches('"').to_string(), - }; - return items.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(); - } - let at = dv.ranges.first().map(|r| r.start).unwrap_or_default(); - match gridcraft_calc::evaluate(wb, sheet, at, f) { - Value::Array(a) => a.data.iter().filter(|v| !v.is_empty()).map(Value::display).collect(), - v if !v.is_empty() && !v.is_error() => vec![v.display()], - _ => vec![], - } -} - -/// Checks typed input against the validation of a cell. `Ok(None)` = valid. -pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -> Option<(Validation, String)> { - let sh = wb.sheet(sheet)?; - let dv = sh.validations.iter().find(|d| d.ranges.iter().any(|r| r.contains(at)))?; - if dv.kind == ValidationKind::Any || !dv.show_error { - return None; - } - if input.is_empty() && dv.allow_blank { - return None; - } - let v = gridcraft_core::parse::parse_input(input, wb.date_system).value; - // The formulas are written for the first cell of the range and see the value being entered, - // as in Excel (a custom `=A1>10` on A1:A9 checks A5's new value at A5). - let first = dv.ranges.first().map(|r| r.start).unwrap_or(at); - let entered; - let wb = if sh.value(at) == v { - wb - } else { - let mut w = wb.clone(); - if let Some(sh) = w.sheet_mut(sheet) { - let style = sh.style_id(at); - sh.cells.set(at, Cell { value: v.clone(), style, ..Default::default() }); - } - entered = w; - &entered - }; - let eval = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, &formula_at(f, first, at)); - let num = |f: &str| eval(f).to_number().ok(); - let ok = match dv.kind { - ValidationKind::List => list_items(wb, sheet, dv).iter().any(|x| x.eq_ignore_ascii_case(input)), - ValidationKind::Custom => eval(&dv.f1).to_bool().unwrap_or(false), - ValidationKind::TextLength => { - let n = input.chars().count() as f64; - compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num)) - } - _ => match v.as_f64() { - Some(n) => { - if dv.kind == ValidationKind::Whole && n.fract() != 0.0 { - false - } else { - compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num)) - } - } - None => false, - }, - }; - if ok { - return None; - } - let msg = if dv.error_message.is_empty() { - "This value doesn't match the data validation restrictions defined for this cell.".to_string() - } else { - dv.error_message.clone() - }; - Some((dv.clone(), msg)) -} - -/// A formula written for `first`, as seen from `at` (relative references shifted). -fn formula_at(f: &str, first: CellRef, at: CellRef) -> String { - if first == at { - return f.to_string(); - } - match gridcraft_formula::parse(f.trim_start_matches('=')) { - Ok(e) => gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative( - e, - at.row as i64 - first.row as i64, - at.col as i64 - first.col as i64, - )), - Err(_) => f.to_string(), - } -} - -/// Moves the relative references of a rule formula written for `first` so it reads the same cells from `to` -/// (pasting a rule); text without relative references (constants, literal lists) stays as typed. -pub(super) fn move_rule_formula(f: &str, first: CellRef, to: CellRef) -> String { - if first == to { - return f.to_string(); - } - let moved = formula_at(f, first, to); - let has_relative = gridcraft_formula::parse(f.trim_start_matches('=')).is_ok_and(|e| gridcraft_formula::print(&e) != moved); - let eq = if f.starts_with('=') { "=" } else { "" }; - if has_relative { format!("{eq}{moved}") } else { f.to_string() } -} - -fn compare_op(op: CfOperator, n: f64, a: Option, b: Option) -> bool { - let Some(a) = a else { return false }; - match op { - CfOperator::Between => b.is_some_and(|b| n >= a.min(b) && n <= a.max(b)), - CfOperator::NotBetween => b.is_some_and(|b| n < a.min(b) || n > a.max(b)), - CfOperator::Equal => n == a, - CfOperator::NotEqual => n != a, - CfOperator::Greater => n > a, - CfOperator::Less => n < a, - CfOperator::GreaterOrEqual => n >= a, - CfOperator::LessOrEqual => n <= a, - } -} - -fn validate_cmd(s: &mut Session, p: &Json) -> Result { - let d = s.doc()?; - let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active); - let input = str_param(p, "input").unwrap_or(""); - match check_validation(&d.wb, d.wb.active_sheet(), at, input) { - None => Ok(json!({"ok": true})), - Some((dv, msg)) => Ok(json!({"ok": false, "message": msg, "title": dv.error_title, "style": format!("{:?}", dv.error_style)})), - } -} - -fn circle_invalid(s: &mut Session, _: &Json) -> Result { - let d = s.doc()?; - let sheet = d.wb.active_sheet(); - let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; - let mut bad_cells = Vec::new(); - for dv in &sh.validations { - for r in &dv.ranges { - let r = sh.used_range().and_then(|u| r.intersection(&u)); - let Some(r) = r else { continue }; - for c in r.iter().take(100_000) { - let text = sh.input_text(c); - if !text.is_empty() && check_validation(&d.wb, sheet, c, &text).is_some() { - bad_cells.push(c.a1()); - } - } - } - } - Ok(json!({"invalid": bad_cells})) -} - -// ---------------------------------------------------------------- outline - -fn outline_lines(s: &Session, p: &Json) -> Result<(bool, u32, u32)> { - if let Some(r) = str_param(p, "rows").and_then(parse_lines) { - return Ok((true, r.start.row, r.end.row)); - } - if let Some(r) = str_param(p, "cols").and_then(parse_lines) { - return Ok((false, r.start.col, r.end.col)); - } - let r = s.doc()?.selection.current(); - match str_param(p, "by") { - Some("rows") => Ok((true, r.start.row, r.end.row)), - Some("cols" | "columns") => Ok((false, r.start.col, r.end.col)), - _ if r.is_full_cols() && !r.is_full_rows() => Ok((false, r.start.col, r.end.col)), - _ => Ok((true, r.start.row, r.end.row)), - } -} - -fn group(s: &mut Session, p: &Json, on: bool) -> Result { - let si = target_sheet(s, p)?; - // The selection belongs to the active sheet, so another sheet needs its lines. - if si != s.doc()?.wb.active_sheet() && p.get("rows").is_none() && p.get("cols").is_none() { - return Err(bad(if on { "data.group" } else { "data.ungroup" }, "missing `rows` or `cols`: the selection is on the active sheet")); - } - let (rows, a, b) = outline_lines(s, p)?; - edit(s, |cx| { - let sh = cx.sheet_mut(si)?; - let before = outline::summary_before(sh, rows); - let map = if rows { &mut sh.rows } else { &mut sh.cols }; - let b = b.min(a.saturating_add(1_048_575)); - for i in a..=b { - let e = map.entry(i).or_default(); - e.outline = if on { (e.outline + 1).min(outline::MAX_LEVEL) } else { e.outline.saturating_sub(1) }; - if !on && e.outline == 0 { - e.hidden = false; - } - } - // A summary line whose group is gone has nothing left to collapse. - let summary = if before { a.checked_sub(1) } else { b.checked_add(1) }; - if !on - && !outline::groups_with(map, before).iter().any(|g| if before { g.start == a } else { g.end == b }) - && let Some(e) = summary.and_then(|i| map.get_mut(&i)) - { - e.collapsed = false; - } - cx.structural = true; // ungrouping reveals hidden rows: SUBTOTAL(10x) depends on it - Ok(Json::Null) - }) -} - -/// Hide Detail / Show Detail: the innermost group (or the one at `level`) that holds the lines, or -/// failing that the one they are the summary of. Hiding marks the summary line collapsed (the -/// + button, saved to XLSX); showing keeps inner groups that were collapsed on their own collapsed. -fn detail(s: &mut Session, p: &Json, hide: bool) -> Result { - let (rows, a, b) = outline_lines(s, p)?; - let want = p.get("level").and_then(Json::as_u64).map(|l| l.min(outline::MAX_LEVEL as u64) as u8); - edit(s, |cx| { - let si = cx.sheet_index(); - let sh = cx.sheet_mut(si)?; - let before = outline::summary_before(sh, rows); - let map = if rows { &mut sh.rows } else { &mut sh.cols }; - let all = outline::groups_with(map, before); - let level_ok = |g: &outline::OutlineGroup| want.is_none_or(|l| g.level == l); - let pick = |hit: &dyn Fn(&outline::OutlineGroup) -> bool| -> Vec { - let hits: Vec<_> = all.iter().filter(|g| level_ok(g) && hit(g)).copied().collect(); - let deepest = hits.iter().map(|g| g.level).max().unwrap_or(0); - hits.into_iter().filter(|g| g.level == deepest).collect() - }; - let mut chosen = pick(&|g| g.start <= b && g.end >= a); - if chosen.is_empty() { - chosen = pick(&|g| g.has_summary() && g.summary() >= a && g.summary() <= b); - } - for g in chosen { - // Inner groups collapsed on their own (their summary marked), before this one changes. - let inner: Vec = all - .iter() - .filter(|o| o.level > g.level && o.start >= g.start && o.end <= g.end && o.has_summary() && o.summary() != g.summary()) - .filter(|o| map.get(&o.summary()).is_some_and(|e| e.collapsed)) - .copied() - .collect(); - for i in g.start..=g.end { - if let Some(e) = map.get_mut(&i) { - set_hidden(e, hide || inner.iter().any(|o| o.contains(i))); - } - } - if !g.has_summary() { - continue; - } - if hide { - map.entry(g.summary()).or_default().collapsed = true; - } else if let Some(e) = map.get_mut(&g.summary()) { - e.collapsed = false; - } - } - cx.structural = true; - Ok(Json::Null) - }) -} - -/// Hides or shows an outline line. A line shown with a zero size (files that hide columns as -/// `width="0" hidden="1"`) gets the default size back, as Unhide does; otherwise + would mark the -/// group expanded and leave it invisible (#1714). -fn set_hidden(e: &mut LineInfo, hidden: bool) { - e.hidden = hidden; - if !hidden && e.size == Some(0.0) { - e.size = None; - } -} - -/// The outline's level buttons: show rows / columns down to outline level `n` (1 = only the -/// top-level summaries); deeper detail is hidden and its summary lines marked collapsed. -fn show_levels(s: &mut Session, p: &Json) -> Result { - let level = |k: &str| p.get(k).and_then(Json::as_u64).map(|n| n.clamp(1, outline::MAX_LEVEL as u64 + 1) as u8); - let (rows, cols) = (level("rows"), level("cols")); - if rows.is_none() && cols.is_none() { - return Err(EngineError::BadParams { - cmd: "data.showLevels".into(), - msg: "give `rows` or `cols`: the outline level to show (1 = top-level summaries only)".into(), - }); - } - edit(s, |cx| { - let si = cx.sheet_index(); - let sh = cx.sheet_mut(si)?; - let before = (outline::summary_before(sh, true), outline::summary_before(sh, false)); - for (map, n, before) in [(&mut sh.rows, rows, before.0), (&mut sh.cols, cols, before.1)] { - let Some(n) = n else { continue }; - let groups = outline::groups_with(map, before); - for e in map.values_mut().filter(|e| e.outline > 0) { - set_hidden(e, e.outline >= n); - } - // Inner groups come first, so a summary line shared with the group around it ends up - // as that outer group says. - for g in groups.into_iter().filter(|g| g.has_summary()) { - map.entry(g.summary()).or_default().collapsed = g.level >= n; - } - } - cx.structural = true; - Ok(Json::Null) - }) -} - -/// Data ▸ Outline ▸ Settings: whether summary rows sit below their detail and summary columns -/// right of it. A changed direction moves each collapsed group's mark (+) to its new summary line. -/// Moves the collapsed marks of a line axis to the summary line on its new side (`on` is the new -/// setting, `was_before` the old one). A line that nested groups share keeps its mark on the outermost -/// group whose detail is all hidden, or the outermost when none is. -fn move_marks(map: &mut std::collections::BTreeMap, was_before: bool, on: bool) { - let mut marked: Vec = - outline::groups_with(map, was_before).into_iter().filter(|g| g.has_summary() && map.get(&g.summary()).is_some_and(|e| e.collapsed)).collect(); - // A mark on a line that nested groups share moves with the outermost of them whose - // detail is all hidden, or with the outermost when none is. - let mut owner: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for g in &marked { - let key = (!g.collapsed, g.level); - let best = owner.entry(g.summary()).or_insert(key); - *best = (*best).min(key); - } - marked.retain(|g| owner.get(&g.summary()) == Some(&(!g.collapsed, g.level))); - for g in &marked { - if let Some(e) = map.get_mut(&g.summary()) { - e.collapsed = false; - } - } - for g in marked { - let g = outline::OutlineGroup { summary_before: !on, ..g }; - if g.has_summary() { - map.entry(g.summary()).or_default().collapsed = true; - } - } -} - -fn outline_settings(s: &mut Session, p: &Json) -> Result { - let si = target_sheet(s, p)?; - edit(s, |cx| { - let sh = cx.sheet_mut(si)?; - for (rows, key) in [(true, "summaryBelow"), (false, "summaryRight")] { - let Some(on) = bool_param(p, key) else { continue }; - let was_before = outline::summary_before(sh, rows); - if rows { - sh.summary_below = on; - } else { - sh.summary_right = on; - } - if was_before != on { - continue; - } - move_marks(if rows { &mut sh.rows } else { &mut sh.cols }, was_before, on); - } - Ok(json!({"summaryBelow": sh.summary_below, "summaryRight": sh.summary_right})) - }) -} - -fn subtotal(s: &mut Session, p: &Json) -> Result { - let (sheet, r) = data_target(s, p, "data.subtotal")?; - let header = bool_param(p, "header").unwrap_or(true); - let group_col = col_param(p.get("groupBy"), r.start.col).unwrap_or(r.start.col); - let func = str_param(p, "function").unwrap_or("sum"); - let code = match func { - "count" => 3, - "average" => 1, - "max" => 4, - "min" => 5, - "product" => 6, - _ => 9, - }; - let cols: Vec = p - .get("columns") - .and_then(Json::as_array) - .map(|a| a.iter().filter_map(|c| col_param(Some(c), r.start.col)).collect()) - .unwrap_or_else(|| vec![r.end.col]); - let label = match func { - "count" => "Count", - "average" => "Average", - "max" => "Max", - "min" => "Min", - "product" => "Product", - _ => "Total", - }; - // Group boundaries (header in the first row). - let d = s.doc()?; - let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; - let mut groups: Vec<(u32, u32, String)> = Vec::new(); - let first = r.start.row + u32::from(header); - let mut start = first; - for row in first..=r.end.row + 1 { - let cur = sh.value(CellRef::new(row, group_col)).display(); - let prev = sh.value(CellRef::new(start, group_col)).display(); - if row > r.end.row || cur != prev { - groups.push((start, row - 1, prev)); - start = row; - } - } - // The totals go below each group, so the outline puts summary rows below their detail (the - // Subtotal dialog's "Summary below data"), in the same undo step. - if !sh.summary_below { - s.execute("data.outlineSettings", json!({"sheet": sheet, "summaryBelow": true}))?; - } - // Insert a total row after each group, bottom-up so indices stay valid. - let mut inserted = 0; - for (g0, g1, name) in groups.iter().rev() { - s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", g1 + 2, g1 + 2)}))?; - let row = g1 + 1; - let lbl = CellRef::new(row, group_col).a1(); - s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("{name} {label}")}))?; - for c in &cols { - let range = RangeRef::new(CellRef::new(*g0, *c), CellRef::new(*g1, *c)).a1(); - s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(row, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?; - } - s.execute( - "home.bold", - json!({"sheet": sheet, "range": RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col)).a1(), "on": true}), - )?; - s.execute("data.group", json!({"sheet": sheet, "rows": format!("{}:{}", g0 + 1, g1 + 1)}))?; - inserted += 1; - } - let last = r.end.row + inserted + 1; - let lbl = CellRef::new(last, group_col).a1(); - s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", last + 1, last + 1)}))?; - s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("Grand {label}")}))?; - for c in &cols { - let range = RangeRef::new(CellRef::new(first, *c), CellRef::new(last - 1, *c)).a1(); - s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(last, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?; - } - Ok(json!({"groups": inserted})) -} - #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn filter_blanks_include_empty_text_and_formula_results() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["id", "f"], ["e", null], ["ef", "=\"\""], ["sp", " "], ["z", 0]]})).unwrap(); - s.execute("data.filter", json!({"range": "A1:B5"})).unwrap(); - let r = s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap(); - assert_eq!(r["hiddenRows"], json!(2)); - let vals = filter_values(&s.doc().unwrap().wb, 0, 1); - // The `=""` result joins (Blanks) instead of showing as its own empty entry. - assert!(!vals.iter().any(|(t, _)| t.is_empty()), "{vals:?}"); - let blanks: Vec<_> = vals.into_iter().filter(|(t, _)| t == "(Blanks)").collect(); - assert_eq!(blanks, vec![("(Blanks)".to_string(), true)]); - } - - #[test] - fn subtotal_honours_header_false() { - // #131: with header:false the first data row was treated as a header and left out of its - // group's subtotal and the grand total. - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["East", 10], ["East", 20], ["West", 30], ["West", 40]]})).unwrap(); - s.execute("data.subtotal", json!({"range": "A1:B4", "groupBy": "A", "function": "sum", "columns": ["B"], "header": false})).unwrap(); - let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - assert_eq!(get(&mut s, "A1")["value"], json!("East")); - assert_eq!(get(&mut s, "A3")["text"], json!("East Total")); - assert_eq!(get(&mut s, "B3")["value"], json!(30.0), "East's subtotal counts both East rows"); - assert_eq!(get(&mut s, "A7")["text"], json!("Grand Total")); - assert_eq!(get(&mut s, "B7")["value"], json!(100.0), "the grand total counts every data row"); - } - - #[test] - fn subtotal_puts_summary_rows_below_their_detail() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Sales"], ["East", 10], ["East", 20], ["West", 30]]})).unwrap(); - s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); - s.execute("data.subtotal", json!({"range": "A1:B4", "groupBy": "A", "columns": ["B"]})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap().clone(); - assert!(sh.summary_below, "the totals sit below their groups"); - // East's detail is rows 2–3 and its total row 4: collapsing level 1 keeps the total showing. - s.execute("data.showLevels", json!({"rows": 1})).unwrap(); - let hidden = |s: &Session, row: u32| s.doc().unwrap().wb.active().unwrap().is_row_hidden(row); - assert!(hidden(&s, 1) && hidden(&s, 2), "East's detail rows are hidden"); - assert!(!hidden(&s, 3), "East Total stays visible"); - // One undo takes the subtotals and the setting back. - s.execute("edit.undo", json!({})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert!(!sh.summary_below); - assert_eq!(sh.value(CellRef::new(3, 0)).display(), "West"); - } - - #[test] - fn filter_by_huge_numeric_column_is_rejected_not_overflowed() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "B1", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap(); - s.execute("data.filter", json!({"range": "B1:C3"})).unwrap(); - for col in [json!(2), json!(u64::from(u32::MAX)), json!(u64::MAX)] { - let err = s.execute("data.filterBy", json!({"column": col, "values": ["a"]})).unwrap_err(); - assert!(err.to_string().contains("column outside the filter range"), "{col}: {err}"); - } - let ok = s.execute("data.filterBy", json!({"column": 0, "values": ["a"]})).unwrap(); - assert_eq!(ok["hiddenRows"], json!(1)); - } - - #[test] - fn filter_by_inside_a_table_installs_the_autofilter_and_keeps_the_button() { - for sel in [json!({"cell": "A1"}), json!({"cell": "A2"}), json!({"range": "A1:A3"})] { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"]]})).unwrap(); - s.execute("insert.table", json!({"range": "A1:A3", "header": true})).unwrap(); - s.execute("selection.set", sel.clone()).unwrap(); - s.execute("data.filterBy", json!({"column": "A", "values": ["a"]})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert_eq!(sh.autofilter.as_ref().map(|a| a.range.a1()), Some("A1:A3".to_string()), "{sel}"); - assert!(sh.tables[0].filter_button, "{sel}"); - assert!(!sh.is_row_hidden(1), "{sel}"); - assert!(sh.is_row_hidden(2), "{sel}"); - assert_eq!(sh.value(CellRef::new(2, 0)).display(), "b", "{sel}"); - } - } - - #[test] - fn autofilter_range_grows_when_a_value_is_entered_in_the_row_below() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Qty"], ["d", 4], ["b", 2]]})).unwrap(); - s.execute("data.filter", json!({"range": "A1:B3"})).unwrap(); - let range = |s: &Session| s.doc().unwrap().wb.active().unwrap().autofilter.as_ref().map(|a| a.range.a1()); - s.execute("cell.set", json!({"cell": "A4", "input": "e"})).unwrap(); - assert_eq!(range(&s), Some("A1:B4".to_string())); - s.execute("range.setValues", json!({"range": "A5", "values": [["f", 6]]})).unwrap(); - assert_eq!(range(&s), Some("A1:B5".to_string())); - // A row typed after a blank row does not grow it. - s.execute("cell.set", json!({"cell": "A7", "input": "x"})).unwrap(); - assert_eq!(range(&s), Some("A1:B5".to_string())); - // A cell outside the filter's columns does not either. - s.execute("cell.set", json!({"cell": "C6", "input": "x"})).unwrap(); - assert_eq!(range(&s), Some("A1:B5".to_string())); - // Empty text is a blank entry, not a value. - s.execute("range.setValues", json!({"range": "A6", "parse": false, "values": [[""]]})).unwrap(); - assert_eq!(range(&s), Some("A1:B5".to_string())); - // A formula and Ctrl+Enter (range.fill) are entries too. - s.execute("cell.set", json!({"cell": "B6", "input": "=1+1"})).unwrap(); - assert_eq!(range(&s), Some("A1:B6".to_string())); - s.execute("range.fill", json!({"range": "A7:B7", "input": "g"})).unwrap(); - assert_eq!(range(&s), Some("A1:B7".to_string())); - } - - #[test] - fn list_validation_without_formula1_is_an_error() { - let mut s = Session::new(); - s.new_workbook(); - assert!(s.execute("data.validation", json!({"range": "A1:A3", "type": "list", "source": "\"a,b,c\""})).is_err()); - assert!(s.execute("data.validation", json!({"range": "A1:A3", "type": "list"})).is_err()); - assert!(s.doc().unwrap().wb.active().unwrap().validations.is_empty()); - s.execute("data.validation", json!({"range": "A1:A3", "type": "list", "formula1": "\"a,b,c\""})).unwrap(); - assert_eq!(s.execute("data.validate", json!({"cell": "A1", "input": "a"})).unwrap()["ok"], json!(true)); - } - - #[test] - fn partial_validation_edits_keep_the_rest_of_the_old_rule() { - let mut s = Session::new(); - s.new_workbook(); - let rule = |range: &str, lo: &str, hi: &str| json!({"range": range, "type": "whole", "operator": "between", "formula1": lo, "formula2": hi}); - let ok = |s: &mut Session, cell: &str, input: &str| { - s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == json!(true) - }; - s.execute("data.validation", rule("B1:B3", "1", "10")).unwrap(); - s.execute("data.validation", json!({"range": "B2", "clear": true})).unwrap(); - assert!(ok(&mut s, "B2", "999")); - assert!(!ok(&mut s, "B1", "999")); - assert!(!ok(&mut s, "B3", "999")); - s.execute("data.validation", rule("B2:B4", "100", "200")).unwrap(); - for cell in ["B2", "B3", "B4"] { - assert!(ok(&mut s, cell, "150"), "{cell}"); - assert!(!ok(&mut s, cell, "5"), "{cell}"); - } - assert!(ok(&mut s, "B1", "5")); - assert!(!ok(&mut s, "B1", "150")); - } - - #[test] - fn showing_detail_gives_zero_width_columns_their_width_back() { - // #1714: templates hide grouped columns as `width="0" hidden="1"`; + must show them. - let mut s = Session::new(); - s.new_workbook(); - let hidden = LineInfo { size: Some(0.0), hidden: true, outline: 1, ..LineInfo::default() }; - let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); - for c in 2..=4 { - sh.cols.insert(c, hidden); - } - sh.cols.insert(5, LineInfo { collapsed: true, ..LineInfo::default() }); - s.execute("data.showDetail", json!({"cols": "C:E", "level": 1})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - for c in 2..=4 { - assert_eq!(sh.col_width(c), sh.default_col_width, "column {c}"); - } - // Hiding again hides them; the level buttons show zero-width columns too. - s.execute("data.hideDetail", json!({"cols": "C:E", "level": 1})).unwrap(); - assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(2), 0.0); - Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().cols.insert(3, hidden); - s.execute("data.showLevels", json!({"cols": 2})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert_eq!((sh.col_width(2), sh.col_width(3)), (sh.default_col_width, sh.default_col_width)); - } - - #[test] - fn removing_an_autofilter_keeps_manually_hidden_and_collapsed_rows() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap(); - s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap(); - s.execute("data.group", json!({"rows": "2:4"})).unwrap(); - s.execute("data.hideDetail", json!({"rows": "2:4"})).unwrap(); - s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap(); - let hidden = |s: &Session| -> Vec { - let sh = s.doc().unwrap().wb.active().unwrap(); - sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect() - }; - let before = hidden(&s); - assert_eq!(before, [1, 2, 3, 9]); - s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); - s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); - assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none()); - assert_eq!(hidden(&s), before); - assert_eq!(row_state(&s, 4..=4), [(false, true)]); - } - - #[test] - fn table_dropdown_setup_outside_the_table_keeps_manually_hidden_rows() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap(); - s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap(); - s.execute("insert.table", json!({"range": "A1:A4", "header": true})).unwrap(); - s.execute("home.hideRows", json!({"rows": "3:3"})).unwrap(); - s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap(); - s.execute("selection.set", json!({"range": "E1"})).unwrap(); - // The table filter dropdown installs an AutoFilter on demand by toggling `data.filter` twice. - s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); - s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert_eq!(sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect::>(), [2, 9]); - } - - /// Rows 5:8 grouped, with 6:7 grouped again inside (0-based 4..=7 and 5..=6). - fn nested_rows() -> Session { - let mut s = Session::new(); - s.new_workbook(); - s.execute("data.group", json!({"rows": "5:8"})).unwrap(); - s.execute("data.group", json!({"rows": "6:7"})).unwrap(); - s - } - - /// (hidden, collapsed) of 0-based rows. - fn row_state(s: &Session, rows: std::ops::RangeInclusive) -> Vec<(bool, bool)> { - let sh = s.doc().unwrap().wb.active().unwrap(); - rows.map(|r| sh.rows.get(&r).map(|l| (l.hidden, l.collapsed)).unwrap_or_default()).collect() - } - - #[test] - fn hide_detail_marks_the_summary_collapsed_and_show_detail_keeps_inner_groups_collapsed() { - let mut s = nested_rows(); - s.execute("data.hideDetail", json!({"rows": "6:7", "level": 2})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); - s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]); - s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); - s.execute("data.showDetail", json!({"rows": "6:7", "level": 2})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(false, false); 5]); - // Each step is one undoable command. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(row_state(&s, 5..=7), [(true, false), (true, false), (false, true)]); - } - - #[test] - fn hide_detail_on_the_summary_row_collapses_the_group_above_it() { - let mut s = nested_rows(); - s.execute("data.hideDetail", json!({"rows": "9:9"})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, false), (false, true)]); - } - - #[test] - fn show_levels_collapses_and_expands_to_a_level() { - let mut s = nested_rows(); - s.execute("data.showLevels", json!({"rows": 1})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]); - s.execute("data.showLevels", json!({"rows": 2})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); - s.execute("data.showLevels", json!({"rows": 3})).unwrap(); - assert_eq!(row_state(&s, 4..=8), [(false, false); 5]); - // Columns are separate; no level at all is an error rather than a guess. - s.execute("data.group", json!({"cols": "C:E"})).unwrap(); - s.execute("data.showLevels", json!({"cols": 1})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert!((2..=4).all(|c| sh.cols.get(&c).is_some_and(|l| l.hidden))); - assert!(sh.cols.get(&5).is_some_and(|l| l.collapsed)); - assert_eq!(row_state(&s, 4..=4), [(false, false)]); - assert!(s.execute("data.showLevels", json!({})).is_err()); - } - - #[test] - fn group_by_columns_for_a_block_of_cells() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); - s.execute("data.group", json!({"by": "cols"})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert!((1..=2).all(|c| sh.cols.get(&c).is_some_and(|l| l.outline == 1))); - assert!(sh.rows.values().all(|l| l.outline == 0)); - } - - #[test] - fn group_shortcuts_are_the_windows_ones() { - let sc = |id: &str| specs().into_iter().find(|c| c.id == id).and_then(|c| c.shortcut); - assert_eq!(sc("data.group"), Some("Alt+Shift+Right")); - assert_eq!(sc("data.ungroup"), Some("Alt+Shift+Left")); - } - - #[test] - fn summary_rows_above_the_detail_take_the_collapsed_mark() { - let mut s = nested_rows(); - let r = s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); - assert_eq!(r, json!({"summaryBelow": false, "summaryRight": true})); - // Row 4 (index 3) is the outer group's summary, row 5 the inner one's. - s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, true), (true, false), (true, false), (true, false), (true, false), (false, false)]); - s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, false); 6]); - // Hide Detail on the summary row collapses the group below it. - s.execute("data.hideDetail", json!({"rows": "4:4"})).unwrap(); - assert_eq!(row_state(&s, 3..=4), [(false, true), (true, false)]); - s.execute("data.showLevels", json!({"rows": 1})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, true), (true, true), (true, false), (true, false), (true, false), (false, false)]); - // Ungrouping the outer group clears its mark on the row above. - s.execute("data.showLevels", json!({"rows": 3})).unwrap(); - s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - s.execute("data.ungroup", json!({"rows": "5:8"})).unwrap(); - assert_eq!(row_state(&s, 3..=3), [(false, false)]); - } - - #[test] - fn changing_the_summary_direction_moves_collapsed_marks() { - let mut s = nested_rows(); - s.execute("data.group", json!({"cols": "C:E"})).unwrap(); - s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - s.execute("data.hideDetail", json!({"cols": "C:E"})).unwrap(); - s.execute("data.outlineSettings", json!({"summaryBelow": false, "summaryRight": false})).unwrap(); - let col_marked = |s: &Session, c: u32| s.doc().unwrap().wb.active().unwrap().cols.get(&c).is_some_and(|l| l.collapsed); - assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [true, false, false, false, false, false]); - assert!(col_marked(&s, 1) && !col_marked(&s, 5)); - s.execute("data.outlineSettings", json!({"summaryBelow": true})).unwrap(); - assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [false, false, false, false, false, true]); - assert!(col_marked(&s, 1), "columns keep their direction"); - // One undo step per change; no params leaves the settings as they are. - s.execute("edit.undo", json!({})).unwrap(); - assert!(row_state(&s, 3..=3)[0].1); - assert_eq!(s.execute("data.outlineSettings", json!({})).unwrap(), json!({"summaryBelow": false, "summaryRight": false})); - // Nested groups that end on one row share its mark: it moves to the outer group only. - let mut s = Session::new(); - s.new_workbook(); - s.execute("data.group", json!({"rows": "5:8"})).unwrap(); - s.execute("data.group", json!({"rows": "6:8"})).unwrap(); - s.execute("data.showLevels", json!({"rows": 1})).unwrap(); - s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); - assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [true, false, false, false, false, false]); - s.execute("data.showDetail", json!({"rows": "4:4"})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, false); 6]); - // With only the inner group collapsed, its mark goes to row 5, and the outer group's - // Hide and Show Detail keep it collapsed. - s.execute("data.outlineSettings", json!({"summaryBelow": true})).unwrap(); - s.execute("data.hideDetail", json!({"rows": "6:8", "level": 2})).unwrap(); - s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, false), (false, true), (true, false), (true, false), (true, false), (false, false)]); - s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); - assert_eq!(row_state(&s, 3..=8), [(false, false), (false, true), (true, false), (true, false), (true, false), (false, false)]); - // A group on the first row has no row above it to mark. - let mut s = Session::new(); - s.new_workbook(); - s.execute("data.group", json!({"rows": "1:3"})).unwrap(); - s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); - s.execute("data.hideDetail", json!({"rows": "1:3"})).unwrap(); - assert_eq!(row_state(&s, 0..=3), [(true, false), (true, false), (true, false), (false, false)]); - } - - #[test] - fn column_sort_rejects_row_key_zero_without_panicking() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("cell.set", json!({"cell": "A1", "input": "2"})).unwrap(); - for row in [0u64, 1 << 32] { - let params = json!({"range": "A1:B2", "header": false, "orientation": "columns", "keys": [{"row": row}]}); - let err = s.execute("data.sort", params).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "row {row}: {err:?}"); - } - } - - #[test] - fn single_row_and_column_parameters() { - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2], [3, 4]]})).unwrap(); - s.execute("home.insertRows", json!({"rows": "2"})).unwrap(); - s.execute("home.insertColumns", json!({"cols": "B"})).unwrap(); - let v = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); - assert_eq!(v(&mut s, "C3"), json!(4.0)); - s.execute("home.hideRows", json!({"rows": "1"})).unwrap(); - s.execute("data.group", json!({"cols": "C"})).unwrap(); - assert!(s.execute("home.deleteRows", json!({"rows": "0"})).is_err()); - s.execute("home.deleteRows", json!({"rows": "2"})).unwrap(); - s.execute("home.deleteColumns", json!({"cols": "B"})).unwrap(); - assert_eq!(v(&mut s, "B2"), json!(4.0)); - } - - #[test] - fn t2c_fixed_widths_are_positions_in_any_order_without_duplicates() { - let cases: [(Json, [&str; 4]); 5] = [ - (json!([6, 3]), ["abc", "def", "ghij", ""]), - (json!([3, 3]), ["abc", "defghij", "", ""]), - (json!([0]), ["abcdefghij", "", "", ""]), - (json!([20]), ["abcdefghij", "", "", ""]), - (json!([7, 0, 3, 7, 10]), ["abc", "defg", "hij", ""]), - ]; - for (widths, want) in cases { - let mut s = Session::new(); - s.new_workbook(); - s.execute("cell.set", json!({"cell": "A1", "input": "abcdefghij"})).unwrap(); - s.execute("data.textToColumns", json!({"range": "A1:A1", "fixedWidths": widths})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - let got: Vec = (0..4).map(|c| sh.value(CellRef::new(0, c)).display()).collect(); - assert_eq!(got, want, "{widths}"); - } - } - - #[test] - fn split() { - assert_eq!(split_delimited("a,b,,c", &[','], false, '"'), ["a", "b", "", "c"]); - assert_eq!(split_delimited("a,b,,c", &[','], true, '"'), ["a", "b", "c"]); - assert_eq!(split_delimited("\"x,y\",z", &[','], false, '"'), ["x,y", "z"]); - } - - #[test] - fn remove_duplicates_without_a_valid_column_is_refused() { - // `columns: []` (or only unusable names) used to compare nothing and delete every row - // but the first. - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [["a"], ["b"], ["c"]]})).unwrap(); - for columns in [json!([]), json!(["ZZZ"])] { - let err = s.execute("data.removeDuplicates", json!({"range": "A1:A3", "columns": columns})).unwrap_err(); - assert!(err.to_string().contains("columns"), "{err}"); - } - let sh = s.doc().unwrap().wb.active().unwrap(); - assert_eq!(sh.value(CellRef::new(0, 0)), Value::text("a")); - assert_eq!(sh.value(CellRef::new(2, 0)), Value::text("c")); - } - - #[test] - fn a_list_typed_without_quotes_is_saved_as_a_quoted_list() { - // In a file an inline list is a string literal (`"a,b"`); unquoted it reads as a formula. - // References, names and formulas stay unquoted, and every rule survives a save and reopen. - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "K1:K3", "values": [["Red"], ["Green"], ["Blue"]]})).unwrap(); - s.execute("formulas.defineName", json!({"name": "Colors", "refersTo": "=Sheet1!$K$1:$K$3"})).unwrap(); - let rules = [ - ("A1", "Open,In progress,Closed", r#""Open,In progress,Closed""#), - ("B1", r#""Open,In progress,Closed""#, r#""Open,In progress,Closed""#), - ("C1", " 1,2,3 ", r#""1,2,3""#), - ("D1", r#"Say "hi",Bye"#, r#""Say ""hi"",Bye""#), - ("E1", "=$K$1:$K$3", "$K$1:$K$3"), - ("F1", "$K$1:$K$3", "$K$1:$K$3"), - ("G1", "=Colors", "Colors"), - ("H1", "Sheet1!$K$1:$K$3", "Sheet1!$K$1:$K$3"), - ("I1", "=OFFSET($K$1,0,0,3,1)", "OFFSET($K$1,0,0,3,1)"), - ]; - for (cell, source, _) in rules { - s.execute("data.validation", json!({"range": cell, "type": "list", "formula1": source})).unwrap(); - } - let accepted = [ - ("A1", "In progress"), - ("B1", "Closed"), - ("C1", "2"), - ("D1", r#"Say "hi""#), - ("E1", "Green"), - ("F1", "Blue"), - ("G1", "Red"), - ("H1", "Green"), - ]; - let check = |wb: &Workbook| { - for (cell, input) in accepted { - let at = CellRef::parse(cell).unwrap(); - assert!(check_validation(wb, 0, at, input).is_none(), "{cell} refuses {input}"); - assert!(check_validation(wb, 0, at, "Pending").is_some(), "{cell} accepts Pending"); - } - }; - let wb = s.doc().unwrap().wb.clone(); - check(&wb); - - let sheet_xml = |wb: &Workbook| { - let bytes = gridcraft_xlsx::write_xlsx(wb).unwrap(); - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut xml = String::new(); - std::io::Read::read_to_string(&mut zip.by_name("xl/worksheets/sheet1.xml").unwrap(), &mut xml).unwrap(); - xml - }; - let xml = sheet_xml(&wb); - for (cell, _, saved) in rules { - assert!(xml.contains(&format!(r#"sqref="{cell}">{saved}"#)), "{cell}: {saved} missing from {xml}"); - } - let (reopened, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap(); - check(&reopened); - assert_eq!(sheet_xml(&reopened), xml, "a second save writes the same rules"); - } - - #[test] - fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() { - // A typo used to give a rule that validates nothing (`type="none"`) or the wrong check, - // with no error. - let mut s = Session::new(); - s.new_workbook(); - for params in [ - json!({"range": "A1", "type": "lst", "formula1": "\"a,b\""}), - json!({"range": "A1", "type": "whole", "operator": "greaterthan", "formula1": "1"}), - json!({"range": "A1", "type": "whole", "operator": ">", "formula1": "1"}), - json!({"range": "A1", "type": "list", "formula1": "\"a,b\"", "errorStyle": "warn"}), - ] { - let e = s.execute("data.validation", params.clone()).unwrap_err().to_string(); - assert!(e.contains("unknown"), "{params}: {e}"); - } - assert!(s.doc().unwrap().wb.active().unwrap().validations.is_empty()); - for params in [ - json!({"range": "A1", "type": "any"}), - json!({"range": "A2", "type": "whole", "operator": "greaterThan", "formula1": "1"}), - json!({"range": "A3", "type": "list", "formula1": "\"a,b\"", "errorStyle": "warning"}), - ] { - s.execute("data.validation", params).unwrap(); - } - let sh = s.doc().unwrap().wb.active().unwrap().clone(); - assert_eq!(sh.validations.len(), 3); - assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some()); - } -} +mod tests; diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs new file mode 100644 index 0000000000..1b52e45372 --- /dev/null +++ b/crates/engine/src/cmd/data/filter.rs @@ -0,0 +1,319 @@ +use super::sort::sort_key; +use super::{ + AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, + current_region, data_target, edit, json, +}; + +// ---------------------------------------------------------------- filter + +pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { + let (sheet, r) = data_target(s, p, "data.filter")?; + crate::cmd::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?; + // The active cell belongs to the active sheet: on another sheet the table is the one at `range`. + let at = if sheet == s.doc()?.wb.active_sheet() { s.doc()?.selection.active } else { r.start }; + 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 { + return edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + 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(); + } + } + Ok(Json::Null) + }); + } + if has { + return edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + // Reveal only rows the filter hid; rows hidden by hand or by a collapsed group stay hidden. + let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); + sh.autofilter = None; + for r in filtered { + if let Some(info) = sh.rows.get_mut(&r) { + info.hidden = false; + } + } + cx.structural = true; + Ok(json!({"filter": false})) + }); + } + install_filter(s, p) +} + +/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection. +fn install_filter(s: &mut Session, p: &Json) -> Result { + let (sheet, mut r) = data_target(s, p, "data.filter")?; + // A selected header row filters the data below it (#201). + if p.get("range").is_none() && r.height() == 1 { + let d = s.doc()?; + let sh = d.wb.active().ok_or(EngineError::NoDocument)?; + let below = current_region(sh, r.start).end.row; + if below > r.end.row { + r = RangeRef::new(r.start, CellRef::new(below, r.end.col)); + } + } + edit(s, |cx| { + cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] }); + Ok(json!({"filter": true, "range": r.a1()})) + }) +} + +pub(super) fn filter_by(s: &mut Session, p: &Json) -> Result { + let sheet = s.doc()?.wb.active_sheet(); + crate::cmd::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?; + let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + let af = match &sh.autofilter { + Some(a) => a.clone(), + None => { + install_filter(s, &json!({}))?; + s.doc()?.wb.sheet(sheet).and_then(|sh| sh.autofilter.clone()).ok_or_else(|| EngineError::Other("no filter".into()))? + } + }; + let col = match col_param(p.get("column"), af.range.start.col) { + Some(c) => c, + // A number too large to be a column is outside the filter range, not a missing parameter. + None if p.get("column").is_some_and(|v| v.as_u64().is_some()) => return Err(bad("data.filterBy", "column outside the filter range")), + None => return Err(bad("data.filterBy", "missing `column`")), + }; + if col < af.range.start.col || col > af.range.end.col { + return Err(bad("data.filterBy", "column outside the filter range")); + } + let off = col - af.range.start.col; + let crit = if bool_param(p, "clear").unwrap_or(false) { + None + } else if let Some(vals) = p.get("values").and_then(Json::as_array) { + Some(FilterCriterion::Values { + values: vals.iter().map(crate::cmd::edit::json_to_input).collect(), + blanks: bool_param(p, "blanks").unwrap_or(false), + }) + } else if let Some(c) = p.get("custom") { + let a = + (c.get("op").and_then(Json::as_str).unwrap_or("=").to_string(), c.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default()); + let b = + c.get("op2").and_then(Json::as_str).map(|o| (o.to_string(), c.get("value2").map(crate::cmd::edit::json_to_input).unwrap_or_default())); + Some(FilterCriterion::Custom { a, b, and: c.get("and").and_then(Json::as_bool).unwrap_or(true) }) + } else if let Some(t) = p.get("top") { + Some(FilterCriterion::Top10 { + bottom: t.get("bottom").and_then(Json::as_bool).unwrap_or(false), + percent: t.get("percent").and_then(Json::as_bool).unwrap_or(false), + count: t.get("count").and_then(Json::as_u64).unwrap_or(10) as u32, + }) + } else { + bool_param(p, "aboveAverage").map(FilterCriterion::AboveAverage) + }; + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + if let Some(a) = sh.autofilter.as_mut() { + a.criteria.retain(|(o, _)| *o != off); + if let Some(c) = crit.clone() { + a.criteria.push((off, c)); + } + } + apply_filter(&mut cx.wb, sheet); + cx.structural = true; + Ok(Json::Null) + })?; + let hidden = s.doc()?.wb.sheet(sheet).map(|sh| sh.rows.values().filter(|r| r.hidden).count()).unwrap_or(0); + Ok(json!({"hiddenRows": hidden})) +} + +/// Does a value pass a custom comparison (`>`, `=*abc*`, `<>x`…)? +fn custom_ok(v: &Value, text: &str, op: &str, crit: &str) -> bool { + let num = gridcraft_core::parse::parse_number_text(crit); + let cmp = match (v.as_f64(), num) { + (Some(a), Some(b)) => a.partial_cmp(&b), + // A numeric ordering comparison only matches numbers; blanks and text never do. + (None, Some(_)) if matches!(op, "<" | "<=" | ">" | ">=") => None, + _ => Some(gridcraft_core::compare_text(text, crit)), + }; + let wild = || crate::cmd::edit::wildcard(&text.to_lowercase(), &crit.to_lowercase()); + match op { + "=" => { + if crit.contains(['*', '?']) { + wild() + } else { + cmp == Some(Ordering::Equal) + } + } + "<>" => { + if crit.contains(['*', '?']) { + !wild() + } else { + cmp != Some(Ordering::Equal) + } + } + ">" => cmp == Some(Ordering::Greater), + "<" => cmp == Some(Ordering::Less), + ">=" => matches!(cmp, Some(Ordering::Greater | Ordering::Equal)), + "<=" => matches!(cmp, Some(Ordering::Less | Ordering::Equal)), + "beginsWith" => text.to_lowercase().starts_with(&crit.to_lowercase()), + "endsWith" => text.to_lowercase().ends_with(&crit.to_lowercase()), + "contains" => text.to_lowercase().contains(&crit.to_lowercase()), + "notContains" => !text.to_lowercase().contains(&crit.to_lowercase()), + _ => true, + } +} + +/// The filter's "(Blanks)" group: truly empty cells and zero-length text such as a `=""` result. +fn filter_blank(v: &Value) -> bool { + v.is_empty() || matches!(v, Value::Text(t) if t.is_empty()) +} + +/// Excel grows an AutoFilter range when a value is entered in the row right below it, in one of its columns (#2342). +/// A table's own filter is left to the table, and a row typed after a blank row does not count. +/// A formula counts before it is calculated: this runs inside the edit, ahead of the recalc. +pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { + if !sh.cells.get(at).is_some_and(|c| !filter_blank(&c.value) || c.formula.is_some()) { + return; + } + let Some(af) = sh.autofilter.as_ref() else { return }; + let r = af.range; + if r.end.row.checked_add(1) != Some(at.row) || at.col < r.start.col || at.col > r.end.col || sh.tables.iter().any(|t| t.range == r) { + return; + } + let grown = RangeRef::new(r.start, CellRef::new(at.row, r.end.col)); + if let Some(af) = sh.autofilter.as_mut() { + af.range = grown; + } +} + +/// 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 }; + let r = af.range; + let mut hide = Vec::new(); + // Precompute per-criterion top10 threshold and average once, not per row. + let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); + for (i, (off, c)) in af.criteria.iter().enumerate() { + if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { + let col = r.start.col + off; + let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); + let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::() / nums.len() as f64 }; + let thr = match c { + FilterCriterion::Top10 { bottom, percent, count } => { + nums.sort_by(|a, b| if *bottom { a.partial_cmp(b) } else { b.partial_cmp(a) }.unwrap_or(Ordering::Equal)); + let k = if *percent { ((nums.len() as f64) * (*count as f64) / 100.0).ceil() as usize } else { *count as usize }; + let k = k.clamp(1, nums.len().max(1)); + nums.get(k - 1).copied() + } + _ => None, + }; + col_stats.insert(i, (thr, avg)); + } + } + for row in r.start.row + 1..=r.end.row { + let mut visible = true; + for (i, (off, crit)) in af.criteria.iter().enumerate() { + let c = CellRef::new(row, r.start.col + off); + let v = sh.value(c); + let text = crate::display::cell_text(wb, sh, c); + let ok = match crit { + FilterCriterion::Values { values, blanks } => { + if filter_blank(&v) { + *blanks + } else { + values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + } + } + FilterCriterion::Custom { a, b, and } => { + let x = custom_ok(&v, &text, &a.0, &a.1); + match b { + Some(b) => { + let y = custom_ok(&v, &text, &b.0, &b.1); + if *and { x && y } else { x || y } + } + None => x, + } + } + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { + (Some(n), Some((thr, _))) => { + let thr = thr.unwrap_or(n); + if *bottom { n <= thr } else { n >= thr } + } + _ => false, + }, + FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { + (Some(n), Some((_, avg))) => { + if *above { + n > *avg + } else { + n < *avg + } + } + _ => false, + }, + FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, + // Icons are not evaluated here: the row keeps its current visibility. + FilterCriterion::Icon { .. } => !sh.is_row_hidden(row), + }; + if !ok { + visible = false; + break; + } + } + hide.push((row, !visible)); + } + let Some(shm) = wb.sheet_mut(sheet) else { return }; + for (row, h) in hide { + if h { + shm.rows.entry(row).or_default().hidden = true; + } else if let Some(e) = shm.rows.get_mut(&row) { + e.hidden = false; + } + } +} + +pub(super) fn clear_filter(s: &mut Session, _: &Json) -> Result { + let sheet = s.doc()?.wb.active_sheet(); + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + if let Some(a) = sh.autofilter.as_mut() { + a.criteria.clear(); + } + apply_filter(&mut cx.wb, sheet); + cx.structural = true; + Ok(Json::Null) + }) +} + +pub(super) fn reapply(s: &mut Session, _: &Json) -> Result { + let sheet = s.doc()?.wb.active_sheet(); + edit(s, |cx| { + apply_filter(&mut cx.wb, sheet); + cx.structural = true; + Ok(Json::Null) + }) +} + +/// Distinct display values of a filter column (for the dropdown list). +pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> { + let Some(sh) = wb.sheet(sheet) else { return vec![] }; + let Some(af) = &sh.autofilter else { return vec![] }; + let off = col.saturating_sub(af.range.start.col); + let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); + let mut seen = std::collections::BTreeMap::new(); + for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) { + let c = CellRef::new(row, col); + let v = sh.value(c); + let blank = filter_blank(&v); + let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; + let on = match selected { + Some(FilterCriterion::Values { values, blanks }) => { + if blank { + *blanks + } else { + values.iter().any(|x| x.eq_ignore_ascii_case(&t)) + } + } + _ => true, + }; + let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; + seen.entry((key, t)).or_insert(on); + } + seen.into_iter().map(|((_, t), on)| (t, on)).collect() +} diff --git a/crates/engine/src/cmd/data/grouping.rs b/crates/engine/src/cmd/data/grouping.rs new file mode 100644 index 0000000000..d2e183ae15 --- /dev/null +++ b/crates/engine/src/cmd/data/grouping.rs @@ -0,0 +1,270 @@ +use super::{ + CellRef, EngineError, Json, LineInfo, RangeRef, Result, Session, bad, bool_param, col_param, data_target, edit, json, outline, parse_lines, + str_param, target_sheet, +}; + +// ---------------------------------------------------------------- outline + +fn outline_lines(s: &Session, p: &Json) -> Result<(bool, u32, u32)> { + if let Some(r) = str_param(p, "rows").and_then(parse_lines) { + return Ok((true, r.start.row, r.end.row)); + } + if let Some(r) = str_param(p, "cols").and_then(parse_lines) { + return Ok((false, r.start.col, r.end.col)); + } + let r = s.doc()?.selection.current(); + match str_param(p, "by") { + Some("rows") => Ok((true, r.start.row, r.end.row)), + Some("cols" | "columns") => Ok((false, r.start.col, r.end.col)), + _ if r.is_full_cols() && !r.is_full_rows() => Ok((false, r.start.col, r.end.col)), + _ => Ok((true, r.start.row, r.end.row)), + } +} + +pub(super) fn group(s: &mut Session, p: &Json, on: bool) -> Result { + let si = target_sheet(s, p)?; + // The selection belongs to the active sheet, so another sheet needs its lines. + if si != s.doc()?.wb.active_sheet() && p.get("rows").is_none() && p.get("cols").is_none() { + return Err(bad(if on { "data.group" } else { "data.ungroup" }, "missing `rows` or `cols`: the selection is on the active sheet")); + } + let (rows, a, b) = outline_lines(s, p)?; + edit(s, |cx| { + let sh = cx.sheet_mut(si)?; + let before = outline::summary_before(sh, rows); + let map = if rows { &mut sh.rows } else { &mut sh.cols }; + let b = b.min(a.saturating_add(1_048_575)); + for i in a..=b { + let e = map.entry(i).or_default(); + e.outline = if on { (e.outline + 1).min(outline::MAX_LEVEL) } else { e.outline.saturating_sub(1) }; + if !on && e.outline == 0 { + e.hidden = false; + } + } + // A summary line whose group is gone has nothing left to collapse. + let summary = if before { a.checked_sub(1) } else { b.checked_add(1) }; + if !on + && !outline::groups_with(map, before).iter().any(|g| if before { g.start == a } else { g.end == b }) + && let Some(e) = summary.and_then(|i| map.get_mut(&i)) + { + e.collapsed = false; + } + cx.structural = true; // ungrouping reveals hidden rows: SUBTOTAL(10x) depends on it + Ok(Json::Null) + }) +} + +/// Hide Detail / Show Detail: the innermost group (or the one at `level`) that holds the lines, or +/// failing that the one they are the summary of. Hiding marks the summary line collapsed (the +/// + button, saved to XLSX); showing keeps inner groups that were collapsed on their own collapsed. +pub(super) fn detail(s: &mut Session, p: &Json, hide: bool) -> Result { + let (rows, a, b) = outline_lines(s, p)?; + let want = p.get("level").and_then(Json::as_u64).map(|l| l.min(outline::MAX_LEVEL as u64) as u8); + edit(s, |cx| { + let si = cx.sheet_index(); + let sh = cx.sheet_mut(si)?; + let before = outline::summary_before(sh, rows); + let map = if rows { &mut sh.rows } else { &mut sh.cols }; + let all = outline::groups_with(map, before); + let level_ok = |g: &outline::OutlineGroup| want.is_none_or(|l| g.level == l); + let pick = |hit: &dyn Fn(&outline::OutlineGroup) -> bool| -> Vec { + let hits: Vec<_> = all.iter().filter(|g| level_ok(g) && hit(g)).copied().collect(); + let deepest = hits.iter().map(|g| g.level).max().unwrap_or(0); + hits.into_iter().filter(|g| g.level == deepest).collect() + }; + let mut chosen = pick(&|g| g.start <= b && g.end >= a); + if chosen.is_empty() { + chosen = pick(&|g| g.has_summary() && g.summary() >= a && g.summary() <= b); + } + for g in chosen { + // Inner groups collapsed on their own (their summary marked), before this one changes. + let inner: Vec = all + .iter() + .filter(|o| o.level > g.level && o.start >= g.start && o.end <= g.end && o.has_summary() && o.summary() != g.summary()) + .filter(|o| map.get(&o.summary()).is_some_and(|e| e.collapsed)) + .copied() + .collect(); + for i in g.start..=g.end { + if let Some(e) = map.get_mut(&i) { + set_hidden(e, hide || inner.iter().any(|o| o.contains(i))); + } + } + if !g.has_summary() { + continue; + } + if hide { + map.entry(g.summary()).or_default().collapsed = true; + } else if let Some(e) = map.get_mut(&g.summary()) { + e.collapsed = false; + } + } + cx.structural = true; + Ok(Json::Null) + }) +} + +/// Hides or shows an outline line. A line shown with a zero size (files that hide columns as +/// `width="0" hidden="1"`) gets the default size back, as Unhide does; otherwise + would mark the +/// group expanded and leave it invisible (#1714). +fn set_hidden(e: &mut LineInfo, hidden: bool) { + e.hidden = hidden; + if !hidden && e.size == Some(0.0) { + e.size = None; + } +} + +/// The outline's level buttons: show rows / columns down to outline level `n` (1 = only the +/// top-level summaries); deeper detail is hidden and its summary lines marked collapsed. +pub(super) fn show_levels(s: &mut Session, p: &Json) -> Result { + let level = |k: &str| p.get(k).and_then(Json::as_u64).map(|n| n.clamp(1, outline::MAX_LEVEL as u64 + 1) as u8); + let (rows, cols) = (level("rows"), level("cols")); + if rows.is_none() && cols.is_none() { + return Err(EngineError::BadParams { + cmd: "data.showLevels".into(), + msg: "give `rows` or `cols`: the outline level to show (1 = top-level summaries only)".into(), + }); + } + edit(s, |cx| { + let si = cx.sheet_index(); + let sh = cx.sheet_mut(si)?; + let before = (outline::summary_before(sh, true), outline::summary_before(sh, false)); + for (map, n, before) in [(&mut sh.rows, rows, before.0), (&mut sh.cols, cols, before.1)] { + let Some(n) = n else { continue }; + let groups = outline::groups_with(map, before); + for e in map.values_mut().filter(|e| e.outline > 0) { + set_hidden(e, e.outline >= n); + } + // Inner groups come first, so a summary line shared with the group around it ends up + // as that outer group says. + for g in groups.into_iter().filter(|g| g.has_summary()) { + map.entry(g.summary()).or_default().collapsed = g.level >= n; + } + } + cx.structural = true; + Ok(Json::Null) + }) +} + +/// Data ▸ Outline ▸ Settings: whether summary rows sit below their detail and summary columns +/// right of it. A changed direction moves each collapsed group's mark (+) to its new summary line. +/// Moves the collapsed marks of a line axis to the summary line on its new side (`on` is the new +/// setting, `was_before` the old one). A line that nested groups share keeps its mark on the outermost +/// group whose detail is all hidden, or the outermost when none is. +fn move_marks(map: &mut std::collections::BTreeMap, was_before: bool, on: bool) { + let mut marked: Vec = + outline::groups_with(map, was_before).into_iter().filter(|g| g.has_summary() && map.get(&g.summary()).is_some_and(|e| e.collapsed)).collect(); + // A mark on a line that nested groups share moves with the outermost of them whose + // detail is all hidden, or with the outermost when none is. + let mut owner: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for g in &marked { + let key = (!g.collapsed, g.level); + let best = owner.entry(g.summary()).or_insert(key); + *best = (*best).min(key); + } + marked.retain(|g| owner.get(&g.summary()) == Some(&(!g.collapsed, g.level))); + for g in &marked { + if let Some(e) = map.get_mut(&g.summary()) { + e.collapsed = false; + } + } + for g in marked { + let g = outline::OutlineGroup { summary_before: !on, ..g }; + if g.has_summary() { + map.entry(g.summary()).or_default().collapsed = true; + } + } +} + +pub(super) fn outline_settings(s: &mut Session, p: &Json) -> Result { + let si = target_sheet(s, p)?; + edit(s, |cx| { + let sh = cx.sheet_mut(si)?; + for (rows, key) in [(true, "summaryBelow"), (false, "summaryRight")] { + let Some(on) = bool_param(p, key) else { continue }; + let was_before = outline::summary_before(sh, rows); + if rows { + sh.summary_below = on; + } else { + sh.summary_right = on; + } + if was_before != on { + continue; + } + move_marks(if rows { &mut sh.rows } else { &mut sh.cols }, was_before, on); + } + Ok(json!({"summaryBelow": sh.summary_below, "summaryRight": sh.summary_right})) + }) +} + +pub(super) fn subtotal(s: &mut Session, p: &Json) -> Result { + let (sheet, r) = data_target(s, p, "data.subtotal")?; + let header = bool_param(p, "header").unwrap_or(true); + let group_col = col_param(p.get("groupBy"), r.start.col).unwrap_or(r.start.col); + let func = str_param(p, "function").unwrap_or("sum"); + let code = match func { + "count" => 3, + "average" => 1, + "max" => 4, + "min" => 5, + "product" => 6, + _ => 9, + }; + let cols: Vec = p + .get("columns") + .and_then(Json::as_array) + .map(|a| a.iter().filter_map(|c| col_param(Some(c), r.start.col)).collect()) + .unwrap_or_else(|| vec![r.end.col]); + let label = match func { + "count" => "Count", + "average" => "Average", + "max" => "Max", + "min" => "Min", + "product" => "Product", + _ => "Total", + }; + // Group boundaries (header in the first row). + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + let mut groups: Vec<(u32, u32, String)> = Vec::new(); + let first = r.start.row + u32::from(header); + let mut start = first; + for row in first..=r.end.row + 1 { + let cur = sh.value(CellRef::new(row, group_col)).display(); + let prev = sh.value(CellRef::new(start, group_col)).display(); + if row > r.end.row || cur != prev { + groups.push((start, row - 1, prev)); + start = row; + } + } + // The totals go below each group, so the outline puts summary rows below their detail (the + // Subtotal dialog's "Summary below data"), in the same undo step. + if !sh.summary_below { + s.execute("data.outlineSettings", json!({"sheet": sheet, "summaryBelow": true}))?; + } + // Insert a total row after each group, bottom-up so indices stay valid. + let mut inserted = 0; + for (g0, g1, name) in groups.iter().rev() { + s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", g1 + 2, g1 + 2)}))?; + let row = g1 + 1; + let lbl = CellRef::new(row, group_col).a1(); + s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("{name} {label}")}))?; + for c in &cols { + let range = RangeRef::new(CellRef::new(*g0, *c), CellRef::new(*g1, *c)).a1(); + s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(row, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?; + } + s.execute( + "home.bold", + json!({"sheet": sheet, "range": RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col)).a1(), "on": true}), + )?; + s.execute("data.group", json!({"sheet": sheet, "rows": format!("{}:{}", g0 + 1, g1 + 1)}))?; + inserted += 1; + } + let last = r.end.row + inserted + 1; + let lbl = CellRef::new(last, group_col).a1(); + s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", last + 1, last + 1)}))?; + s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("Grand {label}")}))?; + for c in &cols { + let range = RangeRef::new(CellRef::new(first, *c), CellRef::new(last - 1, *c)).a1(); + s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(last, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?; + } + Ok(json!({"groups": inserted})) +} diff --git a/crates/engine/src/cmd/data/sort.rs b/crates/engine/src/cmd/data/sort.rs new file mode 100644 index 0000000000..491e3d51e4 --- /dev/null +++ b/crates/engine/src/cmd/data/sort.rs @@ -0,0 +1,318 @@ +use super::{ + Anchor, AnchorMode, Arc, Cell, CellRef, Comment, EngineError, Formula, Hyperlink, Json, LineInfo, Ordering, RangeRef, Result, Session, Sheet, + Value, bad, bool_param, col_param, data_range, edit, guess_header, json, ok, sort_compare, split_sheet, str_param, target_sheet, +}; + +#[derive(Clone)] +struct SortKey { + col: u32, + desc: bool, + by: String, + list: Option>, +} + +/// The sheet and range a sort works on: the sheet `sheet` or a `Sheet!` prefix on `range` names, +/// else the active one. The selection belongs to the active sheet, so another sheet needs `range`. +fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> { + let sheet = target_sheet(s, p)?; + let d = s.doc()?; + if let Some(t) = str_param(p, "range") + && let (Some(name), _) = split_sheet(t) + && d.wb.sheet_index(&name) != Some(sheet) + { + return Err(bad("data.sort", format!("`{t}` names a sheet other than `sheet`"))); + } + if sheet != d.wb.active_sheet() && p.get("range").is_none() { + return Err(bad("data.sort", "missing `range`: the selection is on the active sheet")); + } + Ok((sheet, data_range(s, p)?)) +} + +pub(super) fn quick_sort(s: &mut Session, p: &Json, asc: bool) -> Result { + let (sheet, r) = sort_target(s, p)?; + let col = col_param(p.get("column"), r.start.col).unwrap_or(s.doc()?.selection.active.col).clamp(r.start.col, r.end.col); + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + let header = guess_header(&d.wb, sh, r); + do_sort(s, sheet, r, header, vec![SortKey { col, desc: !asc, by: "values".into(), list: None }], false, false) +} + +pub(super) fn sort(s: &mut Session, p: &Json) -> Result { + let (sheet, r) = sort_target(s, p)?; + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r)); + let by_cols = str_param(p, "orientation") == Some("columns"); + let case = bool_param(p, "matchCase").unwrap_or(false); + let mut keys: Vec = Vec::new(); + for k in p.get("keys").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default() { + let col = if by_cols { + let row = match k.get("row").and_then(Json::as_u64) { + // Worksheet rows are 1-based; 0 (or a value past u32) has no coordinate. + Some(n) => { + let row = u32::try_from(n).ok().and_then(|n| n.checked_sub(1)); + Some(row.ok_or_else(|| bad("data.sort", "sort key row must be 1 or greater"))?) + } + None => None, + }; + row.or_else(|| col_param(k.get("column"), r.start.row)) + } else { + col_param(k.get("column"), r.start.col) + }; + let Some(col) = col else { continue }; + keys.push(SortKey { + col, + desc: k.get("order").and_then(Json::as_str) == Some("desc"), + by: k.get("by").and_then(Json::as_str).unwrap_or("values").to_string(), + list: k.get("customList").and_then(Json::as_array).map(|l| l.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()), + }); + } + if keys.is_empty() { + s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header}))); + return ok(); + } + if keys.len() > 64 { + return Err(bad("data.sort", "too many sort levels (64 max)")); + } + do_sort(s, sheet, r, header, keys, by_cols, case) +} + +fn do_sort(s: &mut Session, sheet: usize, r: RangeRef, header: bool, keys: Vec, by_cols: bool, case: bool) -> Result { + // Protect Sheet ▸ Sort. Both Sort… and the A-to-Z buttons come through here. + crate::cmd::refuse_unless_allowed(s, sheet, "Sorting", |p| p.sort)?; + let body = if by_cols { + if header && r.width() > 1 { RangeRef::new(CellRef::new(r.start.row, r.start.col + 1), r.end) } else { r } + } else if header && r.height() > 1 { + RangeRef::new(CellRef::new(r.start.row + 1, r.start.col), r.end) + } else { + r + }; + if body.count() > 20_000_000 { + return Err(bad("data.sort", "range too large")); + } + edit(s, |cx| { + let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) }; + if sh.merges.iter().any(|m| m.intersects(&body) && !m.is_single()) { + return Err(EngineError::Other("To do this, all the merged cells need to be the same size.".into())); + } + let n = if by_cols { body.width() } else { body.height() }; + let line = |i: u32, k: u32| if by_cols { CellRef::new(k, body.start.col + i) } else { CellRef::new(body.start.row + i, k) }; + let theme = cx.wb.theme.clone(); + let styles = &cx.wb.styles; + let key_val = |i: u32, k: &SortKey| -> (Value, u32) { + let c = line(i, k.col); + let v = sh.value(c); + let color = match k.by.as_str() { + "cellColor" => { + styles.get(sh.style_id(c)).fill.fg.resolve(&theme).map(|[r, g, b]| u32::from_be_bytes([0, r, g, b])).unwrap_or(u32::MAX) + } + "fontColor" => { + styles.get(sh.style_id(c)).font.color.resolve(&theme).map(|[r, g, b]| u32::from_be_bytes([0, r, g, b])).unwrap_or(u32::MAX) + } + _ => 0, + }; + (v, color) + }; + let mut order: Vec = (0..n).collect(); + let keyed: Vec> = (0..n).map(|i| keys.iter().map(|k| key_val(i, k)).collect()).collect(); + order.sort_by(|&a, &b| { + for (ki, k) in keys.iter().enumerate() { + let (va, ca) = &keyed[a as usize][ki]; + let (vb, cb) = &keyed[b as usize][ki]; + let o = if k.by != "values" { + ca.cmp(cb) + } else if let Some(list) = &k.list { + let pos = |v: &Value| v.as_text().and_then(|t| list.iter().position(|x| x.eq_ignore_ascii_case(t))).unwrap_or(usize::MAX); + pos(va).cmp(&pos(vb)) + } else if case && va.is_text() && vb.is_text() { + sort_compare(va, vb).then_with(|| case_order(va.as_text().unwrap_or(""), vb.as_text().unwrap_or(""))) + } else { + sort_compare(va, vb) + }; + // Blanks always sort last, whatever the order. + let o = if k.desc && !(va.is_empty() || vb.is_empty()) { o.reverse() } else { o }; + if o != Ordering::Equal { + return o; + } + } + Ordering::Equal + }); + if order.iter().enumerate().all(|(i, &o)| i as u32 == o) { + return Ok(Json::Null); + } + // Move whole lines (cells with formulas adjusted for relative references). + let lanes: Vec = if by_cols { (body.start.row..=body.end.row).collect() } else { (body.start.col..=body.end.col).collect() }; + // Notes and hyperlinks hang off a cell, not a row, so they travel with the row they + // describe — the way cell pictures and row heights do. Collect them before inserting, + // so a swap can't resurrect one from a destination that is also a source. + let side: Vec<(CellRef, Comment)> = order + .iter() + .enumerate() + .flat_map(|(dst_i, &src_i)| lanes.iter().map(move |&k| (src_i, dst_i as u32, k))) + .filter_map(|(src_i, dst_i, k)| sh.comments.get(&line(src_i, k)).map(|cm| (line(dst_i, k), cm.clone()))) + .collect(); + let links: Vec<(CellRef, Hyperlink)> = order + .iter() + .enumerate() + .flat_map(|(dst_i, &src_i)| lanes.iter().map(move |&k| (src_i, dst_i as u32, k))) + .filter_map(|(src_i, dst_i, k)| sh.hyperlinks.get(&line(src_i, k)).map(|h| (line(dst_i, k), h.clone()))) + .collect(); + let mut moved: Vec<(CellRef, Option)> = Vec::with_capacity(body.count() as usize); + let mut pictures = Vec::new(); + for (dst_i, &src_i) in order.iter().enumerate() { + for &k in &lanes { + let src = line(src_i, k); + let dst = line(dst_i as u32, k); + let mut cell = sh.cell(src).cloned(); + if let Some(c) = cell.as_mut() + && let Some(f) = &c.formula + && let Some(e) = f.expr() + { + let shifted = gridcraft_formula::adjust::shift_relative(e, dst.row as i64 - src.row as i64, dst.col as i64 - src.col as i64); + c.formula = Some(Arc::new(Formula::from_expr(shifted))); + } + if let Some(picture) = sh.cell_pictures.get(&src) { + pictures.push((dst, picture.clone())); + } + moved.push((dst, cell)); + } + } + // Row heights travel with rows. + let heights: Vec> = + if by_cols { vec![] } else { order.iter().map(|&i| sh.rows.get(&(body.start.row + i)).copied()).collect() }; + // Floating objects anchored inside the sorted body travel with their lines, unless they + // are pinned absolutely ("Don't move or size with cells", `editAs="absolute"`). Reordering + // is the inverse of `order`: `dst_of[src] = dst`. + let dst_of: Vec = { + let mut v = vec![0u32; order.len()]; + for (dst_i, &src_i) in order.iter().enumerate() { + if let Some(slot) = v.get_mut(src_i as usize) { + *slot = dst_i as u32; + } + } + v + }; + // The object's own geometry (its top-left anchor cell, offset and size) is read from the + // pre-sort `sh`; a two-cell object's bottom-right cell is derived from its size here so it + // can be re-fitted to the lines it spans after the sort. + let objs: Vec = sh.object_anchors().copied().collect(); + let descs: Vec<(u32, u32, f32, f32)> = objs + .iter() + .map(|a| { + let x2 = sh.col_left(a.cell.col) + a.dx as f64 + a.width.max(0.0) as f64; + let y2 = sh.row_top(a.cell.row) + a.dy as f64 + a.height.max(0.0) as f64; + let tc = sh.col_at(x2); + let tr = sh.row_at(y2); + (tc, tr, (x2 - sh.col_left(tc)) as f32, (y2 - sh.row_top(tr)) as f32) + }) + .collect(); + let shm = cx.sheet_mut(sheet)?; + for (c, cell) in &moved { + match cell { + Some(x) => shm.set_cell(*c, x.clone()), + None => { + shm.remove_cell(*c); + } + } + } + // Every cell of the body is the destination of exactly one source cell, so clearing the + // body and inserting the permuted entries is the same permutation the cells went through. + for c in body.iter() { + shm.comments.remove(&c); + shm.hyperlinks.remove(&c); + } + for (at, cm) in side { + shm.comments.insert(at, cm); + } + for (at, h) in links { + shm.hyperlinks.insert(at, h); + } + shm.cell_pictures.extend(pictures); + for (i, h) in heights.into_iter().enumerate() { + let row = body.start.row + i as u32; + match h { + Some(info) => { + shm.rows.insert(row, LineInfo { hidden: shm.rows.get(&row).is_some_and(|x| x.hidden), ..info }); + } + None => { + if let Some(e) = shm.rows.get_mut(&row) { + e.size = None; + } + } + } + } + // Re-anchor floating objects now that the row heights are final. `objs` was collected in + // `object_anchors` order, which `object_anchors_mut` repeats. + // Only objects anchored inside the sorted block move: within its lines on the sort axis + // and within its span on the other axis (a picture beside the block stays put). + let (b0, b1) = if by_cols { (body.start.col, body.end.col) } else { (body.start.row, body.end.row) }; + let (o0, o1) = if by_cols { (body.start.row, body.end.row) } else { (body.start.col, body.end.col) }; + let new_anchors: Vec = objs + .into_iter() + .zip(descs) + .map(|(a, desc)| { + let other = if by_cols { a.cell.row } else { a.cell.col }; + if other < o0 || other > o1 { a } else { sorted_anchor(shm, a, desc, by_cols, b0, b1, &dst_of) } + }) + .collect(); + for (a, n) in shm.object_anchors_mut().zip(new_anchors) { + *a = n; + } + for (c, _) in moved { + cx.changed.push((sheet, c)); + } + cx.structural = true; + Ok(Json::Null) + })?; + Ok(json!({"sorted": body.a1()})) +} + +/// Re-anchor one floating object for a sort. `bottom` is the object's bottom-right line and the +/// offset of that corner inside it, measured before the sort. `map` (via `dst_of`) translates a +/// line index on the moving axis and is the identity outside `b0..=b1`. `sh` is the post-sort +/// grid (row heights already reordered), so re-fitting uses the heights the object lands on. +/// Objects pinned absolutely ("Don't move or size with cells") never move; "move but don't size" +/// keeps its size; "move and size" is re-fitted when its whole extent stays inside the body, and +/// keeps its size when the sort turns its lines around (its bottom line now sorts before its top +/// line), since the lines then enclose nothing to stretch it between. +fn sorted_anchor(sh: &Sheet, a: Anchor, bottom: (u32, u32, f32, f32), by_cols: bool, b0: u32, b1: u32, dst_of: &[u32]) -> Anchor { + if a.mode == AnchorMode::Absolute { + return a; + } + let (tc, tr, tdx, tdy) = bottom; + let map = |v: u32| -> u32 { if v >= b0 && v <= b1 { dst_of.get((v - b0) as usize).map_or(v, |&d| b0 + d) } else { v } }; + let (axis_start, axis_end) = if by_cols { (a.cell.col, tc) } else { (a.cell.row, tr) }; + if axis_start < b0 || axis_start > b1 { + return a; + } + let (nr, nc) = if by_cols { (a.cell.row, map(a.cell.col)) } else { (map(a.cell.row), a.cell.col) }; + if a.mode == AnchorMode::MoveAndSize && axis_end >= b0 && axis_end <= b1 { + let (nbr, nbc) = if by_cols { (tr, map(tc)) } else { (map(tr), tc) }; + let x1 = sh.col_left(nc) + a.dx as f64; + let y1 = sh.row_top(nr) + a.dy as f64; + let x2 = sh.col_left(nbc) + tdx as f64; + let y2 = sh.row_top(nbr) + tdy as f64; + // An extent that is not positive means the sort put the bottom-right line before the + // top-left one on that axis: the object keeps its old size there. + let fit = |extent: f64, old: f32| if extent > 0.0 { extent as f32 } else { old.max(0.0) }; + Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: fit(x2 - x1, a.width), height: fit(y2 - y1, a.height), mode: a.mode } + } else { + Anchor { cell: CellRef::new(nr, nc), ..a } + } +} + +/// Case-sensitive tie-break for text that is equal ignoring case: as in Excel, lowercase sorts +/// before uppercase at the first letter that differs in case. +fn case_order(a: &str, b: &str) -> Ordering { + a.chars().zip(b.chars()).find(|(x, y)| x != y).map_or(Ordering::Equal, |(x, y)| y.is_lowercase().cmp(&x.is_lowercase())) +} + +pub(super) fn sort_key(v: &Value) -> (u8, i64, String) { + match v { + Value::Number(n) => (0, (n * 1e6) as i64, String::new()), + Value::Text(t) => (1, 0, t.to_lowercase()), + Value::Bool(b) => (2, *b as i64, String::new()), + Value::Empty => (9, 0, String::new()), + _ => (3, 0, v.display()), + } +} diff --git a/crates/engine/src/cmd/data/tests.rs b/crates/engine/src/cmd/data/tests.rs new file mode 100644 index 0000000000..3c27824441 --- /dev/null +++ b/crates/engine/src/cmd/data/tests.rs @@ -0,0 +1,548 @@ +use super::*; + +#[test] +fn filter_blanks_include_empty_text_and_formula_results() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["id", "f"], ["e", null], ["ef", "=\"\""], ["sp", " "], ["z", 0]]})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B5"})).unwrap(); + let r = s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap(); + assert_eq!(r["hiddenRows"], json!(2)); + let vals = filter_values(&s.doc().unwrap().wb, 0, 1); + // The `=""` result joins (Blanks) instead of showing as its own empty entry. + assert!(!vals.iter().any(|(t, _)| t.is_empty()), "{vals:?}"); + let blanks: Vec<_> = vals.into_iter().filter(|(t, _)| t == "(Blanks)").collect(); + assert_eq!(blanks, vec![("(Blanks)".to_string(), true)]); +} + +#[test] +fn subtotal_honours_header_false() { + // #131: with header:false the first data row was treated as a header and left out of its + // group's subtotal and the grand total. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["East", 10], ["East", 20], ["West", 30], ["West", 40]]})).unwrap(); + s.execute("data.subtotal", json!({"range": "A1:B4", "groupBy": "A", "function": "sum", "columns": ["B"], "header": false})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + assert_eq!(get(&mut s, "A1")["value"], json!("East")); + assert_eq!(get(&mut s, "A3")["text"], json!("East Total")); + assert_eq!(get(&mut s, "B3")["value"], json!(30.0), "East's subtotal counts both East rows"); + assert_eq!(get(&mut s, "A7")["text"], json!("Grand Total")); + assert_eq!(get(&mut s, "B7")["value"], json!(100.0), "the grand total counts every data row"); +} + +#[test] +fn subtotal_puts_summary_rows_below_their_detail() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Sales"], ["East", 10], ["East", 20], ["West", 30]]})).unwrap(); + s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); + s.execute("data.subtotal", json!({"range": "A1:B4", "groupBy": "A", "columns": ["B"]})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + assert!(sh.summary_below, "the totals sit below their groups"); + // East's detail is rows 2–3 and its total row 4: collapsing level 1 keeps the total showing. + s.execute("data.showLevels", json!({"rows": 1})).unwrap(); + let hidden = |s: &Session, row: u32| s.doc().unwrap().wb.active().unwrap().is_row_hidden(row); + assert!(hidden(&s, 1) && hidden(&s, 2), "East's detail rows are hidden"); + assert!(!hidden(&s, 3), "East Total stays visible"); + // One undo takes the subtotals and the setting back. + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.summary_below); + assert_eq!(sh.value(CellRef::new(3, 0)).display(), "West"); +} + +#[test] +fn filter_by_huge_numeric_column_is_rejected_not_overflowed() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B1", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap(); + s.execute("data.filter", json!({"range": "B1:C3"})).unwrap(); + for col in [json!(2), json!(u64::from(u32::MAX)), json!(u64::MAX)] { + let err = s.execute("data.filterBy", json!({"column": col, "values": ["a"]})).unwrap_err(); + assert!(err.to_string().contains("column outside the filter range"), "{col}: {err}"); + } + let ok = s.execute("data.filterBy", json!({"column": 0, "values": ["a"]})).unwrap(); + assert_eq!(ok["hiddenRows"], json!(1)); +} + +#[test] +fn filter_by_inside_a_table_installs_the_autofilter_and_keeps_the_button() { + for sel in [json!({"cell": "A1"}), json!({"cell": "A2"}), json!({"range": "A1:A3"})] { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A3", "header": true})).unwrap(); + s.execute("selection.set", sel.clone()).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["a"]})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.autofilter.as_ref().map(|a| a.range.a1()), Some("A1:A3".to_string()), "{sel}"); + assert!(sh.tables[0].filter_button, "{sel}"); + assert!(!sh.is_row_hidden(1), "{sel}"); + assert!(sh.is_row_hidden(2), "{sel}"); + assert_eq!(sh.value(CellRef::new(2, 0)).display(), "b", "{sel}"); + } +} + +#[test] +fn autofilter_range_grows_when_a_value_is_entered_in_the_row_below() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Qty"], ["d", 4], ["b", 2]]})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B3"})).unwrap(); + let range = |s: &Session| s.doc().unwrap().wb.active().unwrap().autofilter.as_ref().map(|a| a.range.a1()); + s.execute("cell.set", json!({"cell": "A4", "input": "e"})).unwrap(); + assert_eq!(range(&s), Some("A1:B4".to_string())); + s.execute("range.setValues", json!({"range": "A5", "values": [["f", 6]]})).unwrap(); + assert_eq!(range(&s), Some("A1:B5".to_string())); + // A row typed after a blank row does not grow it. + s.execute("cell.set", json!({"cell": "A7", "input": "x"})).unwrap(); + assert_eq!(range(&s), Some("A1:B5".to_string())); + // A cell outside the filter's columns does not either. + s.execute("cell.set", json!({"cell": "C6", "input": "x"})).unwrap(); + assert_eq!(range(&s), Some("A1:B5".to_string())); + // Empty text is a blank entry, not a value. + s.execute("range.setValues", json!({"range": "A6", "parse": false, "values": [[""]]})).unwrap(); + assert_eq!(range(&s), Some("A1:B5".to_string())); + // A formula and Ctrl+Enter (range.fill) are entries too. + s.execute("cell.set", json!({"cell": "B6", "input": "=1+1"})).unwrap(); + assert_eq!(range(&s), Some("A1:B6".to_string())); + s.execute("range.fill", json!({"range": "A7:B7", "input": "g"})).unwrap(); + assert_eq!(range(&s), Some("A1:B7".to_string())); +} + +#[test] +fn list_validation_without_formula1_is_an_error() { + let mut s = Session::new(); + s.new_workbook(); + assert!(s.execute("data.validation", json!({"range": "A1:A3", "type": "list", "source": "\"a,b,c\""})).is_err()); + assert!(s.execute("data.validation", json!({"range": "A1:A3", "type": "list"})).is_err()); + assert!(s.doc().unwrap().wb.active().unwrap().validations.is_empty()); + s.execute("data.validation", json!({"range": "A1:A3", "type": "list", "formula1": "\"a,b,c\""})).unwrap(); + assert_eq!(s.execute("data.validate", json!({"cell": "A1", "input": "a"})).unwrap()["ok"], json!(true)); +} + +#[test] +fn partial_validation_edits_keep_the_rest_of_the_old_rule() { + let mut s = Session::new(); + s.new_workbook(); + let rule = |range: &str, lo: &str, hi: &str| json!({"range": range, "type": "whole", "operator": "between", "formula1": lo, "formula2": hi}); + let ok = + |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == json!(true); + s.execute("data.validation", rule("B1:B3", "1", "10")).unwrap(); + s.execute("data.validation", json!({"range": "B2", "clear": true})).unwrap(); + assert!(ok(&mut s, "B2", "999")); + assert!(!ok(&mut s, "B1", "999")); + assert!(!ok(&mut s, "B3", "999")); + s.execute("data.validation", rule("B2:B4", "100", "200")).unwrap(); + for cell in ["B2", "B3", "B4"] { + assert!(ok(&mut s, cell, "150"), "{cell}"); + assert!(!ok(&mut s, cell, "5"), "{cell}"); + } + assert!(ok(&mut s, "B1", "5")); + assert!(!ok(&mut s, "B1", "150")); +} + +#[test] +fn showing_detail_gives_zero_width_columns_their_width_back() { + // #1714: templates hide grouped columns as `width="0" hidden="1"`; + must show them. + let mut s = Session::new(); + s.new_workbook(); + let hidden = LineInfo { size: Some(0.0), hidden: true, outline: 1, ..LineInfo::default() }; + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + for c in 2..=4 { + sh.cols.insert(c, hidden); + } + sh.cols.insert(5, LineInfo { collapsed: true, ..LineInfo::default() }); + s.execute("data.showDetail", json!({"cols": "C:E", "level": 1})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + for c in 2..=4 { + assert_eq!(sh.col_width(c), sh.default_col_width, "column {c}"); + } + // Hiding again hides them; the level buttons show zero-width columns too. + s.execute("data.hideDetail", json!({"cols": "C:E", "level": 1})).unwrap(); + assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(2), 0.0); + Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().cols.insert(3, hidden); + s.execute("data.showLevels", json!({"cols": 2})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!((sh.col_width(2), sh.col_width(3)), (sh.default_col_width, sh.default_col_width)); +} + +#[test] +fn removing_an_autofilter_keeps_manually_hidden_and_collapsed_rows() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap(); + s.execute("data.group", json!({"rows": "2:4"})).unwrap(); + s.execute("data.hideDetail", json!({"rows": "2:4"})).unwrap(); + s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap(); + let hidden = |s: &Session| -> Vec { + let sh = s.doc().unwrap().wb.active().unwrap(); + sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect() + }; + let before = hidden(&s); + assert_eq!(before, [1, 2, 3, 9]); + s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none()); + assert_eq!(hidden(&s), before); + assert_eq!(row_state(&s, 4..=4), [(false, true)]); +} + +#[test] +fn table_dropdown_setup_outside_the_table_keeps_manually_hidden_rows() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A4", "header": true})).unwrap(); + s.execute("home.hideRows", json!({"rows": "3:3"})).unwrap(); + s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap(); + s.execute("selection.set", json!({"range": "E1"})).unwrap(); + // The table filter dropdown installs an AutoFilter on demand by toggling `data.filter` twice. + s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:A4"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect::>(), [2, 9]); +} + +/// Rows 5:8 grouped, with 6:7 grouped again inside (0-based 4..=7 and 5..=6). +fn nested_rows() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("data.group", json!({"rows": "5:8"})).unwrap(); + s.execute("data.group", json!({"rows": "6:7"})).unwrap(); + s +} + +/// (hidden, collapsed) of 0-based rows. +fn row_state(s: &Session, rows: std::ops::RangeInclusive) -> Vec<(bool, bool)> { + let sh = s.doc().unwrap().wb.active().unwrap(); + rows.map(|r| sh.rows.get(&r).map(|l| (l.hidden, l.collapsed)).unwrap_or_default()).collect() +} + +#[test] +fn hide_detail_marks_the_summary_collapsed_and_show_detail_keeps_inner_groups_collapsed() { + let mut s = nested_rows(); + s.execute("data.hideDetail", json!({"rows": "6:7", "level": 2})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); + s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]); + s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); + s.execute("data.showDetail", json!({"rows": "6:7", "level": 2})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(false, false); 5]); + // Each step is one undoable command. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(row_state(&s, 5..=7), [(true, false), (true, false), (false, true)]); +} + +#[test] +fn hide_detail_on_the_summary_row_collapses_the_group_above_it() { + let mut s = nested_rows(); + s.execute("data.hideDetail", json!({"rows": "9:9"})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, false), (false, true)]); +} + +#[test] +fn show_levels_collapses_and_expands_to_a_level() { + let mut s = nested_rows(); + s.execute("data.showLevels", json!({"rows": 1})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]); + s.execute("data.showLevels", json!({"rows": 2})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]); + s.execute("data.showLevels", json!({"rows": 3})).unwrap(); + assert_eq!(row_state(&s, 4..=8), [(false, false); 5]); + // Columns are separate; no level at all is an error rather than a guess. + s.execute("data.group", json!({"cols": "C:E"})).unwrap(); + s.execute("data.showLevels", json!({"cols": 1})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!((2..=4).all(|c| sh.cols.get(&c).is_some_and(|l| l.hidden))); + assert!(sh.cols.get(&5).is_some_and(|l| l.collapsed)); + assert_eq!(row_state(&s, 4..=4), [(false, false)]); + assert!(s.execute("data.showLevels", json!({})).is_err()); +} + +#[test] +fn group_by_columns_for_a_block_of_cells() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("data.group", json!({"by": "cols"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!((1..=2).all(|c| sh.cols.get(&c).is_some_and(|l| l.outline == 1))); + assert!(sh.rows.values().all(|l| l.outline == 0)); +} + +#[test] +fn group_shortcuts_are_the_windows_ones() { + let sc = |id: &str| specs().into_iter().find(|c| c.id == id).and_then(|c| c.shortcut); + assert_eq!(sc("data.group"), Some("Alt+Shift+Right")); + assert_eq!(sc("data.ungroup"), Some("Alt+Shift+Left")); +} + +#[test] +fn summary_rows_above_the_detail_take_the_collapsed_mark() { + let mut s = nested_rows(); + let r = s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); + assert_eq!(r, json!({"summaryBelow": false, "summaryRight": true})); + // Row 4 (index 3) is the outer group's summary, row 5 the inner one's. + s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, true), (true, false), (true, false), (true, false), (true, false), (false, false)]); + s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, false); 6]); + // Hide Detail on the summary row collapses the group below it. + s.execute("data.hideDetail", json!({"rows": "4:4"})).unwrap(); + assert_eq!(row_state(&s, 3..=4), [(false, true), (true, false)]); + s.execute("data.showLevels", json!({"rows": 1})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, true), (true, true), (true, false), (true, false), (true, false), (false, false)]); + // Ungrouping the outer group clears its mark on the row above. + s.execute("data.showLevels", json!({"rows": 3})).unwrap(); + s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + s.execute("data.ungroup", json!({"rows": "5:8"})).unwrap(); + assert_eq!(row_state(&s, 3..=3), [(false, false)]); +} + +#[test] +fn changing_the_summary_direction_moves_collapsed_marks() { + let mut s = nested_rows(); + s.execute("data.group", json!({"cols": "C:E"})).unwrap(); + s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + s.execute("data.hideDetail", json!({"cols": "C:E"})).unwrap(); + s.execute("data.outlineSettings", json!({"summaryBelow": false, "summaryRight": false})).unwrap(); + let col_marked = |s: &Session, c: u32| s.doc().unwrap().wb.active().unwrap().cols.get(&c).is_some_and(|l| l.collapsed); + assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [true, false, false, false, false, false]); + assert!(col_marked(&s, 1) && !col_marked(&s, 5)); + s.execute("data.outlineSettings", json!({"summaryBelow": true})).unwrap(); + assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [false, false, false, false, false, true]); + assert!(col_marked(&s, 1), "columns keep their direction"); + // One undo step per change; no params leaves the settings as they are. + s.execute("edit.undo", json!({})).unwrap(); + assert!(row_state(&s, 3..=3)[0].1); + assert_eq!(s.execute("data.outlineSettings", json!({})).unwrap(), json!({"summaryBelow": false, "summaryRight": false})); + // Nested groups that end on one row share its mark: it moves to the outer group only. + let mut s = Session::new(); + s.new_workbook(); + s.execute("data.group", json!({"rows": "5:8"})).unwrap(); + s.execute("data.group", json!({"rows": "6:8"})).unwrap(); + s.execute("data.showLevels", json!({"rows": 1})).unwrap(); + s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); + assert_eq!(row_state(&s, 3..=8).iter().map(|r| r.1).collect::>(), [true, false, false, false, false, false]); + s.execute("data.showDetail", json!({"rows": "4:4"})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, false); 6]); + // With only the inner group collapsed, its mark goes to row 5, and the outer group's + // Hide and Show Detail keep it collapsed. + s.execute("data.outlineSettings", json!({"summaryBelow": true})).unwrap(); + s.execute("data.hideDetail", json!({"rows": "6:8", "level": 2})).unwrap(); + s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, false), (false, true), (true, false), (true, false), (true, false), (false, false)]); + s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap(); + assert_eq!(row_state(&s, 3..=8), [(false, false), (false, true), (true, false), (true, false), (true, false), (false, false)]); + // A group on the first row has no row above it to mark. + let mut s = Session::new(); + s.new_workbook(); + s.execute("data.group", json!({"rows": "1:3"})).unwrap(); + s.execute("data.outlineSettings", json!({"summaryBelow": false})).unwrap(); + s.execute("data.hideDetail", json!({"rows": "1:3"})).unwrap(); + assert_eq!(row_state(&s, 0..=3), [(true, false), (true, false), (true, false), (false, false)]); +} + +#[test] +fn column_sort_rejects_row_key_zero_without_panicking() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "2"})).unwrap(); + for row in [0u64, 1 << 32] { + let params = json!({"range": "A1:B2", "header": false, "orientation": "columns", "keys": [{"row": row}]}); + let err = s.execute("data.sort", params).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "row {row}: {err:?}"); + } +} + +#[test] +fn single_row_and_column_parameters() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2], [3, 4]]})).unwrap(); + s.execute("home.insertRows", json!({"rows": "2"})).unwrap(); + s.execute("home.insertColumns", json!({"cols": "B"})).unwrap(); + let v = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + assert_eq!(v(&mut s, "C3"), json!(4.0)); + s.execute("home.hideRows", json!({"rows": "1"})).unwrap(); + s.execute("data.group", json!({"cols": "C"})).unwrap(); + assert!(s.execute("home.deleteRows", json!({"rows": "0"})).is_err()); + s.execute("home.deleteRows", json!({"rows": "2"})).unwrap(); + s.execute("home.deleteColumns", json!({"cols": "B"})).unwrap(); + assert_eq!(v(&mut s, "B2"), json!(4.0)); +} + +#[test] +fn t2c_fixed_widths_are_positions_in_any_order_without_duplicates() { + let cases: [(Json, [&str; 4]); 5] = [ + (json!([6, 3]), ["abc", "def", "ghij", ""]), + (json!([3, 3]), ["abc", "defghij", "", ""]), + (json!([0]), ["abcdefghij", "", "", ""]), + (json!([20]), ["abcdefghij", "", "", ""]), + (json!([7, 0, 3, 7, 10]), ["abc", "defg", "hij", ""]), + ]; + for (widths, want) in cases { + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "abcdefghij"})).unwrap(); + s.execute("data.textToColumns", json!({"range": "A1:A1", "fixedWidths": widths})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + let got: Vec = (0..4).map(|c| sh.value(CellRef::new(0, c)).display()).collect(); + assert_eq!(got, want, "{widths}"); + } +} + +#[test] +fn split() { + assert_eq!(split_delimited("a,b,,c", &[','], false, '"'), ["a", "b", "", "c"]); + assert_eq!(split_delimited("a,b,,c", &[','], true, '"'), ["a", "b", "c"]); + assert_eq!(split_delimited("\"x,y\",z", &[','], false, '"'), ["x,y", "z"]); +} + +#[test] +fn remove_duplicates_without_a_valid_column_is_refused() { + // `columns: []` (or only unusable names) used to compare nothing and delete every row + // but the first. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["a"], ["b"], ["c"]]})).unwrap(); + for columns in [json!([]), json!(["ZZZ"])] { + let err = s.execute("data.removeDuplicates", json!({"range": "A1:A3", "columns": columns})).unwrap_err(); + assert!(err.to_string().contains("columns"), "{err}"); + } + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::new(0, 0)), Value::text("a")); + assert_eq!(sh.value(CellRef::new(2, 0)), Value::text("c")); +} + +#[test] +fn a_list_typed_without_quotes_is_saved_as_a_quoted_list() { + // In a file an inline list is a string literal (`"a,b"`); unquoted it reads as a formula. + // References, names and formulas stay unquoted, and every rule survives a save and reopen. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "K1:K3", "values": [["Red"], ["Green"], ["Blue"]]})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Colors", "refersTo": "=Sheet1!$K$1:$K$3"})).unwrap(); + let rules = [ + ("A1", "Open,In progress,Closed", r#""Open,In progress,Closed""#), + ("B1", r#""Open,In progress,Closed""#, r#""Open,In progress,Closed""#), + ("C1", " 1,2,3 ", r#""1,2,3""#), + ("D1", r#"Say "hi",Bye"#, r#""Say ""hi"",Bye""#), + ("E1", "=$K$1:$K$3", "$K$1:$K$3"), + ("F1", "$K$1:$K$3", "$K$1:$K$3"), + ("G1", "=Colors", "Colors"), + ("H1", "Sheet1!$K$1:$K$3", "Sheet1!$K$1:$K$3"), + ("I1", "=OFFSET($K$1,0,0,3,1)", "OFFSET($K$1,0,0,3,1)"), + ]; + for (cell, source, _) in rules { + s.execute("data.validation", json!({"range": cell, "type": "list", "formula1": source})).unwrap(); + } + let accepted = [ + ("A1", "In progress"), + ("B1", "Closed"), + ("C1", "2"), + ("D1", r#"Say "hi""#), + ("E1", "Green"), + ("F1", "Blue"), + ("G1", "Red"), + ("H1", "Green"), + ]; + let check = |wb: &Workbook| { + for (cell, input) in accepted { + let at = CellRef::parse(cell).unwrap(); + assert!(check_validation(wb, 0, at, input).is_none(), "{cell} refuses {input}"); + assert!(check_validation(wb, 0, at, "Pending").is_some(), "{cell} accepts Pending"); + } + }; + let wb = s.doc().unwrap().wb.clone(); + check(&wb); + + let sheet_xml = |wb: &Workbook| { + let bytes = gridcraft_xlsx::write_xlsx(wb).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("xl/worksheets/sheet1.xml").unwrap(), &mut xml).unwrap(); + xml + }; + let xml = sheet_xml(&wb); + for (cell, _, saved) in rules { + assert!(xml.contains(&format!(r#"sqref="{cell}">{saved}"#)), "{cell}: {saved} missing from {xml}"); + } + let (reopened, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap(); + check(&reopened); + assert_eq!(sheet_xml(&reopened), xml, "a second save writes the same rules"); +} + +#[test] +fn a_relative_list_source_is_read_from_the_cell_being_checked() { + // As in Excel, `=$B1:$B2` on A3:A4,A1:A2 is written for A1 (the top-left cell of all the + // areas) and lists B4:B5 at A4. It used to list B1:B2 in every cell. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B1:B5", "values": [["a"], ["b"], ["c"], ["d"], ["e"]]})).unwrap(); + s.execute("data.validation", json!({"range": "A3:A4,A1:A2", "type": "list", "formula1": "=$B1:$B2"})).unwrap(); + let wb = s.doc().unwrap().wb.clone(); + let dv = wb.active().unwrap().validations[0].clone(); + for (cell, items) in [("A1", ["a", "b"]), ("A2", ["b", "c"]), ("A3", ["c", "d"]), ("A4", ["d", "e"])] { + let at = CellRef::parse(cell).unwrap(); + assert_eq!(list_items(&wb, 0, at, &dv), items, "{cell}"); + for v in ["a", "b", "c", "d", "e"] { + assert_eq!(check_validation(&wb, 0, at, v).is_none(), items.contains(&v), "{cell} with {v}"); + } + } +} + +#[test] +fn a_list_source_that_takes_in_the_cell_does_not_list_the_value_being_typed() { + // `=$A1:$A2` on A2:A3 is A1:A2 at A2 and A2:A3 at A3. The list is the one before the entry, as + // in Excel; a new value used to land in its own source and pass. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1:A2", "values": [["x"], ["y"]]})).unwrap(); + s.execute("data.validation", json!({"range": "A2:A3", "type": "list", "formula1": "=$A1:$A2"})).unwrap(); + let wb = &s.doc().unwrap().wb; + for (cell, accepted, refused) in [("A2", &["x", "y"][..], &["new"][..]), ("A3", &["y"], &["x", "new"])] { + let at = CellRef::parse(cell).unwrap(); + for v in accepted { + assert!(check_validation(wb, 0, at, v).is_none(), "{cell} refuses {v}"); + } + for v in refused { + assert!(check_validation(wb, 0, at, v).is_some(), "{cell} accepts {v}"); + } + } +} + +#[test] +fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() { + // A typo used to give a rule that validates nothing (`type="none"`) or the wrong check, + // with no error. + let mut s = Session::new(); + s.new_workbook(); + for params in [ + json!({"range": "A1", "type": "lst", "formula1": "\"a,b\""}), + json!({"range": "A1", "type": "whole", "operator": "greaterthan", "formula1": "1"}), + json!({"range": "A1", "type": "whole", "operator": ">", "formula1": "1"}), + json!({"range": "A1", "type": "list", "formula1": "\"a,b\"", "errorStyle": "warn"}), + ] { + let e = s.execute("data.validation", params.clone()).unwrap_err().to_string(); + assert!(e.contains("unknown"), "{params}: {e}"); + } + assert!(s.doc().unwrap().wb.active().unwrap().validations.is_empty()); + for params in [ + json!({"range": "A1", "type": "any"}), + json!({"range": "A2", "type": "whole", "operator": "greaterThan", "formula1": "1"}), + json!({"range": "A3", "type": "list", "formula1": "\"a,b\"", "errorStyle": "warning"}), + ] { + s.execute("data.validation", params).unwrap(); + } + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + assert_eq!(sh.validations.len(), 3); + assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some()); +} diff --git a/crates/engine/src/cmd/data/tools.rs b/crates/engine/src/cmd/data/tools.rs new file mode 100644 index 0000000000..c4ae43ef4a --- /dev/null +++ b/crates/engine/src/cmd/data/tools.rs @@ -0,0 +1,202 @@ +use super::{ + Cell, CellRef, EngineError, Json, RangeRef, Result, Session, bad, bool_param, cell_param_on, col_param, data_target, edit, guess_header, json, + ok, str_param, target_range, target_sheet, +}; + +// ---------------------------------------------------------------- tools + +pub(super) fn remove_duplicates(s: &mut Session, p: &Json) -> Result { + let (sheet, r) = data_target(s, p, "data.removeDuplicates")?; + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + // Rows and columns past the data are blank: only the part with data is compared (whole + // columns compared a million blank rows and reported them as removed duplicates). + let r = sh.used_range().and_then(|u| r.intersection(&u)).unwrap_or(RangeRef::cell(r.start)); + let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r)); + let cols: Vec = p + .get("columns") + .and_then(Json::as_array) + .map(|a| a.iter().filter_map(|c| col_param(Some(c), r.start.col)).collect()) + .unwrap_or_else(|| (r.start.col..=r.end.col).collect()); + // With no column to compare, every row key is empty: the first row would survive and every + // other row would be deleted as a duplicate. A column outside the range compares data the + // user didn't select. Excel refuses both. + if cols.is_empty() || cols.iter().any(|c| !(r.start.col..=r.end.col).contains(c)) { + return Err(bad("data.removeDuplicates", "`columns` must name at least one column of the range")); + } + let start = r.start.row + header as u32; + let mut removed = 0; + edit(s, |cx| { + let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; + let mut seen = std::collections::HashSet::new(); + let mut keep: Vec = Vec::new(); + // Cells are compared by the text they show, as in Excel: the same date in two formats + // isn't a duplicate, while 1.01 and 1.02 shown as 1.0 are. + let shown = |c: CellRef| crate::display::format(&sh.value(c), cx.wb.styles.get(sh.style_id(c)).num_fmt.as_str(), &cx.wb).text; + for row in start..=r.end.row { + let key: Vec = cols.iter().map(|c| shown(CellRef::new(row, *c)).to_lowercase()).collect(); + if seen.insert(key) { + keep.push(row); + } else { + removed += 1; + } + } + let pictures: Vec<_> = keep + .iter() + .enumerate() + .flat_map(|(i, row)| { + (r.start.col..=r.end.col) + .filter_map(move |col| sh.cell_pictures.get(&CellRef::new(*row, col)).map(|p| (CellRef::new(start + i as u32, col), p.clone()))) + }) + .collect(); + // Rows a filter keeps are compacted to `start + i`, so the notes and hyperlinks that + // describe them move with them; the ones on removed rows are dropped with the row. + let notes: Vec<_> = keep + .iter() + .enumerate() + .flat_map(|(i, row)| { + (r.start.col..=r.end.col) + .filter_map(move |col| sh.comments.get(&CellRef::new(*row, col)).map(|cm| (CellRef::new(start + i as u32, col), cm.clone()))) + }) + .collect(); + let links: Vec<_> = keep + .iter() + .enumerate() + .flat_map(|(i, row)| { + (r.start.col..=r.end.col) + .filter_map(move |col| sh.hyperlinks.get(&CellRef::new(*row, col)).map(|h| (CellRef::new(start + i as u32, col), h.clone()))) + }) + .collect(); + let rows: Vec>> = + keep.iter().map(|row| (r.start.col..=r.end.col).map(|c| sh.cell(CellRef::new(*row, c)).cloned()).collect()).collect(); + let shm = cx.sheet_mut(sheet)?; + for row in start..=r.end.row { + for c in r.start.col..=r.end.col { + shm.remove_cell(CellRef::new(row, c)); + } + } + for row in start..=r.end.row { + for c in r.start.col..=r.end.col { + let at = CellRef::new(row, c); + shm.comments.remove(&at); + shm.hyperlinks.remove(&at); + } + } + for (i, cells) in rows.into_iter().enumerate() { + for (j, cell) in cells.into_iter().enumerate() { + if let Some(cell) = cell { + shm.set_cell(CellRef::new(start + i as u32, r.start.col + j as u32), cell); + } + } + } + shm.cell_pictures.extend(pictures); + for (at, cm) in notes { + shm.comments.insert(at, cm); + } + for (at, h) in links { + shm.hyperlinks.insert(at, h); + } + for c in RangeRef::new(CellRef::new(start, r.start.col), r.end).iter() { + cx.changed.push((sheet, c)); + } + Ok(()) + })?; + let remaining = (r.end.row + 1 - start) as usize - removed; + Ok(json!({"removed": removed, "remaining": remaining})) +} + +pub(super) fn text_to_columns(s: &mut Session, p: &Json) -> Result { + let r = target_range(s, p)?; + let sheet = target_sheet(s, p)?; + let mut delims: Vec = p + .get("delimiters") + .and_then(Json::as_array) + .map(|a| a.iter().filter_map(|d| d.as_str().and_then(|x| x.chars().next())).collect()) + .unwrap_or_else(|| vec!['\t']); + if let Some(o) = str_param(p, "other").and_then(|o| o.chars().next()) { + delims.push(o); + } + let fixed: Option> = + p.get("fixedWidths").and_then(Json::as_array).map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as usize)).collect()); + let consecutive = bool_param(p, "treatConsecutive").unwrap_or(false); + let quote = str_param(p, "textQualifier").and_then(|q| q.chars().next()).unwrap_or('"'); + let dest = cell_param_on(s, p, "destination", sheet)?.unwrap_or(r.start); + edit(s, |cx| { + let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) }; + let mut out: Vec<(CellRef, String)> = Vec::new(); + for (i, row) in (r.start.row..=r.end.row).enumerate() { + let text = sh.value(CellRef::new(row, r.start.col)).display(); + let parts: Vec = match &fixed { + Some(w) => { + let chars: Vec = text.chars().collect(); + let mut cuts = vec![0]; + let mut breaks: Vec = w.iter().copied().filter(|x| *x > 0 && *x < chars.len()).collect(); + breaks.sort_unstable(); + breaks.dedup(); + cuts.extend(breaks); + cuts.push(chars.len()); + cuts.windows(2) + .map(|p| chars.get(p[0]..p[1]).map(|s| s.iter().collect::().trim().to_string()).unwrap_or_default()) + .collect() + } + None => split_delimited(&text, &delims, consecutive, quote), + }; + for (j, part) in parts.into_iter().enumerate() { + out.push((CellRef::new(dest.row + i as u32, dest.col + j as u32), part)); + } + } + for (c, t) in out { + let cell = match crate::cmd::edit::input_to_cell(&t, sheet, c, &mut cx.wb) { + Ok(cell) => cell, + // `=PY(…)` doesn't make a Python cell (that takes python.set): the piece is kept + // as text rather than lost. + Err(_) if gridcraft_model::python::is_py_formula(&t) => { + let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default(); + Some(Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style, py: None }) + } + Err(_) => None, + }; + let shm = cx.sheet_mut(sheet)?; + match cell { + Some(x) => shm.set_cell(c, x), + None => { + shm.remove_cell(c); + } + } + cx.changed.push((sheet, c)); + } + Ok(()) + })?; + ok() +} + +pub(super) fn split_delimited(text: &str, delims: &[char], consecutive: bool, quote: char) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut in_q = false; + let mut last_delim = false; + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c == quote { + if in_q && chars.peek() == Some("e) { + cur.push(quote); + chars.next(); + } else { + in_q = !in_q; + } + continue; + } + if !in_q && delims.contains(&c) { + if consecutive && last_delim { + continue; + } + out.push(std::mem::take(&mut cur)); + last_delim = true; + continue; + } + last_delim = false; + cur.push(c); + } + out.push(cur); + out +} diff --git a/crates/engine/src/cmd/data/validation.rs b/crates/engine/src/cmd/data/validation.rs new file mode 100644 index 0000000000..2217a372a7 --- /dev/null +++ b/crates/engine/src/cmd/data/validation.rs @@ -0,0 +1,305 @@ +use super::{ + Cell, CellRef, CfOperator, EngineError, ErrorStyle, Json, RangeRef, Result, Session, Validation, ValidationKind, Value, Workbook, bad, + bool_param, cell_param, edit, json, ok, str_param, target_ranges, target_sheet, +}; + +// ---------------------------------------------------------------- validation + +fn op_param(s: Option<&str>) -> CfOperator { + match s.unwrap_or("between") { + "notBetween" => CfOperator::NotBetween, + "equal" => CfOperator::Equal, + "notEqual" => CfOperator::NotEqual, + "greater" | "greaterThan" => CfOperator::Greater, + "less" | "lessThan" => CfOperator::Less, + "greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual, + "lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual, + _ => CfOperator::Between, + } +} + +/// `r` minus `cut`, as up to four non-overlapping rectangles. +fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec { + let Some(i) = r.intersection(cut) else { return vec![r] }; + let mut out = Vec::new(); + if i.start.row > r.start.row { + out.push(RangeRef::new(r.start, CellRef::new(i.start.row - 1, r.end.col))); + } + if i.end.row < r.end.row { + out.push(RangeRef::new(CellRef::new(i.end.row + 1, r.start.col), r.end)); + } + if i.start.col > r.start.col { + out.push(RangeRef::new(CellRef::new(i.start.row, r.start.col), CellRef::new(i.end.row, i.start.col - 1))); + } + if i.end.col < r.end.col { + out.push(RangeRef::new(CellRef::new(i.start.row, i.end.col + 1), CellRef::new(i.end.row, r.end.col))); + } + out +} + +/// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges. +/// When the rule's top-left cell goes, its relative formulas are rewritten for the new top-left +/// cell, so the cells left keep checking the same cells. +pub(in super::super) fn remove_validation_cells(validations: &mut Vec, cuts: &[RangeRef]) { + for dv in validations.iter_mut() { + let before = RangeRef::top_left(&dv.ranges); + for cut in cuts { + dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect(); + } + if let (Some(from), Some(to)) = (before, RangeRef::top_left(&dv.ranges)) { + dv.f1 = move_rule_formula(&dv.f1, from, to); + dv.f2 = dv.f2.take().map(|f| move_rule_formula(&f, from, to)); + } + } + validations.retain(|d| !d.ranges.is_empty()); +} + +pub(super) fn validation(s: &mut Session, p: &Json) -> Result { + let ranges = target_ranges(s, p)?; + let sheet = target_sheet(s, p)?; + if bool_param(p, "clear").unwrap_or(false) { + return edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + remove_validation_cells(&mut sh.validations, &ranges); + Ok(Json::Null) + }); + } + let Some(kind) = str_param(p, "type") else { + s.ui_requests.push(crate::UiRequest::Dialog("dataValidation".into(), json!({}))); + return ok(); + }; + let kind = match kind { + "whole" => ValidationKind::Whole, + "decimal" => ValidationKind::Decimal, + "list" => ValidationKind::List, + "date" => ValidationKind::Date, + "time" => ValidationKind::Time, + "textLength" => ValidationKind::TextLength, + "custom" => ValidationKind::Custom, + "any" => ValidationKind::Any, + // An unknown type used to give an "any value" rule, saved as `type="none"`: no validation. + other => return Err(bad("data.validation", format!("unknown type `{other}` (any, whole, decimal, list, date, time, textLength, custom)"))), + }; + if kind == ValidationKind::List && str_param(p, "formula1").is_none_or(|f| f.trim().trim_start_matches('=').is_empty()) { + return Err(bad("data.validation", "a list validation needs `formula1`")); + } + const OPERATORS: [&str; 12] = [ + "between", + "notBetween", + "equal", + "notEqual", + "greater", + "greaterThan", + "less", + "lessThan", + "greaterOrEqual", + "greaterThanOrEqual", + "lessOrEqual", + "lessThanOrEqual", + ]; + if let Some(op) = str_param(p, "operator").filter(|op| !OPERATORS.contains(op)) { + return Err(bad("data.validation", format!("unknown operator `{op}` ({})", OPERATORS.join(", ")))); + } + let error_style = match str_param(p, "errorStyle") { + None | Some("stop") => ErrorStyle::Stop, + Some("warning") => ErrorStyle::Warning, + Some("information") => ErrorStyle::Information, + Some(other) => return Err(bad("data.validation", format!("unknown errorStyle `{other}` (stop, warning, information)"))), + }; + let f1 = str_param(p, "formula1").unwrap_or(""); + let f1 = if kind == ValidationKind::List { list_source(f1) } else { f1.trim_start_matches('=').to_string() }; + let dv = Validation { + ranges: ranges.clone(), + kind, + op: op_param(str_param(p, "operator")), + f1, + f2: str_param(p, "formula2").map(|f| f.trim_start_matches('=').to_string()), + allow_blank: bool_param(p, "ignoreBlank").unwrap_or(true), + in_cell_dropdown: bool_param(p, "dropdown").unwrap_or(true), + input_title: str_param(p, "inputTitle").unwrap_or("").into(), + input_message: str_param(p, "inputMessage").unwrap_or("").into(), + show_input: true, + error_title: str_param(p, "errorTitle").unwrap_or("").into(), + error_message: str_param(p, "errorMessage").unwrap_or("").into(), + error_style, + show_error: true, + }; + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + remove_validation_cells(&mut sh.validations, &ranges); + sh.validations.push(dv.clone()); + Ok(Json::Null) + }) +} + +/// Whether a list rule's source is a literal list (`"a,b"`, or `a,b` typed without quotes) rather +/// than a reference or a name to evaluate. +fn is_literal_list(f: &str) -> bool { + f.starts_with('"') + || (!f.contains('!') + && gridcraft_formula::parse(f).map(|e| !matches!(e, gridcraft_formula::Expr::Ref(_) | gridcraft_formula::Expr::Name(_))).unwrap_or(true)) +} + +/// A list rule's source as a file stores it. A literal list typed without quotes, as in Excel's +/// Source box (`Open,In progress,Closed`), becomes the quoted string Excel saves +/// (`"Open,In progress,Closed"`, inner quotes doubled); unquoted, the file would read it as a +/// formula. A formula (`=…`), a reference, a name or an already quoted list is kept as before. +fn list_source(f: &str) -> String { + let t = f.trim(); + if t.is_empty() || t.starts_with('=') || t.starts_with('"') || !is_literal_list(t) { + return f.trim_start_matches('=').to_string(); + } + format!("\"{}\"", t.replace('"', "\"\"")) +} + +/// List entries of a list validation (literal or from a range) for the cell `at`. A relative +/// source is written for the rule's top-left cell and read from `at`, as in Excel (`=$B1:$B3` on +/// A1:A9 lists B5:B7 at A5). +pub fn list_items(wb: &Workbook, sheet: usize, at: CellRef, dv: &Validation) -> Vec { + let f = dv.f1.trim(); + if is_literal_list(f) { + // A quoted list is a string literal: `""` inside stands for one `"`. + let items = match f.strip_prefix('"').and_then(|x| x.strip_suffix('"')) { + Some(body) => body.replace("\"\"", "\""), + None => f.trim_matches('"').to_string(), + }; + return items.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(); + } + let first = RangeRef::top_left(&dv.ranges).unwrap_or(at); + match gridcraft_calc::evaluate(wb, sheet, at, &formula_at(f, first, at)) { + Value::Array(a) => a.data.iter().filter(|v| !v.is_empty()).map(Value::display).collect(), + v if !v.is_empty() && !v.is_error() => vec![v.display()], + _ => vec![], + } +} + +/// Checks typed input against the validation of a cell. `Ok(None)` = valid. +pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -> Option<(Validation, String)> { + let sh = wb.sheet(sheet)?; + let dv = sh.validations.iter().find(|d| d.ranges.iter().any(|r| r.contains(at)))?; + if dv.kind == ValidationKind::Any || !dv.show_error { + return None; + } + if input.is_empty() && dv.allow_blank { + return None; + } + let v = gridcraft_core::parse::parse_input(input, wb.date_system).value; + // The formulas are written for the top-left cell of all the areas and see the value being entered, + // as in Excel (a custom `=A1>10` on A1:A9 checks A5's new value at A5). + let first = RangeRef::top_left(&dv.ranges).unwrap_or(at); + let original = wb; + let entered; + let wb = if sh.value(at) == v { + wb + } else { + let mut w = wb.clone(); + if let Some(sh) = w.sheet_mut(sheet) { + let style = sh.style_id(at); + sh.cells.set(at, Cell { value: v.clone(), style, ..Default::default() }); + } + entered = w; + &entered + }; + let eval = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, &formula_at(f, first, at)); + let num = |f: &str| eval(f).to_number().ok(); + let ok = match dv.kind { + // The list is the one the dropdown showed before the entry, as in Excel: a source that takes + // in the cell itself (`=$A1:$A2` on A2:A3 is A2:A3 at A3) doesn't list the value being typed. + ValidationKind::List => list_items(original, sheet, at, dv).iter().any(|x| x.eq_ignore_ascii_case(input)), + ValidationKind::Custom => eval(&dv.f1).to_bool().unwrap_or(false), + ValidationKind::TextLength => { + let n = input.chars().count() as f64; + compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num)) + } + _ => match v.as_f64() { + Some(n) => { + if dv.kind == ValidationKind::Whole && n.fract() != 0.0 { + false + } else { + compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num)) + } + } + None => false, + }, + }; + if ok { + return None; + } + let msg = if dv.error_message.is_empty() { + "This value doesn't match the data validation restrictions defined for this cell.".to_string() + } else { + dv.error_message.clone() + }; + Some((dv.clone(), msg)) +} + +/// A formula written for `first`, as seen from `at` (relative references shifted). +fn formula_at(f: &str, first: CellRef, at: CellRef) -> String { + if first == at { + return f.to_string(); + } + match gridcraft_formula::parse(f.trim_start_matches('=')) { + Ok(e) => gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative( + e, + at.row as i64 - first.row as i64, + at.col as i64 - first.col as i64, + )), + Err(_) => f.to_string(), + } +} + +/// Moves the relative references of a rule formula written for `first` so it reads the same cells from `to` +/// (pasting a rule); text without relative references (constants, literal lists) stays as typed. +pub(in super::super) fn move_rule_formula(f: &str, first: CellRef, to: CellRef) -> String { + if first == to { + return f.to_string(); + } + let moved = formula_at(f, first, to); + let has_relative = gridcraft_formula::parse(f.trim_start_matches('=')).is_ok_and(|e| gridcraft_formula::print(&e) != moved); + let eq = if f.starts_with('=') { "=" } else { "" }; + if has_relative { format!("{eq}{moved}") } else { f.to_string() } +} + +fn compare_op(op: CfOperator, n: f64, a: Option, b: Option) -> bool { + let Some(a) = a else { return false }; + match op { + CfOperator::Between => b.is_some_and(|b| n >= a.min(b) && n <= a.max(b)), + CfOperator::NotBetween => b.is_some_and(|b| n < a.min(b) || n > a.max(b)), + CfOperator::Equal => n == a, + CfOperator::NotEqual => n != a, + CfOperator::Greater => n > a, + CfOperator::Less => n < a, + CfOperator::GreaterOrEqual => n >= a, + CfOperator::LessOrEqual => n <= a, + } +} + +pub(super) fn validate_cmd(s: &mut Session, p: &Json) -> Result { + let d = s.doc()?; + let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active); + let input = str_param(p, "input").unwrap_or(""); + match check_validation(&d.wb, d.wb.active_sheet(), at, input) { + None => Ok(json!({"ok": true})), + Some((dv, msg)) => Ok(json!({"ok": false, "message": msg, "title": dv.error_title, "style": format!("{:?}", dv.error_style)})), + } +} + +pub(super) fn circle_invalid(s: &mut Session, _: &Json) -> Result { + let d = s.doc()?; + let sheet = d.wb.active_sheet(); + let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + let mut bad_cells = Vec::new(); + for dv in &sh.validations { + for r in &dv.ranges { + let r = sh.used_range().and_then(|u| r.intersection(&u)); + let Some(r) = r else { continue }; + for c in r.iter().take(100_000) { + let text = sh.input_text(c); + if !text.is_empty() && check_validation(&d.wb, sheet, c, &text).is_some() { + bad_cells.push(c.a1()); + } + } + } + } + Ok(json!({"invalid": bad_cells})) +} diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index a86be30995..c8921718c2 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -1,10 +1,10 @@ //! Draw tab: pen and eraser tools, ink strokes, Ink to Shape. use gridcraft_core::CellRef; -use gridcraft_model::*; +use gridcraft_model::{Anchor, Color, Shape, ShapeKind}; use serde_json::{Value as Json, json}; -use super::*; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_param, cmd, edit, f64_param, has_doc, ok, str_param, u32_param}; pub fn specs() -> Vec { vec![ @@ -80,6 +80,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result { let text = pts.iter().map(|q| format!("{:.1},{:.1}", q[0] - minx, q[1] - miny)).collect::>().join(";"); let id = d.wb.next_object_id(); let shape = Shape { + math: Default::default(), id, kind: ShapeKind::Ink, anchor: Anchor { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 28ce338d6c..83133c01c5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -4,10 +4,40 @@ use gridcraft_core::{CellRef, MAX_ROWS, RangeRef, Value}; use gridcraft_model::{Cell, Formula, StyleId}; use serde_json::{Value as Json, json}; -use super::*; +use super::{ + CommandSpec, EngineError, Result, bad, bool_param, can_redo, can_undo, cell_param, cell_param_on, cmd, edit, f64_param, has_clipboard, has_doc, + locked_cell_error, ok, split_sheet, str_param, target_range, target_ranges, target_sheet, u32_param, +}; use crate::selection::{current_region, jump}; use crate::{Clipboard, Session}; +mod cell; +mod clipboard; +mod fill; +mod find; +mod go_to; +mod paste_special; +mod selection; + +use cell::{cell_set, range_fill, range_set_values}; +pub(crate) use cell::{check_arg_counts, input_to_cell, is_formula_input, json_to_input, parse_typed_formula}; +#[cfg(test)] +pub(crate) use clipboard::parse_tsv; +use clipboard::{clear_clipboard, copy, cut, paste, range_move}; +use fill::{auto_fill, fill_dir, fill_series, flash_fill}; +#[cfg(test)] +use find::replace_ci; +pub(crate) use find::wildcard; +use find::{find, replace}; +pub(super) use go_to::go_to; +pub use go_to::go_to_names; +use go_to::go_to_special; +#[cfg(test)] +use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; +use paste_special::paste_special; +pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs}; +use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set}; + pub fn specs() -> Vec { vec![ cmd!("cell.set", "Enter Cell", [], None, "{cell?: \"B2\", input: \"text, number or =formula\", sheet?, array?: bool}", has_doc, cell_set), @@ -16,7 +46,7 @@ pub fn specs() -> Vec { "Set Values", [], None, - "{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives)}", + "{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives, a leading ' is kept and an empty string clears the cell)} → {cells, convertedCount, converted: [{cell, input, stored}] (up to 20 of the strings typed input read as a number, date, time, boolean or error, so a script can notice)}", has_doc, range_set_values ), @@ -32,6 +62,15 @@ pub fn specs() -> Vec { cmd!(noundo "selection.set", "Select", [], None, "{range: \"A1:B2,D4\" | cell, active?: \"A1\", sheet?}", has_doc, selection_set), cmd!(noundo "selection.move", "Move Selection", [], None, "{dr, dc, extend?: bool, jump?: bool (Ctrl+arrow), page?: bool}", has_doc, selection_move), cmd!(noundo "selection.next", "Next Cell in Selection", [], None, "{forward?: true, byRow?: false} (Enter/Tab inside a selection)", has_doc, selection_next), + cmd!( + noundo "selection.nextCorner", + "Next Corner of Selection", + [], + Some("Ctrl+."), + "{} (the active cell moves clockwise to the next corner of the selected area, which stays selected)", + has_doc, + selection_next_corner + ), cmd!(noundo "edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{} (current region first, then the whole sheet)", has_doc, select_all), cmd!(noundo "selection.currentRegion", "Select Current Region", [], Some("Ctrl+Shift+8"), "{}", has_doc, select_region), cmd!(noundo "selection.row", "Select Entire Row", [], Some("Shift+Space"), "{}", has_doc, select_row), @@ -52,14 +91,26 @@ pub fn specs() -> Vec { paste ), cmd!( - "edit.pasteSpecial", - "Paste Special…", - ["Home", "Clipboard"], - Some("Ctrl+Cmd+V"), - "{what: all|formulas|values|formats|comments|validation|allExceptBorders|columnWidths|formulasAndNumberFormats|valuesAndNumberFormats, operation?: none|add|subtract|multiply|divide, skipBlanks?, transpose?, link?}", - has_clipboard, - paste_special + "range.move", + "Drag and Drop", + [], + None, + "{range?, to: \"C3\", overwrite?: bool} (drag the selection's border: a cut and paste that asks before replacing data unless overwrite)", + has_doc, + range_move ), + CommandSpec { + shortcut_mac: Some("Ctrl+Cmd+V"), + ..cmd!( + "edit.pasteSpecial", + "Paste Special…", + ["Home", "Clipboard"], + Some("Ctrl+Alt+V"), + "{what: all|formulas|values|formats|comments|validation|allExceptBorders|columnWidths|formulasAndNumberFormats|valuesAndNumberFormats, operation?: none|add|subtract|multiply|divide, skipBlanks?, transpose?, link?}", + has_clipboard, + paste_special + ) + }, cmd!(noundo "edit.clearClipboard", "Cancel Copy", [], Some("Escape"), "{}", has_doc, clear_clipboard), cmd!("edit.clearAll", "Clear All", ["Home", "Editing", "Clear"], None, "{range?}", has_doc, |s, p| clear(s, p, "all")), cmd!("edit.clearFormats", "Clear Formats", ["Home", "Editing", "Clear"], None, "{range?}", has_doc, |s, p| clear(s, p, "formats")), @@ -93,13 +144,13 @@ pub fn specs() -> Vec { fill_series ), cmd!("edit.flashFill", "Flash Fill", ["Home", "Editing", "Fill"], Some("Ctrl+E"), "{range?}", has_doc, flash_fill), - cmd!(noundo "edit.find", "Find…", ["Home", "Editing", "Find & Select"], Some("Cmd+F"), "{what, matchCase?, wholeCell?, lookIn?: formulas|values, byColumns?, all?: bool, within?: sheet|workbook}", has_doc, find), + cmd!(noundo "edit.find", "Find…", ["Home", "Editing", "Find & Select"], Some("Cmd+F"), "{what, matchCase?, wholeCell?, lookIn?: formulas|values, byColumns?, all?: bool, within?: sheet|workbook|selection} (selection: only the selected cells; Find Next keeps them selected and moves the active cell)", has_doc, find), cmd!( "edit.replace", "Replace…", ["Home", "Editing", "Find & Select"], Some("Ctrl+H"), - "{what, with, matchCase?, wholeCell?, all?: true, within?: sheet|workbook}", + "{what, with, matchCase?, wholeCell?, all?: true, within?: sheet|workbook|selection} → {replaced, skipped?} (in a Python cell the code is edited; skipped counts Python cells whose code would no longer fit)", has_doc, replace ), @@ -116,657 +167,6 @@ pub fn specs() -> Vec { ] } -// ---------------------------------------------------------------- entry - -/// What typing `input` into a cell produces (constant or formula, plus an automatic number -/// format). Inherits the destination's cell, row or column style, including its number -/// format, before parsing. Errors when the formula can't be parsed. -pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { - let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); - if input.is_empty() { - let c = Cell { value: Value::Empty, formula: None, style }; - return Ok(if c.is_blank() { None } else { Some(c) }); - } - let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; - if fmt_is_text { - return Ok(Some(Cell { value: Value::text(input), formula: None, style })); - } - let is_formula = 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 == '(')); - 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)?; - let mut cell = Cell::formula(Formula::from_expr(expr)); - cell.style = style; - // Formulas whose result is a date/time get a format from functions like TODAY(). - if wb.styles.get(style).num_fmt.as_str() == "General" { - let f = cell.formula.as_ref().map(|f| f.text.to_ascii_uppercase()).unwrap_or_default(); - let auto = if f.starts_with("TODAY(") - || f.starts_with("DATE(") - || f.starts_with("EDATE(") - || f.starts_with("EOMONTH(") - || f.starts_with("WORKDAY(") - { - Some("m/d/yyyy") - } else if f.starts_with("NOW(") { - Some("m/d/yyyy h:mm") - } else if f.starts_with("TIME(") { - Some("h:mm AM/PM") - } else { - None - }; - if let Some(code) = auto { - cell.style = wb.styles.derive(style, |s| s.num_fmt = gridcraft_model::NumFmt::new(code)); - } - } - return Ok(Some(cell)); - } - let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system); - // 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() - && !input.contains('%') - && wb.styles.get(style).num_fmt.as_str().ends_with('%') - && let Value::Number(n) = parsed.value - && n.abs() >= 1.0 - { - parsed.value = Value::Number(n / 100.0); - } - let mut style = style; - if let Some(code) = parsed.format { - let cur = wb.styles.get(style).num_fmt.as_str().to_string(); - if cur == "General" { - style = wb.styles.derive(style, |s| s.num_fmt = gridcraft_model::NumFmt::new(code)); - } - } - // Wrap text automatically when the input has line breaks (Alt+Enter). - if input.contains('\n') && !wb.styles.get(style).align.wrap { - style = wb.styles.derive(style, |s| s.align.wrap = true); - } - Ok(Some(Cell { value: parsed.value, formula: None, style })) -} - -/// Parses a formula as it is typed (without the `=`). Excel closes missing parentheses for you, -/// and refuses a formula that still doesn't parse. -pub(crate) fn parse_typed_formula(body: &str) -> Result { - // Excel closes missing parentheses for you. - let parsed = gridcraft_formula::parse_closing_parens(body, gridcraft_formula::parse); - parsed.map_err(|e| EngineError::Other(format!("There's a problem with this formula: {e}"))) -} - -/// Like Excel, a formula that calls a built-in function with too few or too many arguments is -/// refused when it's entered, rather than stored to show `#VALUE!`. Functions the registry doesn't -/// hold (special forms like LET, LAMBDA, OFFSET, INDIRECT, SUBTOTAL), defined LAMBDA names and -/// unknown functions are skipped. -pub(crate) fn check_arg_counts(expr: &gridcraft_formula::Expr) -> Result<()> { - let mut bad = None; - expr.walk(&mut |e| { - if bad.is_none() - && let gridcraft_formula::Expr::Call(name, args) = e - && let Some(spec) = gridcraft_functions::lookup(name) - && !spec.accepts(args.len()) - { - let few = args.len() < spec.min_args; - bad = Some(format!("{} has too {} arguments. Use {}", spec.name, if few { "few" } else { "many" }, spec.signature)); - } - }); - match bad { - Some(msg) => Err(EngineError::Other(msg)), - None => Ok(()), - } -} - -fn cell_set(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let at = match cell_param_on(s, p, "cell", sheet)? { - Some(c) => c, - None => s.doc()?.selection.active, - }; - // Both spellings take a string, number or boolean, as typed (#697). - let input = p.get("input").or_else(|| p.get("value")).map(json_to_input).ok_or_else(|| bad("cell.set", "missing `input` (or `value`)"))?; - let array = bool_param(p, "array").unwrap_or(false); - let d = s.doc()?; - if let Some(sh) = d.wb.sheet(sheet) - && sh.is_protected() - && d.wb.styles.get(sh.style_id(at)).protection.locked - && let Some(m) = locked_cell_error(sh, at, &d.unlocked_ranges) - { - return Err(EngineError::Other(m)); - } - let active_sheet = s.doc()?.wb.active_sheet(); - edit(s, |cx| { - if array { - // Legacy Ctrl+Shift+Enter array formula over the selection, when the selection holds - // 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) }; - // 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. - for c in range.iter().skip(1).take(1_000_000) { - if let Some(old) = sh.cells.get(c).filter(|x| !x.value.is_empty() || x.formula.is_some()) { - let style = old.style; - sh.set_cell(c, Cell { style, ..Cell::default() }); - } - } - sh.set_cell(range.start, cell); - cx.touch(sheet, range.start); - return Ok(Json::Null); - } - let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?; - let sh = cx.sheet_mut(sheet)?; - match cell { - Some(c) => sh.set_cell(at, c), - None => { - sh.remove_cell(at); - } - } - super::data::grow_autofilter(sh, at); - cx.touch(sheet, at); - Ok(Json::Null) - })?; - let v = s.doc()?.wb.sheet(sheet).map(|sh| sh.value(at)).unwrap_or_default(); - Ok(json!({"cell": at.a1(), "value": v.display()})) -} - -pub(crate) fn json_to_input(v: &Json) -> String { - match v { - Json::Null => String::new(), - Json::Bool(b) => { - if *b { - "TRUE".into() - } else { - "FALSE".into() - } - } - Json::Number(n) => n.to_string(), - Json::String(s) => s.clone(), - other => other.to_string(), - } -} - -fn range_set_values(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let start = target_range(s, p)?.start; - let Some(rows) = p.get("values").and_then(Json::as_array) else { return Err(bad("range.setValues", "missing `values` (array of rows)")) }; - // A string is run through typed input by default, which reads it with en-US rules: a caller - // sending "05.04.2026" from a dd.mm.yyyy export got 4 May, and "2.500" became 2.5, in silence - // (#2255). `parse: false` stores a string as the text it is; numbers, booleans and formulas - // are unaffected either way. - let parse = match p.get("parse") { - None | Some(Json::Null) => true, - Some(Json::Bool(b)) => *b, - Some(other) => return Err(bad("range.setValues", format!("parse {other}: true or false"))), - }; - if rows.len() > MAX_ROWS as usize { - return Err(bad("range.setValues", "too many rows")); - } - let mut count = 0; - edit(s, |cx| { - for (ri, row) in rows.iter().enumerate() { - let cols: Vec<&Json> = match row.as_array() { - Some(a) => a.iter().collect(), - None => vec![row], - }; - for (ci, v) in cols.iter().enumerate() { - let Some(at) = start.offset(ri as i64, ci as i64) else { continue }; - let input = json_to_input(v); - let cell = match v { - Json::Number(n) => Some(Cell { - value: Value::number(n.as_f64().unwrap_or(0.0)), - formula: None, - style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), - }), - Json::Bool(b) => { - Some(Cell { value: Value::Bool(*b), formula: None, style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default() }) - } - // Text as given: no date or number reading, and a leading `'` is part of the - // text rather than the marker that makes it text. A formula is still a - // formula, which is what the ticket asks for and what `=` means in a cell. - Json::String(text) if !parse && !text.starts_with('=') => { - let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); - // Line breaks still turn on Wrap Text, as typed input does. - if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { - style = cx.wb.styles.derive(style, |s| s.align.wrap = true); - } - Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style }) - } - _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, - }; - let sh = cx.sheet_mut(sheet)?; - match cell { - Some(c) => sh.set_cell(at, c), - None => { - sh.remove_cell(at); - } - } - super::data::grow_autofilter(sh, at); - cx.touch(sheet, at); - count += 1; - } - } - Ok(()) - })?; - Ok(json!({"cells": count})) -} - -fn range_fill(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let ranges = target_ranges(s, p)?; - let input = str_param(p, "input").unwrap_or("").to_string(); - let origin = s.doc()?.selection.active; - edit(s, |cx| { - // Each cell gets what typing the input there gives: the automatic number format where - // it's General, its own format otherwise, text where it's Text. That depends only on - // the cell's style, so the input is parsed once per style. - let mut by_style: std::collections::HashMap> = std::collections::HashMap::new(); - for r in &ranges { - if r.count() > 2_000_000 { - return Err(bad("range.fill", "range too large")); - } - for at in r.iter() { - let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); - let base = match by_style.get(&style) { - Some(c) => c.clone(), - None => { - let c = input_to_cell(&input, sheet, at, &mut cx.wb)?; - by_style.insert(style, c.clone()); - c - } - }; - let mut cell = base.unwrap_or_default(); - if let Some(f) = &cell.formula - && let Some(e) = f.expr() - { - let shifted = gridcraft_formula::adjust::shift_relative(e, at.row as i64 - origin.row as i64, at.col as i64 - origin.col as i64); - cell.formula = Some(std::sync::Arc::new(Formula::from_expr(shifted))); - } - let sh = cx.sheet_mut(sheet)?; - sh.set_cell(at, cell); - super::data::grow_autofilter(sh, at); - cx.touch(sheet, at); - } - } - Ok(Json::Null) - }) -} - -// ---------------------------------------------------------------- selection - -/// Whether the cell may be selected: a protected sheet can forbid selecting locked and/or unlocked cells. -fn cell_selectable(wb: &gridcraft_model::Workbook, sheet: &gridcraft_model::Sheet, c: CellRef) -> bool { - let Some(p) = sheet.protection.as_ref() else { return true }; - if wb.styles.get(sheet.style_id(c)).protection.locked { p.select_locked } else { p.select_unlocked } -} - -fn selection_set(s: &mut Session, p: &Json) -> Result { - if p.get("sheet").is_some() { - let i = target_sheet(s, p)?; - s.doc_mut()?.wb_switch_sheet(i); - } else if let Some(r) = str_param(p, "range").or_else(|| str_param(p, "cell")) - && let (Some(_), _) = split_sheet(r) - { - let i = target_sheet(s, p)?; - s.doc_mut()?.wb_switch_sheet(i); - } - let ranges = target_ranges(s, p)?; - let active = cell_param(s, p, "active")?; - let d = s.doc_mut()?; - let active = active.or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default(); - let mut sel = crate::Selection { active, anchor: ranges.last().map(|r| r.start).unwrap_or(active), ranges }; - if let Some(sh) = d.wb.active() { - sel.expand_merges(sh); - if !cell_selectable(&d.wb, sh, sel.active) { - return Err(EngineError::Other("The cell you are trying to change is on a protected sheet that does not allow selecting it.".into())); - } - } - d.selection = sel; - Ok(json!({"selection": d.selection.a1(), "active": d.selection.active.a1()})) -} - -impl crate::DocState { - /// Switches the active sheet, remembering each sheet's selection. - pub fn wb_switch_sheet(&mut self, i: usize) { - if i >= self.wb.sheets.len() || i == self.wb.active_sheet() { - return; - } - let cur = self.wb.active_sheet(); - if self.sheet_selections.len() < self.wb.sheets.len() { - self.sheet_selections.resize(self.wb.sheets.len(), crate::Selection::default()); - } - if let Some(slot) = self.sheet_selections.get_mut(cur) { - *slot = self.selection.clone(); - } - // 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(); - } -} - -fn selection_move(s: &mut Session, p: &Json) -> Result { - let dr = p.get("dr").and_then(Json::as_i64).unwrap_or(0); - let dc = p.get("dc").and_then(Json::as_i64).unwrap_or(0); - let extend = bool_param(p, "extend").unwrap_or(false); - let jmp = bool_param(p, "jump").unwrap_or(false); - let d = s.doc_mut()?; - let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; - let sel = &mut d.selection; - // Extension moves the far corner, not the active cell. - let from = if extend { sel.moving_end() } else { sel.active }; - // Skip hidden rows/columns and step over merged areas. - let mut to = if jmp { - jump(sheet, from, dr.signum(), dc.signum()) - } else { - let mut t = from.offset_clamped(dr, dc); - let mut guard = 0; - while (sheet.is_row_hidden(t.row) || sheet.is_col_hidden(t.col)) && guard < 100_000 { - let n = t.offset_clamped(dr.signum(), dc.signum()); - if n == t { - break; - } - t = n; - guard += 1; - } - if !extend && let Some(m) = sheet.merge_at(from) { - // Leaving a merged cell moves from its edge. - if dr > 0 { - t = CellRef::new(m.end.offset_clamped(dr, 0).row, from.col); - } else if dc > 0 { - t = CellRef::new(from.row, m.end.offset_clamped(0, dc).col); - } - } - t - }; - if let Some(m) = sheet.merge_at(to) - && !extend - { - to = m.start; - } - if !extend && !cell_selectable(&d.wb, sheet, to) { - // Step on to the next selectable cell in the same direction; stay put if there is none. - let (sr, sc) = (dr.signum(), dc.signum()); - let mut t = to; - let mut found = false; - if !jmp && (sr, sc) != (0, 0) { - for _ in 0..10_000 { - let n = t.offset_clamped(sr, sc); - if n == t { - break; - } - t = n; - if !sheet.is_row_hidden(t.row) && !sheet.is_col_hidden(t.col) && cell_selectable(&d.wb, sheet, t) { - found = true; - break; - } - } - } - if !found { - return Ok(json!({"selection": sel.a1(), "active": sel.active.a1()})); - } - to = t; - } - if extend { - sel.extend_to(to); - sel.expand_merges(sheet); - } else { - *sel = crate::Selection::at(to); - if let Some(m) = sheet.merge_at(to) { - sel.ranges = vec![m]; - } - } - Ok(json!({"selection": sel.a1(), "active": sel.active.a1()})) -} - -fn selection_next(s: &mut Session, p: &Json) -> Result { - let fwd = bool_param(p, "forward").unwrap_or(true); - let by_row = bool_param(p, "byRow").unwrap_or(false); - let d = s.doc_mut()?; - d.selection.cycle(fwd, by_row); - Ok(json!({"active": d.selection.active.a1()})) -} - -fn select_all(s: &mut Session, _: &Json) -> Result { - let d = s.doc_mut()?; - let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; - let region = current_region(sheet, d.selection.active); - let all = RangeRef::all(); - let r = if region.is_single() || d.selection.current() == region { all } else { region }; - let active = d.selection.active; - d.selection = crate::Selection { active, anchor: r.start, ranges: vec![r] }; - Ok(json!({"selection": d.selection.a1()})) -} - -fn select_region(s: &mut Session, _: &Json) -> Result { - let d = s.doc_mut()?; - let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; - let r = current_region(sheet, d.selection.active); - let active = d.selection.active; - d.selection = crate::Selection { active, anchor: r.start, ranges: vec![r] }; - Ok(json!({"selection": d.selection.a1()})) -} - -fn select_row(s: &mut Session, _: &Json) -> Result { - let d = s.doc_mut()?; - let r = d.selection.current(); - let active = d.selection.active; - d.selection = crate::Selection { active, anchor: CellRef::new(r.start.row, 0), ranges: vec![RangeRef::rows(r.start.row, r.end.row)] }; - Ok(json!({"selection": d.selection.a1()})) -} - -fn select_col(s: &mut Session, _: &Json) -> Result { - let d = s.doc_mut()?; - let r = d.selection.current(); - let active = d.selection.active; - d.selection = crate::Selection { active, anchor: CellRef::new(0, r.start.col), ranges: vec![RangeRef::cols(r.start.col, r.end.col)] }; - Ok(json!({"selection": d.selection.a1()})) -} - -/// How many references the Go To dialog keeps for going back to. -const GO_TO_RECENT: usize = 10; -/// The most areas one Go To selects. -const GO_TO_MAX_AREAS: usize = 2000; -/// How deep a name that refers to other names is followed. -const GO_TO_NAME_DEPTH: usize = 8; - -pub(super) fn go_to(s: &mut Session, p: &Json) -> Result { - if bool_param(p, "list") == Some(true) { - let d = s.doc()?; - return Ok(json!({"names": go_to_names(&d.wb, d.wb.active_sheet()), "recent": d.go_to_recent})); - } - let Some(reference) = str_param(p, "reference").or_else(|| str_param(p, "range")) else { return Err(bad("edit.goTo", "missing `reference`")) }; - let d = s.doc()?; - let mut target: Option = None; - let mut areas: Vec = Vec::new(); - let mut named = false; - for part in reference_parts(reference) { - let Some((sheet, found, by_name)) = go_to_target(&d.wb, d.wb.active_sheet(), part, 0) else { - return Err(EngineError::Other("Reference isn't valid.".into())); - }; - // One selection holds the areas of one sheet. - if target.is_some_and(|t| t != sheet) { - return Err(EngineError::Other("Reference isn't valid.".into())); - } - target = Some(sheet); - named |= by_name; - areas.extend(found); - if areas.len() > GO_TO_MAX_AREAS { - return Err(EngineError::Other(format!("Go To selects at most {GO_TO_MAX_AREAS} areas."))); - } - } - let Some(sheet) = target else { return Err(EngineError::Other("Reference isn't valid.".into())) }; - let range = areas.iter().map(RangeRef::a1).collect::>().join(","); - let out = selection_set(s, &json!({"sheet": sheet, "range": range}))?; - if bool_param(p, "record") == Some(true) && !named { - let d = s.doc_mut()?; - let prefix = gridcraft_core::quote_sheet(&d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default()); - let entry = areas.iter().map(|r| format!("{prefix}!{}", r.a1())).collect::>().join(","); - d.go_to_recent.retain(|r| !r.eq_ignore_ascii_case(&entry)); - d.go_to_recent.insert(0, entry); - d.go_to_recent.truncate(GO_TO_RECENT); - } - Ok(out) -} - -/// The parts of a Go To reference, split at the commas outside quoted sheet names and -/// parentheses: `Price, Type` or `B14:C22,F19:G30`. The parts are read one at a time, so a caller -/// that stops at an invalid part or at `GO_TO_MAX_AREAS` does not split the rest of the text. -fn reference_parts(text: &str) -> impl Iterator { - let (mut depth, mut quoted, mut start, mut done) = (0usize, false, 0, false); - let mut chars = text.char_indices(); - std::iter::from_fn(move || { - if done { - return None; - } - for (i, c) in chars.by_ref() { - match c { - '\'' => quoted = !quoted, - '(' if !quoted => depth += 1, - ')' if !quoted => depth = depth.saturating_sub(1), - ',' if !quoted && depth == 0 => { - let part = text.get(start..i).unwrap_or("").trim(); - start = i + 1; - return Some(part); - } - _ => {} - } - } - done = true; - Some(text.get(start..).unwrap_or("").trim()) - }) -} - -/// Where one part of a Go To reference points, seen from sheet `sheet`: the sheet, its areas, -/// and whether a defined name or a table gave them. `Sheet2!Name` is the name scoped to Sheet2. -/// A name counts when what it refers to is a reference; a constant or a formula is not one. -fn go_to_target(wb: &gridcraft_model::Workbook, sheet: usize, part: &str, depth: usize) -> Option<(usize, Vec, bool)> { - if part.is_empty() || depth > GO_TO_NAME_DEPTH { - return None; - } - let (prefix, body) = split_sheet(part); - let on = match &prefix { - Some(n) => wb.sheet_index(n)?, - None => sheet, - }; - if let Some(r) = RangeRef::parse(&body.replace('$', "")) { - return Some((on, vec![r], false)); - } - let name = match prefix { - Some(_) => wb.names.iter().find(|n| n.scope == Some(on) && gridcraft_formula::same_name(&n.name, body)), - None => wb.name(body, sheet), - }; - if let Some(n) = name { - return name_areas(wb, n, sheet, depth).map(|(t, areas)| (t, areas, true)); - } - if prefix.is_none() - && let Some((si, ti)) = wb.table(body) - { - // As in Excel, a table's name stands for its data, without the header and totals rows. - let t = wb.sheet(si)?.tables.get(ti)?; - return Some((si, vec![t.data_range().unwrap_or(t.range)], true)); - } - None -} - -/// The sheet and areas defined name `n` refers to, seen from sheet `sheet`, when that is a -/// reference. -fn name_areas(wb: &gridcraft_model::Workbook, n: &gridcraft_model::DefinedName, sheet: usize, depth: usize) -> Option<(usize, Vec)> { - let from = n.scope.unwrap_or(sheet); - let formula = n.formula.trim().trim_start_matches('='); - let mut target: Option = None; - let mut areas = Vec::new(); - for p in reference_parts(formula) { - let (s, found, _) = go_to_target(wb, from, p, depth + 1)?; - if target.is_some_and(|t| t != s) { - return None; - } - target = Some(s); - areas.extend(found); - if areas.len() > GO_TO_MAX_AREAS { - return None; - } - } - target.map(|t| (t, areas)) -} - -/// The names the Go To dialog lists, seen from sheet `sheet`: the named ranges of the workbook and -/// of every sheet, in alphabetical order. A name scoped to another sheet is written `Sheet2!Name`, -/// and the active sheet's own name hides the workbook name it shares. Hidden names and names that -/// do not refer to a range are left out. -pub fn go_to_names(wb: &gridcraft_model::Workbook, sheet: usize) -> Vec { - let own: std::collections::HashSet = - wb.names.iter().filter(|n| n.scope == Some(sheet)).map(|n| gridcraft_formula::fold_name(&n.name)).collect(); - let mut out: Vec = wb - .names - .iter() - .filter(|n| !n.hidden && name_areas(wb, n, sheet, 0).is_some()) - .filter_map(|n| match n.scope { - None if own.contains(&gridcraft_formula::fold_name(&n.name)) => None, - None => Some(n.name.clone()), - Some(s) if s == sheet => Some(n.name.clone()), - Some(s) => Some(format!("{}!{}", gridcraft_core::quote_sheet(&wb.sheet(s)?.name), n.name)), - }) - .collect(); - out.sort_by_cached_key(|n| gridcraft_formula::fold_name(n)); - out.dedup_by(|a, b| gridcraft_formula::same_name(a, b)); - out -} - -fn go_to_special(s: &mut Session, p: &Json) -> Result { - let kind = str_param(p, "kind").unwrap_or("blanks"); - let d = s.doc()?; - let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; - let scope = if d.selection.is_single_cell() { sheet.used_range().unwrap_or(RangeRef::cell(d.selection.active)) } else { d.selection.bounds() }; - if kind == "lastCell" { - let c = sheet.used_range().map(|r| r.end).unwrap_or_default(); - return selection_set(s, &json!({"cell": c.a1()})); - } - if kind == "currentRegion" { - return select_region(s, &json!({})); - } - let mut hits: Vec = Vec::new(); - if scope.count() > 4_000_000 { - return Err(bad("edit.goToSpecial", "range too large")); - } - for c in scope.iter() { - let cell = sheet.cell(c); - let v = sheet.value(c); - let ok = match kind { - "blanks" => v.is_empty(), - "constants" => cell.is_some_and(|x| x.formula.is_none() && !x.value.is_empty()), - "formulas" => cell.is_some_and(|x| x.formula.is_some()), - "comments" | "notes" => sheet.comments.contains_key(&c), - "errors" => v.is_error(), - "numbers" => v.is_number(), - "text" => v.is_text(), - "visible" => !sheet.is_row_hidden(c.row) && !sheet.is_col_hidden(c.col), - "conditionalFormats" => sheet.cond_formats.iter().any(|cf| cf.ranges.iter().any(|r| r.contains(c))), - "dataValidation" => sheet.validations.iter().any(|dv| dv.ranges.iter().any(|r| r.contains(c))), - _ => return Err(bad("edit.goToSpecial", format!("unknown kind `{kind}`"))), - }; - if ok { - hits.push(c); - } - } - if hits.is_empty() { - return Err(EngineError::Other("No cells were found.".into())); - } - let ranges = coalesce(&hits); - let d = s.doc_mut()?; - d.selection = crate::Selection { active: hits[0], anchor: hits[0], ranges }; - Ok(json!({"selection": d.selection.a1(), "count": hits.len()})) -} - /// Merges cells into vertical runs per column (a compact multi-area selection). fn coalesce(cells: &[CellRef]) -> Vec { let mut sorted = cells.to_vec(); @@ -804,6 +204,8 @@ fn undo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; 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); crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); @@ -824,6 +226,7 @@ fn redo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; d.selection = e.selection; + super::extra::keep_view_modes(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); @@ -832,621 +235,15 @@ fn redo(s: &mut Session, p: &Json) -> Result { Ok(json!({"redone": label})) } -// ---------------------------------------------------------------- clipboard - -fn copy_impl(s: &mut Session, p: &Json, cut: bool) -> Result { - let multiple = || EngineError::Other("This action won't work on multiple selections.".into()); - let sheet = target_sheet(s, p)?; - let ranges = target_ranges(s, p)?; - if ranges.len() > 1 && cut { - return Err(multiple()); - } - // The selection as made (untrimmed), for Insert Copied Cells. - let selected = ranges.first().copied().unwrap_or_default(); - let d = s.doc()?; - let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; - let trim = |range: RangeRef| { - if range.is_full_cols() || range.is_full_rows() { - let used = sh.used_range().unwrap_or(RangeRef::cell(range.start)); - range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range) - } else { - range - } - }; - let (wb, range, areas) = if ranges.len() > 1 { - let areas: Vec = ranges.iter().map(|r| trim(*r)).collect(); - let (wb, block) = slide_together(&d.wb, sheet, &areas).ok_or_else(multiple)?; - (std::sync::Arc::new(wb), block, areas) - } else { - (d.wb.clone(), trim(ranges.first().copied().unwrap_or_default()), Vec::new()) - }; - let text = crate::display::range_text(&wb, sheet, range); - // The HTML rendering is for the host clipboard (UI); it can reach 4 MB, so agents and - // scripts get it only when they ask for it. - let html = if p.get("html").and_then(Json::as_bool) == Some(true) { crate::io::range_html(&wb, sheet, range, &text) } else { None }; - let clip = Clipboard { wb, sheet, range, cut, doc_uid: d.uid, text: text.clone(), areas, selected, trust: d.trust }; - s.clipboard = Some(clip); - let mut result = json!({"range": range.a1(), "text": text}); - if let Some(html) = html { - result["html"] = Json::String(html); - } - Ok(result) -} - -/// Excel copies a multi-area selection only when the areas line up: all cover the same rows (they -/// slide together side by side, left to right) or all cover the same columns (stacked, top to -/// bottom), without overlapping. Returns a copy of the workbook whose sheet holds the areas packed -/// into one block at the first area's place, and that block. Formulas travel as their values, as -/// in Excel. `None` when the areas don't line up. -fn slide_together(wb: &gridcraft_model::Workbook, sheet: usize, areas: &[RangeRef]) -> Option<(gridcraft_model::Workbook, RangeRef)> { - let first = *areas.first()?; - let across = areas.iter().all(|a| a.start.row == first.start.row && a.end.row == first.end.row); - let down = areas.iter().all(|a| a.start.col == first.start.col && a.end.col == first.end.col); - let mut sorted = areas.to_vec(); - if across { - sorted.sort_by_key(|a| a.start.col); - } else if down { - sorted.sort_by_key(|a| a.start.row); - } else { - return None; - } - if sorted.windows(2).any(|w| matches!(w, [a, b] if a.intersects(b))) { - return None; - } - let anchor = sorted.first()?.start; - let (h, w) = if across { - (first.height(), sorted.iter().map(RangeRef::width).fold(0u32, u32::saturating_add)) - } else { - (sorted.iter().map(RangeRef::height).fold(0u32, u32::saturating_add), first.width()) - }; - let block = RangeRef::new(anchor, anchor.offset(i64::from(h) - 1, i64::from(w) - 1)?); - let src = wb.sheet(sheet)?; - let mut out = wb.clone(); - let dst = out.sheet_mut(sheet)?; - dst.take_cells(block); - dst.spill.retain(|c, _| !block.contains(*c)); - dst.spill_ranges.retain(|c, _| !block.contains(*c)); - dst.comments.retain(|c, _| !block.contains(*c)); - dst.merges.retain(|m| !m.intersects(&block)); - if across { - dst.cols.retain(|c, _| !(block.start.col..=block.end.col).contains(c)); - } else { - dst.rows.retain(|r, _| !(block.start.row..=block.end.row).contains(r)); - } - let mut next = if across { anchor.col } else { anchor.row }; - for a in &sorted { - let (dr, dc) = if across { (0, i64::from(next) - i64::from(a.start.col)) } else { (i64::from(next) - i64::from(a.start.row), 0) }; - let cells = src.cells.iter_range(*a).map(|(c, _)| c).chain(src.spill.keys().copied().filter(|c| a.contains(*c))); - for c in cells { - let Some(to) = c.offset(dr, dc) else { continue }; - let style = src.cell(c).map(|x| x.style).unwrap_or_default(); - dst.set_cell(to, Cell { value: src.value(c), formula: None, style }); - if let Some(picture) = src.cell_pictures.get(&c) { - dst.cell_pictures.insert(to, picture.clone()); - } - } - for (c, comment) in src.comments.iter().filter(|(c, _)| a.contains(**c)) { - if let Some(to) = c.offset(dr, dc) { - dst.comments.insert(to, comment.clone()); - } - } - for m in src.merges.iter().filter(|m| a.contains_range(m)) { - if let (Some(s), Some(e)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) { - dst.merges.push(RangeRef::new(s, e)); - } - } - // Column widths (side by side) or row heights and hidden rows (stacked) follow their cells. - if across { - for (c, info) in src.cols.range(a.start.col..=a.end.col) { - dst.cols.insert(next.saturating_add(c.saturating_sub(a.start.col)), *info); - } - } else { - for (r, info) in src.rows.range(a.start.row..=a.end.row) { - dst.rows.insert(next.saturating_add(r.saturating_sub(a.start.row)), *info); - } - } - next = next.saturating_add(if across { a.width() } else { a.height() }); - } - Some((out, block)) -} - -fn copy(s: &mut Session, p: &Json) -> Result { - copy_impl(s, p, false) -} -fn cut(s: &mut Session, p: &Json) -> Result { - copy_impl(s, p, true) -} -fn clear_clipboard(s: &mut Session, _: &Json) -> Result { - s.clipboard = None; - s.format_painter = None; - ok() -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum What { - All, - Formulas, - Values, - Formats, - Comments, - Validation, - AllExceptBorders, - ColumnWidths, - FormulasAndNumberFormats, - ValuesAndNumberFormats, -} - -fn paste(s: &mut Session, p: &Json) -> Result { - // External text (from the system clipboard) when it differs from ours. - if let Some(text) = str_param(p, "text") - && s.clipboard.as_ref().is_none_or(|c| c.text.trim_end_matches(['\r', '\n']) != text.trim_end_matches(['\r', '\n'])) - { - return paste_text(s, p, text); - } - if s.clipboard.is_none() { - return Err(EngineError::Other("Nothing to paste.".into())); - } - paste_special(s, &json!({"what": "all", "at": p.get("at").cloned().unwrap_or(Json::Null)})) -} - -fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result { - let sheet = target_sheet(s, p)?; - let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(s.doc()?.selection.current().start); - let rows: Vec> = parse_tsv(text); - let h = rows.len(); - let w = rows.iter().map(Vec::len).max().unwrap_or(0); - // The HTML flavour, when the host passed it: the number behind each cell's shown text. Read - // only as far as the text's own shape, so spans in the markup can't expand without bound. - let html = str_param(p, "html").map(|html| crate::clip_html::table_cells(html, h, w)).unwrap_or_default(); - edit(s, |cx| { - for (ri, row) in rows.iter().enumerate() { - for (ci, v) in row.iter().enumerate() { - let Some(c) = at.offset(ri as i64, ci as i64) else { continue }; - let mut cell = input_to_cell(v, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str())))); - if let Some(cl) = cell.as_mut() { - numeric_from_html(cl, v, html.get(ri).and_then(|r| r.get(ci)), &mut cx.wb); - } - let sh = cx.sheet_mut(sheet)?; - match cell { - Some(cell) => sh.set_cell(c, cell), - None => { - sh.remove_cell(c); - } - } - cx.touch(sheet, c); - } - } - if h > 0 && w > 0 { - let end = at.offset_clamped(h as i64 - 1, w as i64 - 1); - *cx.sel = crate::Selection { active: at, anchor: at, ranges: vec![RangeRef::new(at, end)] }; - } - Ok(()) - })?; - Ok(json!({"rows": h, "cols": w})) -} - -/// A pasted cell that came out as text ("Rp10,000.00" isn't en-US input) becomes the number the -/// source recorded for it in its HTML, with a format that shows the same text when one can be -/// inferred and the cell has none. The HTML cell must show the same text as the tab-separated -/// field, so HTML that belongs to another copy (or a table laid out differently) changes nothing. -fn numeric_from_html(cell: &mut Cell, field: &str, html: Option<&crate::clip_html::HtmlCell>, wb: &mut gridcraft_model::Workbook) { - let Some(hc) = html else { return }; - let Some(n) = hc.num else { return }; - if cell.formula.is_some() || !matches!(cell.value, Value::Text(_)) || wb.styles.get(cell.style).num_fmt.as_str() == "@" { - return; - } - if crate::clip_html::normalized(&hc.text) != crate::clip_html::normalized(field) { - return; - } - cell.value = Value::number(n); - if wb.styles.get(cell.style).num_fmt.as_str() == "General" - && let Some(code) = crate::clip_html::format_for(field, n) - { - cell.style = wb.styles.derive(cell.style, |s| s.num_fmt = gridcraft_model::NumFmt::new(&code)); - } -} - -/// Tab-separated text with Excel-style quoting. -pub(crate) fn parse_tsv(text: &str) -> Vec> { - let mut rows = Vec::new(); - let mut row = Vec::new(); - let mut field = String::new(); - let mut chars = text.chars().peekable(); - let mut quoted = false; - let mut at_start = true; - while let Some(c) = chars.next() { - if quoted { - if c == '"' { - if chars.peek() == Some(&'"') { - field.push('"'); - chars.next(); - } else { - quoted = false; - } - } else { - field.push(c); - } - continue; - } - match c { - '"' if at_start => { - quoted = true; - at_start = false; - } - '\t' => { - row.push(std::mem::take(&mut field)); - at_start = true; - } - '\r' => {} - '\n' => { - row.push(std::mem::take(&mut field)); - rows.push(std::mem::take(&mut row)); - at_start = true; - } - _ => { - field.push(c); - at_start = false; - } - } - } - if !field.is_empty() || !row.is_empty() { - row.push(field); - rows.push(row); - } - rows -} - -fn paste_special(s: &mut Session, p: &Json) -> Result { - let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) }; - let what = match str_param(p, "what").unwrap_or("all") { - "all" => What::All, - "formulas" => What::Formulas, - "values" => What::Values, - "formats" => What::Formats, - "comments" | "notes" => What::Comments, - "validation" => What::Validation, - "allExceptBorders" => What::AllExceptBorders, - "columnWidths" => What::ColumnWidths, - "formulasAndNumberFormats" => What::FormulasAndNumberFormats, - "valuesAndNumberFormats" => What::ValuesAndNumberFormats, - other => return Err(bad("edit.pasteSpecial", format!("unknown `what`: {other}"))), - }; - let op = str_param(p, "operation").unwrap_or("none").to_string(); - let skip_blanks = bool_param(p, "skipBlanks").unwrap_or(false); - let transpose = bool_param(p, "transpose").unwrap_or(false); - let link = bool_param(p, "link").unwrap_or(false); - if link && !clip.areas.is_empty() { - return Err(EngineError::Other("This action won't work on multiple selections.".into())); - } - let dest_sheet = target_sheet(s, p)?; - let sel = s.doc()?.selection.current(); - let at = cell_param_on(s, p, "at", dest_sheet)?.unwrap_or(sel.start); - let src = clip.range; - let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) }; - // Tile the copy over a larger destination that is a multiple of its size. - let tile = sel.height() % h == 0 - && sel.width() % w == 0 - && !sel.is_single() - && cell_param_on(s, p, "at", dest_sheet)?.is_none() - && !sel.is_full_cols() - && !sel.is_full_rows() - && sel.count() <= 4_000_000; - let (tiles_r, tiles_c) = if tile { (sel.height() / h, sel.width() / w) } else { (1, 1) }; - let same_doc = s.doc()?.uid == clip.doc_uid; - 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())) }; - let src_sheet_name = src_sheet.name.clone(); - if cut_move && at.offset((tiles_r * h).saturating_sub(1) as i64, (tiles_c * w).saturating_sub(1) as i64).is_none() { - // Check the whole footprint before the source is emptied, so a move that overflows the grid loses nothing. - return Err(EngineError::Other("The cut area doesn't fit at this position; nothing was moved.".into())); - } - edit(s, |cx| { - // Styles from another workbook must be re-interned. - let mut style_map = std::collections::HashMap::new(); - let mut map_style = |id: StyleId, wb: &mut gridcraft_model::Workbook| -> StyleId { - if same_doc { - return id; - } - *style_map.entry(id).or_insert_with(|| wb.styles.intern(src_wb.styles.get(id).clone())) - }; - let mut moved_formulas = Vec::new(); - let mut moved_pictures = std::collections::BTreeMap::new(); - if cut_move { - // Remove the source first (contents and formats), and fix references to it. - let source = cx.sheet_mut(clip.sheet)?; - moved_pictures = source.cell_pictures.iter().filter(|(c, _)| src.contains(**c)).map(|(c, p)| (*c, p.clone())).collect(); - let taken = source.take_cells(src); - // Notes, hyperlinks and merged areas sit beside the cells, and a cut takes them - // with the block: the destination is written from the clipboard snapshot taken - // before the cut, so removing them here loses nothing and leaves the old place - // clean instead of leaving one merged block and one note behind. - source.comments.retain(|c, _| !src.contains(*c)); - source.hyperlinks.retain(|c, _| !src.contains(*c)); - source.merges.retain(|m| !src.contains_range(m)); - for (c, _) in &taken { - cx.touch(clip.sheet, *c); - } - moved_formulas = taken; - } - for tr in 0..tiles_r { - for tc in 0..tiles_c { - for r in 0..src.height() { - for c in 0..src.width() { - let sc = CellRef::new(src.start.row + r, src.start.col + c); - let (dr, dc) = if transpose { (c, r) } else { (r, c) }; - let Some(dest) = at.offset((tr * h + dr) as i64, (tc * w + dc) as i64) else { continue }; - let src_cell = if cut_move { - moved_formulas.iter().find(|(k, _)| *k == sc).map(|(_, v)| v.clone()) - } else { - src_sheet.cell(sc).cloned() - }; - let src_val = src_sheet.value(sc); - let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned(); - if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none()) { - continue; - } - let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default(); - let old_picture = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell_pictures.get(&dest)).cloned(); - let mut new_picture = old_picture.clone(); - let mut new = old.clone(); - let shift = |cell: &Cell| -> Option> { - let f = cell.formula.as_ref()?; - let e = f.expr()?; - if cut_move { - // A moved formula still reads cells on its original sheet. Qualify - // those references before the workbook-wide move adjustment below. - let e = if dest_sheet != clip.sheet { - e.map(&mut |x| match x { - gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { - r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); - gridcraft_formula::Expr::Ref(r) - } - other => other, - }) - } else { - e - }; - let mut moved = Formula::from_expr(e); - // The array range moves with its formula. - let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); - moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?))); - moved.dynamic = f.dynamic; - return Some(std::sync::Arc::new(moved)); - } - 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) })) - }; - if link { - let sheet_prefix = if dest_sheet == clip.sheet && same_doc { - String::new() - } else { - format!("{}!", gridcraft_formula::quote_sheet(&src_sheet_name)) - }; - new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1())))); - new.value = Value::Empty; - new_picture = None; - } else { - let sc_cell = src_cell.clone().unwrap_or_default(); - match what { - What::All | What::AllExceptBorders => { - new_picture = src_picture.clone(); - new.formula = shift(&sc_cell); - new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; - let st = map_style(sc_cell.style, &mut cx.wb); - new.style = if what == What::AllExceptBorders { - let borders = cx.wb.styles.get(old.style).borders; - cx.wb.styles.derive(st, |s| s.borders = borders) - } else { - st - }; - } - What::Formulas | What::FormulasAndNumberFormats => { - new_picture = src_picture.clone(); - new.formula = shift(&sc_cell); - new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; - if what == What::FormulasAndNumberFormats { - let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); - new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); - } - } - What::Values | What::ValuesAndNumberFormats => { - new_picture = src_picture.clone(); - new.formula = None; - new.value = src_val.clone(); - if what == What::ValuesAndNumberFormats { - let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); - new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); - } - } - What::Formats => new.style = map_style(sc_cell.style, &mut cx.wb), - What::Comments | What::Validation | What::ColumnWidths => {} - } - // Operations combine numbers with what is already there. - if op != "none" - && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) - && new.formula.is_none() - { - if old_picture.is_some() || new_picture.is_some() { - new_picture = None; - new.value = Value::Error(gridcraft_core::CellError::Value); - } - let a = old.value.clone(); - let b = new.value.clone(); - // Numbers stored as text take part (multiplying by 1 turns them into - // numbers); other text and errors stay as they are. - if let (Ok(x), Ok(y)) = (a.to_number(), b.to_number()) - && (a.is_number() || a.is_empty() || a.is_text()) - && (b.is_number() || b.is_empty()) - { - new.value = match op.as_str() { - "add" => Value::number(x + y), - "subtract" => Value::number(x - y), - "multiply" => Value::number(x * y), - "divide" => { - if y == 0.0 { - Value::Error(gridcraft_core::CellError::Div0) - } else { - Value::number(x / y) - } - } - _ => b.clone(), - }; - } else if (a.is_text() || a.is_error()) && (b.is_number() || b.is_empty()) { - new.value = a; - } - // A formula already there is kept and combined with the pasted number. - if let Some(f) = &old.formula - && let Ok(y) = b.to_number() - && (b.is_number() || b.is_empty()) - && let Some(sym) = match op.as_str() { - "add" => Some('+'), - "subtract" => Some('-'), - "multiply" => Some('*'), - "divide" => Some('/'), - _ => None, - } - { - let text = format!("=({}){sym}{}", f.text, gridcraft_core::number_to_text(y)); - new.formula = Some(std::sync::Arc::new(Formula::new(&text))); - new.value = Value::Empty; - } - } - } - // The copied cell's validation rule replaces whatever rule the destination had. - if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { - let rule = src_sheet.validations.iter().find(|dv| dv.ranges.iter().any(|r| r.contains(sc))).cloned(); - let sh = cx.sheet_mut(dest_sheet)?; - super::data::remove_validation_cells(&mut sh.validations, &[RangeRef::new(dest, dest)]); - if let Some(mut dv) = rule { - // Relative references move with the rule, as pasted formulas do. - let first = dv.ranges.first().map_or(sc, |r| r.start); - dv.f1 = super::data::move_rule_formula(&dv.f1, first, dest); - dv.f2 = dv.f2.map(|f| super::data::move_rule_formula(&f, first, dest)); - dv.ranges = vec![RangeRef::new(dest, dest)]; - sh.validations.push(dv); - } - } - match what { - What::Comments => { - if let Some(cm) = src_sheet.comments.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); - } - } - What::ColumnWidths => { - if let Some(info) = src_sheet.cols.get(&sc.col).copied() { - cx.sheet_mut(dest_sheet)?.cols.insert(dest.col, info); - } - } - What::All => { - if let Some(cm) = src_sheet.comments.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); - } - if let Some(h) = src_sheet.hyperlinks.get(&sc).cloned() { - cx.sheet_mut(dest_sheet)?.hyperlinks.insert(dest, h); - } - cx.sheet_mut(dest_sheet)?.set_cell(dest, new); - } - _ => cx.sheet_mut(dest_sheet)?.set_cell(dest, new), - } - if let Some(picture) = new_picture { - cx.sheet_mut(dest_sheet)?.cell_pictures.insert(dest, picture); - } - cx.touch(dest_sheet, dest); - } - } - } - } - // Merged areas inside the copied block travel with it. - if matches!(what, What::All | What::Formats) && !transpose { - let merges: Vec = src_sheet.merges.iter().filter(|m| src.contains_range(m)).copied().collect(); - for m in merges { - let dr = at.row as i64 - src.start.row as i64; - let dc = at.col as i64 - src.start.col as i64; - 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)?; - sh.merges.retain(|x| !x.intersects(&nm)); - sh.merges.push(nm); - } - } - } - if cut_move { - // References elsewhere to the moved block now point to its new place. - let dest_name = cx.wb.sheet(dest_sheet).map(|s| s.name.clone()).unwrap_or_default(); - let e = if dest_sheet == clip.sheet { - gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col } - } else { - gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name, to_row: at.row, to_col: at.col } - }; - rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e); - cx.structural = true; - } - let end = at.offset_clamped((tiles_r * h) as i64 - 1, (tiles_c * w) as i64 - 1); - *cx.sel = crate::Selection { active: at, anchor: at, ranges: vec![RangeRef::new(at, end)] }; - Ok(()) - })?; - // Formulas and validation from an untrusted file leave the destination untrusted; plain values, - // formats (cell styles and merged areas, no conditional formats), column widths and notes - // carry nothing active. A linked paste writes a formula into every cell whatever `what` says, - // except for column widths and notes, which write no cells at all. - let passive = - matches!(what, What::ColumnWidths | What::Comments) || (!link && matches!(what, What::Formats | What::Values | What::ValuesAndNumberFormats)); - if !same_doc && !passive { - let d = s.doc_mut()?; - d.trust = d.trust.receive(clip.trust); - } - if cut_move { - s.clipboard = None; - } - Ok(json!({"pasted": s.doc()?.selection.a1()})) -} - -/// Applies a reference adjustment to every cell formula and defined name in the workbook. -pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) { - use gridcraft_formula::adjust::Edit; - // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too - // (a cut moves its arrays itself). - let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); - for si in 0..wb.sheets.len() { - let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); - let keys: Vec<(CellRef, std::sync::Arc)> = - wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, cell)| cell.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); - if keys.is_empty() { - continue; - } - let on_target = moves_arrays && host.eq_ignore_ascii_case(target); - let Some(sheet) = wb.sheet_mut(si) else { continue }; - for (c, f) in keys { - let Some(expr) = f.expr() else { continue }; - let new = gridcraft_formula::adjust::adjust(expr, &host, target, e); - let text = gridcraft_formula::print(&new); - let array = match f.array { - Some(a) if on_target => super::sheet::map_range(a, e), - a => a, - }; - if (text != f.text || array != f.array) - && let Some(cell) = sheet.cells.get_mut(c) - { - let mut nf = Formula::from_expr(new); - nf.array = array; - nf.dynamic = f.dynamic; - cell.formula = Some(std::sync::Arc::new(nf)); - } - } - } - for n in wb.names.iter_mut() { - if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) { - // Names are workbook-level: unqualified refs don't occur; qualified ones adjust. - let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e); - n.formula = gridcraft_formula::print(&new); - } - } -} - // ---------------------------------------------------------------- clear +/// The rows of `range` an applied filter hides (rows hidden by hand are not among them). +fn filtered_rows(sh: &gridcraft_model::Sheet, range: RangeRef) -> std::collections::BTreeSet { + sh.rows.range(range.start.row..=range.end.row).filter(|(r, info)| info.hidden && sh.is_row_filtered(**r)).map(|(r, _)| *r).collect() +} + +/// The Clear commands (Delete is Clear Contents). As in Excel, the rows an applied filter hides +/// are left as they are; rows hidden by hand are cleared. fn clear(s: &mut Session, p: &Json, what: &str) -> Result { let sheet = target_sheet(s, p)?; let ranges = target_ranges(s, p)?; @@ -1457,22 +254,44 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { d.wb.sheet(sheet).is_some_and(|sh| { ranges.iter().any(|r| { r.intersection(&sh.used_range().unwrap_or(RangeRef::cell(r.start))).is_some_and(|r| { - sh.cells.iter_range(r).any(|(c, x)| x.value == Value::Bool(true) && super::extra::is_checkbox_cell(&d.wb, sh, c)) + let skip = filtered_rows(sh, r); + sh.cells + .iter_range(r) + .any(|(c, x)| !skip.contains(&c.row) && x.value == Value::Bool(true) && super::extra::is_checkbox_cell(&d.wb, sh, c)) }) }) }) }; + // Notes and links aren't cell contents, so the cell comparison that guards a protected sheet + // doesn't see them go: a locked cell's are refused here, stored cell or not. + if matches!(what, "all" | "comments" | "hyperlinks") { + let d = s.doc()?; + if let Some(sh) = d.wb.sheet(sheet).filter(|sh| sh.is_protected()) { + for &whole in &ranges { + let skip = filtered_rows(sh, whole); + let notes = matches!(what, "all" | "comments").then(|| sh.comments.keys()).into_iter().flatten(); + let links = matches!(what, "all" | "hyperlinks").then(|| sh.hyperlinks.keys()).into_iter().flatten(); + for &c in notes.chain(links).filter(|c| whole.contains(**c) && !skip.contains(&c.row)) { + if d.wb.styles.get(sh.style_id(c)).protection.locked + && let Some(m) = locked_cell_error(sh, c, &d.unlocked_ranges) + { + return Err(EngineError::Other(m)); + } + } + } + } + } edit(s, |cx| { - for r in &ranges { - let r = match cx.wb.sheet(sheet).and_then(|sh| sh.used_range()) { - Some(u) => match r.intersection(&u) { - Some(x) => x, - None => continue, - }, - None => continue, + for &whole in &ranges { + // Cells are only stored inside the used range. Notes and links are kept apart from + // them, so they are cleared over the whole range: one from a file can sit on a cell + // with nothing stored in it. + let used = cx.wb.sheet(sheet).and_then(|sh| sh.used_range()).and_then(|u| whole.intersection(&u)); + let skip = cx.wb.sheet(sheet).map(|sh| filtered_rows(sh, whole)).unwrap_or_default(); + let cells: Vec<(CellRef, Cell)> = match (cx.wb.sheet(sheet), used) { + (Some(sh), Some(r)) => sh.cells.iter_range(r).filter(|(c, _)| !skip.contains(&c.row)).map(|(c, x)| (c, x.clone())).collect(), + _ => Vec::new(), }; - let cells: Vec<(CellRef, Cell)> = - cx.wb.sheet(sheet).map(|sh| sh.cells.iter_range(r).map(|(c, x)| (c, x.clone())).collect()).unwrap_or_default(); // Report every stored cell we touch, even beyond a million coordinates in a sparse // selection. Removed formula anchors must also reach calc so their spills disappear. cx.changed.extend(cells.iter().map(|(c, _)| (sheet, *c))); @@ -1481,6 +300,7 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { for (_, cell) in cells.iter_mut() { let checkbox = cx.wb.styles.get(cell.style).num_fmt.as_str() == "checkbox"; cell.formula = None; + cell.py = None; if checkbox && uncheck_only { cell.value = Value::Bool(false); } else { @@ -1491,6 +311,18 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { } } } + let cleared = |c: CellRef| whole.contains(c) && !skip.contains(&c.row); + // A removed note or link changes its cell even with nothing stored there. + let metadata: Vec = cx + .wb + .sheet(sheet) + .map(|sh| { + let notes = matches!(what, "all" | "comments").then(|| sh.comments.keys()).into_iter().flatten(); + let links = matches!(what, "all" | "hyperlinks").then(|| sh.hyperlinks.keys()).into_iter().flatten(); + notes.chain(links).copied().filter(|c| cleared(*c)).collect() + }) + .unwrap_or_default(); + cx.changed.extend(metadata.into_iter().map(|c| (sheet, c))); let sh = cx.sheet_mut(sheet)?; for (c, mut cell) in cells { match what { @@ -1508,15 +340,17 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { } } if matches!(what, "all" | "comments") { - sh.comments.retain(|c, _| !r.contains(*c)); + sh.comments.retain(|c, _| !cleared(*c)); } if matches!(what, "all" | "hyperlinks") { - sh.hyperlinks.retain(|c, _| !r.contains(*c)); + sh.hyperlinks.retain(|c, _| !cleared(*c)); } - if matches!(what, "all" | "formats") { + if let Some(r) = used + && matches!(what, "all" | "formats") + { let mut unmerged = false; sh.merges.retain(|m| { - let keep = !r.contains_range(m); + let keep = !r.contains_range(m) || skip.range(m.start.row..=m.end.row).next().is_some(); unmerged |= !keep; keep }); @@ -1538,283 +372,6 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { }) } -// ---------------------------------------------------------------- fill - -fn fill_dir(s: &mut Session, p: &Json, dr: i64, dc: i64) -> Result { - let sheet = target_sheet(s, p)?; - let mut r = target_range(s, p)?; - // Whole rows or columns fill only where the sheet has content (nothing on an empty sheet). - if r.is_full_cols() || r.is_full_rows() { - match s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()).and_then(|u| r.intersection(&u)) { - Some(u) => r = u, - None => return Ok(Json::Null), - } - } - if r.count() > crate::fill::MAX_FILL_CELLS { - return Err(bad("edit.fill", "range too large")); - } - // With one row selected, Fill Down copies from the row above (Excel behaviour). - if dr == 1 && r.height() == 1 { - r.start.row = r.start.row.saturating_sub(1); - } - if dc == 1 && r.width() == 1 { - r.start.col = r.start.col.saturating_sub(1); - } - let src = if dr == 1 { - RangeRef::new(r.start, CellRef::new(r.start.row, r.end.col)) - } else if dr == -1 { - RangeRef::new(CellRef::new(r.end.row, r.start.col), r.end) - } else if dc == 1 { - RangeRef::new(r.start, CellRef::new(r.end.row, r.start.col)) - } else { - RangeRef::new(CellRef::new(r.start.row, r.end.col), r.end) - }; - edit(s, |cx| { - crate::fill::fill(cx, sheet, src, r, crate::fill::FillMode::Copy)?; - Ok(Json::Null) - }) -} - -fn auto_fill(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let src = str_param(p, "source").and_then(RangeRef::parse).map_or_else(|| target_range(s, p), Ok)?; - let Some(target) = str_param(p, "target").and_then(RangeRef::parse) else { return Err(bad("edit.autoFill", "missing `target`")) }; - let mode = match str_param(p, "mode").unwrap_or("series") { - "copy" => crate::fill::FillMode::Copy, - "alternate" => crate::fill::FillMode::Alternate, - "formats" => crate::fill::FillMode::Formats, - "values" => crate::fill::FillMode::ValuesOnly, - "extend" => crate::fill::FillMode::Extend, - "days" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Day), - "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), - _ => crate::fill::FillMode::Series, - }; - if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS { - return Err(bad("edit.autoFill", "range too large")); - } - // Excel refuses a target that doesn't hold the source in a corner. Such targets used to fill - // every source lane across the whole target extent: billions of cells for whole rows (`2:3`) - // into whole columns (`A:A`). - if !crate::fill::holds_source_in_corner(src, target) { - return Err(bad("edit.autoFill", "the target must contain the source in one of its corners")); - } - edit(s, |cx| { - crate::fill::fill(cx, sheet, src, target, mode)?; - *cx.sel = crate::Selection { active: src.start, anchor: src.start, ranges: vec![target.union(&src)] }; - Ok(Json::Null) - }) -} - -fn fill_series(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let r = target_range(s, p)?; - let rows = str_param(p, "direction").map(|d| d == "rows").unwrap_or(r.width() > r.height()); - let kind = str_param(p, "type").unwrap_or("linear").to_string(); - let step = f64_param(p, "step").unwrap_or(1.0); - let stop = f64_param(p, "stop"); - let unit = str_param(p, "dateUnit").unwrap_or("day").to_string(); - edit(s, |cx| { - crate::fill::series(cx, sheet, r, rows, &kind, step, stop, &unit)?; - Ok(Json::Null) - }) -} - -fn flash_fill(s: &mut Session, p: &Json) -> Result { - let sheet = target_sheet(s, p)?; - let r = target_range(s, p)?; - let n = edit(s, |cx| crate::fill::flash_fill(cx, sheet, r.start))?; - if n == 0 { - return Err(EngineError::Other( - "We looked at all the data next to your selection and didn't see a pattern for filling in values for you.".into(), - )); - } - Ok(json!({"filled": n})) -} - -// ---------------------------------------------------------------- find & replace - -fn matches(hay: &str, what: &str, case: bool, whole: bool) -> bool { - let (h, w) = if case { (hay.to_string(), what.to_string()) } else { (hay.to_lowercase(), what.to_lowercase()) }; - let has_wild = w.contains(['*', '?']); - if has_wild { - let pat = if whole { w } else { format!("*{w}*") }; - return wildcard(&h, &pat); - } - if whole { h == w } else { h.contains(&w) } -} - -/// `*`/`?` wildcard match with `~` escapes. -pub(crate) fn wildcard(text: &str, pat: &str) -> bool { - let t: Vec = text.chars().collect(); - let mut p: Vec<(char, bool)> = Vec::new(); - let mut it = pat.chars(); - while let Some(c) = it.next() { - if c == '~' { - if let Some(n) = it.next() { - p.push((n, true)); - } - } else { - p.push((c, false)); - } - } - let (mut ti, mut pi) = (0usize, 0usize); - let (mut star, mut mark) = (None, 0usize); - while ti < t.len() { - if pi < p.len() && (p[pi] == ('?', false) || (p[pi].0 == t[ti] && p[pi] != ('*', false))) { - ti += 1; - pi += 1; - } else if pi < p.len() && p[pi] == ('*', false) { - star = Some(pi); - mark = ti; - pi += 1; - } else if let Some(sp) = star { - pi = sp + 1; - mark += 1; - ti = mark; - } else { - return false; - } - } - while pi < p.len() && p[pi] == ('*', false) { - pi += 1; - } - pi == p.len() -} - -fn find(s: &mut Session, p: &Json) -> Result { - let what = str_param(p, "what").unwrap_or("").to_string(); - if what.is_empty() { - return Err(bad("edit.find", "missing `what`")); - } - let case = bool_param(p, "matchCase").unwrap_or(false); - let whole = bool_param(p, "wholeCell").unwrap_or(false); - let values = str_param(p, "lookIn") == Some("values"); - let by_cols = bool_param(p, "byColumns").unwrap_or(false); - let all = bool_param(p, "all").unwrap_or(false); - let workbook = str_param(p, "within") == Some("workbook"); - s.last_find = Some(p.clone()); - let d = s.doc()?; - let sheets: Vec = if workbook { (0..d.wb.sheets.len()).collect() } else { vec![d.wb.active_sheet()] }; - let mut hits: Vec<(usize, CellRef, String)> = Vec::new(); - for si in sheets { - let Some(sh) = d.wb.sheet(si) else { continue }; - let mut cells: Vec<(CellRef, String)> = sh - .cells - .iter() - .filter_map(|(c, cell)| { - let text = if values || cell.formula.is_none() || crate::display::formula_hidden(&d.wb, sh, c) { - crate::display::cell_text(&d.wb, sh, c) - } else { - cell.input_text() - }; - matches(&text, &what, case, whole).then_some((c, text)) - }) - .collect(); - if by_cols { - cells.sort_by_key(|(c, _)| (c.col, c.row)); - } - hits.extend(cells.into_iter().map(|(c, t)| (si, c, t))); - } - if hits.is_empty() { - return Err(EngineError::Other(format!("We couldn't find what you were looking for: {what}"))); - } - if all { - let list: Vec = - hits.iter().map(|(si, c, t)| json!({"sheet": d.wb.sheet(*si).map(|s| s.name.clone()), "cell": c.a1(), "value": t})).collect(); - return Ok(json!({"count": list.len(), "results": list})); - } - // Next hit after the active cell. - let cur = (d.wb.active_sheet(), d.selection.active); - let key = |si: usize, c: CellRef| if by_cols { (si, c.col, c.row) } else { (si, c.row, c.col) }; - let next = hits.iter().find(|(si, c, _)| key(*si, *c) > key(cur.0, cur.1)).or_else(|| hits.first()).cloned(); - let Some((si, c, t)) = next else { return Err(EngineError::Other("not found".into())) }; - let dd = s.doc_mut()?; - dd.wb_switch_sheet(si); - dd.selection = crate::Selection::at(c); - Ok(json!({"cell": c.a1(), "sheet": si, "value": t, "count": hits.len()})) -} - -fn replace(s: &mut Session, p: &Json) -> Result { - let what = str_param(p, "what").unwrap_or("").to_string(); - let with = str_param(p, "with").unwrap_or("").to_string(); - if what.is_empty() { - return Err(bad("edit.replace", "missing `what`")); - } - let case = bool_param(p, "matchCase").unwrap_or(false); - let whole = bool_param(p, "wholeCell").unwrap_or(false); - let all = bool_param(p, "all").unwrap_or(true); - let workbook = str_param(p, "within") == Some("workbook"); - let active = s.doc()?.selection.active; - let n = edit(s, |cx| { - let sheets: Vec = if workbook { (0..cx.wb.sheets.len()).collect() } else { vec![cx.wb.active_sheet()] }; - let mut n = 0; - for si in sheets { - let cells: Vec<(CellRef, String)> = - cx.wb.sheet(si).map(|sh| sh.cells.iter().map(|(c, _)| (c, sh.input_text(c))).collect()).unwrap_or_default(); - for (c, text) in cells { - if !all && c != active { - continue; - } - if !matches(&text, &what, case, whole) { - continue; - } - let new = if whole { - with.clone() - } else if case { - text.replace(&what, &with) - } else { - replace_ci(&text, &what, &with) - }; - let cell = input_to_cell(&new, si, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(new.as_str())))); - let sh = cx.sheet_mut(si)?; - match cell { - Some(cell) => sh.set_cell(c, cell), - None => { - sh.remove_cell(c); - } - } - cx.touch(si, c); - n += 1; - } - } - Ok(n) - })?; - Ok(json!({"replaced": n})) -} - -/// Whether case-folding `s` maps every char to exactly one char of the same UTF-8 length, so -/// byte positions in the folded text still line up with the original's character boundaries. -fn folds_in_place(s: &str) -> bool { - s.chars().all(|c| { - let mut folded = c.to_lowercase(); - let first = folded.next(); - folded.next().is_none() && first.is_some_and(|l| l.len_utf8() == c.len_utf8()) - }) -} - -fn replace_ci(text: &str, what: &str, with: &str) -> String { - let lower = text.to_lowercase(); - let w = what.to_lowercase(); - // Slicing `text` at positions found in `lower` is only sound when folding kept every byte - // boundary: a length check alone misses foldings that keep the total length while shifting - // boundaries (U+212A KELVIN SIGN shrinks 3→1 bytes, U+0130 grows 2→3), where the tail used - // to be dropped. Those fall back to the case-sensitive replace, as length changes already do. - if lower.len() != text.len() || w.is_empty() || !folds_in_place(text) || !folds_in_place(what) { - return text.replace(what, with); - } - let mut out = String::new(); - let mut i = 0; - while let Some(pos) = lower.get(i..).and_then(|s| s.find(&w)) { - out.push_str(text.get(i..i + pos).unwrap_or("")); - out.push_str(with); - i += pos + w.len(); - } - out.push_str(text.get(i..).unwrap_or("")); - out -} - // ---------------------------------------------------------------- format painter fn format_painter(s: &mut Session, p: &Json) -> Result { @@ -1910,310 +467,4 @@ fn begin_edit(s: &mut Session, _: &Json) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - /// Sheet1 and Sheet2 with a workbook range name, a name scoped to each sheet, a constant, a - /// formula and a hidden name. - fn go_to_workbook() -> Session { - let mut s = Session::new(); - s.new_workbook(); - s.execute("home.insertSheet", json!({"name": "Sheet2"})).unwrap(); - s.execute("selection.set", json!({"sheet": 0})).unwrap(); - let define = |s: &mut Session, name: &str, refers: &str, scope: &str| { - s.execute("formulas.defineName", json!({"name": name, "refersTo": refers, "scope": scope})).unwrap(); - }; - define(&mut s, "Price", "=Sheet1!$B$2:$B$5", "Workbook"); - define(&mut s, "type", "=Sheet1!$D$2:$D$5", "Workbook"); - define(&mut s, "Areas", "=Sheet1!$A$1,Sheet1!$C$3:$C$4", "Workbook"); - define(&mut s, "Local", "=Sheet2!$C$3", "Sheet2"); - define(&mut s, "Own", "=Sheet1!$E$1", "Sheet1"); - define(&mut s, "Rate", "=0.07", "Workbook"); - define(&mut s, "Total", "=SUM(Sheet1!$B$2:$B$5)", "Workbook"); - let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); - wb.names.push(gridcraft_model::DefinedName { - name: "Secret".into(), - scope: None, - formula: "Sheet1!$Z$9".into(), - comment: String::new(), - hidden: true, - }); - s - } - - /// "The Go to popup window shows named ranges on every worksheet in your workbook." Names - /// that are not ranges, and hidden names, are not listed. - #[test] - fn go_to_lists_the_named_ranges_of_every_sheet() { - let mut s = go_to_workbook(); - let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); - assert_eq!(list["names"], json!(["Areas", "Own", "Price", "Sheet2!Local", "type"]), "{list}"); - assert_eq!(list["recent"], json!([]), "{list}"); - // Seen from Sheet2, its own name is bare and Sheet1's is qualified. - s.execute("selection.set", json!({"sheet": 1})).unwrap(); - let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); - assert_eq!(list["names"], json!(["Areas", "Local", "Price", "Sheet1!Own", "type"]), "{list}"); - } - - #[test] - fn go_to_a_name_scoped_to_another_sheet_goes_to_that_sheet() { - let mut s = go_to_workbook(); - let out = s.execute("edit.goTo", json!({"reference": "Sheet2!Local"})).unwrap(); - assert_eq!(out["selection"], "C3", "{out}"); - assert_eq!(s.doc().unwrap().wb.active_sheet(), 1); - // A name of several areas selects all of them. - let out = s.execute("edit.goTo", json!({"reference": "Areas"})).unwrap(); - assert_eq!(out["selection"], "A1,C3:C4", "{out}"); - assert_eq!(s.doc().unwrap().wb.active_sheet(), 0); - } - - /// A name matches in any case and any script, as a formula matches it. - #[test] - fn go_to_matches_a_sheet_name_in_any_case() { - let mut s = go_to_workbook(); - s.execute("formulas.defineName", json!({"name": "Größe", "refersTo": "=Sheet2!$D$4", "scope": "Sheet2"})).unwrap(); - s.execute("formulas.defineName", json!({"name": "GRÖSSE", "refersTo": "=Sheet1!$F$6", "scope": "Workbook"})).unwrap(); - let out = s.execute("edit.goTo", json!({"reference": "Sheet2!GRÖSSE"})).unwrap(); - assert_eq!(out["selection"], "D4", "{out}"); - // Seen from Sheet2, its own name hides the workbook name it shares. - let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); - assert_eq!(list["names"], json!(["Areas", "Größe", "Local", "Price", "Sheet1!Own", "type"]), "{list}"); - } - - /// "You can enter multiple named ranges or cell references in the Reference box. Separating - /// each with a comma ... Excel will highlight all the ranges." - #[test] - fn go_to_selects_every_reference_and_name_in_a_list() { - let mut s = go_to_workbook(); - let out = s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30,H21:H29"})).unwrap(); - assert_eq!(out["selection"], "B14:C22,F19:G30,H21:H29", "{out}"); - let out = s.execute("edit.goTo", json!({"reference": "Price, Type"})).unwrap(); - assert_eq!(out["selection"], "B2:B5,D2:D5", "{out}"); - let out = s.execute("edit.goTo", json!({"reference": "Sheet2!$A$1,Sheet2!B2"})).unwrap(); - assert_eq!(out["selection"], "A1,B2", "{out}"); - assert_eq!(s.doc().unwrap().wb.active_sheet(), 1); - // Areas on two sheets, and a part that is not a reference, leave the selection alone. - for bad in ["A1,Sheet1!B2", "A1,Rate", "A1,", "Total"] { - assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err(), "{bad}"); - assert_eq!(s.doc().unwrap().selection.a1(), "A1,B2", "{bad}"); - } - } - - #[test] - fn go_to_reads_the_parts_of_a_long_reference_one_at_a_time() { - let mut parts = reference_parts("A1, 'Q1, Q2'!B2,SUM(C3,D4)"); - assert_eq!(parts.next(), Some("A1")); - assert_eq!(parts.next(), Some("'Q1, Q2'!B2")); - assert_eq!(parts.next(), Some("SUM(C3,D4)")); - assert_eq!(parts.next(), None); - assert_eq!(reference_parts("").collect::>(), vec![""]); - let mut s = go_to_workbook(); - let err = s.execute("edit.goTo", json!({"reference": "A1,".repeat(GO_TO_MAX_AREAS + 1)})).unwrap_err(); - assert!(err.to_string().contains("at most"), "{err}"); - let bad = format!("Total{}", ",".repeat(1_000_000)); - assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err()); - } - - /// "The Go to box keeps track of ranges as you enter them, and you can return to any of them." - #[test] - fn go_to_keeps_the_references_entered_newest_first() { - let mut s = go_to_workbook(); - s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30", "record": true})).unwrap(); - s.execute("edit.goTo", json!({"reference": "Sheet2!A5", "record": true})).unwrap(); - // Names are listed already; a call without `record` (the Name Box) is not kept. - s.execute("edit.goTo", json!({"reference": "Price", "record": true})).unwrap(); - s.execute("edit.goTo", json!({"reference": "Z9"})).unwrap(); - s.execute("edit.goTo", json!({"reference": "b14:c22,f19:g30", "record": true})).unwrap(); - let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); - assert_eq!(list["recent"], json!(["Sheet1!B14:C22,Sheet1!F19:G30", "Sheet2!A5"]), "{list}"); - // Going back from Sheet2 to a recent reference returns to its sheet. - s.execute("selection.set", json!({"sheet": 1})).unwrap(); - let out = s.execute("edit.goTo", json!({"reference": "Sheet1!B14:C22,Sheet1!F19:G30", "record": true})).unwrap(); - assert_eq!(out["selection"], "B14:C22,F19:G30", "{out}"); - assert_eq!(s.doc().unwrap().wb.active_sheet(), 0); - for i in 0..GO_TO_RECENT + 2 { - s.execute("edit.goTo", json!({"reference": format!("A{}", i + 1), "record": true})).unwrap(); - } - let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); - assert_eq!(list["recent"].as_array().map(Vec::len), Some(GO_TO_RECENT), "{list}"); - assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); - } - - #[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. - let mut s = Session::new(); - s.new_workbook(); - s.execute("cell.set", json!({"cell": "A1", "input": 123.5})).unwrap(); - s.execute("cell.set", json!({"cell": "A2", "value": 77})).unwrap(); - s.execute("cell.set", json!({"cell": "A3", "input": true})).unwrap(); - s.execute("cell.set", json!({"cell": "A4", "input": "=A1+A2"})).unwrap(); - let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - assert_eq!(get(&mut s, "A1")["value"], json!(123.5)); - assert_eq!(get(&mut s, "A2")["value"], json!(77.0)); - assert_eq!(get(&mut s, "A3")["value"], json!(true)); - assert_eq!(get(&mut s, "A4")["value"], json!(200.5)); - assert!(s.execute("cell.set", json!({"cell": "A5"})).is_err()); - } - - /// Every string in `values` went through typed input, read with en-US rules, in silence: a - /// caller sending "05.04.2026" from a dd.mm.yyyy export stored 4 May, "2.500" became 2.5 and - /// "4.25 %" became a percentage (#2255). `parse: false` stores a string as the text it is. - #[test] - fn set_values_can_store_strings_as_the_text_they_are() { - let mut s = Session::new(); - s.new_workbook(); - let strings = ["05.04.2026", "02/11/2026", "2.500", "4.25 %", "=1+1", "'keep"]; - let row: Vec = strings.iter().map(|v| json!(v)).collect(); - let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - - // The default is unchanged: the dates swap, the thousands separator is a decimal point. - s.execute("range.setValues", json!({"range": "A1", "values": [row.clone()]})).unwrap(); - assert_eq!(get(&mut s, "A1")["text"], "5/4/2026", "dd.mm.yyyy read as mm.dd.yyyy"); - assert_eq!(get(&mut s, "C1")["value"], json!(2.5), "\"2.500\" read as a decimal"); - assert_eq!(get(&mut s, "D1")["value"], json!(0.0425), "\"4.25 %\" read as a percentage"); - - // With `parse: false` each string is the text it was given, and a formula is still a - // formula. - s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [row.clone()]})).unwrap(); - for (i, want) in strings.iter().enumerate() { - let cell = format!("{}3", (b'A' + i as u8) as char); - let got = get(&mut s, &cell); - if *want == "=1+1" { - assert_eq!(got["value"], json!(2.0), "{cell} is still a formula: {got}"); - assert_eq!(got["formula"], "=1+1", "{got}"); - } else { - assert_eq!(got["value"], json!(*want), "{cell} is the text it was given: {got}"); - assert!(got["formula"].is_null(), "{cell} is not a formula: {got}"); - } - } - // Numbers and booleans are untouched either way. - s.execute("range.setValues", json!({"range": "A5", "parse": false, "values": [[12.5, true, null]]})).unwrap(); - assert_eq!(get(&mut s, "A5")["value"], json!(12.5)); - assert_eq!(get(&mut s, "B5")["value"], json!(true)); - assert_eq!(get(&mut s, "C5")["text"], ""); - // `parse` is a flag, and anything else is a usage error rather than a quiet default. - s.execute("range.setValues", json!({"range": "A7", "parse": true, "values": [["2.500"]]})).unwrap(); - assert_eq!(get(&mut s, "A7")["value"], json!(2.5)); - assert!(s.execute("range.setValues", json!({"range": "A8", "parse": "no", "values": [["x"]]})).is_err()); - 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(); - assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); - let d = s.doc().unwrap(); - let sh = d.wb.active().unwrap(); - assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A9").unwrap())).align.wrap); - } - - #[test] - fn legacy_array_entry() { - 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": "C4", "input": "old"})).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 get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - assert_eq!(get(&mut s, "C3")["value"], json!(4.0)); - // Past the result Excel shows #N/A; the old content of the range is replaced. - assert_eq!(get(&mut s, "C4")["text"], "#N/A"); - let bar = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("C2").unwrap()).map(|c| c.bar_text()); - assert_eq!(bar.as_deref(), Some("{=B2:B3*2}")); - } - - #[test] - fn an_array_entered_outside_the_selection_covers_only_its_cell() { - // Found by the command-sequence fuzzer: the array took the selection's range even with - // `cell` elsewhere (or on another sheet), so its formula sat outside its own range and the - // selected cells were wiped. - let mut s = Session::new(); - s.new_workbook(); - s.execute("cell.set", json!({"cell": "K20", "input": "keep"})).unwrap(); - s.execute("selection.set", json!({"range": "K20:K22"})).unwrap(); - s.execute("cell.set", json!({"cell": "H5", "input": "=1+1", "array": true})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - let f = sh.cell(CellRef::parse("H5").unwrap()).and_then(|c| c.formula.clone()).unwrap(); - assert_eq!(f.array, Some(RangeRef::parse("H5").unwrap())); - assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep")); - } - - #[test] - fn wildcards() { - assert!(wildcard("hello", "h*o")); - assert!(wildcard("hello", "h?llo")); - assert!(!wildcard("hello", "h?lo")); - assert!(wildcard("a*b", "a~*b")); - assert!(!wildcard("axb", "a~*b")); - assert!(wildcard("", "*")); - } - - #[test] - fn tsv() { - assert_eq!(parse_tsv("a\tb\n1\t2\n"), vec![vec!["a", "b"], vec!["1", "2"]]); - assert_eq!(parse_tsv("\"x\ty\"\tz"), vec![vec!["x\ty", "z"]]); - assert_eq!(parse_tsv("\"he said \"\"hi\"\"\""), vec![vec!["he said \"hi\""]]); - } - - #[test] - fn paste_special_operations_keep_text_errors_and_formulas() { - let mut s = Session::new(); - s.new_workbook(); - s.execute( - "range.setValues", - json!({"range": "A1", "values": [["'123", "Total", "=NA()", "=B3*2", 5], [1, null, null, null, null], [null, 4, null, null, null]]}), - ) - .unwrap(); - let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - assert_eq!(get(&mut s, "A1")["value"], "123"); - s.execute("edit.copy", json!({"range": "A2"})).unwrap(); - s.execute("selection.set", json!({"range": "A1:E1"})).unwrap(); - s.execute("edit.pasteSpecial", json!({"what": "values", "operation": "multiply"})).unwrap(); - assert_eq!(get(&mut s, "A1")["value"], json!(123.0)); - assert_eq!(get(&mut s, "B1")["value"], "Total"); - assert_eq!(get(&mut s, "C1")["value"]["error"], "#N/A"); - assert_eq!(get(&mut s, "D1")["formula"], "=(B3*2)*1"); - assert_eq!(get(&mut s, "D1")["value"], json!(8.0)); - assert_eq!(get(&mut s, "E1")["value"], json!(5.0)); - } - - #[test] - fn cut_paste_that_overflows_the_grid_moves_nothing() { - // #997: the source was emptied first and the cells that fell off the grid were skipped. - let mut s = Session::new(); - s.new_workbook(); - s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2]]})).unwrap(); - let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); - s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); - // Transposed, the 2 rows become 2 columns and the second one is past XFD. - assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "XFD1"})).is_err()); - assert_eq!(get(&mut s, "A1")["value"], json!(1.0)); - assert_eq!(get(&mut s, "A2")["value"], json!(2.0)); - // Not transposed, the second row would be past the last row. - assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "at": "A1048576"})).is_err()); - assert_eq!(get(&mut s, "A1")["value"], json!(1.0)); - assert_eq!(get(&mut s, "A2")["value"], json!(2.0)); - // Not transposed it still fits in column XFD. - s.execute("edit.pasteSpecial", json!({"what": "all", "at": "XFD1"})).unwrap(); - assert_eq!(get(&mut s, "XFD1")["value"], json!(1.0)); - assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0)); - } - - #[test] - fn replace_case_insensitive() { - assert_eq!(replace_ci("Apple apple APPLE", "apple", "pear"), "pear pear pear"); - } - - #[test] - fn replace_case_insensitive_keeps_text_when_folding_moves_boundaries() { - // U+212A KELVIN SIGN folds to `k` (3→1 bytes) while U+0130 folds to `i` plus a - // combining dot (2→3 bytes): the folded text is the same length but its byte positions - // no longer line up with the original, and the old slicing dropped the tail. - let mut s = Session::new(); - s.new_workbook(); - let text = "\u{212A}\u{0130}\u{0130}"; - s.execute("cell.set", json!({"cell": "A1", "input": text})).unwrap(); - s.execute("edit.replace", json!({"what": "k", "with": "x"})).unwrap(); - let sh = s.doc().unwrap().wb.active().unwrap(); - assert_eq!(sh.value(CellRef::new(0, 0)), Value::text(text)); - } -} +mod tests; diff --git a/crates/engine/src/cmd/edit/cell.rs b/crates/engine/src/cmd/edit/cell.rs new file mode 100644 index 0000000000..6101356824 --- /dev/null +++ b/crates/engine/src/cmd/edit/cell.rs @@ -0,0 +1,356 @@ +use super::{ + Cell, CellRef, EngineError, Formula, Json, MAX_ROWS, RangeRef, Result, Session, StyleId, Value, bad, bool_param, cell_param_on, edit, json, + locked_cell_error, str_param, target_range, target_ranges, target_sheet, +}; + +// ---------------------------------------------------------------- entry + +/// 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 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 { + 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 +/// format). Inherits the destination's cell, row or column style, including its number +/// format, before parsing. Errors when the formula can't be parsed. +pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { + let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); + if input.is_empty() { + let c = Cell { value: Value::Empty, formula: None, style, py: None }; + return Ok(if c.is_blank() { None } else { Some(c) }); + } + let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; + if fmt_is_text { + return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None })); + } + let is_formula = is_formula_input(input); + if is_formula && gridcraft_model::python::is_py_formula(input) { + return Err(EngineError::Other(PY_FORMULA.into())); + } + 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)?; + let mut cell = Cell::formula(Formula::from_expr(expr)); + cell.style = style; + // Formulas whose result is a date/time get a format from functions like TODAY(). + if wb.styles.get(style).num_fmt.as_str() == "General" { + let f = cell.formula.as_ref().map(|f| f.text.to_ascii_uppercase()).unwrap_or_default(); + let auto = if f.starts_with("TODAY(") + || f.starts_with("DATE(") + || f.starts_with("EDATE(") + || f.starts_with("EOMONTH(") + || f.starts_with("WORKDAY(") + { + Some("m/d/yyyy") + } else if f.starts_with("NOW(") { + Some("m/d/yyyy h:mm") + } else if f.starts_with("TIME(") { + Some("h:mm AM/PM") + } else { + None + }; + if let Some(code) = auto { + cell.style = wb.styles.derive(style, |s| s.num_fmt = gridcraft_model::NumFmt::new(code)); + } + } + return Ok(Some(cell)); + } + let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system); + // 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() + && !input.contains('%') + && wb.styles.get(style).num_fmt.as_str().ends_with('%') + && let Value::Number(n) = parsed.value + && n.abs() >= 1.0 + { + parsed.value = Value::Number(n / 100.0); + } + let mut style = style; + if let Some(code) = parsed.format { + let cur = wb.styles.get(style).num_fmt.as_str().to_string(); + if cur == "General" { + style = wb.styles.derive(style, |s| s.num_fmt = gridcraft_model::NumFmt::new(code)); + } + } + // Wrap text automatically when the input has line breaks (Alt+Enter). + if input.contains('\n') && !wb.styles.get(style).align.wrap { + style = wb.styles.derive(style, |s| s.align.wrap = true); + } + Ok(Some(Cell { value: parsed.value, formula: None, style, py: None })) +} + +/// Parses a formula as it is typed (without the `=`). Excel closes missing parentheses for you, +/// and refuses a formula that still doesn't parse. +pub(crate) fn parse_typed_formula(body: &str) -> Result { + // Excel closes missing parentheses for you. + let parsed = gridcraft_formula::parse_closing_parens(body, gridcraft_formula::parse); + parsed.map_err(|e| EngineError::Other(format!("There's a problem with this formula: {e}"))) +} + +/// Like Excel, a formula that calls a built-in function with too few or too many arguments is +/// refused when it's entered, rather than stored to show `#VALUE!`. Functions the registry doesn't +/// hold (special forms like LET, LAMBDA, OFFSET, INDIRECT, SUBTOTAL), defined LAMBDA names and +/// unknown functions are skipped. +pub(crate) fn check_arg_counts(expr: &gridcraft_formula::Expr) -> Result<()> { + let mut bad = None; + expr.walk(&mut |e| { + if bad.is_none() + && let gridcraft_formula::Expr::Call(name, args) = e + && let Some(spec) = gridcraft_functions::lookup(name) + && !spec.accepts(args.len()) + { + let few = args.len() < spec.min_args; + bad = Some(format!("{} has too {} arguments. Use {}", spec.name, if few { "few" } else { "many" }, spec.signature)); + } + }); + match bad { + Some(msg) => Err(EngineError::Other(msg)), + None => Ok(()), + } +} + +pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let at = match cell_param_on(s, p, "cell", sheet)? { + Some(c) => c, + None => s.doc()?.selection.active, + }; + // Both spellings take a string, number or boolean, as typed (#697). + let input = p.get("input").or_else(|| p.get("value")).map(json_to_input).ok_or_else(|| bad("cell.set", "missing `input` (or `value`)"))?; + let array = bool_param(p, "array").unwrap_or(false); + let d = s.doc()?; + if let Some(sh) = d.wb.sheet(sheet) + && sh.is_protected() + && d.wb.styles.get(sh.style_id(at)).protection.locked + && let Some(m) = locked_cell_error(sh, at, &d.unlocked_ranges) + { + return Err(EngineError::Other(m)); + } + let active_sheet = s.doc()?.wb.active_sheet(); + edit(s, |cx| { + if array { + // Legacy Ctrl+Shift+Enter array formula over the selection, when the selection holds + // 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) }; + // 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. + 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); + return Ok(Json::Null); + } + let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?; + let sh = cx.sheet_mut(sheet)?; + match cell { + Some(c) => sh.set_cell(at, c), + None => { + sh.remove_cell(at); + } + } + crate::cmd::data::grow_autofilter(sh, at); + cx.touch(sheet, at); + Ok(Json::Null) + })?; + let v = s.doc()?.wb.sheet(sheet).map(|sh| sh.value(at)).unwrap_or_default(); + Ok(json!({"cell": at.a1(), "value": v.display()})) +} + +pub(crate) fn json_to_input(v: &Json) -> String { + match v { + Json::Null => String::new(), + Json::Bool(b) => { + if *b { + "TRUE".into() + } else { + "FALSE".into() + } + } + Json::Number(n) => n.to_string(), + Json::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// How many converted strings `range.setValues` reports back, and how much of each input and +/// stored text: the report is a diagnostic, so a big write must not put a second copy of its data +/// in the result. +const MAX_REPORTED_CONVERSIONS: usize = 20; +const MAX_REPORTED_CHARS: usize = 32; + +/// `text` cut to [`MAX_REPORTED_CHARS`] characters for the conversion report, with `…` when it was +/// cut. Counting characters keeps a multi-byte input whole. +fn clipped(text: &str) -> String { + let mut out: String = text.chars().take(MAX_REPORTED_CHARS).collect(); + if out.len() < text.len() { + out.push('…'); + } + out +} + +pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let start = target_range(s, p)?.start; + let Some(rows) = p.get("values").and_then(Json::as_array) else { return Err(bad("range.setValues", "missing `values` (array of rows)")) }; + // A string is run through typed input by default, which reads it with en-US rules: a caller + // sending "05.04.2026" from a dd.mm.yyyy export got 4 May, and "2.500" became 2.5, in silence + // (#2255). `parse: false` stores a string as the text it is; numbers, booleans and formulas + // are unaffected either way. + let parse = match p.get("parse") { + None | Some(Json::Null) => true, + Some(Json::Bool(b)) => *b, + Some(other) => return Err(bad("range.setValues", format!("parse {other}: true or false"))), + }; + if rows.len() > MAX_ROWS as usize { + return Err(bad("range.setValues", "too many rows")); + } + let mut count = 0; + // The strings typed input read as something other than the text given, for the result: a + // caller can notice a "05.04.2026" that became a date without reading the file back (#2255). + let mut converted: Vec<(CellRef, String)> = Vec::new(); + let mut converted_count = 0; + edit(s, |cx| { + for (ri, row) in rows.iter().enumerate() { + let cols: Vec<&Json> = match row.as_array() { + Some(a) => a.iter().collect(), + None => vec![row], + }; + for (ci, v) in cols.iter().enumerate() { + let Some(at) = start.offset(ri as i64, ci as i64) else { continue }; + let input = json_to_input(v); + let cell = match v { + Json::Number(n) => Some(Cell { + value: Value::number(n.as_f64().unwrap_or(0.0)), + formula: None, + style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), + py: None, + }), + Json::Bool(b) => Some(Cell { + value: Value::Bool(*b), + formula: None, + style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), + py: None, + }), + // Text as given: no date or number reading, and a leading `'` is part of the + // text rather than the marker that makes it text. A formula is still a + // formula, which is what the ticket asks for and what `=` means in a cell. + Json::String(text) if !parse && !text.starts_with('=') => { + if text.is_empty() { + // An empty string clears the cell, as `null` and the default path do: + // an empty text cell is not blank, and a script clearing cells with + // `""` would leave cells `COUNTA` counts. The cell keeps its formatting. + input_to_cell("", sheet, at, &mut cx.wb)? + } else { + let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); + // Line breaks still turn on Wrap Text, as typed input does. + if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { + style = cx.wb.styles.derive(style, |s| s.align.wrap = true); + } + Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None }) + } + } + _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, + }; + // A string that became a formula was written as one (`=`), which is deliberate; + // only a number (dates and times included), boolean or error is a reading of the + // string and worth reporting. + if let Some(c) = &cell + && matches!(v, Json::String(_)) + && c.formula.is_none() + && matches!(c.value, Value::Number(_) | Value::Bool(_) | Value::Error(_)) + { + converted_count += 1; + if converted.len() < MAX_REPORTED_CONVERSIONS { + converted.push((at, input.clone())); + } + } + let sh = cx.sheet_mut(sheet)?; + match cell { + Some(c) => sh.set_cell(at, c), + None => { + sh.remove_cell(at); + } + } + crate::cmd::data::grow_autofilter(sh, at); + cx.touch(sheet, at); + count += 1; + } + } + Ok(()) + })?; + let d = s.doc()?; + let reported: Vec = + d.wb.sheet(sheet) + .map(|sh| { + converted + .iter() + .map(|(at, input)| json!({"cell": at.a1(), "input": clipped(input), "stored": clipped(&crate::display::cell_text(&d.wb, sh, *at))})) + .collect() + }) + .unwrap_or_default(); + Ok(json!({"cells": count, "convertedCount": converted_count, "converted": reported})) +} + +pub(super) fn range_fill(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let ranges = target_ranges(s, p)?; + let input = str_param(p, "input").unwrap_or("").to_string(); + let origin = s.doc()?.selection.active; + edit(s, |cx| { + // Each cell gets what typing the input there gives: the automatic number format where + // it's General, its own format otherwise, text where it's Text. That depends only on + // the cell's style, so the input is parsed once per style. + let mut by_style: std::collections::HashMap> = std::collections::HashMap::new(); + for r in &ranges { + if r.count() > 2_000_000 { + return Err(bad("range.fill", "range too large")); + } + for at in r.iter() { + let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); + let base = match by_style.get(&style) { + Some(c) => c.clone(), + None => { + let c = input_to_cell(&input, sheet, at, &mut cx.wb)?; + by_style.insert(style, c.clone()); + c + } + }; + let mut cell = base.unwrap_or_default(); + if let Some(f) = &cell.formula + && let Some(e) = f.expr() + { + let shifted = gridcraft_formula::adjust::shift_relative(e, at.row as i64 - origin.row as i64, at.col as i64 - origin.col as i64); + cell.formula = Some(std::sync::Arc::new(Formula::from_expr(shifted))); + } + let sh = cx.sheet_mut(sheet)?; + sh.set_cell(at, cell); + crate::cmd::data::grow_autofilter(sh, at); + cx.touch(sheet, at); + } + } + Ok(Json::Null) + }) +} diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs new file mode 100644 index 0000000000..da34c017a0 --- /dev/null +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -0,0 +1,346 @@ +use super::cell::input_to_cell; +use super::paste_special::paste_special; +use super::{ + Cell, Clipboard, EngineError, Json, RangeRef, Result, Session, Value, bad, bool_param, cell_param_on, edit, json, ok, str_param, target_ranges, + target_sheet, +}; + +// ---------------------------------------------------------------- clipboard + +fn copy_impl(s: &mut Session, p: &Json, cut: bool) -> Result { + let multiple = || EngineError::Other("This action won't work on multiple selections.".into()); + let sheet = target_sheet(s, p)?; + let ranges = target_ranges(s, p)?; + if ranges.len() > 1 && cut { + return Err(multiple()); + } + // The selection as made (untrimmed), for Insert Copied Cells. + let selected = ranges.first().copied().unwrap_or_default(); + let d = s.doc()?; + let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + let trim = |range: RangeRef| { + if range.is_full_cols() || range.is_full_rows() { + let used = sh.used_range().unwrap_or(RangeRef::cell(range.start)); + range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range) + } else { + range + } + }; + let (wb, range, areas) = if ranges.len() > 1 { + let areas: Vec = ranges.iter().map(|r| trim(*r)).collect(); + let (wb, block) = slide_together(&d.wb, sheet, &areas).ok_or_else(multiple)?; + (std::sync::Arc::new(wb), block, areas) + } else { + (d.wb.clone(), trim(ranges.first().copied().unwrap_or_default()), Vec::new()) + }; + let text = crate::display::range_text(&wb, sheet, range); + // The HTML rendering is for the host clipboard (UI); it can reach 4 MB, so agents and + // scripts get it only when they ask for it. + let html = if p.get("html").and_then(Json::as_bool) == Some(true) { crate::io::range_html(&wb, sheet, range, &text) } else { None }; + let clip = Clipboard { wb, sheet, range, cut, doc_uid: d.uid, text: text.clone(), areas, selected, trust: d.trust }; + s.clipboard = Some(clip); + let mut result = json!({"range": range.a1(), "text": text}); + if let Some(html) = html { + result["html"] = Json::String(html); + } + Ok(result) +} + +/// Excel copies a multi-area selection only when the areas line up: all cover the same rows (they +/// slide together side by side, left to right) or all cover the same columns (stacked, top to +/// bottom), without overlapping. Returns a copy of the workbook whose sheet holds the areas packed +/// into one block at the first area's place, and that block. Formulas travel as their values, as +/// in Excel. `None` when the areas don't line up. +fn slide_together(wb: &gridcraft_model::Workbook, sheet: usize, areas: &[RangeRef]) -> Option<(gridcraft_model::Workbook, RangeRef)> { + let first = *areas.first()?; + let across = areas.iter().all(|a| a.start.row == first.start.row && a.end.row == first.end.row); + let down = areas.iter().all(|a| a.start.col == first.start.col && a.end.col == first.end.col); + let mut sorted = areas.to_vec(); + if across { + sorted.sort_by_key(|a| a.start.col); + } else if down { + sorted.sort_by_key(|a| a.start.row); + } else { + return None; + } + if sorted.windows(2).any(|w| matches!(w, [a, b] if a.intersects(b))) { + return None; + } + let anchor = sorted.first()?.start; + let (h, w) = if across { + (first.height(), sorted.iter().map(RangeRef::width).fold(0u32, u32::saturating_add)) + } else { + (sorted.iter().map(RangeRef::height).fold(0u32, u32::saturating_add), first.width()) + }; + let block = RangeRef::new(anchor, anchor.offset(i64::from(h) - 1, i64::from(w) - 1)?); + let src = wb.sheet(sheet)?; + let mut out = wb.clone(); + let dst = out.sheet_mut(sheet)?; + dst.take_cells(block); + dst.spill.retain(|c, _| !block.contains(*c)); + dst.spill_ranges.retain(|c, _| !block.contains(*c)); + dst.comments.retain(|c, _| !block.contains(*c)); + dst.merges.retain(|m| !m.intersects(&block)); + if across { + dst.cols.retain(|c, _| !(block.start.col..=block.end.col).contains(c)); + } else { + dst.rows.retain(|r, _| !(block.start.row..=block.end.row).contains(r)); + } + let mut next = if across { anchor.col } else { anchor.row }; + for a in &sorted { + let (dr, dc) = if across { (0, i64::from(next) - i64::from(a.start.col)) } else { (i64::from(next) - i64::from(a.start.row), 0) }; + let cells = src.cells.iter_range(*a).map(|(c, _)| c).chain(src.spill.keys().copied().filter(|c| a.contains(*c))); + for c in cells { + let Some(to) = c.offset(dr, dc) else { continue }; + let style = src.cell(c).map(|x| x.style).unwrap_or_default(); + dst.set_cell(to, Cell { value: src.value(c), formula: None, style, py: None }); + if let Some(picture) = src.cell_pictures.get(&c) { + dst.cell_pictures.insert(to, picture.clone()); + } + } + for (c, comment) in src.comments.iter().filter(|(c, _)| a.contains(**c)) { + if let Some(to) = c.offset(dr, dc) { + dst.comments.insert(to, comment.clone()); + } + } + for m in src.merges.iter().filter(|m| a.contains_range(m)) { + if let (Some(s), Some(e)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) { + dst.merges.push(RangeRef::new(s, e)); + } + } + // Column widths (side by side) or row heights and hidden rows (stacked) follow their cells. + if across { + for (c, info) in src.cols.range(a.start.col..=a.end.col) { + dst.cols.insert(next.saturating_add(c.saturating_sub(a.start.col)), *info); + } + } else { + for (r, info) in src.rows.range(a.start.row..=a.end.row) { + dst.rows.insert(next.saturating_add(r.saturating_sub(a.start.row)), *info); + } + } + next = next.saturating_add(if across { a.width() } else { a.height() }); + } + Some((out, block)) +} + +pub(super) fn copy(s: &mut Session, p: &Json) -> Result { + copy_impl(s, p, false) +} + +pub(super) fn cut(s: &mut Session, p: &Json) -> Result { + copy_impl(s, p, true) +} + +pub(super) fn clear_clipboard(s: &mut Session, _: &Json) -> Result { + s.clipboard = None; + s.format_painter = None; + ok() +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum What { + All, + Formulas, + Values, + Formats, + Comments, + Validation, + AllExceptBorders, + ColumnWidths, + FormulasAndNumberFormats, + ValuesAndNumberFormats, +} + +pub(super) fn paste(s: &mut Session, p: &Json) -> Result { + // External text (from the system clipboard) when it differs from ours. + if let Some(text) = str_param(p, "text") + && s.clipboard.as_ref().is_none_or(|c| c.text.trim_end_matches(['\r', '\n']) != text.trim_end_matches(['\r', '\n'])) + { + return paste_text(s, p, text); + } + if s.clipboard.is_none() { + return Err(EngineError::Other("Nothing to paste.".into())); + } + paste_special(s, &json!({"what": "all", "at": p.get("at").cloned().unwrap_or(Json::Null)})) +} + +/// Drag and drop (dragging the selection's border): moves `range` so its top-left cell lands on +/// `to`, as Cut and Paste would. Like Excel, it asks before replacing cells that hold data or show a +/// spilled value (other than the moved cells themselves); run it again with `overwrite: true` to replace them. A +/// refused or failed move leaves the clipboard as it was. +pub(super) fn range_move(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let to = cell_param_on(s, p, "to", sheet)?.ok_or_else(|| bad("range.move", "missing `to`"))?; + let kept = s.clipboard.take(); + let moved = cut(s, p).and_then(|_| { + let src = s.clipboard.as_ref().map(|c| c.range).unwrap_or_default(); + let dest = to.offset(i64::from(src.height()) - 1, i64::from(src.width()) - 1).map(|end| RangeRef::new(to, end)); + if bool_param(p, "overwrite") != Some(true) + && let Some(dest) = dest + && let Some(sh) = s.doc()?.wb.sheet(sheet) + && (sh.cells.iter_range(dest).any(|(c, cell)| !src.contains(c) && cell.has_content()) + || sh.spill.range(dest.start..=dest.end).any(|(c, v)| dest.contains(*c) && !src.contains(*c) && *v != Value::Empty)) + { + return Err(EngineError::Confirm("There's already data here. Do you want to replace it?".into())); + } + // On the range's sheet, which `paste` would leave to the active one. The selection + // belongs to the active sheet: it follows the moved cells only when they are on it. + let selection = s.doc()?.selection.clone(); + let pasted = paste_special(s, &json!({"what": "all", "at": to.a1(), "sheet": sheet}))?; + if sheet != s.doc()?.wb.active_sheet() { + s.doc_mut()?.selection = selection; + } + Ok(pasted) + }); + if moved.is_err() { + s.clipboard = kept; + } + moved +} + +fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result { + let sheet = target_sheet(s, p)?; + let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(s.doc()?.selection.current().start); + let rows: Vec> = parse_tsv(text); + let h = rows.len(); + let w = rows.iter().map(Vec::len).max().unwrap_or(0); + // The HTML flavour, when the host passed it: the number behind each cell's shown text. Read + // only as far as the text's own shape, so spans in the markup can't expand without bound. + let html = str_param(p, "html").map(|html| crate::clip_html::table_cells(html, h, w)).unwrap_or_default(); + edit(s, |cx| { + for (ri, row) in rows.iter().enumerate() { + for (ci, v) in row.iter().enumerate() { + let Some(c) = at.offset(ri as i64, ci as i64) else { continue }; + let mut cell = input_to_cell(v, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str())))); + if let Some(cl) = cell.as_mut() { + numeric_from_html(cl, v, html.get(ri).and_then(|r| r.get(ci)), &mut cx.wb); + } + let sh = cx.sheet_mut(sheet)?; + match cell { + Some(cell) => sh.set_cell(c, cell), + None => { + sh.remove_cell(c); + } + } + cx.touch(sheet, c); + } + } + if h > 0 && w > 0 { + let end = at.offset_clamped(h as i64 - 1, w as i64 - 1); + *cx.sel = crate::Selection { active: at, anchor: at, ranges: vec![RangeRef::new(at, end)] }; + } + Ok(()) + })?; + Ok(json!({"rows": h, "cols": w})) +} + +/// A pasted cell that came out as text ("Rp10,000.00" isn't en-US input) becomes the number the +/// source recorded for it in its HTML, with a format that shows the same text when one can be +/// inferred and the cell has none. The HTML cell must show the same text as the tab-separated +/// field, so HTML that belongs to another copy (or a table laid out differently) changes nothing. +fn numeric_from_html(cell: &mut Cell, field: &str, html: Option<&crate::clip_html::HtmlCell>, wb: &mut gridcraft_model::Workbook) { + let Some(hc) = html else { return }; + let Some(n) = hc.num else { return }; + if cell.formula.is_some() || !matches!(cell.value, Value::Text(_)) || wb.styles.get(cell.style).num_fmt.as_str() == "@" { + return; + } + if crate::clip_html::normalized(&hc.text) != crate::clip_html::normalized(field) { + return; + } + cell.value = Value::number(n); + if wb.styles.get(cell.style).num_fmt.as_str() == "General" + && let Some(code) = crate::clip_html::format_for(field, n) + { + cell.style = wb.styles.derive(cell.style, |s| s.num_fmt = gridcraft_model::NumFmt::new(&code)); + } +} + +/// Tab-separated text with Excel-style quoting. +pub(crate) fn parse_tsv(text: &str) -> Vec> { + let mut rows = Vec::new(); + let mut row = Vec::new(); + let mut field = String::new(); + let mut chars = text.chars().peekable(); + // Text read again as unquoted, ahead of the rest of the input: a field that opened with a + // quote but turned out not to be quoted. + let mut replay: std::collections::VecDeque = std::collections::VecDeque::new(); + // Text is replayed at most as much as the input is long; past that, quotes are text, so + // hostile input full of fields that only look quoted reads in linear time. + let mut replay_budget = text.len(); + let mut quoted = false; + let mut at_start = true; + // A quoted field's text as it stands in the input, for a field that turns out not to be one. + let mut raw = String::new(); + loop { + let c = match replay.pop_front().or_else(|| chars.next()) { + Some(c) => c, + // A quote that never closes: the field is its text as written. + None if quoted => { + quoted = false; + field.clear(); + field.push('"'); + replay_budget = replay_budget.saturating_sub(raw.len()); + replay.extend(raw.chars().skip(1)); + raw.clear(); + continue; + } + None => break, + }; + if quoted { + raw.push(c); + if c == '"' { + let next = replay.front().copied().or_else(|| chars.peek().copied()); + if next == Some('"') { + field.push('"'); + raw.push('"'); + if replay.pop_front().is_none() { + chars.next(); + } + } else { + quoted = false; + // A field is quoted only when its closing quote ends it, as Excel reads it: + // `"hi" there` is that text, quotes included, and a tab or line break inside + // it still ends the cell, as if the leading quote weren't there. + if !matches!(next, None | Some('\t' | '\n' | '\r')) { + field.clear(); + field.push('"'); + replay_budget = replay_budget.saturating_sub(raw.len()); + let rest: Vec = std::mem::take(&mut raw).chars().skip(1).collect(); + for ch in rest.into_iter().rev() { + replay.push_front(ch); + } + } + } + } else { + field.push(c); + } + continue; + } + match c { + '"' if at_start && replay_budget > 0 => { + quoted = true; + at_start = false; + raw = String::from('"'); + } + '\t' => { + row.push(std::mem::take(&mut field)); + at_start = true; + } + '\r' => {} + '\n' => { + row.push(std::mem::take(&mut field)); + rows.push(std::mem::take(&mut row)); + at_start = true; + } + _ => { + field.push(c); + at_start = false; + } + } + } + if !field.is_empty() || !row.is_empty() { + row.push(field); + rows.push(row); + } + rows +} diff --git a/crates/engine/src/cmd/edit/fill.rs b/crates/engine/src/cmd/edit/fill.rs new file mode 100644 index 0000000000..8cd1e3d884 --- /dev/null +++ b/crates/engine/src/cmd/edit/fill.rs @@ -0,0 +1,96 @@ +use super::{CellRef, EngineError, Json, RangeRef, Result, Session, bad, edit, f64_param, json, str_param, target_range, target_sheet}; + +// ---------------------------------------------------------------- fill + +pub(super) fn fill_dir(s: &mut Session, p: &Json, dr: i64, dc: i64) -> Result { + let sheet = target_sheet(s, p)?; + let mut r = target_range(s, p)?; + // Whole rows or columns fill only where the sheet has content (nothing on an empty sheet). + if r.is_full_cols() || r.is_full_rows() { + match s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()).and_then(|u| r.intersection(&u)) { + Some(u) => r = u, + None => return Ok(Json::Null), + } + } + if r.count() > crate::fill::MAX_FILL_CELLS { + return Err(bad("edit.fill", "range too large")); + } + // With one row selected, Fill Down copies from the row above (Excel behaviour). + if dr == 1 && r.height() == 1 { + r.start.row = r.start.row.saturating_sub(1); + } + if dc == 1 && r.width() == 1 { + r.start.col = r.start.col.saturating_sub(1); + } + let src = if dr == 1 { + RangeRef::new(r.start, CellRef::new(r.start.row, r.end.col)) + } else if dr == -1 { + RangeRef::new(CellRef::new(r.end.row, r.start.col), r.end) + } else if dc == 1 { + RangeRef::new(r.start, CellRef::new(r.end.row, r.start.col)) + } else { + RangeRef::new(CellRef::new(r.start.row, r.end.col), r.end) + }; + edit(s, |cx| { + crate::fill::fill(cx, sheet, src, r, crate::fill::FillMode::Copy)?; + Ok(Json::Null) + }) +} + +pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let src = str_param(p, "source").and_then(RangeRef::parse).map_or_else(|| target_range(s, p), Ok)?; + let Some(target) = str_param(p, "target").and_then(RangeRef::parse) else { return Err(bad("edit.autoFill", "missing `target`")) }; + let mode = match str_param(p, "mode").unwrap_or("series") { + "copy" => crate::fill::FillMode::Copy, + "alternate" => crate::fill::FillMode::Alternate, + "formats" => crate::fill::FillMode::Formats, + "values" => crate::fill::FillMode::ValuesOnly, + "extend" => crate::fill::FillMode::Extend, + "days" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Day), + "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), + _ => crate::fill::FillMode::Series, + }; + if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS { + return Err(bad("edit.autoFill", "range too large")); + } + // Excel refuses a target that doesn't hold the source in a corner. Such targets used to fill + // every source lane across the whole target extent: billions of cells for whole rows (`2:3`) + // into whole columns (`A:A`). + if !crate::fill::holds_source_in_corner(src, target) { + return Err(bad("edit.autoFill", "the target must contain the source in one of its corners")); + } + edit(s, |cx| { + crate::fill::fill(cx, sheet, src, target, mode)?; + *cx.sel = crate::Selection { active: src.start, anchor: src.start, ranges: vec![target.union(&src)] }; + Ok(Json::Null) + }) +} + +pub(super) fn fill_series(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let r = target_range(s, p)?; + let rows = str_param(p, "direction").map(|d| d == "rows").unwrap_or(r.width() > r.height()); + let kind = str_param(p, "type").unwrap_or("linear").to_string(); + let step = f64_param(p, "step").unwrap_or(1.0); + let stop = f64_param(p, "stop"); + let unit = str_param(p, "dateUnit").unwrap_or("day").to_string(); + edit(s, |cx| { + crate::fill::series(cx, sheet, crate::fill::SeriesOptions { range: r, rows, kind: &kind, step, stop, unit: &unit })?; + Ok(Json::Null) + }) +} + +pub(super) fn flash_fill(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let r = target_range(s, p)?; + let n = edit(s, |cx| crate::fill::flash_fill(cx, sheet, r.start))?; + if n == 0 { + return Err(EngineError::Other( + "We looked at all the data next to your selection and didn't see a pattern for filling in values for you.".into(), + )); + } + Ok(json!({"filled": n})) +} diff --git a/crates/engine/src/cmd/edit/find.rs b/crates/engine/src/cmd/edit/find.rs new file mode 100644 index 0000000000..ddb9ecaf79 --- /dev/null +++ b/crates/engine/src/cmd/edit/find.rs @@ -0,0 +1,221 @@ +use super::cell::input_to_cell; +use super::{Cell, CellRef, EngineError, Json, Result, Session, Value, bad, bool_param, edit, json, str_param}; + +// ---------------------------------------------------------------- find & replace + +fn matches(hay: &str, what: &str, case: bool, whole: bool) -> bool { + let (h, w) = if case { (hay.to_string(), what.to_string()) } else { (hay.to_lowercase(), what.to_lowercase()) }; + let has_wild = w.contains(['*', '?']); + if has_wild { + let pat = if whole { w } else { format!("*{w}*") }; + return wildcard(&h, &pat); + } + if whole { h == w } else { h.contains(&w) } +} + +/// `*`/`?` wildcard match with `~` escapes. +pub(crate) fn wildcard(text: &str, pat: &str) -> bool { + let t: Vec = text.chars().collect(); + let mut p: Vec<(char, bool)> = Vec::new(); + let mut it = pat.chars(); + while let Some(c) = it.next() { + if c == '~' { + if let Some(n) = it.next() { + p.push((n, true)); + } + } else { + p.push((c, false)); + } + } + let (mut ti, mut pi) = (0usize, 0usize); + let (mut star, mut mark) = (None, 0usize); + while ti < t.len() { + if pi < p.len() && (p[pi] == ('?', false) || (p[pi].0 == t[ti] && p[pi] != ('*', false))) { + ti += 1; + pi += 1; + } else if pi < p.len() && p[pi] == ('*', false) { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(sp) = star { + pi = sp + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == ('*', false) { + pi += 1; + } + pi == p.len() +} + +pub(super) fn find(s: &mut Session, p: &Json) -> Result { + let what = str_param(p, "what").unwrap_or("").to_string(); + if what.is_empty() { + return Err(bad("edit.find", "missing `what`")); + } + let case = bool_param(p, "matchCase").unwrap_or(false); + let whole = bool_param(p, "wholeCell").unwrap_or(false); + let values = str_param(p, "lookIn") == Some("values"); + let by_cols = bool_param(p, "byColumns").unwrap_or(false); + let all = bool_param(p, "all").unwrap_or(false); + let workbook = str_param(p, "within") == Some("workbook"); + // `selection`: only the selected cells of the active sheet, as Excel searches a selected range. + let in_selection = str_param(p, "within") == Some("selection"); + s.last_find = Some(p.clone()); + let d = s.doc()?; + let sheets: Vec = if workbook { (0..d.wb.sheets.len()).collect() } else { vec![d.wb.active_sheet()] }; + let mut hits: Vec<(usize, CellRef, String)> = Vec::new(); + for si in sheets { + let Some(sh) = d.wb.sheet(si) else { continue }; + let mut cells: Vec<(CellRef, String)> = sh + .cells + .iter() + .filter(|(c, _)| !in_selection || d.selection.contains(*c)) + .filter_map(|(c, cell)| { + let text = if values || cell.formula.is_none() || crate::display::formula_hidden(&d.wb, sh, c) { + crate::display::cell_text(&d.wb, sh, c) + } else { + cell.input_text() + }; + matches(&text, &what, case, whole).then_some((c, text)) + }) + .collect(); + if by_cols { + cells.sort_by_key(|(c, _)| (c.col, c.row)); + } + hits.extend(cells.into_iter().map(|(c, t)| (si, c, t))); + } + if hits.is_empty() { + return Err(EngineError::Other(format!("We couldn't find what you were looking for: {what}"))); + } + if all { + let list: Vec = + hits.iter().map(|(si, c, t)| json!({"sheet": d.wb.sheet(*si).map(|s| s.name.clone()), "cell": c.a1(), "value": t})).collect(); + return Ok(json!({"count": list.len(), "results": list})); + } + // Next hit after the active cell. + let cur = (d.wb.active_sheet(), d.selection.active); + let key = |si: usize, c: CellRef| if by_cols { (si, c.col, c.row) } else { (si, c.row, c.col) }; + let next = hits.iter().find(|(si, c, _)| key(*si, *c) > key(cur.0, cur.1)).or_else(|| hits.first()).cloned(); + let Some((si, c, t)) = next else { return Err(EngineError::Other("not found".into())) }; + let dd = s.doc_mut()?; + dd.wb_switch_sheet(si); + if in_selection { + // The range stays selected and the active cell moves through it, as in Excel. + dd.selection.active = c; + } else { + dd.selection = crate::Selection::at(c); + } + Ok(json!({"cell": c.a1(), "sheet": si, "value": t, "count": hits.len()})) +} + +pub(super) fn replace(s: &mut Session, p: &Json) -> Result { + let what = str_param(p, "what").unwrap_or("").to_string(); + let with = str_param(p, "with").unwrap_or("").to_string(); + if what.is_empty() { + return Err(bad("edit.replace", "missing `what`")); + } + let case = bool_param(p, "matchCase").unwrap_or(false); + let whole = bool_param(p, "wholeCell").unwrap_or(false); + let all = bool_param(p, "all").unwrap_or(true); + let workbook = str_param(p, "within") == Some("workbook"); + let selection = (str_param(p, "within") == Some("selection")).then(|| s.doc().map(|d| d.selection.clone())).transpose()?; + let active = s.doc()?.selection.active; + let mut skipped = 0usize; + let n = edit(s, |cx| { + let sheets: Vec = if workbook { (0..cx.wb.sheets.len()).collect() } else { vec![cx.wb.active_sheet()] }; + let mut n = 0; + for si in sheets { + let cells: Vec<(CellRef, String)> = + cx.wb.sheet(si).map(|sh| sh.cells.iter().map(|(c, _)| (c, sh.input_text(c))).collect()).unwrap_or_default(); + for (c, text) in cells { + if (!all && c != active) || selection.as_ref().is_some_and(|sel| !sel.contains(c)) { + continue; + } + if !matches(&text, &what, case, whole) { + continue; + } + let new = if whole { + with.clone() + } else if case { + text.replace(&what, &with) + } else { + replace_ci(&text, &what, &with) + }; + // A Python cell's text is its code: the replacement edits the code and the cell + // stays a Python cell. Code that would no longer fit in a PY formula is left as it was. + let old_py = cx.wb.sheet(si).and_then(|sh| sh.cell(c)).and_then(|x| x.py.clone()); + if let Some(old) = old_py { + let py = gridcraft_model::PyCode { object: old.object, ..gridcraft_model::PyCode::new(&new) }; + if py.code == old.code { + continue; + } + if !py.fits() { + skipped += 1; + continue; + } + // Its old spill is left to the recalculation, which removes it and + // recalculates what read it. + let sh = cx.sheet_mut(si)?; + let style = sh.style_id(c); + sh.set_cell( + c, + Cell { value: Value::Error(gridcraft_core::CellError::Blocked), formula: None, style, py: Some(std::sync::Arc::new(py)) }, + ); + cx.touch(si, c); + n += 1; + continue; + } + let cell = input_to_cell(&new, si, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(new.as_str())))); + let sh = cx.sheet_mut(si)?; + match cell { + Some(cell) => sh.set_cell(c, cell), + None => { + sh.remove_cell(c); + } + } + cx.touch(si, c); + n += 1; + } + } + Ok(n) + })?; + if skipped > 0 { + return Ok(json!({"replaced": n, "skipped": skipped})); + } + Ok(json!({"replaced": n})) +} + +/// Whether case-folding `s` maps every char to exactly one char of the same UTF-8 length, so +/// byte positions in the folded text still line up with the original's character boundaries. +fn folds_in_place(s: &str) -> bool { + s.chars().all(|c| { + let mut folded = c.to_lowercase(); + let first = folded.next(); + folded.next().is_none() && first.is_some_and(|l| l.len_utf8() == c.len_utf8()) + }) +} + +pub(super) fn replace_ci(text: &str, what: &str, with: &str) -> String { + let lower = text.to_lowercase(); + let w = what.to_lowercase(); + // Slicing `text` at positions found in `lower` is only sound when folding kept every byte + // boundary: a length check alone misses foldings that keep the total length while shifting + // boundaries (U+212A KELVIN SIGN shrinks 3→1 bytes, U+0130 grows 2→3), where the tail used + // to be dropped. Those fall back to the case-sensitive replace, as length changes already do. + if lower.len() != text.len() || w.is_empty() || !folds_in_place(text) || !folds_in_place(what) { + return text.replace(what, with); + } + let mut out = String::new(); + let mut i = 0; + while let Some(pos) = lower.get(i..).and_then(|s| s.find(&w)) { + out.push_str(text.get(i..i + pos).unwrap_or("")); + out.push_str(with); + i += pos + w.len(); + } + out.push_str(text.get(i..).unwrap_or("")); + out +} diff --git a/crates/engine/src/cmd/edit/go_to.rs b/crates/engine/src/cmd/edit/go_to.rs new file mode 100644 index 0000000000..0cd7a3de9f --- /dev/null +++ b/crates/engine/src/cmd/edit/go_to.rs @@ -0,0 +1,199 @@ +use super::selection::{select_region, selection_set}; +use super::{CellRef, EngineError, Json, RangeRef, Result, Session, bad, bool_param, coalesce, json, split_sheet, str_param}; + +/// How many references the Go To dialog keeps for going back to. +pub(super) const GO_TO_RECENT: usize = 10; + +/// The most areas one Go To selects. +pub(super) const GO_TO_MAX_AREAS: usize = 2000; + +/// How deep a name that refers to other names is followed. +const GO_TO_NAME_DEPTH: usize = 8; + +pub(in super::super) fn go_to(s: &mut Session, p: &Json) -> Result { + if bool_param(p, "list") == Some(true) { + let d = s.doc()?; + return Ok(json!({"names": go_to_names(&d.wb, d.wb.active_sheet()), "recent": d.go_to_recent})); + } + let Some(reference) = str_param(p, "reference").or_else(|| str_param(p, "range")) else { return Err(bad("edit.goTo", "missing `reference`")) }; + let d = s.doc()?; + let mut target: Option = None; + let mut areas: Vec = Vec::new(); + let mut named = false; + for part in reference_parts(reference) { + let Some((sheet, found, by_name)) = go_to_target(&d.wb, d.wb.active_sheet(), part, 0) else { + return Err(EngineError::Other("Reference isn't valid.".into())); + }; + // One selection holds the areas of one sheet. + if target.is_some_and(|t| t != sheet) { + return Err(EngineError::Other("Reference isn't valid.".into())); + } + target = Some(sheet); + named |= by_name; + areas.extend(found); + if areas.len() > GO_TO_MAX_AREAS { + return Err(EngineError::Other(format!("Go To selects at most {GO_TO_MAX_AREAS} areas."))); + } + } + let Some(sheet) = target else { return Err(EngineError::Other("Reference isn't valid.".into())) }; + let range = areas.iter().map(RangeRef::a1).collect::>().join(","); + let out = selection_set(s, &json!({"sheet": sheet, "range": range}))?; + if bool_param(p, "record") == Some(true) && !named { + let d = s.doc_mut()?; + let prefix = gridcraft_core::quote_sheet(&d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default()); + let entry = areas.iter().map(|r| format!("{prefix}!{}", r.a1())).collect::>().join(","); + d.go_to_recent.retain(|r| !r.eq_ignore_ascii_case(&entry)); + d.go_to_recent.insert(0, entry); + d.go_to_recent.truncate(GO_TO_RECENT); + } + Ok(out) +} + +/// The parts of a Go To reference, split at the commas outside quoted sheet names and +/// parentheses: `Price, Type` or `B14:C22,F19:G30`. The parts are read one at a time, so a caller +/// that stops at an invalid part or at `GO_TO_MAX_AREAS` does not split the rest of the text. +pub(super) fn reference_parts(text: &str) -> impl Iterator { + let (mut depth, mut quoted, mut start, mut done) = (0usize, false, 0, false); + let mut chars = text.char_indices(); + std::iter::from_fn(move || { + if done { + return None; + } + for (i, c) in chars.by_ref() { + match c { + '\'' => quoted = !quoted, + '(' if !quoted => depth += 1, + ')' if !quoted => depth = depth.saturating_sub(1), + ',' if !quoted && depth == 0 => { + let part = text.get(start..i).unwrap_or("").trim(); + start = i + 1; + return Some(part); + } + _ => {} + } + } + done = true; + Some(text.get(start..).unwrap_or("").trim()) + }) +} + +/// Where one part of a Go To reference points, seen from sheet `sheet`: the sheet, its areas, +/// and whether a defined name or a table gave them. `Sheet2!Name` is the name scoped to Sheet2. +/// A name counts when what it refers to is a reference; a constant or a formula is not one. +fn go_to_target(wb: &gridcraft_model::Workbook, sheet: usize, part: &str, depth: usize) -> Option<(usize, Vec, bool)> { + if part.is_empty() || depth > GO_TO_NAME_DEPTH { + return None; + } + let (prefix, body) = split_sheet(part); + let on = match &prefix { + Some(n) => wb.sheet_index(n)?, + None => sheet, + }; + if let Some(r) = RangeRef::parse(&body.replace('$', "")) { + return Some((on, vec![r], false)); + } + let name = match prefix { + Some(_) => wb.names.iter().find(|n| n.scope == Some(on) && gridcraft_formula::same_name(&n.name, body)), + None => wb.name(body, sheet), + }; + if let Some(n) = name { + return name_areas(wb, n, sheet, depth).map(|(t, areas)| (t, areas, true)); + } + if prefix.is_none() + && let Some((si, ti)) = wb.table(body) + { + // As in Excel, a table's name stands for its data, without the header and totals rows. + let t = wb.sheet(si)?.tables.get(ti)?; + return Some((si, vec![t.data_range().unwrap_or(t.range)], true)); + } + None +} + +/// The sheet and areas defined name `n` refers to, seen from sheet `sheet`, when that is a +/// reference. +fn name_areas(wb: &gridcraft_model::Workbook, n: &gridcraft_model::DefinedName, sheet: usize, depth: usize) -> Option<(usize, Vec)> { + let from = n.scope.unwrap_or(sheet); + let formula = n.formula.trim().trim_start_matches('='); + let mut target: Option = None; + let mut areas = Vec::new(); + for p in reference_parts(formula) { + let (s, found, _) = go_to_target(wb, from, p, depth + 1)?; + if target.is_some_and(|t| t != s) { + return None; + } + target = Some(s); + areas.extend(found); + if areas.len() > GO_TO_MAX_AREAS { + return None; + } + } + target.map(|t| (t, areas)) +} + +/// The names the Go To dialog lists, seen from sheet `sheet`: the named ranges of the workbook and +/// of every sheet, in alphabetical order. A name scoped to another sheet is written `Sheet2!Name`, +/// and the active sheet's own name hides the workbook name it shares. Hidden names and names that +/// do not refer to a range are left out. +pub fn go_to_names(wb: &gridcraft_model::Workbook, sheet: usize) -> Vec { + let own: std::collections::HashSet = + wb.names.iter().filter(|n| n.scope == Some(sheet)).map(|n| gridcraft_formula::fold_name(&n.name)).collect(); + let mut out: Vec = wb + .names + .iter() + .filter(|n| !n.hidden && name_areas(wb, n, sheet, 0).is_some()) + .filter_map(|n| match n.scope { + None if own.contains(&gridcraft_formula::fold_name(&n.name)) => None, + None => Some(n.name.clone()), + Some(s) if s == sheet => Some(n.name.clone()), + Some(s) => Some(format!("{}!{}", gridcraft_core::quote_sheet(&wb.sheet(s)?.name), n.name)), + }) + .collect(); + out.sort_by_cached_key(|n| gridcraft_formula::fold_name(n)); + out.dedup_by(|a, b| gridcraft_formula::same_name(a, b)); + out +} + +pub(super) fn go_to_special(s: &mut Session, p: &Json) -> Result { + let kind = str_param(p, "kind").unwrap_or("blanks"); + let d = s.doc()?; + let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; + let scope = if d.selection.is_single_cell() { sheet.used_range().unwrap_or(RangeRef::cell(d.selection.active)) } else { d.selection.bounds() }; + if kind == "lastCell" { + let c = sheet.used_range().map(|r| r.end).unwrap_or_default(); + return selection_set(s, &json!({"cell": c.a1()})); + } + if kind == "currentRegion" { + return select_region(s, &json!({})); + } + let mut hits: Vec = Vec::new(); + if scope.count() > 4_000_000 { + return Err(bad("edit.goToSpecial", "range too large")); + } + for c in scope.iter() { + let cell = sheet.cell(c); + let v = sheet.value(c); + let ok = match kind { + "blanks" => v.is_empty(), + "constants" => cell.is_some_and(|x| x.formula.is_none() && x.py.is_none() && !x.value.is_empty()), + "formulas" => cell.is_some_and(|x| x.formula.is_some() || x.py.is_some()), + "comments" | "notes" => sheet.comments.contains_key(&c), + "errors" => v.is_error(), + "numbers" => v.is_number(), + "text" => v.is_text(), + "visible" => !sheet.is_row_hidden(c.row) && !sheet.is_col_hidden(c.col), + "conditionalFormats" => sheet.cond_formats.iter().any(|cf| cf.ranges.iter().any(|r| r.contains(c))), + "dataValidation" => sheet.validations.iter().any(|dv| dv.ranges.iter().any(|r| r.contains(c))), + _ => return Err(bad("edit.goToSpecial", format!("unknown kind `{kind}`"))), + }; + if ok { + hits.push(c); + } + } + if hits.is_empty() { + return Err(EngineError::Other("No cells were found.".into())); + } + let ranges = coalesce(&hits); + let d = s.doc_mut()?; + d.selection = crate::Selection { active: hits[0], anchor: hits[0], ranges }; + Ok(json!({"selection": d.selection.a1(), "count": hits.len()})) +} diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs new file mode 100644 index 0000000000..a19bceb67e --- /dev/null +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -0,0 +1,499 @@ +use super::clipboard::What; +use super::{ + Cell, CellRef, EngineError, Formula, Json, RangeRef, Result, Session, StyleId, Value, bad, bool_param, cell_param_on, edit, json, str_param, + target_sheet, +}; + +fn tiled_cells(rows: u32, cols: u32, tiles_r: u32, tiles_c: u32) -> impl Iterator + Clone { + (0..tiles_r).flat_map(move |tr| (0..tiles_c).flat_map(move |tc| (0..rows).flat_map(move |r| (0..cols).map(move |c| (tr, tc, r, c))))) +} + +fn apply_operation(op: &str, old: &Cell, new: &mut Cell) { + let operand = new.value.clone(); + if let (Ok(x), Ok(y)) = (old.value.to_number(), operand.to_number()) + && (old.value.is_number() || old.value.is_empty() || old.value.is_text()) + && (operand.is_number() || operand.is_empty()) + { + new.value = match op { + "add" => Value::number(x + y), + "subtract" => Value::number(x - y), + "multiply" => Value::number(x * y), + "divide" if y == 0.0 => Value::Error(gridcraft_core::CellError::Div0), + "divide" => Value::number(x / y), + _ => operand.clone(), + }; + } else if (old.value.is_text() || old.value.is_error()) && (operand.is_number() || operand.is_empty()) { + new.value = old.value.clone(); + } + if let Some(formula) = &old.formula + && let Ok(y) = operand.to_number() + && (operand.is_number() || operand.is_empty()) + && let Some(symbol) = operation_symbol(op) + { + let text = format!("=({}){symbol}{}", formula.text, gridcraft_core::number_to_text(y)); + new.formula = Some(std::sync::Arc::new(Formula::new(&text))); + new.value = Value::Empty; + } +} + +fn operation_symbol(op: &str) -> Option { + match op { + "add" => Some('+'), + "subtract" => Some('-'), + "multiply" => Some('*'), + "divide" => Some('/'), + _ => None, + } +} + +fn copy_merges( + cx: &mut crate::cmd::Ctx, + dest_sheet: usize, + src_sheet: &gridcraft_model::Sheet, + src: RangeRef, + at: CellRef, + what: What, + transpose: bool, +) -> Result<()> { + if !matches!(what, What::All | What::Formats) || transpose { + return Ok(()); + } + let merges: Vec = src_sheet.merges.iter().filter(|merge| src.contains_range(merge)).copied().collect(); + for merge in merges { + let row_offset = at.row as i64 - src.start.row as i64; + let col_offset = at.col as i64 - src.start.col as i64; + if let (Some(start), Some(end)) = (merge.start.offset(row_offset, col_offset), merge.end.offset(row_offset, col_offset)) { + let moved = RangeRef::new(start, end); + let sheet = cx.sheet_mut(dest_sheet)?; + sheet.merges.retain(|existing| !existing.intersects(&moved)); + sheet.merges.push(moved); + } + } + Ok(()) +} + +pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { + let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) }; + let what = match str_param(p, "what").unwrap_or("all") { + "all" => What::All, + "formulas" => What::Formulas, + "values" => What::Values, + "formats" => What::Formats, + "comments" | "notes" => What::Comments, + "validation" => What::Validation, + "allExceptBorders" => What::AllExceptBorders, + "columnWidths" => What::ColumnWidths, + "formulasAndNumberFormats" => What::FormulasAndNumberFormats, + "valuesAndNumberFormats" => What::ValuesAndNumberFormats, + other => return Err(bad("edit.pasteSpecial", format!("unknown `what`: {other}"))), + }; + let op = str_param(p, "operation").unwrap_or("none").to_string(); + let skip_blanks = bool_param(p, "skipBlanks").unwrap_or(false); + let transpose = bool_param(p, "transpose").unwrap_or(false); + let link = bool_param(p, "link").unwrap_or(false); + if link && !clip.areas.is_empty() { + return Err(EngineError::Other("This action won't work on multiple selections.".into())); + } + let dest_sheet = target_sheet(s, p)?; + let sel = s.doc()?.selection.current(); + let at = cell_param_on(s, p, "at", dest_sheet)?.unwrap_or(sel.start); + let src = clip.range; + let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) }; + // Tile the copy over a larger destination that is a multiple of its size. + let tile = sel.height() % h == 0 + && sel.width() % w == 0 + && !sel.is_single() + && cell_param_on(s, p, "at", dest_sheet)?.is_none() + && !sel.is_full_cols() + && !sel.is_full_rows() + && sel.count() <= 4_000_000; + let (tiles_r, tiles_c) = if tile { (sel.height() / h, sel.width() / w) } else { (1, 1) }; + let same_doc = s.doc()?.uid == clip.doc_uid; + 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())) }; + let src_sheet_name = src_sheet.name.clone(); + if cut_move && at.offset((tiles_r * h).saturating_sub(1) as i64, (tiles_c * w).saturating_sub(1) as i64).is_none() { + // Check the whole footprint before the source is emptied, so a move that overflows the grid loses nothing. + return Err(EngineError::Other("The cut area doesn't fit at this position; nothing was moved.".into())); + } + edit(s, |cx| { + // Styles from another workbook must be re-interned. + let mut style_map = std::collections::HashMap::new(); + let mut map_style = |id: StyleId, wb: &mut gridcraft_model::Workbook| -> StyleId { + if same_doc { + return id; + } + *style_map.entry(id).or_insert_with(|| wb.styles.intern(src_wb.styles.get(id).clone())) + }; + let mut moved_formulas = Vec::new(); + let mut moved_pictures = std::collections::BTreeMap::new(); + if cut_move { + // Remove the source first (contents and formats), and fix references to it. + let source = cx.sheet_mut(clip.sheet)?; + moved_pictures = source.cell_pictures.iter().filter(|(c, _)| src.contains(**c)).map(|(c, p)| (*c, p.clone())).collect(); + let taken = source.take_cells(src); + // Notes, hyperlinks and merged areas sit beside the cells, and a cut takes them + // with the block: the destination is written from the clipboard snapshot taken + // before the cut, so removing them here loses nothing and leaves the old place + // clean instead of leaving one merged block and one note behind. + source.comments.retain(|c, _| !src.contains(*c)); + source.hyperlinks.retain(|c, _| !src.contains(*c)); + source.merges.retain(|m| !src.contains_range(m)); + for (c, _) in &taken { + cx.touch(clip.sheet, *c); + } + moved_formulas = taken; + } + let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default(); + for (tr, tc, r, c) in tiled_cells(src.height(), src.width(), tiles_r, tiles_c) { + let sc = CellRef::new(src.start.row + r, src.start.col + c); + let (dr, dc) = if transpose { (c, r) } else { (r, c) }; + let Some(dest) = at.offset((tr * h + dr) as i64, (tc * w + dc) as i64) else { continue }; + let src_cell = if cut_move { moved_formulas.iter().find(|(k, _)| *k == sc).map(|(_, v)| v.clone()) } else { src_sheet.cell(sc).cloned() }; + let src_val = src_sheet.value(sc); + let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned(); + if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none() && x.py.is_none()) { + continue; + } + let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default(); + let old_picture = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell_pictures.get(&dest)).cloned(); + let mut new_picture = old_picture.clone(); + let mut new = old.clone(); + let shift = |cell: &Cell| -> Option> { + let f = cell.formula.as_ref()?; + let e = f.expr()?; + if cut_move { + // A moved formula still reads cells on its original sheet. Qualify + // those references before the workbook-wide move adjustment below. + let e = if dest_sheet != clip.sheet { + e.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }) + } else { + e + }; + let mut moved = Formula::from_expr(e); + // The array range moves with its formula. + let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); + moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?))); + moved.dynamic = f.dynamic; + return Some(std::sync::Arc::new(moved)); + } + 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) })) + }; + // A Python cell's code travels with it. Cut to another sheet, it keeps reading the + // cells its `xl()` references named on its original sheet, as a moved formula does: + // they are qualified with that sheet before the workbook-wide move adjustment below. + let moved_py = |cell: &Cell| -> Result>> { + let Some(py) = cell.py.clone() else { return Ok(None) }; + if !cut_move || dest_sheet == clip.sheet { + return Ok(Some(py)); + } + let qualified = gridcraft_model::python::rewrite_xl(&py.code, |reference| { + let e = gridcraft_formula::parse(reference).ok()?.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }); + Some(gridcraft_formula::print(&e)) + }); + Ok(Some(match qualified { + Some(code) => { + let moved = gridcraft_model::PyCode { code, ..(*py).clone() }; + check_python_fits(&moved, &dest_name, dest)?; + std::sync::Arc::new(moved) + } + None => py, + })) + }; + if link { + let sheet_prefix = if dest_sheet == clip.sheet && same_doc { + String::new() + } else { + format!("{}!", gridcraft_formula::quote_sheet(&src_sheet_name)) + }; + new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1())))); + new.value = Value::Empty; + new.py = None; + new_picture = None; + } else { + let sc_cell = src_cell.clone().unwrap_or_default(); + match what { + What::All | What::AllExceptBorders => { + new_picture = src_picture.clone(); + new.formula = shift(&sc_cell); + new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; + let st = map_style(sc_cell.style, &mut cx.wb); + new.style = if what == What::AllExceptBorders { + let borders = cx.wb.styles.get(old.style).borders; + cx.wb.styles.derive(st, |s| s.borders = borders) + } else { + st + }; + } + What::Formulas | What::FormulasAndNumberFormats => { + new_picture = src_picture.clone(); + new.formula = shift(&sc_cell); + new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; + if what == What::FormulasAndNumberFormats { + let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); + new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); + } + } + What::Values | What::ValuesAndNumberFormats => { + new_picture = src_picture.clone(); + new.formula = None; + new.py = None; + new.value = src_val.clone(); + if what == What::ValuesAndNumberFormats { + let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); + new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); + } + } + What::Formats => new.style = map_style(sc_cell.style, &mut cx.wb), + What::Comments | What::Validation | What::ColumnWidths => {} + } + // Operations combine numbers with what is already there. + if op != "none" + && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) + && new.formula.is_none() + && new.py.is_none() + { + if old_picture.is_some() || new_picture.is_some() { + new_picture = None; + new.value = Value::Error(gridcraft_core::CellError::Value); + } + // Numbers stored as text participate; other text and errors stay as they are. + apply_operation(&op, &old, &mut new); + } + } + // The copied cell's validation rule replaces whatever rule the destination had. + if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) { + let rule = src_sheet.validations.iter().find(|dv| dv.ranges.iter().any(|r| r.contains(sc))).cloned(); + let sh = cx.sheet_mut(dest_sheet)?; + crate::cmd::data::remove_validation_cells(&mut sh.validations, &[RangeRef::new(dest, dest)]); + if let Some(mut dv) = rule { + // Relative references move with the rule, as pasted formulas do. + let first = RangeRef::top_left(&dv.ranges).unwrap_or(sc); + dv.f1 = crate::cmd::data::move_rule_formula(&dv.f1, first, dest); + dv.f2 = dv.f2.map(|f| crate::cmd::data::move_rule_formula(&f, first, dest)); + dv.ranges = vec![RangeRef::new(dest, dest)]; + sh.validations.push(dv); + } + } + match what { + What::Comments => { + if let Some(cm) = src_sheet.comments.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); + } + } + What::ColumnWidths => { + if let Some(info) = src_sheet.cols.get(&sc.col).copied() { + cx.sheet_mut(dest_sheet)?.cols.insert(dest.col, info); + } + } + What::All => { + if let Some(cm) = src_sheet.comments.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm); + } + if let Some(h) = src_sheet.hyperlinks.get(&sc).cloned() { + cx.sheet_mut(dest_sheet)?.hyperlinks.insert(dest, h); + } + cx.sheet_mut(dest_sheet)?.set_cell(dest, new); + } + _ => cx.sheet_mut(dest_sheet)?.set_cell(dest, new), + } + if let Some(picture) = new_picture { + cx.sheet_mut(dest_sheet)?.cell_pictures.insert(dest, picture); + } + cx.touch(dest_sheet, dest); + } + // Merged areas inside the copied block travel with it. + copy_merges(cx, dest_sheet, src_sheet, src, at, what, transpose)?; + if cut_move { + // References elsewhere to the moved block now point to its new place. + let dest_name = cx.wb.sheet(dest_sheet).map(|s| s.name.clone()).unwrap_or_default(); + let e = if dest_sheet == clip.sheet { + gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col } + } else { + gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name, to_row: at.row, to_col: at.col } + }; + rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e)?; + cx.structural = true; + } + let end = at.offset_clamped((tiles_r * h) as i64 - 1, (tiles_c * w) as i64 - 1); + *cx.sel = crate::Selection { active: at, anchor: at, ranges: vec![RangeRef::new(at, end)] }; + Ok(()) + })?; + // Formulas and validation from an untrusted file leave the destination untrusted; plain values, + // formats (cell styles and merged areas, no conditional formats), column widths and notes + // carry nothing active. A linked paste writes a formula into every cell whatever `what` says, + // except for column widths and notes, which write no cells at all. + let passive = + matches!(what, What::ColumnWidths | What::Comments) || (!link && matches!(what, What::Formats | What::Values | What::ValuesAndNumberFormats)); + if !same_doc && !passive { + let d = s.doc_mut()?; + d.trust = d.trust.receive(clip.trust); + } + if cut_move { + s.clipboard = None; + } + Ok(json!({"pasted": s.doc()?.selection.a1()})) +} + +/// Applies a reference adjustment to every cell formula and defined name in the workbook. +pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { + use gridcraft_formula::adjust::Edit; + // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too + // (a cut moves its arrays itself). + let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); + for si in 0..wb.sheets.len() { + let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); + let keys: Vec<(CellRef, std::sync::Arc)> = + wb.sheets.get(si).map(|s| s.cells.iter().filter_map(|(c, cell)| cell.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default(); + if keys.is_empty() { + continue; + } + let on_target = moves_arrays && host.eq_ignore_ascii_case(target); + let Some(sheet) = wb.sheet_mut(si) else { continue }; + for (c, f) in keys { + let Some(expr) = f.expr() else { continue }; + let new = gridcraft_formula::adjust::adjust(expr, &host, target, e); + let text = gridcraft_formula::print(&new); + let array = match f.array { + Some(a) if on_target => crate::cmd::sheet::map_range(a, e), + a => a, + }; + if (text != f.text || array != f.array) + && let Some(cell) = sheet.cells.get_mut(c) + { + let mut nf = Formula::from_expr(new); + nf.array = array; + nf.dynamic = f.dynamic; + cell.formula = Some(std::sync::Arc::new(nf)); + } + } + } + for n in wb.names.iter_mut() { + if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) { + // Names are workbook-level: unqualified refs don't occur; qualified ones adjust. + let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e); + n.formula = gridcraft_formula::print(&new); + } + } + rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)); + rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)) +} + +/// Runs `f` over every reference a floating object holds (a chart's series values, categories, +/// name and bubble sizes, and the source block it was made from). Every edit that moves +/// references calls it: inserting and deleting lines and cells and cut-moves (through +/// [`rewrite_all_formulas`]), and renaming and deleting sheets. `f` maps a reference held by an +/// object on the sheet named `host` to its new form; text that does not parse is kept. A source +/// block that no longer exists is dropped. +pub(crate) fn rewrite_cell_links(wb: &mut gridcraft_model::Workbook, f: impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr) { + for si in 0..wb.sheets.len() { + let Some(host) = wb.sheets.get(si).filter(|s| !s.charts.is_empty()).map(|s| s.name.clone()) else { continue }; + let Some(sh) = wb.sheet_mut(si) else { continue }; + let fix = |text: &str| -> String { + match gridcraft_formula::parse(text) { + Ok(expr) => gridcraft_formula::print(&f(&host, expr)), + Err(_) => text.to_string(), + } + }; + for ch in sh.charts.iter_mut() { + ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!")); + for se in ch.series.iter_mut() { + se.values = fix(&se.values); + se.categories = se.categories.as_deref().map(fix); + se.name = se.name.as_deref().map(fix); + se.bubble_sizes = se.bubble_sizes.as_deref().map(fix); + } + } + } +} + +/// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on +/// sheet `host` to its new form. Every reference-moving edit (insert and delete of lines or cells, +/// cut-move, sheet rename and delete) runs it, as it adjusts formulas. A literal is only replaced +/// when the reference it names changed, and text that doesn't parse is kept. A cell's cached +/// result is kept while its references still name the same data (a rename, a move); a reference +/// the edit deleted (`#REF!`), or one that grew or shrank (rows or columns inserted or deleted +/// inside it), leaves the result stale, so the cell is new code (`#BLOCKED!`) and the +/// recalculation removes its spill. A rewrite that would +/// make a cell's code longer than one cell holds (a longer sheet name, `Z1` becoming `AA1`) refuses +/// the whole edit, which then changes nothing: see [`check_python_fits`]. +pub(crate) fn rewrite_python_refs( + wb: &mut gridcraft_model::Workbook, + f: &impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr, +) -> Result<()> { + for si in 0..wb.sheets.len() { + let Some(sh) = wb.sheets.get(si) else { continue }; + let host = sh.name.clone(); + let mut new_code: Vec<(CellRef, String, bool)> = Vec::new(); + for (c, cell) in sh.cells.iter() { + let Some(py) = &cell.py else { continue }; + let mut lost = false; + let changed = gridcraft_model::python::rewrite_xl(&py.code, |reference| { + let expr = gridcraft_formula::parse(reference).ok()?; + let before = gridcraft_formula::print(&expr); + let after = gridcraft_formula::print(&f(&host, expr)); + lost |= (after.contains("#REF!") && !before.contains("#REF!")) || area_shape(&before) != area_shape(&after); + (after != before).then_some(after) + }); + if let Some(code) = changed { + check_python_fits(&gridcraft_model::PyCode { code: code.clone(), object: py.object, ..Default::default() }, &host, c)?; + new_code.push((c, code, lost)); + } + } + if new_code.is_empty() { + continue; + } + let Some(sh) = wb.sheet_mut(si) else { continue }; + for (c, code, lost) in new_code { + if let Some(cell) = sh.cells.get_mut(c) + && let Some(py) = cell.py.as_mut() + { + let py = std::sync::Arc::make_mut(py); + py.code = code; + if lost { + py.output = None; + cell.value = Value::Error(gridcraft_core::CellError::Blocked); + } + } + } + } + Ok(()) +} + +/// The rows and columns a printed reference covers (`A1:B3`, `Sheet2!$A$1`, `C:E`), or `None` +/// for any other form (a name, an error). +fn area_shape(reference: &str) -> Option<(u32, u32)> { + let r = RangeRef::parse(reference.rsplit('!').next()?)?; + Some((r.height(), r.width())) +} + +/// Refuses Python code an edit has made longer than one cell holds: the limit `python.set` +/// enforces and opening a file applies (code over it is dropped to its value on open). The edit +/// is refused rather than made, so no code is lost and none keeps a reference the edit moved. +pub(crate) fn check_python_fits(py: &gridcraft_model::PyCode, sheet: &str, at: CellRef) -> Result<()> { + if py.fits() { + return Ok(()); + } + Err(EngineError::Other(format!( + "The edit would make the Python code in {}!{} longer than Excel's {}-character formula limit, so nothing was changed. Shorten the code first.", + gridcraft_formula::quote_sheet(sheet), + at.a1(), + gridcraft_model::python::MAX_FORMULA_CHARS + ))) +} diff --git a/crates/engine/src/cmd/edit/selection.rs b/crates/engine/src/cmd/edit/selection.rs new file mode 100644 index 0000000000..8115f63900 --- /dev/null +++ b/crates/engine/src/cmd/edit/selection.rs @@ -0,0 +1,191 @@ +use super::{ + CellRef, EngineError, Json, RangeRef, Result, Session, bool_param, cell_param, current_region, json, jump, split_sheet, str_param, target_ranges, + target_sheet, +}; + +// ---------------------------------------------------------------- selection + +/// Whether the cell may be selected: a protected sheet can forbid selecting locked and/or unlocked cells. +fn cell_selectable(wb: &gridcraft_model::Workbook, sheet: &gridcraft_model::Sheet, c: CellRef) -> bool { + let Some(p) = sheet.protection.as_ref() else { return true }; + if wb.styles.get(sheet.style_id(c)).protection.locked { p.select_locked } else { p.select_unlocked } +} + +pub(super) fn selection_set(s: &mut Session, p: &Json) -> Result { + if p.get("sheet").is_some() { + let i = target_sheet(s, p)?; + s.doc_mut()?.wb_switch_sheet(i); + } else if let Some(r) = str_param(p, "range").or_else(|| str_param(p, "cell")) + && let (Some(_), _) = split_sheet(r) + { + let i = target_sheet(s, p)?; + s.doc_mut()?.wb_switch_sheet(i); + } + let ranges = target_ranges(s, p)?; + let active = cell_param(s, p, "active")?; + let d = s.doc_mut()?; + let active = active.or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default(); + let mut sel = crate::Selection { active, anchor: ranges.last().map(|r| r.start).unwrap_or(active), ranges }; + if let Some(sh) = d.wb.active() { + sel.expand_merges(sh); + if !cell_selectable(&d.wb, sh, sel.active) { + return Err(EngineError::Other("The cell you are trying to change is on a protected sheet that does not allow selecting it.".into())); + } + } + d.selection = sel; + Ok(json!({"selection": d.selection.a1(), "active": d.selection.active.a1()})) +} + +impl crate::DocState { + /// Switches the active sheet, remembering each sheet's selection. + pub fn wb_switch_sheet(&mut self, i: usize) { + if i >= self.wb.sheets.len() || i == self.wb.active_sheet() { + return; + } + let cur = self.wb.active_sheet(); + if self.sheet_selections.len() < self.wb.sheets.len() { + self.sheet_selections.resize(self.wb.sheets.len(), crate::Selection::default()); + } + if let Some(slot) = self.sheet_selections.get_mut(cur) { + *slot = self.selection.clone(); + } + // 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(); + } +} + +pub(super) fn selection_move(s: &mut Session, p: &Json) -> Result { + let dr = p.get("dr").and_then(Json::as_i64).unwrap_or(0); + let dc = p.get("dc").and_then(Json::as_i64).unwrap_or(0); + let extend = bool_param(p, "extend").unwrap_or(false); + let jmp = bool_param(p, "jump").unwrap_or(false); + let d = s.doc_mut()?; + let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; + let sel = &mut d.selection; + // Extension moves the far corner, not the active cell. + let from = if extend { sel.moving_end() } else { sel.active }; + // Skip hidden rows/columns and step over merged areas. + let mut to = if jmp { + jump(sheet, from, dr.signum(), dc.signum()) + } else { + let mut t = from.offset_clamped(dr, dc); + let mut guard = 0; + while (sheet.is_row_hidden(t.row) || sheet.is_col_hidden(t.col)) && guard < 100_000 { + let n = t.offset_clamped(dr.signum(), dc.signum()); + if n == t { + break; + } + t = n; + guard += 1; + } + if !extend && let Some(m) = sheet.merge_at(from) { + // Leaving a merged cell moves from its edge. + if dr > 0 { + t = CellRef::new(m.end.offset_clamped(dr, 0).row, from.col); + } else if dc > 0 { + t = CellRef::new(from.row, m.end.offset_clamped(0, dc).col); + } + } + t + }; + if let Some(m) = sheet.merge_at(to) + && !extend + { + to = m.start; + } + if !extend && !cell_selectable(&d.wb, sheet, to) { + // Step on to the next selectable cell in the same direction; stay put if there is none. + let (sr, sc) = (dr.signum(), dc.signum()); + let mut t = to; + let mut found = false; + if !jmp && (sr, sc) != (0, 0) { + for _ in 0..10_000 { + let n = t.offset_clamped(sr, sc); + if n == t { + break; + } + t = n; + if !sheet.is_row_hidden(t.row) && !sheet.is_col_hidden(t.col) && cell_selectable(&d.wb, sheet, t) { + found = true; + break; + } + } + } + if !found { + return Ok(json!({"selection": sel.a1(), "active": sel.active.a1()})); + } + to = t; + } + if extend { + sel.extend_to(to); + sel.expand_merges(sheet); + } else { + *sel = crate::Selection::at(to); + if let Some(m) = sheet.merge_at(to) { + sel.ranges = vec![m]; + } + } + Ok(json!({"selection": sel.a1(), "active": sel.active.a1()})) +} + +pub(super) fn selection_next(s: &mut Session, p: &Json) -> Result { + let fwd = bool_param(p, "forward").unwrap_or(true); + let by_row = bool_param(p, "byRow").unwrap_or(false); + let d = s.doc_mut()?; + d.selection.cycle(fwd, by_row); + Ok(json!({"active": d.selection.active.a1()})) +} + +pub(super) fn selection_next_corner(s: &mut Session, _: &Json) -> Result { + let d = s.doc_mut()?; + let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; + // A corner in a merged cell lands on its top-left cell. One in a hidden row or column, one + // the sheet's protection doesn't let you select, and a merged cell that starts outside the + // selected area are skipped. + let area = d.selection.current(); + let stop = |c: CellRef| { + Some(sheet.merge_at(c).map_or(c, |m| m.start)) + .filter(|c| area.contains(*c) && !sheet.is_row_hidden(c.row) && !sheet.is_col_hidden(c.col) && cell_selectable(&d.wb, sheet, *c)) + }; + let mut next = d.selection.clone(); + next.next_corner_by(stop); + d.selection = next; + Ok(json!({"active": d.selection.active.a1(), "selection": d.selection.a1()})) +} + +pub(super) fn select_all(s: &mut Session, _: &Json) -> Result { + let d = s.doc_mut()?; + let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; + let region = current_region(sheet, d.selection.active); + let all = RangeRef::all(); + let r = if region.is_single() || d.selection.current() == region { all } else { region }; + let active = d.selection.active; + d.selection = crate::Selection { active, anchor: r.start, ranges: vec![r] }; + Ok(json!({"selection": d.selection.a1()})) +} + +pub(super) fn select_region(s: &mut Session, _: &Json) -> Result { + let d = s.doc_mut()?; + let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) }; + let r = current_region(sheet, d.selection.active); + let active = d.selection.active; + d.selection = crate::Selection { active, anchor: r.start, ranges: vec![r] }; + Ok(json!({"selection": d.selection.a1()})) +} + +pub(super) fn select_row(s: &mut Session, _: &Json) -> Result { + let d = s.doc_mut()?; + let r = d.selection.current(); + let active = d.selection.active; + d.selection = crate::Selection { active, anchor: CellRef::new(r.start.row, 0), ranges: vec![RangeRef::rows(r.start.row, r.end.row)] }; + Ok(json!({"selection": d.selection.a1()})) +} + +pub(super) fn select_col(s: &mut Session, _: &Json) -> Result { + let d = s.doc_mut()?; + let r = d.selection.current(); + let active = d.selection.active; + d.selection = crate::Selection { active, anchor: CellRef::new(0, r.start.col), ranges: vec![RangeRef::cols(r.start.col, r.end.col)] }; + Ok(json!({"selection": d.selection.a1()})) +} diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..49317caa06 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,582 @@ +use super::*; + +/// Sheet1 and Sheet2 with a workbook range name, a name scoped to each sheet, a constant, a +/// formula and a hidden name. +fn go_to_workbook() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.insertSheet", json!({"name": "Sheet2"})).unwrap(); + s.execute("selection.set", json!({"sheet": 0})).unwrap(); + let define = |s: &mut Session, name: &str, refers: &str, scope: &str| { + s.execute("formulas.defineName", json!({"name": name, "refersTo": refers, "scope": scope})).unwrap(); + }; + define(&mut s, "Price", "=Sheet1!$B$2:$B$5", "Workbook"); + define(&mut s, "type", "=Sheet1!$D$2:$D$5", "Workbook"); + define(&mut s, "Areas", "=Sheet1!$A$1,Sheet1!$C$3:$C$4", "Workbook"); + define(&mut s, "Local", "=Sheet2!$C$3", "Sheet2"); + define(&mut s, "Own", "=Sheet1!$E$1", "Sheet1"); + define(&mut s, "Rate", "=0.07", "Workbook"); + define(&mut s, "Total", "=SUM(Sheet1!$B$2:$B$5)", "Workbook"); + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + wb.names.push(gridcraft_model::DefinedName { + name: "Secret".into(), + scope: None, + formula: "Sheet1!$Z$9".into(), + comment: String::new(), + hidden: true, + }); + s +} + +/// "The Go to popup window shows named ranges on every worksheet in your workbook." Names +/// that are not ranges, and hidden names, are not listed. +#[test] +fn go_to_lists_the_named_ranges_of_every_sheet() { + let mut s = go_to_workbook(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["names"], json!(["Areas", "Own", "Price", "Sheet2!Local", "type"]), "{list}"); + assert_eq!(list["recent"], json!([]), "{list}"); + // Seen from Sheet2, its own name is bare and Sheet1's is qualified. + s.execute("selection.set", json!({"sheet": 1})).unwrap(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["names"], json!(["Areas", "Local", "Price", "Sheet1!Own", "type"]), "{list}"); +} + +#[test] +fn go_to_a_name_scoped_to_another_sheet_goes_to_that_sheet() { + let mut s = go_to_workbook(); + let out = s.execute("edit.goTo", json!({"reference": "Sheet2!Local"})).unwrap(); + assert_eq!(out["selection"], "C3", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet(), 1); + // A name of several areas selects all of them. + let out = s.execute("edit.goTo", json!({"reference": "Areas"})).unwrap(); + assert_eq!(out["selection"], "A1,C3:C4", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet(), 0); +} + +/// A name matches in any case and any script, as a formula matches it. +#[test] +fn go_to_matches_a_sheet_name_in_any_case() { + let mut s = go_to_workbook(); + s.execute("formulas.defineName", json!({"name": "Größe", "refersTo": "=Sheet2!$D$4", "scope": "Sheet2"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "GRÖSSE", "refersTo": "=Sheet1!$F$6", "scope": "Workbook"})).unwrap(); + let out = s.execute("edit.goTo", json!({"reference": "Sheet2!GRÖSSE"})).unwrap(); + assert_eq!(out["selection"], "D4", "{out}"); + // Seen from Sheet2, its own name hides the workbook name it shares. + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["names"], json!(["Areas", "Größe", "Local", "Price", "Sheet1!Own", "type"]), "{list}"); +} + +/// "You can enter multiple named ranges or cell references in the Reference box. Separating +/// each with a comma ... Excel will highlight all the ranges." +#[test] +fn go_to_selects_every_reference_and_name_in_a_list() { + let mut s = go_to_workbook(); + let out = s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30,H21:H29"})).unwrap(); + assert_eq!(out["selection"], "B14:C22,F19:G30,H21:H29", "{out}"); + let out = s.execute("edit.goTo", json!({"reference": "Price, Type"})).unwrap(); + assert_eq!(out["selection"], "B2:B5,D2:D5", "{out}"); + let out = s.execute("edit.goTo", json!({"reference": "Sheet2!$A$1,Sheet2!B2"})).unwrap(); + assert_eq!(out["selection"], "A1,B2", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet(), 1); + // Areas on two sheets, and a part that is not a reference, leave the selection alone. + for bad in ["A1,Sheet1!B2", "A1,Rate", "A1,", "Total"] { + assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().selection.a1(), "A1,B2", "{bad}"); + } +} + +#[test] +fn go_to_reads_the_parts_of_a_long_reference_one_at_a_time() { + let mut parts = reference_parts("A1, 'Q1, Q2'!B2,SUM(C3,D4)"); + assert_eq!(parts.next(), Some("A1")); + assert_eq!(parts.next(), Some("'Q1, Q2'!B2")); + assert_eq!(parts.next(), Some("SUM(C3,D4)")); + assert_eq!(parts.next(), None); + assert_eq!(reference_parts("").collect::>(), vec![""]); + let mut s = go_to_workbook(); + let err = s.execute("edit.goTo", json!({"reference": "A1,".repeat(GO_TO_MAX_AREAS + 1)})).unwrap_err(); + assert!(err.to_string().contains("at most"), "{err}"); + let bad = format!("Total{}", ",".repeat(1_000_000)); + assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err()); +} + +/// "The Go to box keeps track of ranges as you enter them, and you can return to any of them." +#[test] +fn go_to_keeps_the_references_entered_newest_first() { + let mut s = go_to_workbook(); + s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30", "record": true})).unwrap(); + s.execute("edit.goTo", json!({"reference": "Sheet2!A5", "record": true})).unwrap(); + // Names are listed already; a call without `record` (the Name Box) is not kept. + s.execute("edit.goTo", json!({"reference": "Price", "record": true})).unwrap(); + s.execute("edit.goTo", json!({"reference": "Z9"})).unwrap(); + s.execute("edit.goTo", json!({"reference": "b14:c22,f19:g30", "record": true})).unwrap(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["recent"], json!(["Sheet1!B14:C22,Sheet1!F19:G30", "Sheet2!A5"]), "{list}"); + // Going back from Sheet2 to a recent reference returns to its sheet. + s.execute("selection.set", json!({"sheet": 1})).unwrap(); + let out = s.execute("edit.goTo", json!({"reference": "Sheet1!B14:C22,Sheet1!F19:G30", "record": true})).unwrap(); + assert_eq!(out["selection"], "B14:C22,F19:G30", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet(), 0); + for i in 0..GO_TO_RECENT + 2 { + s.execute("edit.goTo", json!({"reference": format!("A{}", i + 1), "record": true})).unwrap(); + } + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["recent"].as_array().map(Vec::len), Some(GO_TO_RECENT), "{list}"); + assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); +} + +#[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. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": 123.5})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "value": 77})).unwrap(); + s.execute("cell.set", json!({"cell": "A3", "input": true})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "=A1+A2"})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + assert_eq!(get(&mut s, "A1")["value"], json!(123.5)); + assert_eq!(get(&mut s, "A2")["value"], json!(77.0)); + assert_eq!(get(&mut s, "A3")["value"], json!(true)); + assert_eq!(get(&mut s, "A4")["value"], json!(200.5)); + assert!(s.execute("cell.set", json!({"cell": "A5"})).is_err()); +} + +/// Every string in `values` went through typed input, read with en-US rules, in silence: a +/// caller sending "05.04.2026" from a dd.mm.yyyy export stored 4 May, "2.500" became 2.5 and +/// "4.25 %" became a percentage (#2255). `parse: false` stores a string as the text it is. +#[test] +fn set_values_can_store_strings_as_the_text_they_are() { + let mut s = Session::new(); + s.new_workbook(); + let strings = ["05.04.2026", "02/11/2026", "2.500", "4.25 %", "=1+1", "'keep"]; + let row: Vec = strings.iter().map(|v| json!(v)).collect(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + + // The default is unchanged: the dates swap, the thousands separator is a decimal point. + s.execute("range.setValues", json!({"range": "A1", "values": [row.clone()]})).unwrap(); + assert_eq!(get(&mut s, "A1")["text"], "5/4/2026", "dd.mm.yyyy read as mm.dd.yyyy"); + assert_eq!(get(&mut s, "C1")["value"], json!(2.5), "\"2.500\" read as a decimal"); + assert_eq!(get(&mut s, "D1")["value"], json!(0.0425), "\"4.25 %\" read as a percentage"); + + // With `parse: false` each string is the text it was given, and a formula is still a + // formula. + s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [row.clone()]})).unwrap(); + for (i, want) in strings.iter().enumerate() { + let cell = format!("{}3", (b'A' + i as u8) as char); + let got = get(&mut s, &cell); + if *want == "=1+1" { + assert_eq!(got["value"], json!(2.0), "{cell} is still a formula: {got}"); + assert_eq!(got["formula"], "=1+1", "{got}"); + } else { + assert_eq!(got["value"], json!(*want), "{cell} is the text it was given: {got}"); + assert!(got["formula"].is_null(), "{cell} is not a formula: {got}"); + } + } + // Numbers and booleans are untouched either way. + s.execute("range.setValues", json!({"range": "A5", "parse": false, "values": [[12.5, true, null]]})).unwrap(); + assert_eq!(get(&mut s, "A5")["value"], json!(12.5)); + assert_eq!(get(&mut s, "B5")["value"], json!(true)); + assert_eq!(get(&mut s, "C5")["text"], ""); + // `parse` is a flag, and anything else is a usage error rather than a quiet default. + s.execute("range.setValues", json!({"range": "A7", "parse": true, "values": [["2.500"]]})).unwrap(); + assert_eq!(get(&mut s, "A7")["value"], json!(2.5)); + assert!(s.execute("range.setValues", json!({"range": "A8", "parse": "no", "values": [["x"]]})).is_err()); + 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(); + assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A9").unwrap())).align.wrap); +} + +/// The result names the strings typed input read as something else, so a script notices without +/// reading the file back (#2255). A formula and a leading apostrophe are not conversions. +#[test] +fn set_values_reports_the_strings_typed_input_read() { + let mut s = Session::new(); + s.new_workbook(); + let row = json!(["05.04.2026", "02/11/2026", "2.500", "4.25 %", "=1+1", "'keep"]); + let r = s.execute("range.setValues", json!({"range": "A1", "values": [row.clone()]})).unwrap(); + assert_eq!(r["cells"], 6, "{r}"); + assert_eq!(r["convertedCount"], 4, "{r}"); + assert_eq!(r["converted"][0], json!({"cell": "A1", "input": "05.04.2026", "stored": "5/4/2026"}), "{r}"); + assert_eq!(r["converted"][1], json!({"cell": "B1", "input": "02/11/2026", "stored": "2/11/2026"}), "{r}"); + assert_eq!(r["converted"][2], json!({"cell": "C1", "input": "2.500", "stored": "2.5"}), "{r}"); + assert_eq!(r["converted"][3], json!({"cell": "D1", "input": "4.25 %", "stored": "4.25%"}), "{r}"); + // The report is a diagnostic, not a second copy of the data: a long input is cut. + let long = s.execute("range.setValues", json!({"range": "J1", "values": [["9".repeat(100)]]})).unwrap(); + assert_eq!(long["convertedCount"], 1, "{long}"); + let input = long["converted"][0]["input"].as_str().unwrap_or_default(); + assert_eq!(input.chars().count(), 33, "32 characters and the ellipsis: {input}"); + assert!(input.ends_with('…'), "{input}"); + // Nothing is read with `parse: false`, so nothing is reported. + let verbatim = s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [row]})).unwrap(); + assert_eq!(verbatim["convertedCount"], 0, "{verbatim}"); + assert_eq!(verbatim["converted"], json!([]), "{verbatim}"); +} + +/// An empty string clears the cell with `parse: false` too, as `null` and the default path do: a +/// script clearing cells with "" must not leave cells `COUNTA` counts. +#[test] +fn set_values_parse_false_clears_an_empty_string() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1:B1", "values": [["keep", "keep"]]})).unwrap(); + s.execute("home.bold", json!({"range": "A1"})).unwrap(); + s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": [["", ""]]})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + assert_eq!(get(&mut s, "A1")["type"], "empty"); + assert_eq!(get(&mut s, "B1")["type"], "empty"); + let d = s.doc().unwrap(); + let sh = d.wb.sheet(0).unwrap(); + assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A1").unwrap())).font.bold, "clearing with \"\" keeps the formatting"); + assert_eq!(s.execute("formulas.evaluate", json!({"formula": "=COUNTA(A1:B1)"})).unwrap(), json!(0.0)); +} + +/// The text `parse: false` stores is still text after the workbook is saved and reopened, and the +/// default's reading of a date survives as a date (#2255). +#[test] +fn set_values_text_survives_an_xlsx_roundtrip() { + let mut s = Session::new(); + s.new_workbook(); + let values = json!([["05.04.2026", "2.500", "4.25 %", "=1+1", 3, true]]); + s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": values})).unwrap(); + s.execute("range.setValues", json!({"range": "A3", "values": [["05.04.2026"]]})).unwrap(); + let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); + let (wb, _) = crate::io::open_bytes("book.xlsx", &bytes).unwrap(); + let sh = wb.sheet(0).unwrap(); + for (col, want) in [(0, "05.04.2026"), (1, "2.500"), (2, "4.25 %")] { + assert_eq!(sh.value(CellRef::new(0, col)), Value::text(want), "column {col} is the text it was given"); + } + assert_eq!(sh.value(CellRef::new(0, 3)), Value::number(2.0), "=1+1 is still a formula"); + assert_eq!(sh.value(CellRef::new(0, 4)), Value::number(3.0)); + assert_eq!(sh.value(CellRef::new(0, 5)), Value::Bool(true)); + // The default read the date, and the file keeps it as one. + let at = CellRef::new(2, 0); + assert_eq!(crate::display::cell_text(&wb, sh, at), "5/4/2026"); + assert_eq!(wb.styles.get(sh.style_id(at)).num_fmt.as_str(), "m/d/yyyy"); +} + +#[test] +fn legacy_array_entry() { + 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": "C4", "input": "old"})).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 get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + assert_eq!(get(&mut s, "C3")["value"], json!(4.0)); + // Past the result Excel shows #N/A; the old content of the range is replaced. + assert_eq!(get(&mut s, "C4")["text"], "#N/A"); + let bar = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("C2").unwrap()).map(|c| c.bar_text()); + assert_eq!(bar.as_deref(), Some("{=B2:B3*2}")); +} + +#[test] +fn an_array_entered_outside_the_selection_covers_only_its_cell() { + // Found by the command-sequence fuzzer: the array took the selection's range even with + // `cell` elsewhere (or on another sheet), so its formula sat outside its own range and the + // selected cells were wiped. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "K20", "input": "keep"})).unwrap(); + s.execute("selection.set", json!({"range": "K20:K22"})).unwrap(); + s.execute("cell.set", json!({"cell": "H5", "input": "=1+1", "array": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + let f = sh.cell(CellRef::parse("H5").unwrap()).and_then(|c| c.formula.clone()).unwrap(); + assert_eq!(f.array, Some(RangeRef::parse("H5").unwrap())); + assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep")); +} + +#[test] +fn wildcards() { + assert!(wildcard("hello", "h*o")); + assert!(wildcard("hello", "h?llo")); + assert!(!wildcard("hello", "h?lo")); + assert!(wildcard("a*b", "a~*b")); + assert!(!wildcard("axb", "a~*b")); + assert!(wildcard("", "*")); +} + +#[test] +fn tsv() { + assert_eq!(parse_tsv("a\tb\n1\t2\n"), vec![vec!["a", "b"], vec!["1", "2"]]); + assert_eq!(parse_tsv("\"x\ty\"\tz"), vec![vec!["x\ty", "z"]]); + assert_eq!(parse_tsv("\"he said \"\"hi\"\"\""), vec![vec!["he said \"hi\""]]); + // #2225: a quote that doesn't close the field leaves it as written, as Excel pastes it. + assert_eq!(parse_tsv("\"hi\" there\tx\n"), vec![vec!["\"hi\" there", "x"]]); + assert_eq!(parse_tsv("say \"hi\"\n"), vec![vec!["say \"hi\""]]); +} + +#[test] +fn paste_special_operations_keep_text_errors_and_formulas() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["'123", "Total", "=NA()", "=B3*2", 5], [1, null, null, null, null], [null, 4, null, null, null]]}), + ) + .unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + assert_eq!(get(&mut s, "A1")["value"], "123"); + s.execute("edit.copy", json!({"range": "A2"})).unwrap(); + s.execute("selection.set", json!({"range": "A1:E1"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "values", "operation": "multiply"})).unwrap(); + assert_eq!(get(&mut s, "A1")["value"], json!(123.0)); + assert_eq!(get(&mut s, "B1")["value"], "Total"); + assert_eq!(get(&mut s, "C1")["value"]["error"], "#N/A"); + assert_eq!(get(&mut s, "D1")["formula"], "=(B3*2)*1"); + assert_eq!(get(&mut s, "D1")["value"], json!(8.0)); + assert_eq!(get(&mut s, "E1")["value"], json!(5.0)); +} + +#[test] +fn cut_paste_that_overflows_the_grid_moves_nothing() { + // #997: the source was emptied first and the cells that fell off the grid were skipped. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2]]})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); + // Transposed, the 2 rows become 2 columns and the second one is past XFD. + assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "XFD1"})).is_err()); + assert_eq!(get(&mut s, "A1")["value"], json!(1.0)); + assert_eq!(get(&mut s, "A2")["value"], json!(2.0)); + // Not transposed, the second row would be past the last row. + assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "at": "A1048576"})).is_err()); + assert_eq!(get(&mut s, "A1")["value"], json!(1.0)); + assert_eq!(get(&mut s, "A2")["value"], json!(2.0)); + // Not transposed it still fits in column XFD. + s.execute("edit.pasteSpecial", json!({"what": "all", "at": "XFD1"})).unwrap(); + assert_eq!(get(&mut s, "XFD1")["value"], json!(1.0)); + assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0)); +} + +#[test] +fn drag_and_drop_asks_before_replacing_data() { + // #3136: dragging column B's border onto column A replaced A without asking. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Apple", "Kiwi"], ["Pear", "Plum"], ["Fig", "Lime"]]})).unwrap(); + s.execute("edit.copy", json!({"range": "D9"})).unwrap(); + let text = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["input"].clone(); + let r = s.execute("range.move", json!({"range": "B:B", "to": "A1"})); + let Err(EngineError::Confirm(q)) = r else { panic!("{r:?}") }; + assert_eq!(q, "There's already data here. Do you want to replace it?"); + // Nothing moved, and the copy made before is still on the clipboard. + assert_eq!(text(&mut s, "A1"), json!("Apple")); + assert_eq!(text(&mut s, "B1"), json!("Kiwi")); + assert!(s.clipboard.as_ref().is_some_and(|c| !c.cut && c.range.a1() == "D9")); + // Confirmed, column B replaces column A. + s.execute("range.move", json!({"range": "B:B", "to": "A1", "overwrite": true})).unwrap(); + assert_eq!(text(&mut s, "A1"), json!("Kiwi")); + assert_eq!(text(&mut s, "A3"), json!("Lime")); + assert_eq!(text(&mut s, "B1"), json!("")); + // Onto empty cells, or overlapping only the moved cells themselves, nothing is asked. + s.execute("range.move", json!({"range": "A1:A3", "to": "A2"})).unwrap(); + assert_eq!(text(&mut s, "A4"), json!("Lime")); + s.execute("range.move", json!({"range": "A2:A4", "to": "C2"})).unwrap(); + assert_eq!(text(&mut s, "C2"), json!("Kiwi")); + assert!(s.execute("range.move", json!({"range": "C2"})).is_err(), "`to` is required"); +} + +#[test] +fn drag_and_drop_asks_before_replacing_spilled_values() { + // Cells showing a dynamic array's spilled values hold no cell of their own, but they are data. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(3)"})).unwrap(); + s.execute("range.setValues", json!({"range": "C2:C3", "values": [["Kiwi"], ["Plum"]]})).unwrap(); + let r = s.execute("range.move", json!({"range": "C2:C3", "to": "A2"})); + let Err(EngineError::Confirm(q)) = r else { panic!("{r:?}") }; + assert_eq!(q, "There's already data here. Do you want to replace it?"); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::new(2, 2)), Value::text("Plum")); + s.execute("range.move", json!({"range": "C2:C3", "to": "A2", "overwrite": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::new(1, 0)), Value::text("Kiwi")); +} + +#[test] +fn drag_and_drop_on_another_sheet_stays_on_that_sheet() { + // The move was checked on the range's sheet but pasted on the active one, replacing its data + // without asking. + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + s.execute("range.setValues", json!({"range": "B1:B2", "values": [["Kiwi"], ["Plum"]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "Keep"})).unwrap(); + s.execute("selection.set", json!({"range": "C5"})).unwrap(); + s.execute("range.move", json!({"range": "Two!B1:B2", "to": "A1"})).unwrap(); + // Sheet1 stays active with its own selection; the moved cells are on Two. + assert_eq!(s.doc().unwrap().wb.active_sheet(), 0); + assert_eq!(s.doc().unwrap().selection.a1(), "C5"); + let wb = &s.doc().unwrap().wb; + let two = wb.sheet_index("Two").unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(0, 0)), Value::text("Keep")); + assert_eq!(wb.sheet(two).unwrap().value(CellRef::new(0, 0)), Value::text("Kiwi")); + assert_eq!(wb.sheet(two).unwrap().value(CellRef::new(1, 0)), Value::text("Plum")); + assert_eq!(wb.sheet(two).unwrap().value(CellRef::new(0, 1)), Value::Empty); +} + +#[test] +fn replace_case_insensitive() { + assert_eq!(replace_ci("Apple apple APPLE", "apple", "pear"), "pear pear pear"); +} + +#[test] +fn replace_case_insensitive_keeps_text_when_folding_moves_boundaries() { + // U+212A KELVIN SIGN folds to `k` (3→1 bytes) while U+0130 folds to `i` plus a + // combining dot (2→3 bytes): the folded text is the same length but its byte positions + // no longer line up with the original, and the old slicing dropped the tail. + let mut s = Session::new(); + s.new_workbook(); + let text = "\u{212A}\u{0130}\u{0130}"; + s.execute("cell.set", json!({"cell": "A1", "input": text})).unwrap(); + s.execute("edit.replace", json!({"what": "k", "with": "x"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.value(CellRef::new(0, 0)), Value::text(text)); +} + +#[test] +fn next_corner_of_selection_goes_clockwise_and_anchors_there() { + // #1442, as Excel does it: B2 → D2 → D4 → B4 → B2, the area stays selected, and Shift+arrows + // then move the corner opposite the new active cell. + let mut s = Session::new(); + s.new_workbook(); + s.execute("selection.set", json!({"range": "B2:D4", "active": "B2"})).unwrap(); + let mut seen = Vec::new(); + for _ in 0..4 { + let r = s.execute("selection.nextCorner", json!({})).unwrap(); + assert_eq!(r["selection"], "B2:D4"); + seen.push(r["active"].as_str().unwrap().to_string()); + } + assert_eq!(seen, ["D2", "D4", "B4", "B2"]); + s.execute("selection.nextCorner", json!({})).unwrap(); + s.execute("selection.nextCorner", json!({})).unwrap(); + s.execute("selection.move", json!({"dr": 0, "dc": 1, "extend": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.current().a1(), "C2:D4"); + // One row goes end to end; a single cell stays. + s.execute("selection.set", json!({"range": "B2:D2", "active": "B2"})).unwrap(); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "D2"); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "B2"); + s.execute("selection.set", json!({"range": "C5"})).unwrap(); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "C5"); +} + +#[test] +fn next_corner_skips_corners_the_sheet_protection_does_not_let_you_select() { + // With locked cells unselectable, Ctrl+. goes on to the next corner it may select. + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.lockCell", json!({"range": "B2:C3", "on": false})).unwrap(); + s.execute("selection.set", json!({"range": "B2:D3", "active": "B2"})).unwrap(); + s.execute("review.protectSheet", json!({"selectLockedCells": false})).unwrap(); + let r = s.execute("selection.nextCorner", json!({})).unwrap(); + assert_eq!((r["active"].as_str(), r["selection"].as_str()), (Some("B3"), Some("B2:D3")), "D2 and D3 are locked"); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "B2"); +} + +#[test] +fn next_corner_stops_once_on_a_merged_corner_at_its_top_left_cell() { + // A corner inside a merged cell is that merged cell, whose active cell is its top-left one. + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap(); + s.execute("selection.set", json!({"range": "B2:D3", "active": "B2"})).unwrap(); + let seen: Vec = (0..4).map(|_| s.execute("selection.nextCorner", json!({})).unwrap()["active"].as_str().unwrap().to_string()).collect(); + assert_eq!(seen, ["C2", "D3", "B3", "B2"]); + // A selection that is one merged cell has no other corner. + s.execute("selection.set", json!({"range": "C2:D2", "active": "C2"})).unwrap(); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "C2"); +} + +#[test] +fn next_corner_skips_hidden_corners_and_stays_inside_the_selected_area() { + // A corner in a hidden column is passed over, as keyboard moves pass over hidden cells. + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap(); + s.execute("selection.set", json!({"range": "B2:D3", "active": "B2"})).unwrap(); + assert_eq!(s.execute("selection.nextCorner", json!({})).unwrap()["active"], "B3"); + // Column C selected with B1:C1 merged: its top corner's merged cell starts in column B, + // outside the selection, so the active cell doesn't go there. + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.mergeCells", json!({"range": "B1:C1"})).unwrap(); + s.execute("selection.set", json!({"cell": "C5"})).unwrap(); + s.execute("selection.column", json!({})).unwrap(); + let r = s.execute("selection.nextCorner", json!({})).unwrap(); + assert_eq!((r["active"].as_str(), r["selection"].as_str()), (Some("C1048576"), Some("C:C"))); +} + +#[test] +fn copy_quotes_only_cells_with_tabs_or_line_breaks() { + // #2225: a cell holding a quote was wrapped in quotes on copy; Excel quotes only text with a + // tab or line break, and pastes the result back as the same cells. + let mut s = Session::new(); + s.new_workbook(); + for (cell, input) in [("A1", "say \"hi\""), ("A2", "plain"), ("A3", "\"hi\" there"), ("A4", "x \"q\"\ny"), ("A5", "tab\tinside")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + let text = s.execute("edit.copy", json!({"range": "A1:A5"})).unwrap()["text"].as_str().unwrap().to_string(); + assert_eq!(text, "say \"hi\"\nplain\n\"hi\" there\n\"x \"\"q\"\"\ny\"\n\"tab\tinside\"\n"); + let rows = parse_tsv(&text); + let cells: Vec<&str> = rows.iter().map(|r| r[0].as_str()).collect(); + assert_eq!(cells, ["say \"hi\"", "plain", "\"hi\" there", "x \"q\"\ny", "tab\tinside"]); +} + +#[test] +fn a_field_that_is_not_really_quoted_keeps_its_separators() { + // A field opening with a quote is quoted only if a closing quote ends it; when it doesn't (or + // never closes), the text is read as written, and the tabs and line breaks inside it still + // separate cells, as they would have without the leading quote. + assert_eq!(parse_tsv("\"a\tb\"x\tc"), vec![vec!["\"a", "b\"x", "c"]]); + assert_eq!(parse_tsv("\"a\tb\nc"), vec![vec!["\"a", "b"], vec!["c"]]); + assert_eq!(parse_tsv("\"a\tb\tc\n"), vec![vec!["\"a", "b", "c"]]); + // Cells copied without quotes (they hold no tab or line break) read back as the same cells. + let mut s = Session::new(); + s.new_workbook(); + for (cell, input) in [("A1", "'\"a"), ("B1", "b\"x"), ("C1", "c")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + let text = s.execute("edit.copy", json!({"range": "A1:C1"})).unwrap()["text"].as_str().unwrap().to_string(); + assert_eq!(parse_tsv(&text), vec![vec!["\"a", "b\"x", "c"]], "{text:?}"); + // Many fields that only look quoted: each is replayed at most once (the replay budget is the + // input's length), and every one is still its own cell. + let hostile = "\"x\t".repeat(50_000); + assert_eq!(parse_tsv(&hostile).first().map(Vec::len), Some(50_001)); +} + +/// `within: selection` searches only the selected cells, as Excel does with a range selected +/// (#3224): Find All lists them, Find Next moves the active cell through them and keeps the range +/// selected, and Replace changes only them. +#[test] +fn find_and_replace_within_the_selection() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1:B4", "values": [["pear", "pear"], ["plum", "pear"], ["pear", "fig"], ["pear", "pear"]]})) + .unwrap(); + s.execute("selection.set", json!({"range": "B1:B4"})).unwrap(); + let all = s.execute("edit.find", json!({"what": "pear", "all": true, "within": "selection"})).unwrap(); + let cells: Vec<&str> = all["results"].as_array().unwrap().iter().filter_map(|r| r["cell"].as_str()).collect(); + assert_eq!(cells, ["B1", "B2", "B4"], "only column B"); + assert_eq!(s.execute("edit.find", json!({"what": "pear", "within": "selection"})).unwrap()["cell"], "B2"); + assert_eq!(s.execute("edit.find", json!({"what": "pear", "within": "selection"})).unwrap()["cell"], "B4"); + assert_eq!(s.execute("edit.find", json!({"what": "pear", "within": "selection"})).unwrap()["cell"], "B1", "wraps inside the range"); + let sel = &s.doc().unwrap().selection; + assert_eq!((sel.a1(), sel.active.a1()), ("B1:B4".to_string(), "B1".to_string()), "the range stays selected"); + assert!(s.execute("edit.find", json!({"what": "plum", "within": "selection"})).is_err(), "A2 is outside the range"); + assert_eq!(s.execute("edit.replace", json!({"what": "pear", "with": "kiwi", "within": "selection"})).unwrap()["replaced"], 3); + let sh = s.doc().unwrap().wb.active().unwrap(); + let at = |a: &str| sh.value(CellRef::parse(a).unwrap()); + assert_eq!((at("A1"), at("B1"), at("B4"), at("A4")), (Value::text("pear"), Value::text("kiwi"), Value::text("kiwi"), Value::text("pear"))); + // The sheet scope is unchanged. + let all = s.execute("edit.find", json!({"what": "pear", "all": true})).unwrap(); + assert_eq!(all["count"], 3, "A1, A3 and A4 on the whole sheet"); +} diff --git a/crates/engine/src/cmd/equation.rs b/crates/engine/src/cmd/equation.rs new file mode 100644 index 0000000000..d485a3535c --- /dev/null +++ b/crates/engine/src/cmd/equation.rs @@ -0,0 +1,305 @@ +//! Equations (Insert › Symbols › Equation): floating shapes holding LaTeX source, laid out by +//! `gridcraft-math` and drawn from the cached layout. +//! +//! An equation is drawn to fit its frame, so resizing the frame scales it. Inserting sizes the +//! frame for the requested font size; editing keeps the current scale and resizes the frame to +//! the new content. + +use gridcraft_math::{MathError, MathList}; +use gridcraft_model::{Anchor, AnchorMode, Color, EquationCache, Shape, ShapeKind}; +use serde_json::{Value as Json, json}; + +use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, cell_param, cmd, edit, f64_param, has_doc, ok, str_param, u32_param}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "insert.equation", + "Equation", + ["Insert", "Symbols"], + None, + "{latex: \"x^2\", cell?|at?: \"B2\", size?: 11 (points), color?: hex|\"auto\"}", + has_doc, + insert_equation + ), + cmd!("equation.edit", "Edit Equation", [], None, "{id, latex}", has_doc, edit_equation), + ] +} + +/// Default equation font size, in points. +pub const DEFAULT_SIZE_PT: f64 = 11.0; +/// Space between an equation's frame and its content, in sheet pixels. +pub const PADDING: f32 = 4.0; +/// Sheet pixels per point. +const PX_PER_PT: f64 = 96.0 / 72.0; + +/// The scale (sheet pixels per em) at which `list` fits a frame of `w` by `h` pixels. +pub fn fit_scale(list: &MathList, w: f32, h: f32) -> f32 { + let (cw, ch) = (list.width.max(0.01), list.total_height().max(0.01)); + let s = ((w - 2.0 * PADDING) / cw).min((h - 2.0 * PADDING) / ch); + if s.is_finite() { s.max(0.0) } else { 0.0 } +} + +/// The frame size for `list` at `scale` pixels per em. +fn frame_for(list: &MathList, scale: f32) -> (f32, f32) { + let w = list.width.max(0.5) * scale + 2.0 * PADDING; + let h = list.total_height().max(1.0) * scale + 2.0 * PADDING; + (w.clamp(8.0, 20_000.0), h.clamp(8.0, 20_000.0)) +} + +/// `latex` laid out, or a readable error with the position of the problem. +fn lay_out(cmd: &str, latex: &str) -> Result { + gridcraft_math::layout(latex).map_err(|e| bad(cmd, describe(latex, &e))) +} + +/// "Error at character 5: Undefined control sequence: \foo". +pub fn describe(latex: &str, e: &MathError) -> String { + match e.char_pos(latex) { + Some(p) => format!("equation error at character {p}: {}", e.message), + None => format!("equation error: {}", e.message), + } +} + +fn insert_equation(s: &mut Session, p: &Json) -> Result { + const CMD: &str = "insert.equation"; + let latex = str_param(p, "latex").ok_or_else(|| bad(CMD, "`latex` must be the equation's LaTeX source, such as \"x^2 + y^2 = r^2\""))?; + if latex.trim().is_empty() { + return Err(bad(CMD, "`latex` is empty")); + } + let size = f64_param(p, "size").unwrap_or(DEFAULT_SIZE_PT); + if !(1.0..=409.0).contains(&size) { + return Err(bad(CMD, "`size` must be between 1 and 409 points")); + } + let color = match p.get("color") { + None | Some(Json::Null) => Color::Auto, + Some(c) => super::format::color_param(Some(c)).ok_or_else(|| bad(CMD, "`color` must be a hex colour such as \"#1F4E79\", or \"auto\""))?, + }; + let list = lay_out(CMD, latex)?; + let at = match cell_param(s, p, "cell")? { + Some(c) => Some(c), + None => cell_param(s, p, "at")?, + }; + let d = s.doc()?; + if d.wb.active().is_some_and(|sh| sh.is_protected()) { + return Err(EngineError::Other(PROTECTED.into())); + } + let at = at.unwrap_or(d.selection.active); + let id = d.wb.next_object_id(); + let (width, height) = frame_for(&list, (size * PX_PER_PT) as f32); + let mut shape = Shape { + id, + kind: ShapeKind::Equation, + anchor: Anchor { cell: at, dx: 0.0, dy: 0.0, width, height, mode: AnchorMode::MoveOnly }, + fill: Color::Auto, + line: color, + text: latex.to_string(), + format: Default::default(), + math: Default::default(), + }; + shape.math.refresh(latex); + let sheet = d.wb.active_sheet(); + edit(s, |cx| { + cx.sheet_mut(sheet)?.shapes.push(shape); + Ok(json!({"equation": id})) + }) +} + +fn edit_equation(s: &mut Session, p: &Json) -> Result { + const CMD: &str = "equation.edit"; + let id = u32_param(p, "id").ok_or_else(|| bad(CMD, "`id` must be an equation id"))?; + let latex = str_param(p, "latex").ok_or_else(|| bad(CMD, "`latex` must be the equation's LaTeX source"))?; + if latex.trim().is_empty() { + return Err(bad(CMD, "`latex` is empty; delete the equation instead")); + } + let d = s.doc()?; + let sheet = d.wb.active_sheet(); + let sh = d.wb.active().ok_or_else(|| bad(CMD, "no such equation"))?; + let shape = sh.shapes.iter().find(|x| x.id == id && x.kind == ShapeKind::Equation).ok_or_else(|| bad(CMD, "no such equation"))?; + if sh.is_protected() { + return Err(EngineError::Other(PROTECTED.into())); + } + // The same source is a no-op, unless it has no layout yet (a file with more equations than + // are laid out at once): then OK lays it out. + if shape.text == latex && matches!(shape.math.get(latex), Some(Ok(_))) { + return ok(); + } + let list = lay_out(CMD, latex)?; + // Keep the size the equation is drawn at now; without a layout, use the default size. + let scale = match shape.math.get(&shape.text) { + Some(Ok(old)) => fit_scale(old, shape.anchor.width, shape.anchor.height), + _ => 0.0, + }; + let scale = if scale > 0.1 { scale } else { (DEFAULT_SIZE_PT * PX_PER_PT) as f32 }; + let (width, height) = frame_for(&list, scale); + edit(s, |cx| { + let shape = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|x| x.id == id).ok_or_else(|| bad(CMD, "no such equation"))?; + shape.text = latex.to_string(); + shape.math = EquationCache::default(); + shape.math.refresh(latex); + shape.anchor.width = width; + shape.anchor.height = height; + Ok(json!({"equation": id})) + }) +} + +// ---------------------------------------------------------------- PDF + +/// The first [`gridcraft_math::MAX_SOURCE_BYTES`] bytes of an equation's source, cut at a char +/// boundary. A longer source never lays out (the editor refuses it, and a file can carry one of +/// megabytes), so what shows it as text, the sheet painter and the PDF fallback, shows this much +/// and does no work on the rest. +pub fn source_excerpt(text: &str) -> &str { + let cap = gridcraft_math::MAX_SOURCE_BYTES; + if text.len() <= cap { + return text; + } + let mut end = cap; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.get(..end).unwrap_or("") +} + +/// The PDF face for a glyph: Symbol for Greek letters and operators, else the Times (or +/// Helvetica, Courier) face for its style. `None` when no standard font can show `c`. +fn pdf_font(c: char, face: gridcraft_math::Face) -> Option { + use gridcraft_math::Face; + use gridcraft_pdf::Font; + let text = match face { + Face::Italic => Font::TimesItalic, + Face::Bold => Font::TimesBold, + Face::BoldItalic => Font::TimesBoldItalic, + Face::Sans => Font::Helvetica, + Face::SansBold => Font::HelveticaBold, + Face::SansItalic => Font::HelveticaOblique, + Face::Mono => Font::Courier, + Face::Roman | Face::Large(_) => Font::TimesRoman, + }; + // Letters and digits stay in the text face; everything Symbol has goes to Symbol, whose + // operators (minus, equals, plus) match the maths better than the text faces'. + if c.is_ascii_alphanumeric() { + return Some(text); + } + if Font::Symbol.can_encode(c) { + return Some(Font::Symbol); + } + text.can_encode(c).then_some(text) +} + +/// Draws an equation's layout into the box `(x, y, w, h)` (page points) of a PDF page, with +/// `pad` points of padding. Glyphs no standard font has are drawn as `[?]` boxes. +pub(crate) fn draw_pdf(pg: &mut gridcraft_pdf::Page, list: &MathList, rect: (f32, f32, f32, f32), pad: f32, ink: gridcraft_pdf::Rgb) { + use gridcraft_math::{Face, Item, PathCmd}; + let (x, y, w, h) = rect; + let (cw, ch) = (list.width.max(0.01), list.total_height().max(0.01)); + let s = ((w - 2.0 * pad) / cw).min((h - 2.0 * pad) / ch); + if !(s.is_finite() && s > 0.01) { + return; + } + let s = s.min(4000.0); + let (ox, oy) = (x + (w - cw * s) / 2.0, y + (h - ch * s) / 2.0); + let col = |c: Option<[u8; 3]>| c.unwrap_or(ink); + for item in list.items.iter().take(gridcraft_math::MAX_ITEMS) { + match item { + Item::Glyph(g) => { + let color = col(g.color); + let (gx, base) = (ox + g.x * s, oy + g.y * s); + // The radical sign: Symbol's glyph (AFM bounding box -147 to 917 high, right edge + // at 558, in 1/1000 em) fitted to the TeX box, so its top meets the vinculum. + if g.ch == '\u{221A}' { + let size = (g.height + g.depth) * s / 1.064; + if size.is_finite() && size >= 0.5 { + let top = base - g.height * s; + pg.text(gx + g.width * s - 0.558 * size, top + 0.917 * size, size, gridcraft_pdf::Font::Symbol, color, "\u{221A}"); + } + continue; + } + let large = matches!(g.face, Face::Large(_)); + let size = if large { (g.height + g.depth) * s } else { g.size * s }; + if !(size.is_finite() && size >= 0.5) { + continue; + } + let pick = pdf_font(g.ch, g.face).map(|f| (g.ch, f)).or_else(|| g.alt.and_then(|a| pdf_font(a, g.face).map(|f| (a, f)))); + match pick { + Some((c, font)) => { + let text = c.to_string(); + if large { + // Centred on the glyph's box, like the screen. + let mid = oy + (g.y - (g.height - g.depth) / 2.0) * s; + let tw = gridcraft_pdf::text_width(font, size, &text); + pg.text(gx + (g.width * s - tw) / 2.0, mid + 0.25 * size, size, font, color, &text); + } else { + pg.text(gx, base, size, font, color, &text); + } + } + None => { + // [?]: the glyph's box with a question mark. + let (bw, bh) = ((g.width.max(0.3)) * s, (g.height + g.depth) * s); + pg.rect_stroke(gx, base - g.height * s, bw, bh, (0.05 * s).clamp(0.2, 1.0), color); + let qs = (bh * 0.6).min(bw * 1.2).max(1.0); + let qw = gridcraft_pdf::text_width(gridcraft_pdf::Font::Helvetica, qs, "?"); + pg.text(gx + (bw - qw) / 2.0, base - g.height * s + (bh + qs * 0.7) / 2.0, qs, gridcraft_pdf::Font::Helvetica, color, "?"); + } + } + } + Item::Rule(r) => { + if r.width > 0.0 && r.height > 0.0 { + pg.fill_rect(ox + r.x * s, oy + r.y * s, r.width * s, (r.height * s).max(0.25), col(r.color)); + } + } + Item::Path(p) => { + let (px, py) = (ox + p.x * s, oy + p.y * s); + let mut subs: Vec> = vec![]; + let mut cur: Vec<[f32; 2]> = vec![]; + let at = |a: f32, b: f32| [px + a * s, py + b * s]; + for c in &p.commands { + match *c { + PathCmd::MoveTo(a, b) => { + if cur.len() > 1 { + subs.push(std::mem::take(&mut cur)); + } + cur = vec![at(a, b)]; + } + PathCmd::LineTo(a, b) => cur.push(at(a, b)), + PathCmd::QuadTo(x1, y1, a, b) => { + let p0 = cur.last().copied().unwrap_or(at(x1, y1)); + let (c1, p1) = (at(x1, y1), at(a, b)); + for k in 1..=8 { + let t = k as f32 / 8.0; + let u = 1.0 - t; + cur.push([u * u * p0[0] + 2.0 * u * t * c1[0] + t * t * p1[0], u * u * p0[1] + 2.0 * u * t * c1[1] + t * t * p1[1]]); + } + } + PathCmd::CubicTo(x1, y1, x2, y2, a, b) => { + let p0 = cur.last().copied().unwrap_or(at(x1, y1)); + let (c1, c2, p1) = (at(x1, y1), at(x2, y2), at(a, b)); + for k in 1..=10 { + let t = k as f32 / 10.0; + let u = 1.0 - t; + let (a3, b3, c3, d3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + cur.push([a3 * p0[0] + b3 * c1[0] + c3 * c2[0] + d3 * p1[0], a3 * p0[1] + b3 * c1[1] + c3 * c2[1] + d3 * p1[1]]); + } + } + PathCmd::Close => { + if cur.len() > 1 { + subs.push(std::mem::take(&mut cur)); + } + } + } + } + if cur.len() > 1 { + subs.push(cur); + } + let color = col(p.color); + for sub in subs.iter().filter(|v| v.len() <= 4000) { + if p.fill && sub.len() >= 3 { + // The PDF fill rule handles concave outlines itself. + pg.polygon(sub, Some(color), None); + } else { + pg.polyline(sub, (0.05 * s).clamp(0.2, 1.0), color, &[]); + } + } + } + } + } +} diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 60ffa102bb..a6f66b41b6 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -2,10 +2,33 @@ //! tools, Get Data, scripts (Automate), cell checkboxes, theme colours and fonts. use gridcraft_core::{CellRef, RangeRef, Value}; -use gridcraft_model::*; +use gridcraft_model::{ + Anchor, Chart, Color, DefinedName, HAlign, LegendPos, NumFmt, Shape, ShapeKind, Sheet, SheetViewMode, TableColumn, TotalsFn, Trendline, + TrendlineKind, Workbook, +}; use serde_json::{Value as Json, json}; -use super::*; +use super::{ + CommandSpec, EngineError, Result, Session, always, anchor_mode_name, bad, bool_param, cell_param, cell_param_on, cmd, edit, f64_param, has_doc, + ok, split_sheet, str_param, target_range, target_ranges, target_sheet, u32_param, +}; + +mod cells; +mod chart; +mod data; +mod objects; +mod scripts; +mod window; + +pub(crate) use cells::is_checkbox_cell; +use cells::{background, checkbox, draw_border, new_cell_style, recently_used, theme_colors, theme_fonts, toggle_checkbox, use_in_formula}; +use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data}; +use data::{from_csv, from_table_range, queries, table_resize}; +use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}; +pub(crate) use scripts::has_scripts; +use scripts::{all_scripts, delete_script, new_script, record, run_script, stop_action, trust_scripts}; +use window::{arrange_all, custom_views, hide_window, new_window, ruler, set_view, split, switch_windows, unhide_window, watch_window}; +pub(crate) use window::{keep_view_modes, keep_watch_list, window_param}; pub fn specs() -> Vec { vec![ @@ -15,7 +38,7 @@ pub fn specs() -> Vec { "Add Chart Element", ["Chart Design", "Chart Layouts"], None, - "{chart?, element: title|legend|dataLabels|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}", + "{chart?, element: title|legend|dataLabels|dataTable|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; dataTable: dataTableKeys?: bool, dataTableHorizontalBorder?: bool, dataTableVerticalBorder?: bool, dataTableOutline?: bool; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}", has_doc, add_element ), @@ -74,7 +97,7 @@ pub fn specs() -> Vec { "Bring Forward", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, id, toFront?: bool}", + "{kind: chart|image|shape|slicer|equation, id, toFront?: bool}", has_doc, |s, p| arrange(s, p, true) ), @@ -83,7 +106,7 @@ pub fn specs() -> Vec { "Send Backward", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, id, toBack?: bool}", + "{kind: chart|image|shape|slicer|equation, id, toBack?: bool}", has_doc, |s, p| arrange(s, p, false) ), @@ -93,7 +116,7 @@ pub fn specs() -> Vec { "Align", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, ids: [..], align: left|center|right|top|middle|bottom}", + "{kind: chart|image|shape|slicer|equation, ids: [..], align: left|center|right|top|middle|bottom}", has_doc, align ), @@ -287,7 +310,7 @@ pub fn specs() -> Vec { new_cell_style ), cmd!(query "home.addIns", "Add-ins", ["Home", "Add-ins"], None, "{} → GridCraft extends through MCP and scripts instead of add-ins", always, |_, _| Ok(json!({"addIns": [], "hint": "Use gridcraft-cli mcp or Automate › scripts"}))), - cmd!(query "formulas.recentlyUsed", "Recently Used", ["Formulas", "Function Library"], None, "{} → recently used functions in this workbook", has_doc, recently_used), + cmd!(query "formulas.recentlyUsed", "Recently Used", ["Formulas", "Function Library"], None, "{} → the functions most recently entered in formulas, newest first", has_doc, recently_used), cmd!(query "formulas.financial", "Financial", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Financial"}))), cmd!(query "formulas.logical", "Logical", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Logical"}))), cmd!(query "formulas.text", "Text", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Text"}))), @@ -308,430 +331,6 @@ pub fn specs() -> Vec { ] } -fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> { - let d = s.doc()?; - let si = d.wb.active_sheet(); - let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?; - let idx = match u32_param(p, "chart") { - Some(id) => sh.charts.iter().position(|c| c.id == id), - None => sh.charts.len().checked_sub(1), - }; - idx.map(|i| (si, i)).ok_or_else(|| bad("chart", "no chart on this sheet")) -} - -fn with_chart(s: &mut Session, p: &Json, f: impl FnOnce(&mut Chart) -> Result<()>) -> Result { - let (si, ci) = find_chart(s, p)?; - edit(s, |cx| { - let c = cx.sheet_mut(si)?.charts.get_mut(ci).ok_or_else(|| bad("chart", "no such chart"))?; - f(c)?; - Ok(json!({"chart": c.id})) - }) -} - -fn add_element(s: &mut Session, p: &Json) -> Result { - let el = str_param(p, "element").unwrap_or("title").to_string(); - let on = bool_param(p, "on").unwrap_or(true); - let pos = str_param(p, "position").map(str::to_string); - with_chart(s, p, |c| { - match el.as_str() { - "title" => c.title = if on { c.title.clone().filter(|t| !t.is_empty()).or(Some("Chart Title".into())) } else { Some(String::new()) }, - "legend" => { - c.legend = if !on { - LegendPos::None - } else { - match pos.as_deref() { - Some("top") => LegendPos::Top, - Some("left") => LegendPos::Left, - Some("right") => LegendPos::Right, - _ => LegendPos::Bottom, - } - } - } - "dataLabels" => c.data_labels = on, - "gridlines" => c.gridlines = on, - "axisTitles" => { - c.x_title = on.then(|| c.x_title.clone().unwrap_or_else(|| "Axis Title".into())); - c.y_title = on.then(|| c.y_title.clone().unwrap_or_else(|| "Axis Title".into())); - } - "smooth" => { - for s in &mut c.series { - s.smooth = on; - } - } - "trendline" => { - let only = u32_param(p, "series").map(|i| i as usize); - if only.is_some_and(|i| i >= c.series.len()) { - return Err(bad("chart.addElement", "no such series")); - } - let targets: Vec = (0..c.series.len()).filter(|i| only.is_none_or(|o| o == *i)).collect(); - if !on { - for i in targets { - if let Some(se) = c.series.get_mut(i) { - se.trendlines.clear(); - } - } - return Ok(()); - } - let t = trendline_param(p)?; - let eligible: Vec = - targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect(); - if eligible.is_empty() { - return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series")); - } - for i in eligible { - if let Some(se) = c.series.get_mut(i) { - se.trendlines.push(t.clone()); - } - } - } - other => return Err(bad("chart.addElement", format!("unknown element `{other}`"))), - } - Ok(()) - }) -} - -/// The trendline described by `chart.addElement`'s trendline parameters (Excel's Add Chart -/// Element ▸ Trendline choices, plus the Format Trendline options). -fn trendline_param(p: &Json) -> Result { - let num = |k: &str| Trendline::clamp_forecast(f64_param(p, k).unwrap_or(0.0)); - let mut t = Trendline { - forward: num("forward"), - backward: num("backward"), - display_equation: bool_param(p, "displayEquation").unwrap_or(false), - display_r_squared: bool_param(p, "displayRSquared").unwrap_or(false), - ..Trendline::default() - }; - t.kind = match str_param(p, "type").unwrap_or("linear") { - "linear" => TrendlineKind::Linear, - // Excel's Linear Forecast: a linear trendline projected two periods ahead. - "linearForecast" => { - if t.forward == 0.0 { - t.forward = 2.0; - } - TrendlineKind::Linear - } - "exponential" => TrendlineKind::Exponential, - "logarithmic" => TrendlineKind::Logarithmic, - "power" => TrendlineKind::Power, - "polynomial" => TrendlineKind::Polynomial(u32_param(p, "order").unwrap_or(2).clamp(2, 6) as u8), - "movingAverage" => TrendlineKind::MovingAverage(u32_param(p, "period").unwrap_or(2).clamp(2, 255)), - other => return Err(bad("chart.addElement", format!("unknown trendline type `{other}`"))), - }; - Ok(t) -} - -fn quick_layout(s: &mut Session, p: &Json) -> Result { - let n = u32_param(p, "layout").unwrap_or(1); - with_chart(s, p, |c| { - let (legend, labels, grid, axes) = match n { - 2 => (LegendPos::Top, true, false, false), - 3 => (LegendPos::Bottom, false, true, false), - 4 => (LegendPos::Bottom, true, false, false), - 5 => (LegendPos::None, false, true, true), - 6 => (LegendPos::Right, false, true, true), - _ => (LegendPos::Right, false, true, false), - }; - c.legend = legend; - c.data_labels = labels; - c.gridlines = grid; - if axes { - c.x_title.get_or_insert_with(|| "Axis Title".into()); - c.y_title.get_or_insert_with(|| "Axis Title".into()); - } else { - c.x_title = None; - c.y_title = None; - } - Ok(()) - }) -} - -fn change_colors(s: &mut Session, p: &Json) -> Result { - let explicit: Option> = - p.get("colors").and_then(Json::as_array).map(|a| a.iter().filter_map(|c| c.as_str().and_then(Color::from_hex)).collect()); - let palette = str_param(p, "palette").unwrap_or("colorful").to_string(); - with_chart(s, p, |c| { - for (i, se) in c.series.iter_mut().enumerate() { - se.color = match &explicit { - Some(cols) if !cols.is_empty() => cols.get(i % cols.len()).copied(), - _ => match palette.as_str() { - "monochrome" => Some(Color::Theme(4, (-400 + (i as i16 * 200)).clamp(-800, 800))), - p if p.starts_with("accent") => { - let k: u8 = p.trim_start_matches("accent").parse().unwrap_or(1); - Some(Color::Theme(3 + k.clamp(1, 6), (-500 + i as i16 * 250).clamp(-800, 800))) - } - _ => None, - }, - }; - } - Ok(()) - }) -} - -fn select_data(s: &mut Session, p: &Json) -> Result { - let d = s.doc()?; - // A new data range rebuilds the series, as in Excel's Select Data › Chart data range. - let rebuilt = match str_param(p, "range") { - Some(range) => { - let range = range.trim_start_matches('='); - let (sheet_name, body) = split_sheet(range); - let src_si = match sheet_name { - Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?, - None => d.wb.active_sheet(), - }; - let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?; - if r.count() > 1_000_000 { - return Err(bad("chart.selectData", "range too large for a chart")); - } - let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?; - let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1); - let series = super::insert::series_from_range(src, r, by_rows); - Some((series, format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1()), by_rows)) - } - None => None, - }; - // Horizontal (Category) Axis Labels › Edit: one labels range for every series ("" clears). - let categories = match str_param(p, "categories") { - None => None, - Some(t) if t.trim().trim_start_matches('=').is_empty() => Some(None), - Some(t) => { - let t = t.trim().trim_start_matches('='); - let (sheet_name, body) = split_sheet(t); - let si = match sheet_name { - Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?, - None => d.wb.active_sheet(), - }; - let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "`categories` is not a range"))?; - let name = d.wb.sheet(si).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?; - let abs = |c: CellRef| format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1); - Some(Some(format!("{}!{}:{}", gridcraft_formula::quote_sheet(&name), abs(r.start), abs(r.end)))) - } - }; - let mut remove: Vec = p - .get("removeSeries") - .and_then(Json::as_array) - .map(|a| a.iter().filter_map(Json::as_u64).filter_map(|i| usize::try_from(i).ok()).collect()) - .unwrap_or_default(); - remove.sort_unstable(); - remove.dedup(); - if rebuilt.is_none() && categories.is_none() && remove.is_empty() { - return Err(bad("chart.selectData", "missing `range`, `categories` or `removeSeries`")); - } - with_chart(s, p, move |c| { - if let Some((series, source, by_rows)) = rebuilt { - c.series = series; - super::insert::scatter_x_from_first(c.kind, &mut c.series); - c.source = Some(source); - c.by_rows = by_rows; - } - for i in remove.iter().rev() { - if *i < c.series.len() && c.series.len() > 1 { - c.series.remove(*i); - } - } - if let Some(cats) = categories { - for se in &mut c.series { - se.categories = cats.clone(); - } - } - Ok(()) - }) -} - -fn move_chart(s: &mut Session, p: &Json) -> Result { - let (si, ci) = find_chart(s, p)?; - let target = match p.get("sheet").and_then(Json::as_str) { - Some(n) => Some(s.doc()?.wb.sheet_index(n).ok_or_else(|| bad("chart.move", "no such sheet"))?), - None => None, - }; - let at = cell_param_on(s, p, "at", target.unwrap_or(si))?; - edit(s, |cx| { - let mut chart = cx.sheet_mut(si)?.charts.remove(ci); - if let Some(a) = at { - chart.anchor.cell = a; - } - let dest = target.unwrap_or(si); - cx.sheet_mut(dest)?.charts.push(chart); - Ok(Json::Null) - }) -} - -fn format_series(s: &mut Session, p: &Json) -> Result { - let idx = u32_param(p, "series").unwrap_or(0) as usize; - let color = str_param(p, "color").and_then(Color::from_hex); - with_chart(s, p, |c| { - if let Some(se) = c.series.get_mut(idx) { - se.color = color; - } - Ok(()) - }) -} - -fn shape_fill(s: &mut Session, p: &Json) -> Result { - if str_param(p, "kind") == Some("shape") { - let color = str_param(p, "color").and_then(Color::from_hex).unwrap_or_default(); - return with_shape(s, p, |sh| sh.fill = color); - } - format_series(s, p) -} - -fn shape_outline(s: &mut Session, p: &Json) -> Result { - let color = str_param(p, "color").and_then(Color::from_hex).unwrap_or_default(); - with_shape(s, p, |sh| sh.line = color) -} - -fn with_shape(s: &mut Session, p: &Json, f: impl FnOnce(&mut Shape)) -> Result { - let si = s.doc()?.wb.active_sheet(); - let id = u32_param(p, "id"); - edit(s, |cx| { - let shapes = &mut cx.sheet_mut(si)?.shapes; - let sh = match id { - Some(id) => shapes.iter_mut().find(|x| x.id == id), - None => shapes.last_mut(), - } - .ok_or_else(|| bad("shape", "no such shape"))?; - f(sh); - Ok(Json::Null) - }) -} - -fn arrange(s: &mut Session, p: &Json, forward: bool) -> Result { - let id = u32_param(p, "id").ok_or_else(|| bad("arrange", "missing `id`"))?; - let kind = str_param(p, "kind").unwrap_or("shape").to_string(); - let extreme = bool_param(p, "toFront").or(bool_param(p, "toBack")).unwrap_or(false); - let si = s.doc()?.wb.active_sheet(); - fn reorder(v: &mut Vec, i: usize, forward: bool, extreme: bool) { - if i >= v.len() { - return; - } - let item = v.remove(i); - let j = match (forward, extreme) { - (true, true) => v.len(), - (false, true) => 0, - (true, false) => (i + 1).min(v.len()), - (false, false) => i.saturating_sub(1), - }; - v.insert(j, item); - } - edit(s, |cx| { - let sh = cx.sheet_mut(si)?; - match kind.as_str() { - "chart" => { - if let Some(i) = sh.charts.iter().position(|c| c.id == id) { - reorder(&mut sh.charts, i, forward, extreme); - } - } - "image" => { - if let Some(i) = sh.images.iter().position(|c| c.id == id) { - reorder(&mut sh.images, i, forward, extreme); - } - } - _ => { - if let Some(i) = sh.shapes.iter().position(|c| c.id == id) { - reorder(&mut sh.shapes, i, forward, extreme); - } - } - } - Ok(Json::Null) - }) -} - -fn selection_pane(s: &mut Session, _: &Json) -> Result { - let d = s.doc()?; - let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let mut v = Vec::new(); - for c in &sh.shapes { - v.push(json!({"kind": "shape", "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); - } - for c in &sh.images { - v.push(json!({"kind": "image", "id": c.id, "name": format!("Picture {}", c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); - } - for c in &sh.charts { - v.push(json!({"kind": "chart", "id": c.id, "name": format!("Chart {}", c.id), "title": c.title, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); - } - Ok(Json::Array(v)) -} - -fn anchors_of<'a>(sh: &'a mut Sheet, kind: &str) -> Vec<(u32, &'a mut Anchor)> { - match kind { - "chart" => sh.charts.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), - "image" => sh.images.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), - _ => sh.shapes.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), - } -} - -fn align(s: &mut Session, p: &Json) -> Result { - let kind = str_param(p, "kind").unwrap_or("shape").to_string(); - let ids: Vec = - p.get("ids").and_then(Json::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()).unwrap_or_default(); - let how = str_param(p, "align").unwrap_or("left").to_string(); - let si = s.doc()?.wb.active_sheet(); - edit(s, |cx| { - let sheet = cx.sheet_mut(si)?; - let geo: Vec<(u32, f64, f64, f32, f32)> = { - let shc = sheet.clone(); - anchors_of(sheet, &kind) - .into_iter() - .filter(|(id, _)| ids.contains(id)) - .map(|(id, a)| (id, shc.col_left(a.cell.col) + a.dx as f64, shc.row_top(a.cell.row) + a.dy as f64, a.width, a.height)) - .collect() - }; - if geo.len() < 2 { - return Ok(Json::Null); - } - let left = geo.iter().map(|g| g.1).fold(f64::INFINITY, f64::min); - let right = geo.iter().map(|g| g.1 + g.3 as f64).fold(f64::NEG_INFINITY, f64::max); - let top = geo.iter().map(|g| g.2).fold(f64::INFINITY, f64::min); - let bottom = geo.iter().map(|g| g.2 + g.4 as f64).fold(f64::NEG_INFINITY, f64::max); - let shc = sheet.clone(); - for (id, a) in anchors_of(sheet, &kind) { - let Some(g) = geo.iter().find(|g| g.0 == id) else { continue }; - let (mut x, mut y) = (g.1, g.2); - match how.as_str() { - "left" => x = left, - "right" => x = right - g.3 as f64, - "center" => x = (left + right) / 2.0 - g.3 as f64 / 2.0, - "top" => y = top, - "bottom" => y = bottom - g.4 as f64, - _ => y = (top + bottom) / 2.0 - g.4 as f64 / 2.0, - } - let c = CellRef::new(shc.row_at(y), shc.col_at(x)); - a.cell = c; - a.dx = (x - shc.col_left(c.col)) as f32; - a.dy = (y - shc.row_top(c.row)) as f32; - } - Ok(Json::Null) - }) -} - -fn rotate(s: &mut Session, p: &Json) -> Result { - if p.get("flip").is_some_and(|f| !f.is_null()) { - return Err(bad("arrange.rotate", "`flip` is not supported: shapes have no flip state")); - } - with_shape(s, p, |sh| std::mem::swap(&mut sh.anchor.width, &mut sh.anchor.height)) -} - -/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it -/// neither records an undo step nor marks a clean workbook as changed. -fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result { - let si = target_sheet(s, p)?; - let d = s.doc_mut()?; - let dirty = d.is_dirty(); - let wb = std::sync::Arc::make_mut(&mut d.wb); - if let Some(sh) = wb.sheet_mut(si) { - sh.view = mode; - } - if !dirty { - d.saved = d.wb.clone(); - } - Ok(json!({"view": mode.as_str()})) -} - -fn ruler(s: &mut Session, p: &Json) -> Result { - let on = bool_param(p, "on").unwrap_or(s.hide_ruler); - s.hide_ruler = !on; - Ok(json!({"on": on})) -} - const VIEWS_NAME: &str = "_sc_custom_views"; const SCRIPTS_NAME: &str = "_sc_scripts"; const WATCH_NAME: &str = "_sc_watch"; @@ -759,592 +358,10 @@ fn stash_set(wb: &mut Workbook, key: &str, v: &Json) { wb.names.push(DefinedName { name: key.into(), scope: None, formula, comment: String::new(), hidden: true }); } -/// The Watch Window list isn't an edit (Excel doesn't undo it): undo and redo keep the current -/// list when they swap in another snapshot of the workbook. -pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc) { - let find = |wb: &Workbook| wb.names.iter().find(|n| n.name == WATCH_NAME).cloned(); - let keep = find(from); - if keep == find(to) { - return; - } - let wb = std::sync::Arc::make_mut(to); - wb.names.retain(|n| n.name != WATCH_NAME); - wb.names.extend(keep); -} - -fn custom_views(s: &mut Session, p: &Json) -> Result { - let d = s.doc()?; - let mut views = stash_map(&d.wb, VIEWS_NAME); - if let Some(name) = str_param(p, "save") { - let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - views[name] = json!({"sheet": d.wb.active_sheet(), "selection": d.selection.a1(), "zoom": sh.zoom, "freeze": sh.freeze}); - let v = views.clone(); - edit(s, |cx| { - stash_set(&mut cx.wb, VIEWS_NAME, &v); - Ok(()) - })?; - } else if let Some(name) = str_param(p, "show") { - let v = views.get(name).cloned().ok_or_else(|| bad("view.customViews", "no such view"))?; - if let Some(si) = v["sheet"].as_u64() { - s.execute("sheet.activate", json!({"sheet": si}))?; - } - if let Some(sel) = v["selection"].as_str() { - s.execute("selection.set", json!({"range": sel}))?; - } - if let Some(z) = v["zoom"].as_u64() { - s.execute("view.zoom", json!({"percent": z}))?; - } - if let Some(f) = v.get("freeze") { - let freeze = match (f[0].as_u64(), f[1].as_u64()) { - (Some(r), Some(c)) => u32::try_from(r).ok().zip(u32::try_from(c).ok()), - _ => None, - }; - edit(s, |cx| { - let si = cx.sheet_index(); - cx.sheet_mut(si)?.freeze = freeze; - Ok(()) - })?; - } - } else if let Some(name) = str_param(p, "delete") { - if let Some(o) = views.as_object_mut() { - o.remove(name); - } - let v = views.clone(); - edit(s, |cx| { - stash_set(&mut cx.wb, VIEWS_NAME, &v); - Ok(()) - })?; - } - Ok(stash_get(&s.doc()?.wb, VIEWS_NAME)) -} - -fn split(s: &mut Session, _: &Json) -> Result { - let has = s.doc()?.wb.active().is_some_and(|sh| sh.freeze.is_some()); - if has { s.execute("view.unfreezePanes", json!({})) } else { s.execute("view.freezePanes", json!({})) } -} - -fn new_window(s: &mut Session, _: &Json) -> Result { - let id = s.new_window()?; - let doc = s.window(id).map(|w| w.doc_uid); - Ok(json!({"window": id, "doc": doc, "title": s.window_title(id)})) -} - -/// The window a window command names: `window` (an id), else `doc` (a workbook id: its most -/// recent window), else the active window. -pub(crate) fn window_param(s: &Session, cmd: &str, p: &Json) -> Result { - let t = crate::Target::from_json(p).map_err(|e| bad(cmd, e.to_string()))?; - s.target_window(t).map_err(|e| bad(cmd, e.to_string())) -} - -/// View › Arrange All. The engine has no window geometry: it picks the windows and the layout, -/// and the interface moves its native windows ([`Session::window_list`] order, active first). -fn arrange_all(s: &mut Session, p: &Json) -> Result { - let arrange = match str_param(p, "arrange").unwrap_or("tiled") { - a @ ("tiled" | "horizontal" | "vertical" | "cascade") => a, - other => return Err(bad("view.arrangeAll", format!("`arrange` must be tiled, horizontal, vertical or cascade, not `{other}`"))), - }; - let active = s.active_window(); - let doc = active.and_then(|w| s.window(w)).map(|w| w.doc_uid); - let only_active = p.get("activeWorkbook").and_then(Json::as_bool).unwrap_or(false); - let mut windows: Vec = s.windows().iter().filter(|w| !w.hidden && (!only_active || Some(w.doc_uid) == doc)).map(|w| w.id).collect(); - if let Some(at) = windows.iter().position(|w| Some(*w) == active) - && let Some(first) = windows.get_mut(..=at) - { - first.rotate_right(1); - } - Ok(json!({"arrange": arrange, "windows": windows})) -} - -fn hide_window(s: &mut Session, p: &Json) -> Result { - let id = window_param(s, "view.hideWindow", p)?; - s.hide_window(id); - ok() -} - -fn unhide_window(s: &mut Session, p: &Json) -> Result { - let id = if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) { - Some(window_param(s, "view.unhideWindow", p)?) - } else if let Some(i) = u32_param(p, "index") { - // A workbook's position in the document list. - let uid = s.documents().get(i as usize).map(|d| d.uid).ok_or_else(|| bad("view.unhideWindow", "no such window"))?; - s.windows().iter().filter(|w| w.doc_uid == uid && w.hidden).map(|w| w.id).next_back().or_else(|| s.doc_window(uid)) - } else { - s.last_hidden_window() - }; - if let Some(id) = id { - s.unhide_window(id); - } - ok() -} - -fn switch_windows(s: &mut Session, p: &Json) -> Result { - if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) { - let id = window_param(s, "view.switchWindows", p)?; - s.unhide_window(id); - } - Ok(s.window_list()) -} - -fn table_resize(s: &mut Session, p: &Json) -> Result { - let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?; - let d = s.doc()?; - let si = d.wb.active_sheet(); - let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?; - let ti = match str_param(p, "table") { - Some(n) => sh.tables.iter().position(|t| t.name.eq_ignore_ascii_case(n)), - None => sh.tables.iter().position(|t| t.range.contains(d.selection.active)), - } - .ok_or_else(|| bad("table.resize", "select a cell in a table"))?; - edit(s, |cx| { - let sheet = cx.sheet_mut(si)?; - let headers: Vec = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect(); - if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) { - return Err(EngineError::Other("A table can't overlap another table.".into())); - } - let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; - if r.start.row != t.range.start.row || !r.intersects(&t.range) { - return Err(EngineError::Other( - "The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(), - )); - } - let mut cols = Vec::new(); - for (i, h) in headers.iter().enumerate() { - let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() }; - let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned(); - cols.push(existing.unwrap_or(TableColumn { - name, - totals: TotalsFn::None, - totals_label: None, - formula: None, - unique_name: None, - xml: None, - })); - } - t.columns = cols; - t.range = r; - cx.structural = true; - Ok(Json::Null) - }) -} - -fn from_csv(s: &mut Session, p: &Json) -> Result { - let bytes = if let Some(t) = str_param(p, "text") { - t.as_bytes().to_vec() - } else if let Some(path) = str_param(p, "path") { - crate::io::read_file(path)? - } else { - s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({}))); - return ok(); - }; - let text = String::from_utf8_lossy(&bytes); - // JSON array of objects → rows. - let rows: Vec> = - if text.trim_start().starts_with('[') { - let arr: Vec = serde_json::from_str(&text).map_err(|e| bad("data.getData", e.to_string()))?; - let mut keys: Vec = Vec::new(); - for o in &arr { - if let Some(m) = o.as_object() { - for k in m.keys() { - if !keys.contains(k) { - keys.push(k.clone()); - } - } - } - } - let mut out = vec![keys.iter().map(|k| json!(k)).collect::>()]; - for o in &arr { - out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect()); - } - out - } else { - let delim = str_param(p, "delimiter") - .and_then(|d| d.chars().next()) - .unwrap_or(if text.lines().next().is_some_and(|l| l.contains('\t')) { '\t' } else { ',' }); - let opts = gridcraft_xlsx::CsvOptions { delimiter: delim as u8, ..Default::default() }; - let wb = gridcraft_xlsx::read_csv(&bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?; - let sh = wb.sheet(0).ok_or(EngineError::NoDocument)?; - let Some(u) = sh.used_range() else { return Err(EngineError::Other("The file is empty.".into())) }; - (u.start.row..=u.end.row) - .map(|r| { - (u.start.col..=u.end.col) - .map(|c| match sh.value(CellRef::new(r, c)) { - Value::Number(n) => json!(n), - Value::Bool(b) => json!(b), - Value::Empty => Json::Null, - v => json!(v.display()), - }) - .collect() - }) - .collect() - }; - if rows.is_empty() || rows.len() > 1_048_576 { - return Err(EngineError::Other("Nothing to import.".into())); - } - let name = str_param(p, "sheet").map(str::to_string).or_else(|| { - str_param(p, "path").and_then(|x| std::path::Path::new(x).file_stem().and_then(std::ffi::OsStr::to_str).map(|f| f.chars().take(31).collect())) - }); - let r = s.execute("home.insertSheet", json!({"name": name})).or_else(|_| s.execute("home.insertSheet", json!({})))?; - let w = rows.iter().map(Vec::len).max().unwrap_or(1).max(1); - s.execute("range.setValues", json!({"range": "A1", "values": rows}))?; - let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.len() as u32 - 1, w as u32 - 1)); - let _ = s.execute("insert.table", json!({"range": range.a1(), "header": true})); - let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, w as u32 - 1).a1()})); - Ok(json!({"sheet": r["name"], "rows": rows.len(), "cols": w})) -} - -fn from_table_range(s: &mut Session, p: &Json) -> Result { - let r = target_range(s, p)?; - let d = s.doc()?; - let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let r = if r.is_single() { crate::selection::current_region(sh, r.start) } else { r }; - let text = crate::display::range_text(&d.wb, d.wb.active_sheet(), r); - from_csv(s, &json!({"text": text, "delimiter": "\t", "sheet": format!("{} (2)", sh.name).chars().take(31).collect::()})) -} - -fn queries(s: &mut Session, _: &Json) -> Result { - let d = s.doc()?; - Ok(Json::Array( - d.wb.sheets - .iter() - .flat_map(|sh| { - sh.tables - .iter() - .map(move |t| json!({"name": t.name, "sheet": sh.name, "range": t.range.a1(), "rows": t.range.height().saturating_sub(1)})) - }) - .collect(), - )) -} - -fn record(s: &mut Session, p: &Json) -> Result { - if bool_param(p, "stop").unwrap_or(false) || s.recording.is_some() { - let Some(start) = s.recording.take() else { return Ok(json!({"recording": false})) }; - let cmds: Vec = - s.journal.iter().skip(start).filter(|(id, _)| !id.starts_with("automate.")).map(|(id, p)| json!({"command": id, "params": p})).collect(); - let name = str_param(p, "name").map(str::to_string).unwrap_or_else(|| format!("Script {}", start)); - s.execute("automate.newScript", json!({"name": name, "commands": cmds}))?; - return Ok(json!({"recording": false, "saved": name, "steps": cmds.len()})); - } - s.recording = Some(s.journal.len()); - Ok(json!({"recording": true})) -} - -fn new_script(s: &mut Session, p: &Json) -> Result { - let name = str_param(p, "name").ok_or_else(|| bad("automate.newScript", "missing `name`"))?.to_string(); - let cmds = p.get("commands").cloned().unwrap_or(json!([])); - if !cmds.is_array() { - return Err(bad("automate.newScript", "`commands` must be an array")); - } - edit(s, |cx| { - let mut all = stash_map(&cx.wb, SCRIPTS_NAME); - all[name.as_str()] = cmds.clone(); - stash_set(&mut cx.wb, SCRIPTS_NAME, &all); - Ok(json!({"name": name})) - }) -} - -fn all_scripts(s: &mut Session, _: &Json) -> Result { - let d = s.doc()?; - let (wb, trusted) = (&d.wb, d.scripts_trusted); - let all = stash_get(wb, SCRIPTS_NAME); - let mut list: Vec = all - .as_object() - .map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len), "trusted": trusted})).collect()) - .unwrap_or_default(); - // A preserved VBA project is reported alongside GridCraft's own scripts; it is carried on - // save but never executed here, so it has no step count. - if let Some(bytes) = &wb.vba_project { - list.push(json!({"name": "(VBA)", "steps": 0, "kind": "vba", "size": bytes.len(), "executed": false})); - } - Ok(Json::Array(list)) -} - -/// Whether `wb` carries GridCraft scripts (a workbook opened with them starts untrusted). -pub(crate) fn has_scripts(wb: &Workbook) -> bool { - stash_map(wb, SCRIPTS_NAME).as_object().is_some_and(|o| !o.is_empty()) -} - -/// Why a script step is refused, whatever the workbook's trust: scripts stay inside the -/// workbook. Anything that reads or writes files (`file.*`, or any `path` parameter: Get Data, -/// From Text/CSV, Insert Picture) or leaves the app (`link.*` opens URLs) is the caller's to run -/// directly, not a stored script's. (Nested `automate.*` steps are skipped.) This check goes by -/// command id and parameter name, so it is only the up-front refusal: the steps also run inside -/// an [`crate::io::ScriptSandbox`] (file access refused whatever the parameter is called) and -/// [`run_script`] drops any `OpenUrl` request a step raises. -fn denied_script_step(id: &str, params: &Json) -> Option { - if id.starts_with("file.") || id.starts_with("link.") { - return Some(format!("scripts can't run `{id}`: it reaches outside the workbook")); - } - // Scripts are scoped to their workbook: a step that switches the active window would - // point every later step at another open document, so those are refused too. - if id.starts_with("window.") || matches!(id, "view.switchWindows" | "view.newWindow" | "view.hideWindow" | "view.unhideWindow") { - return Some(format!("scripts can't run `{id}`: it reaches outside the workbook")); - } - if params.get("path").is_some() { - return Some(format!("scripts can't pass a file `path` to `{id}`")); - } - None -} - -fn trust_scripts(s: &mut Session, p: &Json) -> Result { - // Only a missing `trusted` means "trust"; `"false"`, `0` or `null` are mistakes, not consent. - let trusted = match p.get("trusted") { - None => true, - Some(Json::Bool(b)) => *b, - Some(_) => return Err(bad("automate.trustScripts", "`trusted` must be true or false")), - }; - s.doc_mut()?.scripts_trusted = trusted; - Ok(json!({"trusted": trusted})) -} - -/// Runs a stored script. Scripts in a workbook opened from a file run only once the workbook is -/// trusted for this session (`automate.trustScripts`, or `trusted: true` on this call); steps that -/// reach outside the workbook ([`denied_script_step`]) are refused before any step runs. -fn run_script(s: &mut Session, p: &Json) -> Result { - let name = str_param(p, "name").ok_or_else(|| bad("automate.runScript", "missing `name`"))?; - let d = s.doc()?; - let all = stash_get(&d.wb, SCRIPTS_NAME); - let steps = all.get(name).and_then(Json::as_array).cloned().ok_or_else(|| bad("automate.runScript", "no such script"))?; - if !d.scripts_trusted && !bool_param(p, "trusted").unwrap_or(false) { - return Err(bad( - "automate.runScript", - "scripts in this workbook came from a file and are disabled; trust the workbook first (Trust Scripts in View › Macros, Alt+F8; `automate.trustScripts`; or `trusted: true`)", - )); - } - let steps: Vec = steps.into_iter().take(100_000).collect(); - for st in &steps { - let id = st["command"].as_str().unwrap_or(""); - if let Some(why) = denied_script_step(id, &st["params"]) { - return Err(bad("automate.runScript", why)); - } - } - let _sandbox = crate::io::ScriptSandbox::enter(); - let mut n = 0; - for st in &steps { - let id = st["command"].as_str().unwrap_or(""); - if id.starts_with("automate.") { - continue; - } - let before = s.ui_requests.len(); - let ran = s.execute(id, st["params"].clone()); - // A step that asks the host to open a URL leaves the app: drop the request and stop. - if s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::OpenUrl(_)))) { - let mut i = 0; - s.ui_requests.retain(|r| { - i += 1; - i <= before || !matches!(r, crate::UiRequest::OpenUrl(_)) - }); - return Err(bad("automate.runScript", format!("scripts can't open links (`{id}`)"))); - } - ran?; - n += 1; - } - Ok(json!({"ran": n})) -} - -/// Automate › Stop Action: rolls back the undo groups open on the active workbook, so Undo and -/// Redo work there again. -fn stop_action(s: &mut Session, _: &Json) -> Result { - let uid = s.doc()?.uid; - Ok(json!({"stopped": s.abort_groups(uid)})) -} - -fn delete_script(s: &mut Session, p: &Json) -> Result { - let name = str_param(p, "name").ok_or_else(|| bad("automate.deleteScript", "missing `name`"))?.to_string(); - edit(s, |cx| { - let mut all = stash_map(&cx.wb, SCRIPTS_NAME); - if let Some(o) = all.as_object_mut() { - o.remove(&name); - } - stash_set(&mut cx.wb, SCRIPTS_NAME, &all); - Ok(Json::Null) - }) -} - /// Number format that marks checkbox cells (TRUE/FALSE values drawn as boxes). pub const CHECKBOX_FORMAT: &str = "\"☐\";\"☐\";\"☐\";[=1]\"☑\""; -/// Whether `c` has checkbox formatting. -pub(crate) fn is_checkbox_cell(wb: &gridcraft_model::Workbook, sh: &gridcraft_model::Sheet, c: CellRef) -> bool { - wb.styles.get(sh.style_id(c)).num_fmt.as_str() == "checkbox" -} - -fn checkbox(s: &mut Session, p: &Json) -> Result { - let ranges = target_ranges(s, p)?; - let si = target_sheet(s, p)?; - edit(s, |cx| { - for r in &ranges { - if r.count() > 100_000 { - return Err(bad("insert.checkbox", "range too large")); - } - for c in r.iter() { - let st = cx.wb.sheet(si).map(|sh| sh.style_id(c)).unwrap_or_default(); - let new = cx.wb.styles.derive(st, |s| { - s.num_fmt = NumFmt::new("checkbox"); - s.align.h = HAlign::Center; - }); - let sh = cx.sheet_mut(si)?; - // Values and formulas already there stay (only TRUE/FALSE draw as a box); an empty - // cell starts unchecked. - let mut cell = sh.cell(c).cloned().unwrap_or_default(); - if cell.value.is_empty() && cell.formula.is_none() { - cell.value = Value::Bool(false); - } - cell.style = new; - sh.set_cell(c, cell); - cx.touch(si, c); - } - } - Ok(Json::Null) - }) -} - -fn toggle_checkbox(s: &mut Session, p: &Json) -> Result { - let si = target_sheet(s, p)?; - let d = s.doc()?; - let cells: Vec = match cell_param_on(s, p, "cell", si)? { - Some(c) => vec![c], - None => d.selection.ranges.iter().flat_map(|r| r.iter().take(100_000).collect::>()).collect(), - }; - edit(s, |cx| { - for c in cells { - let checkbox = cx.wb.sheet(si).is_some_and(|sh| is_checkbox_cell(&cx.wb, sh, c)); - let sh = cx.sheet_mut(si)?; - if let Some(cell) = sh.cells.get_mut(c) - && cell.formula.is_none() - { - // An empty checkbox cell counts as FALSE. - let next = match cell.value { - Value::Bool(b) if checkbox => Value::Bool(!b), - Value::Empty if checkbox => Value::Bool(true), - _ => continue, - }; - cell.value = next; - cx.changed.push((si, c)); - } - } - Ok(Json::Null) - }) -} - /// Copy of the params that is always a JSON object, so keys can be assigned; any other JSON value counts as no params (like null). fn object_params(p: &Json) -> Json { Json::Object(p.as_object().cloned().unwrap_or_default()) } - -fn theme_colors(s: &mut Session, p: &Json) -> Result { - let mut params = object_params(p); - if params.get("name").is_none() { - params["name"] = json!(s.doc()?.wb.theme.name.clone()); - } - s.execute("pageLayout.theme", params) -} - -fn theme_fonts(s: &mut Session, p: &Json) -> Result { - let name = s.doc()?.wb.theme.name.clone(); - let colors: Vec = s.doc()?.wb.theme.colors.iter().map(|c| format!("#{c:06X}")).collect(); - s.execute("pageLayout.theme", json!({"name": name, "colors": colors, "majorFont": p.get("major"), "minorFont": p.get("minor")})) -} - -fn background(s: &mut Session, p: &Json) -> Result { - if bool_param(p, "clear").unwrap_or(false) { - let si = s.doc()?.wb.active_sheet(); - return edit(s, |cx| { - cx.sheet_mut(si)?.images.retain(|i| i.alt != "Sheet background"); - Ok(Json::Null) - }); - } - let mut params = object_params(p); - params["alt"] = json!("Sheet background"); - params["at"] = json!("A1"); - s.execute("insert.picture", params) -} - -fn draw_border(s: &mut Session, p: &Json) -> Result { - let edge = str_param(p, "edge").unwrap_or("grid"); - let preset = match edge { - "top" => "top", - "bottom" => "bottom", - "left" => "left", - "right" => "right", - "outline" => "outside", - _ => "all", - }; - let mut params = object_params(p); - params["preset"] = json!(preset); - s.execute("home.borders", params) -} - -fn new_cell_style(s: &mut Session, p: &Json) -> Result { - let name = str_param(p, "name").ok_or_else(|| bad("home.newCellStyle", "missing `name`"))?.to_string(); - let d = s.doc()?; - let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let c = cell_param(s, p, "fromCell")?.unwrap_or(d.selection.active); - let style = d.wb.styles.get(sh.style_id(c)).clone(); - edit(s, |cx| { - cx.wb.cell_styles.retain(|(n, _)| !n.eq_ignore_ascii_case(&name)); - cx.wb.cell_styles.push((name.clone(), style.clone())); - Ok(json!({"name": name})) - }) -} - -fn recently_used(s: &mut Session, _: &Json) -> Result { - let mut seen: Vec = Vec::new(); - for (id, p) in s.journal.iter().rev() { - if id != "cell.set" { - continue; - } - let input = p.get("input").and_then(Json::as_str).unwrap_or(""); - if let Ok(e) = gridcraft_formula::parse(input.trim_start_matches('=')) { - for f in e.functions() { - if !seen.iter().any(|x| x == f) { - seen.push(f.to_string()); - } - } - } - if seen.len() >= 10 { - break; - } - } - Ok(json!(seen)) -} - -fn use_in_formula(s: &mut Session, p: &Json) -> Result { - let name = str_param(p, "name").ok_or_else(|| bad("formulas.useInFormula", "missing `name`"))?; - s.ui_requests.push(crate::UiRequest::InsertName(name.to_string())); - ok() -} - -fn watch_window(s: &mut Session, p: &Json) -> Result { - let mut list: Vec = - stash_get(&s.doc()?.wb, WATCH_NAME).as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(); - let mut changed = false; - if let Some(a) = str_param(p, "add") { - if !list.iter().any(|x| x == a) { - list.push(a.to_string()); - } - changed = true; - } - if let Some(r) = str_param(p, "remove") { - list.retain(|x| x != r); - changed = true; - } - if changed { - let v = json!(list.clone()); - let d = s.doc_mut()?; - // The watch list is view state: don't add an undo step. - let wb = std::sync::Arc::make_mut(&mut d.wb); - stash_set(wb, WATCH_NAME, &v); - } - let d = s.doc()?; - let rows: Vec = list - .iter() - .map(|w| { - let (sheet, body) = split_sheet(w); - let si = sheet.and_then(|n| d.wb.sheet_index(&n)).unwrap_or(d.wb.active_sheet()); - let c = CellRef::parse(body).unwrap_or_default(); - let sh = d.wb.sheet(si); - json!({"cell": w, "value": sh.map(|s| s.value(c).display()), "formula": sh.and_then(|s| s.cell(c)).and_then(|x| x.formula.as_ref()).map(|f| format!("={}", f.text))}) - }) - .collect(); - Ok(Json::Array(rows)) -} diff --git a/crates/engine/src/cmd/extra/cells.rs b/crates/engine/src/cmd/extra/cells.rs new file mode 100644 index 0000000000..838ce83422 --- /dev/null +++ b/crates/engine/src/cmd/extra/cells.rs @@ -0,0 +1,136 @@ +use super::{ + CellRef, EngineError, HAlign, Json, NumFmt, Result, Session, Value, bad, bool_param, cell_param, cell_param_on, edit, json, object_params, ok, + str_param, target_ranges, target_sheet, +}; + +/// Whether `c` has checkbox formatting. +pub(crate) fn is_checkbox_cell(wb: &gridcraft_model::Workbook, sh: &gridcraft_model::Sheet, c: CellRef) -> bool { + wb.styles.get(sh.style_id(c)).num_fmt.as_str() == "checkbox" +} + +pub(super) fn checkbox(s: &mut Session, p: &Json) -> Result { + let ranges = target_ranges(s, p)?; + let si = target_sheet(s, p)?; + edit(s, |cx| { + for r in &ranges { + if r.count() > 100_000 { + return Err(bad("insert.checkbox", "range too large")); + } + for c in r.iter() { + let st = cx.wb.sheet(si).map(|sh| sh.style_id(c)).unwrap_or_default(); + let new = cx.wb.styles.derive(st, |s| { + s.num_fmt = NumFmt::new("checkbox"); + s.align.h = HAlign::Center; + }); + let sh = cx.sheet_mut(si)?; + // Values and formulas already there stay (only TRUE/FALSE draw as a box); an empty + // cell starts unchecked. + let mut cell = sh.cell(c).cloned().unwrap_or_default(); + if cell.value.is_empty() && cell.formula.is_none() { + cell.value = Value::Bool(false); + } + cell.style = new; + sh.set_cell(c, cell); + cx.touch(si, c); + } + } + Ok(Json::Null) + }) +} + +pub(super) fn toggle_checkbox(s: &mut Session, p: &Json) -> Result { + let si = target_sheet(s, p)?; + let d = s.doc()?; + let cells: Vec = match cell_param_on(s, p, "cell", si)? { + Some(c) => vec![c], + None => d.selection.ranges.iter().flat_map(|r| r.iter().take(100_000).collect::>()).collect(), + }; + edit(s, |cx| { + for c in cells { + let checkbox = cx.wb.sheet(si).is_some_and(|sh| is_checkbox_cell(&cx.wb, sh, c)); + let sh = cx.sheet_mut(si)?; + if let Some(cell) = sh.cells.get_mut(c) + && cell.formula.is_none() + && cell.py.is_none() + { + // An empty checkbox cell counts as FALSE. + let next = match cell.value { + Value::Bool(b) if checkbox => Value::Bool(!b), + Value::Empty if checkbox => Value::Bool(true), + _ => continue, + }; + cell.value = next; + cx.changed.push((si, c)); + } + } + Ok(Json::Null) + }) +} + +pub(super) fn theme_colors(s: &mut Session, p: &Json) -> Result { + let mut params = object_params(p); + if params.get("name").is_none() { + params["name"] = json!(s.doc()?.wb.theme.name.clone()); + } + s.execute("pageLayout.theme", params) +} + +pub(super) fn theme_fonts(s: &mut Session, p: &Json) -> Result { + let name = s.doc()?.wb.theme.name.clone(); + let colors: Vec = s.doc()?.wb.theme.colors.iter().map(|c| format!("#{c:06X}")).collect(); + s.execute("pageLayout.theme", json!({"name": name, "colors": colors, "majorFont": p.get("major"), "minorFont": p.get("minor")})) +} + +pub(super) fn background(s: &mut Session, p: &Json) -> Result { + if bool_param(p, "clear").unwrap_or(false) { + let si = s.doc()?.wb.active_sheet(); + return edit(s, |cx| { + cx.sheet_mut(si)?.images.retain(|i| i.alt != "Sheet background"); + Ok(Json::Null) + }); + } + let mut params = object_params(p); + params["alt"] = json!("Sheet background"); + params["at"] = json!("A1"); + s.execute("insert.picture", params) +} + +pub(super) fn draw_border(s: &mut Session, p: &Json) -> Result { + let edge = str_param(p, "edge").unwrap_or("grid"); + let preset = match edge { + "top" => "top", + "bottom" => "bottom", + "left" => "left", + "right" => "right", + "outline" => "outside", + _ => "all", + }; + let mut params = object_params(p); + params["preset"] = json!(preset); + s.execute("home.borders", params) +} + +pub(super) fn new_cell_style(s: &mut Session, p: &Json) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("home.newCellStyle", "missing `name`"))?.to_string(); + let d = s.doc()?; + let sh = d.wb.active().ok_or(EngineError::NoDocument)?; + let c = cell_param(s, p, "fromCell")?.unwrap_or(d.selection.active); + let style = d.wb.styles.get(sh.style_id(c)).clone(); + edit(s, |cx| { + cx.wb.cell_styles.retain(|(n, _)| !n.eq_ignore_ascii_case(&name)); + cx.wb.cell_styles.push((name.clone(), style.clone())); + Ok(json!({"name": name})) + }) +} + +/// Formulas › Recently Used: the functions most recently entered in a formula, newest first +/// ([`crate::Prefs::recent_functions`]). +pub(super) fn recently_used(s: &mut Session, _: &Json) -> Result { + Ok(json!(s.prefs.recent_functions)) +} + +pub(super) fn use_in_formula(s: &mut Session, p: &Json) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("formulas.useInFormula", "missing `name`"))?; + s.ui_requests.push(crate::UiRequest::InsertName(name.to_string())); + ok() +} diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs new file mode 100644 index 0000000000..8d9af2064d --- /dev/null +++ b/crates/engine/src/cmd/extra/chart.rs @@ -0,0 +1,263 @@ +use super::{ + CellRef, Chart, Color, EngineError, Json, LegendPos, RangeRef, Result, Session, Trendline, TrendlineKind, bad, bool_param, cell_param_on, edit, + f64_param, json, split_sheet, str_param, u32_param, +}; + +fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> { + let d = s.doc()?; + let si = d.wb.active_sheet(); + let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?; + let idx = match u32_param(p, "chart") { + Some(id) => sh.charts.iter().position(|c| c.id == id), + None => sh.charts.len().checked_sub(1), + }; + idx.map(|i| (si, i)).ok_or_else(|| bad("chart", "no chart on this sheet")) +} + +fn with_chart(s: &mut Session, p: &Json, f: impl FnOnce(&mut Chart) -> Result<()>) -> Result { + let (si, ci) = find_chart(s, p)?; + edit(s, |cx| { + let c = cx.sheet_mut(si)?.charts.get_mut(ci).ok_or_else(|| bad("chart", "no such chart"))?; + f(c)?; + Ok(json!({"chart": c.id})) + }) +} + +pub(super) fn add_element(s: &mut Session, p: &Json) -> Result { + let el = str_param(p, "element").unwrap_or("title").to_string(); + let on = bool_param(p, "on").unwrap_or(true); + let pos = str_param(p, "position").map(str::to_string); + with_chart(s, p, |c| { + match el.as_str() { + "title" => c.title = if on { c.title.clone().filter(|t| !t.is_empty()).or(Some("Chart Title".into())) } else { Some(String::new()) }, + "legend" => { + c.legend = if !on { + LegendPos::None + } else { + match pos.as_deref() { + Some("top") => LegendPos::Top, + Some("left") => LegendPos::Left, + Some("right") => LegendPos::Right, + _ => LegendPos::Bottom, + } + } + } + "dataLabels" => c.data_labels = on, + "dataTable" => crate::cmd::insert::update_data_table(c, p, Some(on))?, + "gridlines" => c.gridlines = on, + "axisTitles" => { + c.x_title = on.then(|| c.x_title.clone().unwrap_or_else(|| "Axis Title".into())); + c.y_title = on.then(|| c.y_title.clone().unwrap_or_else(|| "Axis Title".into())); + } + "smooth" => { + for s in &mut c.series { + s.smooth = on; + } + } + "trendline" => { + let only = u32_param(p, "series").map(|i| i as usize); + if only.is_some_and(|i| i >= c.series.len()) { + return Err(bad("chart.addElement", "no such series")); + } + let targets: Vec = (0..c.series.len()).filter(|i| only.is_none_or(|o| o == *i)).collect(); + if !on { + for i in targets { + if let Some(se) = c.series.get_mut(i) { + se.trendlines.clear(); + } + } + return Ok(()); + } + let t = trendline_param(p)?; + let eligible: Vec = + targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect(); + if eligible.is_empty() { + return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series")); + } + for i in eligible { + if let Some(se) = c.series.get_mut(i) { + se.trendlines.push(t.clone()); + } + } + } + other => return Err(bad("chart.addElement", format!("unknown element `{other}`"))), + } + Ok(()) + }) +} + +/// The trendline described by `chart.addElement`'s trendline parameters (Excel's Add Chart +/// Element ▸ Trendline choices, plus the Format Trendline options). +fn trendline_param(p: &Json) -> Result { + let num = |k: &str| Trendline::clamp_forecast(f64_param(p, k).unwrap_or(0.0)); + let mut t = Trendline { + forward: num("forward"), + backward: num("backward"), + display_equation: bool_param(p, "displayEquation").unwrap_or(false), + display_r_squared: bool_param(p, "displayRSquared").unwrap_or(false), + ..Trendline::default() + }; + t.kind = match str_param(p, "type").unwrap_or("linear") { + "linear" => TrendlineKind::Linear, + // Excel's Linear Forecast: a linear trendline projected two periods ahead. + "linearForecast" => { + if t.forward == 0.0 { + t.forward = 2.0; + } + TrendlineKind::Linear + } + "exponential" => TrendlineKind::Exponential, + "logarithmic" => TrendlineKind::Logarithmic, + "power" => TrendlineKind::Power, + "polynomial" => TrendlineKind::Polynomial(u32_param(p, "order").unwrap_or(2).clamp(2, 6) as u8), + "movingAverage" => TrendlineKind::MovingAverage(u32_param(p, "period").unwrap_or(2).clamp(2, 255)), + other => return Err(bad("chart.addElement", format!("unknown trendline type `{other}`"))), + }; + Ok(t) +} + +pub(super) fn quick_layout(s: &mut Session, p: &Json) -> Result { + let n = u32_param(p, "layout").unwrap_or(1); + with_chart(s, p, |c| { + let (legend, labels, grid, axes) = match n { + 2 => (LegendPos::Top, true, false, false), + 3 => (LegendPos::Bottom, false, true, false), + 4 => (LegendPos::Bottom, true, false, false), + 5 => (LegendPos::None, false, true, true), + 6 => (LegendPos::Right, false, true, true), + _ => (LegendPos::Right, false, true, false), + }; + c.legend = legend; + c.data_labels = labels; + c.gridlines = grid; + if axes { + c.x_title.get_or_insert_with(|| "Axis Title".into()); + c.y_title.get_or_insert_with(|| "Axis Title".into()); + } else { + c.x_title = None; + c.y_title = None; + } + Ok(()) + }) +} + +pub(super) fn change_colors(s: &mut Session, p: &Json) -> Result { + let explicit: Option> = + p.get("colors").and_then(Json::as_array).map(|a| a.iter().filter_map(|c| c.as_str().and_then(Color::from_hex)).collect()); + let palette = str_param(p, "palette").unwrap_or("colorful").to_string(); + with_chart(s, p, |c| { + for (i, se) in c.series.iter_mut().enumerate() { + se.color = match &explicit { + Some(cols) if !cols.is_empty() => cols.get(i % cols.len()).copied(), + _ => match palette.as_str() { + "monochrome" => Some(Color::Theme(4, (-400 + (i as i16 * 200)).clamp(-800, 800))), + p if p.starts_with("accent") => { + let k: u8 = p.trim_start_matches("accent").parse().unwrap_or(1); + Some(Color::Theme(3 + k.clamp(1, 6), (-500 + i as i16 * 250).clamp(-800, 800))) + } + _ => None, + }, + }; + } + Ok(()) + }) +} + +pub(super) fn select_data(s: &mut Session, p: &Json) -> Result { + let d = s.doc()?; + // A new data range rebuilds the series, as in Excel's Select Data › Chart data range. + let rebuilt = match str_param(p, "range") { + Some(range) => { + let range = range.trim_start_matches('='); + let (sheet_name, body) = split_sheet(range); + let src_si = match sheet_name { + Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?, + None => d.wb.active_sheet(), + }; + let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?; + if r.count() > 1_000_000 { + return Err(bad("chart.selectData", "range too large for a chart")); + } + let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?; + let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1); + let series = crate::cmd::insert::series_from_range(src, r, by_rows); + Some((series, format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1()), by_rows)) + } + None => None, + }; + // Horizontal (Category) Axis Labels › Edit: one labels range for every series ("" clears). + let categories = match str_param(p, "categories") { + None => None, + Some(t) if t.trim().trim_start_matches('=').is_empty() => Some(None), + Some(t) => { + let t = t.trim().trim_start_matches('='); + let (sheet_name, body) = split_sheet(t); + let si = match sheet_name { + Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?, + None => d.wb.active_sheet(), + }; + let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "`categories` is not a range"))?; + let name = d.wb.sheet(si).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?; + let abs = |c: CellRef| format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1); + Some(Some(format!("{}!{}:{}", gridcraft_formula::quote_sheet(&name), abs(r.start), abs(r.end)))) + } + }; + let mut remove: Vec = p + .get("removeSeries") + .and_then(Json::as_array) + .map(|a| a.iter().filter_map(Json::as_u64).filter_map(|i| usize::try_from(i).ok()).collect()) + .unwrap_or_default(); + remove.sort_unstable(); + remove.dedup(); + if rebuilt.is_none() && categories.is_none() && remove.is_empty() { + return Err(bad("chart.selectData", "missing `range`, `categories` or `removeSeries`")); + } + with_chart(s, p, move |c| { + if let Some((series, source, by_rows)) = rebuilt { + c.series = series; + crate::cmd::insert::scatter_x_from_first(c.kind, &mut c.series); + c.source = Some(source); + c.by_rows = by_rows; + } + for i in remove.iter().rev() { + if *i < c.series.len() && c.series.len() > 1 { + c.series.remove(*i); + } + } + if let Some(cats) = categories { + for se in &mut c.series { + se.categories = cats.clone(); + } + } + Ok(()) + }) +} + +pub(super) fn move_chart(s: &mut Session, p: &Json) -> Result { + let (si, ci) = find_chart(s, p)?; + let target = match p.get("sheet").and_then(Json::as_str) { + Some(n) => Some(s.doc()?.wb.sheet_index(n).ok_or_else(|| bad("chart.move", "no such sheet"))?), + None => None, + }; + let at = cell_param_on(s, p, "at", target.unwrap_or(si))?; + edit(s, |cx| { + let mut chart = cx.sheet_mut(si)?.charts.remove(ci); + if let Some(a) = at { + chart.anchor.cell = a; + } + let dest = target.unwrap_or(si); + cx.sheet_mut(dest)?.charts.push(chart); + Ok(Json::Null) + }) +} + +pub(super) fn format_series(s: &mut Session, p: &Json) -> Result { + let idx = u32_param(p, "series").unwrap_or(0) as usize; + let color = str_param(p, "color").and_then(Color::from_hex); + with_chart(s, p, |c| { + if let Some(se) = c.series.get_mut(idx) { + se.color = color; + } + Ok(()) + }) +} diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs new file mode 100644 index 0000000000..9a1ae74175 --- /dev/null +++ b/crates/engine/src/cmd/extra/data.rs @@ -0,0 +1,131 @@ +use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range}; + +pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { + let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?; + let d = s.doc()?; + let si = d.wb.active_sheet(); + let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?; + let ti = match str_param(p, "table") { + Some(n) => sh.tables.iter().position(|t| t.name.eq_ignore_ascii_case(n)), + None => sh.tables.iter().position(|t| t.range.contains(d.selection.active)), + } + .ok_or_else(|| bad("table.resize", "select a cell in a table"))?; + edit(s, |cx| { + let sheet = cx.sheet_mut(si)?; + let headers: Vec = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect(); + if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) { + return Err(EngineError::Other("A table can't overlap another table.".into())); + } + let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; + if r.start.row != t.range.start.row || !r.intersects(&t.range) { + return Err(EngineError::Other( + "The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(), + )); + } + let mut cols = Vec::new(); + for (i, h) in headers.iter().enumerate() { + let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() }; + let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned(); + cols.push(existing.unwrap_or(TableColumn { + name, + totals: TotalsFn::None, + totals_label: None, + formula: None, + unique_name: None, + xml: None, + })); + } + t.columns = cols; + t.range = r; + cx.structural = true; + Ok(Json::Null) + }) +} + +pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result { + let bytes = if let Some(t) = str_param(p, "text") { + t.as_bytes().to_vec() + } else if let Some(path) = str_param(p, "path") { + crate::io::read_file(path)? + } else { + s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({}))); + return ok(); + }; + let text = String::from_utf8_lossy(&bytes); + // JSON array of objects → rows. + let rows: Vec> = + if text.trim_start().starts_with('[') { + let arr: Vec = serde_json::from_str(&text).map_err(|e| bad("data.getData", e.to_string()))?; + let mut keys: Vec = Vec::new(); + for o in &arr { + if let Some(m) = o.as_object() { + for k in m.keys() { + if !keys.contains(k) { + keys.push(k.clone()); + } + } + } + } + let mut out = vec![keys.iter().map(|k| json!(k)).collect::>()]; + for o in &arr { + out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect()); + } + out + } else { + let delim = str_param(p, "delimiter") + .and_then(|d| d.chars().next()) + .unwrap_or(if text.lines().next().is_some_and(|l| l.contains('\t')) { '\t' } else { ',' }); + let opts = gridcraft_xlsx::CsvOptions { delimiter: delim as u8, ..Default::default() }; + let wb = gridcraft_xlsx::read_csv(&bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?; + let sh = wb.sheet(0).ok_or(EngineError::NoDocument)?; + let Some(u) = sh.used_range() else { return Err(EngineError::Other("The file is empty.".into())) }; + (u.start.row..=u.end.row) + .map(|r| { + (u.start.col..=u.end.col) + .map(|c| match sh.value(CellRef::new(r, c)) { + Value::Number(n) => json!(n), + Value::Bool(b) => json!(b), + Value::Empty => Json::Null, + v => json!(v.display()), + }) + .collect() + }) + .collect() + }; + if rows.is_empty() || rows.len() > 1_048_576 { + return Err(EngineError::Other("Nothing to import.".into())); + } + let name = str_param(p, "sheet").map(str::to_string).or_else(|| { + str_param(p, "path").and_then(|x| std::path::Path::new(x).file_stem().and_then(std::ffi::OsStr::to_str).map(|f| f.chars().take(31).collect())) + }); + let r = s.execute("home.insertSheet", json!({"name": name})).or_else(|_| s.execute("home.insertSheet", json!({})))?; + let w = rows.iter().map(Vec::len).max().unwrap_or(1).max(1); + s.execute("range.setValues", json!({"range": "A1", "values": rows}))?; + let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.len() as u32 - 1, w as u32 - 1)); + let _ = s.execute("insert.table", json!({"range": range.a1(), "header": true})); + let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, w as u32 - 1).a1()})); + Ok(json!({"sheet": r["name"], "rows": rows.len(), "cols": w})) +} + +pub(super) fn from_table_range(s: &mut Session, p: &Json) -> Result { + let r = target_range(s, p)?; + let d = s.doc()?; + let sh = d.wb.active().ok_or(EngineError::NoDocument)?; + let r = if r.is_single() { crate::selection::current_region(sh, r.start) } else { r }; + let text = crate::display::range_text(&d.wb, d.wb.active_sheet(), r); + from_csv(s, &json!({"text": text, "delimiter": "\t", "sheet": format!("{} (2)", sh.name).chars().take(31).collect::()})) +} + +pub(super) fn queries(s: &mut Session, _: &Json) -> Result { + let d = s.doc()?; + Ok(Json::Array( + d.wb.sheets + .iter() + .flat_map(|sh| { + sh.tables + .iter() + .map(move |t| json!({"name": t.name, "sheet": sh.name, "range": t.range.a1(), "rows": t.range.height().saturating_sub(1)})) + }) + .collect(), + )) +} diff --git a/crates/engine/src/cmd/extra/objects.rs b/crates/engine/src/cmd/extra/objects.rs new file mode 100644 index 0000000000..fa5a5f438b --- /dev/null +++ b/crates/engine/src/cmd/extra/objects.rs @@ -0,0 +1,182 @@ +use gridcraft_model::ObjKind; + +use super::chart::format_series; +use super::{ + Anchor, CellRef, Color, EngineError, Json, Result, Session, Shape, ShapeKind, Sheet, anchor_mode_name, bad, bool_param, edit, json, str_param, + u32_param, +}; + +/// The kind of object a `kind` parameter names: `shape` when the parameter is absent; one that +/// is present but not one of the names (`null`, a number, an unknown word) is an error, as for +/// the `object.*` commands, where the kind is required. +fn kind_param(p: &Json, cmd: &str) -> Result { + let err = || bad(cmd, "kind must be chart, image, shape, slicer or equation"); + match p.get("kind") { + None => Ok(ObjKind::Shape), + Some(Json::String(k)) => ObjKind::parse(k).ok_or_else(err), + Some(_) => Err(err()), + } +} + +/// Whether `kind` names the shape `sh`: an equation is a shape too, and a plain shape is not an +/// equation, as `Sheet::object_anchor` has it for the `object.*` commands. +fn shape_is(kind: ObjKind, sh: &Shape) -> bool { + kind != ObjKind::Equation || sh.kind == ShapeKind::Equation +} + +pub(super) fn shape_fill(s: &mut Session, p: &Json) -> Result { + if str_param(p, "kind") == Some("shape") { + let color = str_param(p, "color").and_then(Color::from_hex).unwrap_or_default(); + return with_shape(s, p, |sh| sh.fill = color); + } + format_series(s, p) +} + +pub(super) fn shape_outline(s: &mut Session, p: &Json) -> Result { + let color = str_param(p, "color").and_then(Color::from_hex).unwrap_or_default(); + with_shape(s, p, |sh| sh.line = color) +} + +fn with_shape(s: &mut Session, p: &Json, f: impl FnOnce(&mut Shape)) -> Result { + let si = s.doc()?.wb.active_sheet(); + let id = u32_param(p, "id"); + edit(s, |cx| { + let shapes = &mut cx.sheet_mut(si)?.shapes; + let sh = match id { + Some(id) => shapes.iter_mut().find(|x| x.id == id), + None => shapes.last_mut(), + } + .ok_or_else(|| bad("shape", "no such shape"))?; + f(sh); + Ok(Json::Null) + }) +} + +pub(super) fn arrange(s: &mut Session, p: &Json, forward: bool) -> Result { + let id = u32_param(p, "id").ok_or_else(|| bad("arrange", "missing `id`"))?; + let kind = kind_param(p, "arrange")?; + let extreme = bool_param(p, "toFront").or(bool_param(p, "toBack")).unwrap_or(false); + let si = s.doc()?.wb.active_sheet(); + fn reorder(v: &mut Vec, i: usize, forward: bool, extreme: bool) { + if i >= v.len() { + return; + } + let item = v.remove(i); + let j = match (forward, extreme) { + (true, true) => v.len(), + (false, true) => 0, + (true, false) => (i + 1).min(v.len()), + (false, false) => i.saturating_sub(1), + }; + v.insert(j, item); + } + edit(s, |cx| { + let sh = cx.sheet_mut(si)?; + // An id that is not an object of this kind is an error, so a stale id, or a shape's id + // given as an equation, never reorders something else or succeeds silently. + let found = match kind { + ObjKind::Chart => sh.charts.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.charts, i, forward, extreme)), + ObjKind::Image => sh.images.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.images, i, forward, extreme)), + ObjKind::Slicer => sh.slicers.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.slicers, i, forward, extreme)), + ObjKind::Shape | ObjKind::Equation => { + sh.shapes.iter().position(|c| c.id == id && shape_is(kind, c)).map(|i| reorder(&mut sh.shapes, i, forward, extreme)) + } + }; + found.ok_or_else(|| bad("arrange", "no such object"))?; + Ok(Json::Null) + }) +} + +pub(super) fn selection_pane(s: &mut Session, _: &Json) -> Result { + let d = s.doc()?; + let sh = d.wb.active().ok_or(EngineError::NoDocument)?; + let mut v = Vec::new(); + for c in &sh.shapes { + let kind = if c.kind == ShapeKind::Equation { "equation" } else { "shape" }; + v.push(json!({"kind": kind, "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + } + for c in &sh.images { + v.push(json!({"kind": "image", "id": c.id, "name": format!("Picture {}", c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + } + for c in &sh.charts { + v.push(json!({"kind": "chart", "id": c.id, "name": format!("Chart {}", c.id), "title": c.title, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + } + // Slicers paint above the other objects. + for c in &sh.slicers { + let name = if c.caption.is_empty() { &c.column } else { &c.caption }; + v.push(json!({"kind": "slicer", "id": c.id, "name": name, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + } + Ok(Json::Array(v)) +} + +/// The anchors of every object of `kind` on the sheet; under `equation`, only the equations. +fn anchors_of(sh: &mut Sheet, kind: ObjKind) -> Vec<(u32, &mut Anchor)> { + match kind { + ObjKind::Chart => sh.charts.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Image => sh.images.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Slicer => sh.slicers.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Shape | ObjKind::Equation => sh.shapes.iter_mut().filter(|c| shape_is(kind, c)).map(|c| (c.id, &mut c.anchor)).collect(), + } +} + +pub(super) fn align(s: &mut Session, p: &Json) -> Result { + let kind = kind_param(p, "arrange.align")?; + // `ids` may be absent (nothing to align) but, present, must be an array whose every entry is + // an object id naming an object of the kind: a stale or mismatched id, or a value of another + // shape, is an error, as for `arrange` and the `object.*` commands, not something silently + // left out. + let bad_ids = || bad("arrange.align", "ids must be an array of object ids"); + let ids: Vec = match p.get("ids") { + None => Vec::new(), + Some(Json::Array(a)) => a.iter().map(|v| v.as_u64().and_then(|x| u32::try_from(x).ok()).ok_or_else(bad_ids)).collect::>()?, + Some(_) => return Err(bad_ids()), + }; + let how = str_param(p, "align").unwrap_or("left").to_string(); + let si = s.doc()?.wb.active_sheet(); + edit(s, |cx| { + let sheet = cx.sheet_mut(si)?; + let geo: Vec<(u32, f64, f64, f32, f32)> = { + let shc = sheet.clone(); + anchors_of(sheet, kind) + .into_iter() + .filter(|(id, _)| ids.contains(id)) + .map(|(id, a)| (id, shc.col_left(a.cell.col) + a.dx as f64, shc.row_top(a.cell.row) + a.dy as f64, a.width, a.height)) + .collect() + }; + if let Some(missing) = ids.iter().find(|id| !geo.iter().any(|g| g.0 == **id)) { + return Err(bad("arrange.align", format!("no such object: {missing}"))); + } + if geo.len() < 2 { + return Ok(Json::Null); + } + let left = geo.iter().map(|g| g.1).fold(f64::INFINITY, f64::min); + let right = geo.iter().map(|g| g.1 + g.3 as f64).fold(f64::NEG_INFINITY, f64::max); + let top = geo.iter().map(|g| g.2).fold(f64::INFINITY, f64::min); + let bottom = geo.iter().map(|g| g.2 + g.4 as f64).fold(f64::NEG_INFINITY, f64::max); + let shc = sheet.clone(); + for (id, a) in anchors_of(sheet, kind) { + let Some(g) = geo.iter().find(|g| g.0 == id) else { continue }; + let (mut x, mut y) = (g.1, g.2); + match how.as_str() { + "left" => x = left, + "right" => x = right - g.3 as f64, + "center" => x = (left + right) / 2.0 - g.3 as f64 / 2.0, + "top" => y = top, + "bottom" => y = bottom - g.4 as f64, + _ => y = (top + bottom) / 2.0 - g.4 as f64 / 2.0, + } + let c = CellRef::new(shc.row_at(y), shc.col_at(x)); + a.cell = c; + a.dx = (x - shc.col_left(c.col)) as f32; + a.dy = (y - shc.row_top(c.row)) as f32; + } + Ok(Json::Null) + }) +} + +pub(super) fn rotate(s: &mut Session, p: &Json) -> Result { + if p.get("flip").is_some_and(|f| !f.is_null()) { + return Err(bad("arrange.rotate", "`flip` is not supported: shapes have no flip state")); + } + with_shape(s, p, |sh| std::mem::swap(&mut sh.anchor.width, &mut sh.anchor.height)) +} diff --git a/crates/engine/src/cmd/extra/scripts.rs b/crates/engine/src/cmd/extra/scripts.rs new file mode 100644 index 0000000000..e9b8776722 --- /dev/null +++ b/crates/engine/src/cmd/extra/scripts.rs @@ -0,0 +1,181 @@ +use super::{EngineError, Json, Result, SCRIPTS_NAME, Session, Workbook, bad, bool_param, edit, json, stash_get, stash_map, stash_set, str_param}; + +pub(super) fn record(s: &mut Session, p: &Json) -> Result { + if bool_param(p, "stop").unwrap_or(false) || s.recording.is_some() { + let Some(start) = s.recording.take() else { return Ok(json!({"recording": false})) }; + let cmds: Vec = s + .journal + .iter() + .skip(start) + .filter(|(id, _)| !id.starts_with("automate.") && !crate::record::NOT_RECORDED.contains(&id.as_str())) + .map(|(id, p)| json!({"command": id, "params": p})) + .collect(); + let name = str_param(p, "name").map(str::to_string).unwrap_or_else(|| format!("Script {}", start)); + s.execute("automate.newScript", json!({"name": name, "commands": cmds}))?; + return Ok(json!({"recording": false, "saved": name, "steps": cmds.len()})); + } + s.recording = Some(s.journal.len()); + Ok(json!({"recording": true})) +} + +pub(super) fn new_script(s: &mut Session, p: &Json) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("automate.newScript", "missing `name`"))?.to_string(); + let cmds = p.get("commands").cloned().unwrap_or(json!([])); + if !cmds.is_array() { + return Err(bad("automate.newScript", "`commands` must be an array")); + } + edit(s, |cx| { + let mut all = stash_map(&cx.wb, SCRIPTS_NAME); + all[name.as_str()] = cmds.clone(); + stash_set(&mut cx.wb, SCRIPTS_NAME, &all); + Ok(json!({"name": name})) + }) +} + +pub(super) fn all_scripts(s: &mut Session, _: &Json) -> Result { + let d = s.doc()?; + let (wb, trusted) = (&d.wb, d.scripts_trusted); + let all = stash_get(wb, SCRIPTS_NAME); + let mut list: Vec = all + .as_object() + .map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len), "trusted": trusted})).collect()) + .unwrap_or_default(); + // A preserved VBA project is reported alongside GridCraft's own scripts; it is carried on + // save but never executed here, so it has no step count. + if let Some(bytes) = &wb.vba_project { + list.push(json!({"name": "(VBA)", "steps": 0, "kind": "vba", "size": bytes.len(), "executed": false})); + } + Ok(Json::Array(list)) +} + +/// Whether `wb` carries GridCraft scripts (a workbook opened with them starts untrusted). +pub(crate) fn has_scripts(wb: &Workbook) -> bool { + stash_map(wb, SCRIPTS_NAME).as_object().is_some_and(|o| !o.is_empty()) +} + +/// Why a script step is refused, whatever the workbook's trust: scripts stay inside the +/// workbook. Anything that reads or writes files (`file.*`, or any `path` parameter: Get Data, +/// From Text/CSV, Insert Picture) or leaves the app (`link.*` opens URLs) is the caller's to run +/// directly, not a stored script's. (Nested `automate.*` steps are skipped.) This check goes by +/// command id and parameter name, so it is only the up-front refusal: the steps also run inside +/// an [`crate::io::ScriptSandbox`] (file access refused whatever the parameter is called) and +/// [`run_script`] drops any `OpenUrl` request a step raises. +fn denied_script_step(id: &str, params: &Json) -> Option { + if id.starts_with("file.") || id.starts_with("link.") { + return Some(format!("scripts can't run `{id}`: it reaches outside the workbook")); + } + // Scripts are scoped to their workbook: a step that switches the active window would + // point every later step at another open document, so those are refused too. + if id.starts_with("window.") || matches!(id, "view.switchWindows" | "view.newWindow" | "view.hideWindow" | "view.unhideWindow") { + return Some(format!("scripts can't run `{id}`: it reaches outside the workbook")); + } + if params.get("path").is_some() { + return Some(format!("scripts can't pass a file `path` to `{id}`")); + } + None +} + +pub(super) fn trust_scripts(s: &mut Session, p: &Json) -> Result { + // Only a missing `trusted` means "trust"; `"false"`, `0` or `null` are mistakes, not consent. + let trusted = match p.get("trusted") { + None => true, + Some(Json::Bool(b)) => *b, + Some(_) => return Err(bad("automate.trustScripts", "`trusted` must be true or false")), + }; + s.doc_mut()?.scripts_trusted = trusted; + Ok(json!({"trusted": trusted})) +} + +/// Runs a stored script. Scripts in a workbook opened from a file run only once the workbook is +/// trusted for this session (`automate.trustScripts`, or `trusted: true` on this call); steps that +/// reach outside the workbook ([`denied_script_step`]) are refused before any step runs. +pub(super) fn run_script(s: &mut Session, p: &Json) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("automate.runScript", "missing `name`"))?; + let d = s.doc()?; + let all = stash_get(&d.wb, SCRIPTS_NAME); + let steps = all.get(name).and_then(Json::as_array).cloned().ok_or_else(|| bad("automate.runScript", "no such script"))?; + if !d.scripts_trusted && !bool_param(p, "trusted").unwrap_or(false) { + return Err(bad( + "automate.runScript", + "scripts in this workbook came from a file and are disabled; trust the workbook first (Trust Scripts in View › Macros, Alt+F8; `automate.trustScripts`; or `trusted: true`)", + )); + } + let steps: Vec = steps.into_iter().take(100_000).collect(); + for st in &steps { + let id = st["command"].as_str().unwrap_or(""); + if let Some(why) = denied_script_step(id, &st["params"]) { + return Err(bad("automate.runScript", why)); + } + } + let _sandbox = crate::io::ScriptSandbox::enter(); + let mut n = 0; + // What ran, for a recorder in progress: the recording keeps these steps with the run, so + // editing or deleting the script before the recording stops does not change what it saved. + let mut ran_steps: Vec<(String, Json)> = Vec::new(); + for st in &steps { + let id = st["command"].as_str().unwrap_or(""); + if id.starts_with("automate.") { + continue; + } + let before = s.ui_requests.len(); + let wb_before = s.doc().ok().map(|d| (d.uid, d.wb.clone())); + let ran = s.execute(id, st["params"].clone()); + // A step that asks the host to open a URL leaves the app: drop the request and stop. + if s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::OpenUrl(_)))) { + let mut i = 0; + s.ui_requests.retain(|r| { + i += 1; + i <= before || !matches!(r, crate::UiRequest::OpenUrl(_)) + }); + return Err(bad("automate.runScript", format!("scripts can't open links (`{id}`)"))); + } + let result = ran?; + n += 1; + if s.recorder.is_some() { + // The recorder's rule for each step, as for a command run on its own: a menu-style + // step that only opened a dialog is left out (playing it back would stop at the + // dialog), and a toggle keeps the state it set. + let opened_dialog = s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::Dialog(..)))); + let changed = wb_before.as_ref().is_some_and(|(uid, wb)| s.docs.iter().any(|d| d.uid == *uid && !std::sync::Arc::ptr_eq(&d.wb, wb))); + if !opened_dialog || changed { + ran_steps.push((id.to_string(), crate::record::with_toggle_state(id, st["params"].clone(), &result))); + } + } + } + if s.recorder.is_some() { + s.script_ran = Some(ran_steps); + } + Ok(json!({"ran": n})) +} + +/// Redo work there again. A macro being debugged on that workbook is stopped with them. +pub(super) fn stop_action(s: &mut Session, _: &Json) -> Result { + // Inside another command the open groups are that command's own (an action in progress): + // a step of it that stopped them would pull the workbook from under the rest of its run. + if s.depth() > 1 { + return Err(EngineError::Disabled("automate.stopAction".into(), "Stop Action runs on its own, not as a step of a script or macro.".into())); + } + let uid = s.doc()?.uid; + let mut out = json!({"stopped": s.abort_groups(uid)}); + // A macro being debugged here had its group among them: its run is over. + if let Some((name, wrote_files)) = crate::macros::debug::end_stopped(s, uid) { + out["macro"] = json!(name); + out["message"] = json!(format!( + "Macro '{name}', which was being debugged, was stopped and rolled back. {}", + crate::macros::run::rolled_back(&wrote_files) + )); + } + Ok(out) +} + +pub(super) fn delete_script(s: &mut Session, p: &Json) -> Result { + let name = str_param(p, "name").ok_or_else(|| bad("automate.deleteScript", "missing `name`"))?.to_string(); + edit(s, |cx| { + let mut all = stash_map(&cx.wb, SCRIPTS_NAME); + if let Some(o) = all.as_object_mut() { + o.remove(&name); + } + stash_set(&mut cx.wb, SCRIPTS_NAME, &all); + Ok(Json::Null) + }) +} diff --git a/crates/engine/src/cmd/extra/window.rs b/crates/engine/src/cmd/extra/window.rs new file mode 100644 index 0000000000..b8129805f2 --- /dev/null +++ b/crates/engine/src/cmd/extra/window.rs @@ -0,0 +1,216 @@ +use super::{ + CellRef, EngineError, Json, Result, Session, SheetViewMode, VIEWS_NAME, WATCH_NAME, Workbook, bad, bool_param, edit, json, ok, split_sheet, + stash_get, stash_map, stash_set, str_param, target_sheet, u32_param, +}; + +/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it +/// neither records an undo step nor marks a clean workbook as changed. +pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result { + let si = target_sheet(s, p)?; + let d = s.doc_mut()?; + let dirty = d.is_dirty(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + if let Some(sh) = wb.sheet_mut(si) { + sh.view = mode; + } + if !dirty { + d.saved = d.wb.clone(); + } + Ok(json!({"view": mode.as_str()})) +} + +pub(super) fn ruler(s: &mut Session, p: &Json) -> Result { + let on = bool_param(p, "on").unwrap_or(s.hide_ruler); + s.hide_ruler = !on; + Ok(json!({"on": on})) +} + +/// The Watch Window list isn't an edit (Excel doesn't undo it): undo and redo keep the current +/// list when they swap in another snapshot of the workbook. +pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc) { + let find = |wb: &Workbook| wb.names.iter().find(|n| n.name == WATCH_NAME).cloned(); + let keep = find(from); + if keep == find(to) { + return; + } + let wb = std::sync::Arc::make_mut(to); + wb.names.retain(|n| n.name != WATCH_NAME); + wb.names.extend(keep); +} + +/// Normal, Page Layout and Page Break Preview belong to the window, not to the edits: Excel doesn't +/// undo a switch between them, and `set_view` is no undo step. So undo and redo keep each sheet's +/// current view when they swap in another snapshot of the workbook, and a view kept this way +/// doesn't make a saved workbook dirty. +pub(crate) fn keep_view_modes(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.view); + let changed: Vec<(usize, SheetViewMode)> = + d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|v| *v != sh.view).map(|v| (i, v))).collect(); + if changed.is_empty() { + return; + } + let dirty = d.is_dirty(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + for (i, v) in changed { + if let Some(sh) = wb.sheet_mut(i) { + sh.view = v; + } + } + if !dirty { + d.saved = d.wb.clone(); + } +} + +pub(super) fn custom_views(s: &mut Session, p: &Json) -> Result { + let d = s.doc()?; + let mut views = stash_map(&d.wb, VIEWS_NAME); + if let Some(name) = str_param(p, "save") { + let sh = d.wb.active().ok_or(EngineError::NoDocument)?; + views[name] = json!({"sheet": d.wb.active_sheet(), "selection": d.selection.a1(), "zoom": sh.zoom, "freeze": sh.freeze}); + let v = views.clone(); + edit(s, |cx| { + stash_set(&mut cx.wb, VIEWS_NAME, &v); + Ok(()) + })?; + } else if let Some(name) = str_param(p, "show") { + let v = views.get(name).cloned().ok_or_else(|| bad("view.customViews", "no such view"))?; + if let Some(si) = v["sheet"].as_u64() { + s.execute("sheet.activate", json!({"sheet": si}))?; + } + if let Some(sel) = v["selection"].as_str() { + s.execute("selection.set", json!({"range": sel}))?; + } + if let Some(z) = v["zoom"].as_u64() { + s.execute("view.zoom", json!({"percent": z}))?; + } + if let Some(f) = v.get("freeze") { + let freeze = match (f[0].as_u64(), f[1].as_u64()) { + (Some(r), Some(c)) => u32::try_from(r).ok().zip(u32::try_from(c).ok()), + _ => None, + }; + edit(s, |cx| { + let si = cx.sheet_index(); + cx.sheet_mut(si)?.freeze = freeze; + Ok(()) + })?; + } + } else if let Some(name) = str_param(p, "delete") { + if let Some(o) = views.as_object_mut() { + o.remove(name); + } + let v = views.clone(); + edit(s, |cx| { + stash_set(&mut cx.wb, VIEWS_NAME, &v); + Ok(()) + })?; + } + Ok(stash_get(&s.doc()?.wb, VIEWS_NAME)) +} + +pub(super) fn split(s: &mut Session, _: &Json) -> Result { + let has = s.doc()?.wb.active().is_some_and(|sh| sh.freeze.is_some()); + if has { s.execute("view.unfreezePanes", json!({})) } else { s.execute("view.freezePanes", json!({})) } +} + +pub(super) fn new_window(s: &mut Session, _: &Json) -> Result { + let id = s.new_window()?; + let doc = s.window(id).map(|w| w.doc_uid); + Ok(json!({"window": id, "doc": doc, "title": s.window_title(id)})) +} + +/// The window a window command names: `window` (an id), else `doc` (a workbook id: its most +/// recent window), else the active window. +pub(crate) fn window_param(s: &Session, cmd: &str, p: &Json) -> Result { + let t = crate::Target::from_json(p).map_err(|e| bad(cmd, e.to_string()))?; + s.target_window(t).map_err(|e| bad(cmd, e.to_string())) +} + +/// View › Arrange All. The engine has no window geometry: it picks the windows and the layout, +/// and the interface moves its native windows ([`Session::window_list`] order, active first). +pub(super) fn arrange_all(s: &mut Session, p: &Json) -> Result { + let arrange = match str_param(p, "arrange").unwrap_or("tiled") { + a @ ("tiled" | "horizontal" | "vertical" | "cascade") => a, + other => return Err(bad("view.arrangeAll", format!("`arrange` must be tiled, horizontal, vertical or cascade, not `{other}`"))), + }; + let active = s.active_window(); + let doc = active.and_then(|w| s.window(w)).map(|w| w.doc_uid); + let only_active = p.get("activeWorkbook").and_then(Json::as_bool).unwrap_or(false); + let mut windows: Vec = s.windows().iter().filter(|w| !w.hidden && (!only_active || Some(w.doc_uid) == doc)).map(|w| w.id).collect(); + if let Some(at) = windows.iter().position(|w| Some(*w) == active) + && let Some(first) = windows.get_mut(..=at) + { + first.rotate_right(1); + } + Ok(json!({"arrange": arrange, "windows": windows})) +} + +pub(super) fn hide_window(s: &mut Session, p: &Json) -> Result { + let id = window_param(s, "view.hideWindow", p)?; + s.hide_window(id); + ok() +} + +pub(super) fn unhide_window(s: &mut Session, p: &Json) -> Result { + let id = if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) { + Some(window_param(s, "view.unhideWindow", p)?) + } else if let Some(i) = u32_param(p, "index") { + // A workbook's position in the document list. + let uid = s.documents().get(i as usize).map(|d| d.uid).ok_or_else(|| bad("view.unhideWindow", "no such window"))?; + s.windows().iter().filter(|w| w.doc_uid == uid && w.hidden).map(|w| w.id).next_back().or_else(|| s.doc_window(uid)) + } else { + s.last_hidden_window() + }; + if let Some(id) = id { + s.unhide_window(id); + } + ok() +} + +pub(super) fn switch_windows(s: &mut Session, p: &Json) -> Result { + if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) { + let id = window_param(s, "view.switchWindows", p)?; + s.unhide_window(id); + } + Ok(s.window_list()) +} + +pub(super) fn watch_window(s: &mut Session, p: &Json) -> Result { + let mut list: Vec = + stash_get(&s.doc()?.wb, WATCH_NAME).as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(); + let mut changed = false; + if let Some(a) = str_param(p, "add") { + if !list.iter().any(|x| x == a) { + list.push(a.to_string()); + } + changed = true; + } + if let Some(r) = str_param(p, "remove") { + list.retain(|x| x != r); + changed = true; + } + if changed { + let v = json!(list.clone()); + let d = s.doc_mut()?; + // The watch list is view state: don't add an undo step. + let wb = std::sync::Arc::make_mut(&mut d.wb); + stash_set(wb, WATCH_NAME, &v); + } + let d = s.doc()?; + let rows: Vec = list + .iter() + .map(|w| { + let (sheet, body) = split_sheet(w); + let si = sheet.and_then(|n| d.wb.sheet_index(&n)).unwrap_or(d.wb.active_sheet()); + let c = CellRef::parse(body).unwrap_or_default(); + let sh = d.wb.sheet(si); + json!({"cell": w, "value": sh.map(|s| s.value(c).display()), "formula": sh.and_then(|s| s.cell(c)).and_then(|x| x.formula.as_ref()).map(|f| format!("={}", f.text))}) + }) + .collect(); + Ok(Json::Array(rows)) +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9af85b9dde..b3b515c2e0 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -2,7 +2,7 @@ use serde_json::{Value as Json, json}; -use super::*; +use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param}; use crate::DocState; pub fn specs() -> Vec { @@ -13,7 +13,7 @@ pub fn specs() -> Vec { 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), cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool, document?: bool} (closes the active window, or with `document` the workbook and all its windows; the workbook closes with its last window)", has_doc, close), - cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?}", has_doc, |s, p| export(s, p, "csv")), + cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?, values?: bool} → {path, bytes}: writes the cells as displayed, like Excel's Save As CSV; `values: true` writes raw values instead (full-precision numbers, ISO 8601 dates and times, TRUE/FALSE)", has_doc, |s, p| export(s, p, "csv")), cmd!(noundo "file.exportHtml", "Save as Web Page", ["File", "Export"], None, "{path}", has_doc, |s, p| export(s, p, "html")), cmd!("file.properties", "Properties", ["File"], None, "{title?, subject?, author?, company?, keywords?, description?}", has_doc, properties), cmd!( @@ -191,7 +191,11 @@ fn export(s: &mut Session, p: &Json, ext: &str) -> Result { wb.set_active_sheet(target_sheet(s, p)?); } let target = if path.ends_with(&format!(".{ext}")) { path.clone() } else { format!("{path}.{ext}") }; - let bytes = crate::io::save_bytes(&wb, &target)?; + let bytes = if ext == "csv" && bool_param(p, "values").unwrap_or(false) { + crate::io::csv_values_bytes(&wb)? + } else { + crate::io::save_bytes(&wb, &target)? + }; crate::io::write_file(&target, &bytes)?; Ok(json!({"path": target, "bytes": bytes.len()})) } diff --git a/crates/engine/src/cmd/forecast.rs b/crates/engine/src/cmd/forecast.rs index b7472fd22c..3c62e469f5 100644 --- a/crates/engine/src/cmd/forecast.rs +++ b/crates/engine/src/cmd/forecast.rs @@ -11,7 +11,7 @@ use gridcraft_functions::Timeline; use gridcraft_model::{Anchor, Cell, Chart, ChartKind, Formula, LegendPos, Series, Sheet, StyleId, Table, TableColumn, TotalsFn}; use serde_json::{Value as Json, json}; -use super::*; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_param, cmd, edit, has_doc, split_sheet, str_param}; use crate::selection::current_region; const CMD: &str = "data.forecastSheet"; @@ -315,7 +315,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result { let vstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = vfmt.clone()); let mut sheet = Sheet::new(sheet_name.clone()); let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| { - sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style }); + sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style, py: None }); }; let formula = |sheet: &mut Sheet, row: u32, col: u32, text: String, style: StyleId| { let mut cell = Cell::formula(Formula::new(&text)); @@ -424,6 +424,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result { series, legend: LegendPos::Bottom, data_labels: false, + data_table: None, gridlines: true, style: 1, x_title: None, diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 9f44f61adc..6ae40351b0 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -1,10 +1,13 @@ //! Formatting: Home › Font, Alignment, Number, Styles, Cells › Format. use gridcraft_core::{CellRef, RangeRef}; -use gridcraft_model::*; +use gridcraft_model::{BorderLine, BorderStyle, Borders, Color, Fill, HAlign, NumFmt, Style, StyleId, Theme, Underline, VAlign, VertAlign}; use serde_json::{Value as Json, json}; -use super::*; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_param, cmd, edit, f64_param, has_doc, ok, parse_lines, split_sheet, str_param, + target_ranges, target_sheet, +}; pub fn specs() -> Vec { vec![ @@ -87,8 +90,14 @@ pub fn specs() -> Vec { format_cells ), // Alignment - cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)), - cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)), + CommandSpec { + shortcut_mac: Some("Cmd+L"), + ..cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)) + }, + CommandSpec { + shortcut_mac: Some("Cmd+E"), + ..cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)) + }, cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)), cmd!("home.justify", "Justify", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Justify)), cmd!("home.alignTop", "Top Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Top)), @@ -647,8 +656,7 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let others: Vec = sh.cells.iter_range(m).map(|(c, _)| c).filter(|c| *c != m.start).collect(); for c in others { if let Some(mut cell) = sh.cells.get(c).cloned() { - cell.value = gridcraft_core::Value::Empty; - cell.formula = None; + cell.clear_content(); sh.set_cell(c, cell); } touched.push((sheet, c)); @@ -665,8 +673,7 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let others: Vec = sh.cells.iter_range(*r).map(|(c, _)| c).filter(|c| *c != r.start).collect(); for c in others { if let Some(mut cell) = sh.cells.get(c).cloned() { - cell.value = gridcraft_core::Value::Empty; - cell.formula = None; + cell.clear_content(); sh.set_cell(c, cell); } touched.push((sheet, c)); @@ -683,7 +690,10 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let blocked = sh .cells .iter_range(reach) - .filter(|(_, x)| x.formula.is_some() && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill)); + // A Python cell's result is blocked and unblocked like a formula's. + .filter(|(_, x)| { + (x.formula.is_some() || x.py.is_some()) && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill) + }); touched.extend(blocked.map(|(c, _)| (sheet, c))); } cx.changed.extend(touched); @@ -802,450 +812,15 @@ fn decimals(s: &mut Session, p: &Json, delta: i32) -> Result { set_fmt(s, p, &new) } -/// Built-in cell styles (our own palette). -pub fn builtin_cell_style(name: &str, theme: &Theme) -> Option
\ - \ - \ - \ -
NameQty
Apples & <pears>3
Total
" - ); - let cell = "border:1px solid #d4d4d4;padding:2px 4px;white-space:pre-wrap;"; - assert_eq!( - copied(&wb, "A1:B2"), - format!( - "\ - \ -
NameQty
Apples & <pears>3
" - ) - ); - } - - #[test] - fn html_export_fails_instead_of_dropping_cells_past_the_row_limit() { - let mut wb = Workbook::new(); - let sh = wb.sheet_mut(0).unwrap(); - sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("near")); - sh.set_value(CellRef::new(149_999, 0), gridcraft_core::Value::text("far")); - assert!(save_bytes(&wb, "book.html").is_err()); - let sh = wb.sheet_mut(0).unwrap(); - sh.remove_cell(CellRef::new(149_999, 0)); - sh.set_value(CellRef::new(100_000, 0), gridcraft_core::Value::text("far")); - let html = String::from_utf8(save_bytes(&wb, "book.html").unwrap()).unwrap(); - assert!(html.contains(">near") && html.contains(">far")); - } - - #[test] - fn macros_are_saved_only_into_xlsm() { - let mut wb = Workbook::new(); - wb.vba_project = Some(b"vba".to_vec().into()); - let has_macros = |path: &str| { - let bytes = save_bytes(&wb, path).unwrap(); - gridcraft_xlsx::read_xlsx(&bytes).unwrap().0.vba_project.is_some() - }; - assert!(has_macros("book.xlsm")); - assert!(has_macros("BOOK.XLSM")); - assert!(!has_macros("book.xlsx"), "an .xlsx never carries a VBA project"); - assert!(has_macros("book.xltm"), "a macro-enabled template keeps the VBA project"); - assert!(!has_macros("book.xltx"), "a macro-free template never carries a VBA project"); - assert!(wb.vba_project.is_some(), "the open workbook keeps its macros"); - } - - #[test] - fn csv_named_history_does_not_get_the_reserved_sheet_name() { - for file in ["History.csv", "hIsToRy.csv", "history.tsv"] { - let (wb, _) = open_bytes(file, b"1\n").unwrap(); - let name = wb.sheets[0].name.clone(); - assert!(wb.check_sheet_name(&name, Some(0)).is_ok(), "{file} opened as {name:?}"); - } - let (wb, _) = open_bytes("Sales.csv", b"1\n").unwrap(); - assert_eq!(wb.sheets[0].name, "Sales"); - } - - /// A save that can't be put in place (here a folder already has the workbook's name, as - /// with a file another app holds locked) fails without leaving `.sctmp` behind. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn failed_save_leaves_no_temporary_file() { - let dir = std::env::temp_dir().join(format!("gridcraft-write-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let blocked = dir.join("Book1.xlsx"); - std::fs::create_dir(&blocked).unwrap(); - assert!(write_file(blocked.to_str().unwrap(), b"workbook").is_err()); - assert!(!dir.join("Book1.xlsx.sctmp").exists(), "the temporary file is removed"); - // An ordinary save still works and leaves only the workbook. - let ok = dir.join("Book2.xlsx"); - write_file(ok.to_str().unwrap(), b"workbook").unwrap(); - assert_eq!(std::fs::read(&ok).unwrap(), b"workbook"); - assert!(!dir.join("Book2.xlsx.sctmp").exists()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// While a script runs (#2178), file reads and writes are refused whatever command or - /// parameter asked for them; nesting and dropping the sandbox restore access. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn script_sandbox_refuses_file_access_until_dropped() { - let dir = std::env::temp_dir().join(format!("gridcraft-sandbox-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let existing = dir.join("in.csv"); - std::fs::write(&existing, b"a,b\n").unwrap(); - let (existing, out) = (existing.to_string_lossy().to_string(), dir.join("out.xlsx").to_string_lossy().to_string()); - { - let _outer = ScriptSandbox::enter(); - { - let _inner = ScriptSandbox::enter(); - assert!(read_file(&existing).is_err()); - } - assert!(read_file(&existing).is_err(), "the outer sandbox still holds"); - assert!(write_file(&out, b"leak").is_err()); - assert!(!std::path::Path::new(&out).exists()); - } - assert_eq!(read_file(&existing).unwrap(), b"a,b\n"); - write_file(&out, b"ok").unwrap(); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A minimal compound (CFB/OLE2) file — FAT in sector 0, directory in sector 1 — holding a - /// root entry and the given stream names. - fn cfb(streams: &[&str]) -> Vec { - let mut b = vec![0u8; 512 * 3]; - let mut put = |at: usize, v: &[u8]| b[at..at + v.len()].copy_from_slice(v); - put(0, &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]); - put(30, &9u16.to_le_bytes()); - put(44, &1u32.to_le_bytes()); - put(48, &1u32.to_le_bytes()); - put(68, &0xFFFF_FFFEu32.to_le_bytes()); - for i in 1..109 { - put(76 + i * 4, &0xFFFF_FFFFu32.to_le_bytes()); - } - put(512, &0xFFFF_FFFDu32.to_le_bytes()); - put(516, &0xFFFF_FFFEu32.to_le_bytes()); - for (k, name) in std::iter::once("Root Entry").chain(streams.iter().copied()).enumerate() { - let units: Vec = name.encode_utf16().flat_map(u16::to_le_bytes).collect(); - put(1024 + k * 128, &units); - put(1024 + k * 128 + 64, &(units.len() as u16 + 2).to_le_bytes()); - } - b - } - - /// Cut-list rows as a CAD/CAM program exports them: `;`-separated, CRLF, part codes in the last - /// two columns, a part name containing a comma. - const CUT_LIST: &str = "1;511;184;P3_L1_led;2162PE;16;1MM_2162PE;1MM_2162PE;;;1244121406FB;\r\n\ - 1;562.5;510;Komoda, lijevo;2162PE;19;1MM_2162PE;;;;12441214071A;124412140710\r\n"; - - #[test] - fn csv_save_keeps_the_separator_it_was_opened_with() { - let (wb, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap(); - assert_eq!(wb.csv_delimiter, Some(b';')); - assert_eq!(String::from_utf8(save_bytes(&wb, "cut list.csv").unwrap()).unwrap(), CUT_LIST); - // Save As another .csv name keeps it too; a comma file stays a comma file (quoting only - // fields that contain the separator in use). - assert_eq!(String::from_utf8(save_bytes(&wb, "copy.CSV").unwrap()).unwrap(), CUT_LIST); - let commas = "\"Komoda, lijevo\",b\r\n1,x;y\r\n"; - let (wb, _) = open_bytes("plain.csv", commas.as_bytes()).unwrap(); - assert_eq!(String::from_utf8(save_bytes(&wb, "plain.csv").unwrap()).unwrap(), commas); - // A tab-separated file named .csv round-trips with tabs. - let tabs = "a\tb\r\n1\t2\r\n"; - let (wb, _) = open_bytes("tabs.csv", tabs.as_bytes()).unwrap(); - assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs); - } - - #[test] - fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() { - let mut wb = Workbook::new(); - if let Some(sh) = wb.sheet_mut(0) { - sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("a")); - sh.set_value(CellRef::new(0, 1), gridcraft_core::Value::Number(1.0)); - } - assert_eq!(save_bytes(&wb, "new.csv").unwrap(), b"a,1\r\n"); - // Through .xlsx the CSV origin is gone, as in Excel. - let (from_csv, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap(); - let (reopened, _) = open_bytes("book.xlsx", &save_bytes(&from_csv, "book.xlsx").unwrap()).unwrap(); - assert_eq!(reopened.csv_delimiter, None); - assert!(String::from_utf8(save_bytes(&reopened, "again.csv").unwrap()).unwrap().starts_with("1,511,184,")); - // A .tsv/.txt saved as .csv gets commas; as .tsv it keeps tabs. - let (tsv, _) = open_bytes("list.txt", b"a\tb\r\n").unwrap(); - assert_eq!(save_bytes(&tsv, "list.csv").unwrap(), b"a,b\r\n"); - assert_eq!(save_bytes(&tsv, "list.tsv").unwrap(), b"a\tb\r\n"); - } - - #[test] - fn encrypted_workbook_is_reported_not_misread() { - let file = gridcraft_xlsx::testing::encrypt_workbook(b"package", "pw"); - let msg = open_bytes("secret.xlsx", &file).unwrap_err().to_string(); - assert!(msg.contains(PASSWORD_REQUIRED), "got: {msg}"); - assert!(!msg.contains("zip"), "must not surface the zip error: {msg}"); - // A compound file naming the streams but unreadable is damage: no password is asked for, - // and none helps. - let file = cfb(&["EncryptionInfo", "EncryptedPackage"]); - for password in [None, Some("pw")] { - let msg = open_bytes_with_password("secret.xlsx", &file, password).unwrap_err().to_string(); - assert!(msg.contains("damaged") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}"); - } - } - - #[test] - fn encryption_no_password_opens_is_reported_without_asking_for_one() { - let info: &[u8] = &[3, 0, 2, 0, 4, 0, 0, 0]; // Standard header flags: RC4, not AES - let file = gridcraft_xlsx::testing::compound_file(&[("EncryptionInfo", info), ("EncryptedPackage", &[0; 8])]); - let msg = open_bytes("rc4.xlsx", &file).unwrap_err().to_string(); - assert!(msg.contains("RC4") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}"); - let irm = gridcraft_xlsx::testing::compound_file(&[("EncryptedPackage", &[0; 8])]); - let msg = open_bytes("irm.xlsx", &irm).unwrap_err().to_string(); - assert!(msg.contains("rights-management") && !msg.contains("damaged"), "got: {msg}"); - } - - #[test] - fn other_compound_files_are_not_called_encrypted() { - let err = open_bytes("old.doc", &cfb(&["WordDocument", "\u{5}SummaryInformation"])).unwrap_err(); - let msg = err.to_string(); - assert!(msg.contains("not an Excel workbook"), "got: {msg}"); - assert!(!msg.contains("password"), "got: {msg}"); - } - - /// Save As CSV/TSV writes cells as displayed: number formats applied, formula results, - /// whole values in narrow columns (never `#####`), quoting unchanged. - #[test] - fn csv_writes_displayed_text() { - use gridcraft_core::{CellError, Value}; - use gridcraft_model::{Cell, Formula, LineInfo, NumFmt, StyleId}; - let mut wb = Workbook::new(); - let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)); - let (date, money, pct, frac, text, fixed, thousands) = - (styled("yyyy-mm-dd"), styled("$#,##0.00"), styled("0.0%"), styled("# ?/?"), styled("@"), styled("0.00"), styled("#,##0")); - let sh = wb.sheet_mut(0).unwrap(); - let cells = [ - ("A1", Cell { value: Value::Number(46023.0), formula: None, style: date }), - ("B1", Cell { value: Value::Number(1234.5), formula: None, style: money }), - ("C1", Cell { value: Value::Number(0.125), formula: None, style: pct }), - ("D1", Cell { value: Value::Number(1.5), formula: None, style: frac }), - ("E1", Cell { value: Value::text("007"), formula: None, style: text }), - ("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money }), - ("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT }), - ("A2", Cell { value: Value::Number(46024.0), style: date, ..Cell::formula(Formula::new("A1+1")) }), - ("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed }), - ("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT }), - ("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands }), - ]; - for (a, c) in cells { - sh.set_cell(CellRef::parse(a).unwrap(), c); - } - // Column B is far too narrow for its numbers: the grid shows #####, the file must not. - sh.cols.insert(1, LineInfo { size: Some(1.0), ..Default::default() }); - sh.show_formulas = true; - let csv = String::from_utf8(save_bytes(&wb, "out.csv").unwrap()).unwrap(); - assert_eq!(csv, "2026-01-01,\"$1,234.50\",12.5%,1 1/2,007,#N/A,TRUE\r\n2026-01-02,12345678.90,-0.25,\"1,234,567\",,,\r\n"); - let tsv = String::from_utf8(save_bytes(&wb, "out.tsv").unwrap()).unwrap(); - assert!(tsv.starts_with("2026-01-01\t$1,234.50\t12.5%\t"), "{tsv}"); - } - - #[test] - fn delimited_exports_preserve_general_precision_and_explicit_number_formats() { - use gridcraft_core::Value; - use gridcraft_model::{Cell, NumFmt, StyleId}; - let mut workbook = Workbook::new(); - let scientific = workbook.styles.derive(StyleId::DEFAULT, |style| style.num_fmt = NumFmt::new("0.00E+00")); - let sheet = workbook.sheet_mut(0).unwrap(); - sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() }); - sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() }); - sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() }); - for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] { - let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap(); - assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n")); - } - } - - #[test] - fn template_extension_saves_template_content_type() { - let bytes = save_bytes(&Workbook::new(), "Budget.xltx").unwrap(); - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let mut types = String::new(); - std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut types).unwrap(); - assert!( - types.contains( - r#"PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml""# - ), - "{types}" - ); - } - - /// Where `part`'s entry starts in the central directory of `package`. - fn central_entry(package: &[u8], part: &str) -> usize { - let mut at = 0; - while let Some(i) = package.get(at..).and_then(|rest| rest.windows(4).position(|w| w == b"PK\x01\x02")) { - let entry = at + i; - let len = u16::from_le_bytes([package[entry + 28], package[entry + 29]]) as usize; - if &package[entry + 46..entry + 46 + len] == part.as_bytes() { - return entry; - } - at = entry + 46; - } - panic!("{part} is not in the package"); - } - - /// `package` with `part` declaring `size` unpacked bytes: the reader refuses the part on the - /// declared size, so no real 512 MB part has to be built. - fn declaring(mut package: Vec, part: &str, size: u32) -> Vec { - let at = central_entry(&package, part); - package[at + 24..at + 28].copy_from_slice(&size.to_le_bytes()); - package - } - - #[test] - fn a_part_over_the_size_limit_says_how_to_get_the_data_in() { - let mut wb = Workbook::new(); - wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::text("big")); - let package = save_bytes(&wb, "big.xlsx").unwrap(); - // The size reported in storytold/gridcraft#1242. - let msg = open_bytes("big.xlsx", &declaring(package.clone(), "xl/worksheets/sheet1.xml", 540_278_731)).unwrap_err().to_string(); - assert!(msg.starts_with("We can't open 'big.xlsx': "), "{msg}"); - assert!(msg.contains("xl/worksheets/sheet1.xml") && msg.contains("515 MB") && msg.contains("512 MB"), "{msg}"); - assert!(msg.contains("several sheets") && msg.contains("CSV"), "{msg}"); - assert!(!msg.contains("bytes"), "{msg}"); - // Splitting sheets doesn't shrink the shared strings, which every sheet uses: only CSV helps. - let msg = open_bytes("big.xlsx", &declaring(package.clone(), "xl/sharedStrings.xml", 540_278_731)).unwrap_err().to_string(); - assert!(msg.contains("xl/sharedStrings.xml") && msg.contains("515 MB") && msg.contains("CSV"), "{msg}"); - assert!(!msg.contains("several sheets"), "{msg}"); - // Just over the limit never reads as a size equal to it. - let msg = open_bytes("big.xlsx", &declaring(package, "xl/worksheets/sheet1.xml", 512 * 1024 * 1024 + 1)).unwrap_err().to_string(); - assert!(msg.contains("more than 512 MB"), "{msg}"); - // A package that fails for another reason keeps its own error, oversized part or not. - let mut broken = declaring(save_bytes(&wb, "big.xlsx").unwrap(), "xl/worksheets/sheet1.xml", 540_278_731); - let at = central_entry(&broken, "xl/workbook.xml"); - broken[at + 46 + "xl/workbook.xml".len() - 1] = b'x'; - let msg = open_bytes("big.xlsx", &broken).unwrap_err().to_string(); - assert!(msg.starts_with("We can't open 'big.xlsx': ") && !msg.contains("unpacks"), "{msg}"); - } - - #[test] - fn content_wins_over_a_mismatched_extension() { - let mut wb = Workbook::new(); - wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Number(7.0)); - let package = save_bytes(&wb, "book.xlsx").unwrap(); - for name in ["book.xlsx", "book.ods", "book.xlsb", "book.csv"] { - let (opened, _) = open_bytes(name, &package).unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 0)), gridcraft_core::Value::Number(7.0), "{name}"); - } - for name in ["data.xlsx", "data.csv"] { - let (opened, _) = open_bytes(name, b"a,b\n1,2\n").unwrap_or_else(|e| panic!("{name}: {e}")); - assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 1)), gridcraft_core::Value::text("b"), "{name}"); - } - } -} +mod tests; diff --git a/crates/engine/src/io/sylk.rs b/crates/engine/src/io/sylk.rs new file mode 100644 index 0000000000..8eded10428 --- /dev/null +++ b/crates/engine/src/io/sylk.rs @@ -0,0 +1,328 @@ +//! SYLK (`.slk`) import: the symbolic link text format older spreadsheets and some legacy systems +//! export. One record per line, fields separated by `;` (`;;` is a literal semicolon): +//! +//! - `ID` starts the file; `E` ends it. +//! - `C;Y;X;K;E` is a cell. `Y` and `X` may be left out to stay on the +//! current row or column. `K` is a number, `"text"`, `TRUE`/`FALSE` or an error; `E` is a +//! formula in R1C1 notation; `S;R;C` shares the formula of another cell. +//! - `P;P` adds a number format to the file's list; `F;P;Y;X` gives a cell the +//! n-th format (0-based), and `F;W ` sets column widths in characters. +//! +//! Other records (fonts, options, window settings) are skipped. Formulas are converted to A1 with +//! the same relative and absolute references, as Excel does when it opens the file. + +use std::collections::HashMap; +use std::sync::Arc; + +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, Value, col_to_letters}; +use gridcraft_model::{Cell, Formula, NumFmt, Sheet, Style, Workbook}; + +use crate::{EngineError, Result}; + +/// The largest SYLK file read, as for other text imports: past it the file is refused. +const MAX_BYTES: usize = 512 << 20; +/// Column-width records kept from one file; each can cover every column. +const MAX_WIDTH_RECORDS: usize = 1024; + +/// Reads a SYLK file into a one-sheet workbook. Returns the workbook and its warnings. +pub fn read(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec)> { + if bytes.len() > MAX_BYTES { + return Err(EngineError::Other(format!("We can't open '{name}': the SYLK file is larger than {} MB.", MAX_BYTES >> 20))); + } + let text = match std::str::from_utf8(bytes) { + Ok(s) => s.to_string(), + // Older exports are in a single-byte code page: keep each byte as its Latin-1 character. + Err(_) => bytes.iter().map(|&b| char::from(b)).collect(), + }; + let text = text.strip_prefix('\u{feff}').unwrap_or(&text); + if !text.starts_with("ID") { + return Err(EngineError::Other(format!("We can't open '{name}': it isn't a SYLK file (it doesn't start with an ID record)."))); + } + let mut sheet = Sheet::new("Sheet1"); + let mut formats: Vec = Vec::new(); + // Cells' number formats by index into `formats`, applied once every format is known. + let mut cell_formats: Vec<(CellRef, usize)> = Vec::new(); + let mut formulas: HashMap = HashMap::new(); + let mut widths: Vec<(u32, u32, f64)> = Vec::new(); + let (mut row, mut col) = (0u32, 0u32); + let mut skipped = 0usize; + for line in text.lines() { + let fields = split_fields(line); + let Some((kind, rest)) = fields.split_first() else { continue }; + match kind.as_str() { + "C" => { + let (mut value, mut formula, mut shared) = (None, None, None::<(Option, Option)>); + let mut bad = false; + for f in rest { + let (tag, arg) = f.split_at(f.chars().next().map_or(0, char::len_utf8)); + match tag { + "Y" => match position(arg, MAX_ROWS) { + Some(r) => row = r, + None => bad = true, + }, + "X" => match position(arg, MAX_COLS) { + Some(c) => col = c, + None => bad = true, + }, + "K" => value = Some(parse_value(arg)), + "E" => formula = Some(arg.to_string()), + "S" => shared = Some((None, None)), + // In a shared-formula cell, R and C name the cell whose formula it shares. + "R" if shared.is_some() => shared = shared.map(|(_, c)| (position(arg, MAX_ROWS), c)), + "C" if shared.is_some() => shared = shared.map(|(r, _)| (r, position(arg, MAX_COLS))), + _ => {} + } + } + if bad { + skipped += 1; + continue; + } + let at = CellRef::new(row, col); + if let Some((Some(r), Some(c))) = shared { + formula = formulas.get(&CellRef::new(r, c)).cloned(); + } + let mut cell = sheet.cell(at).cloned().unwrap_or_else(|| Cell::value(Value::Empty)); + if let Some(v) = value { + cell.value = v; + } + if let Some(r1c1) = formula { + let a1 = r1c1_formula_to_a1(&r1c1, at); + let f = Formula::new(&a1); + if f.expr.is_some() { + cell.formula = Some(Arc::new(f)); + formulas.insert(at, r1c1); + } else { + skipped += 1; + } + } + sheet.set_cell(at, cell); + } + "F" => { + let mut format = None; + for f in rest { + let (tag, arg) = f.split_at(f.chars().next().map_or(0, char::len_utf8)); + match tag { + "Y" => row = position(arg, MAX_ROWS).unwrap_or(row), + "X" => col = position(arg, MAX_COLS).unwrap_or(col), + "P" => format = arg.parse::().ok(), + "W" => { + let mut parts = arg.split_whitespace(); + if let (Some(first), Some(last), Some(width)) = (parts.next(), parts.next(), parts.next()) + && let (Some(first), Some(last), Ok(width)) = + (position(first, MAX_COLS), position(last, MAX_COLS), width.parse::()) + && first <= last + && (0.0..=255.0).contains(&width) + // A file of width records can't make the import loop over every column + // again and again. + && widths.len() < MAX_WIDTH_RECORDS + { + widths.push((first, last, width)); + } + } + _ => {} + } + } + if let Some(format) = format { + cell_formats.push((CellRef::new(row, col), format)); + } + } + // Number formats only: `P;F…` and `P;E…` are fonts. + "P" => { + if let Some(code) = rest.first().and_then(|f| f.strip_prefix('P')) { + formats.push(code.to_string()); + } + } + "E" => break, + _ => {} + } + } + for (first, last, width) in widths { + let size = crate::cmd::format::chars_to_points(width) as f32; + for c in first..=last { + sheet.cols.entry(c).or_default().size = Some(size); + } + } + let mut wb = Workbook::new(); + let mut styles = HashMap::new(); + for (at, index) in cell_formats { + let Some(code) = formats.get(index).filter(|code| !code.is_empty() && *code != "General") else { continue }; + let style = *styles.entry(index).or_insert_with(|| wb.styles.intern(Style { num_fmt: NumFmt(Arc::from(code.as_str())), ..Style::default() })); + let mut cell = sheet.cell(at).cloned().unwrap_or_else(|| Cell::value(Value::Empty)); + cell.style = style; + sheet.set_cell(at, cell); + } + if let Some(first) = wb.sheet_mut(0) { + sheet.name = std::mem::take(&mut first.name); + *first = sheet; + } + let mut warnings = Vec::new(); + if skipped > 0 { + warnings.push(format!("{name}: {skipped} SYLK records GridCraft couldn't read were skipped")); + } + Ok((wb, warnings)) +} + +/// A record's fields: `;` separates them and `;;` is a literal semicolon. +fn split_fields(line: &str) -> Vec { + let mut fields = vec![String::new()]; + let mut chars = line.trim_end_matches('\r').chars().peekable(); + while let Some(c) = chars.next() { + if c == ';' { + if chars.peek() == Some(&';') { + chars.next(); + if let Some(f) = fields.last_mut() { + f.push(';'); + } + } else { + fields.push(String::new()); + } + } else if let Some(f) = fields.last_mut() { + f.push(c); + } + } + fields +} + +/// A 1-based row or column number → 0-based, within `max`. +fn position(arg: &str, max: u32) -> Option { + arg.trim().parse::().ok().filter(|n| (1..=max).contains(n)).map(|n| n - 1) +} + +/// A `K` value: `"text"` (everything between the first and the last quote, as written), a +/// boolean, an error or a number. +fn parse_value(arg: &str) -> Value { + if let Some(text) = arg.strip_prefix('"') { + let text = text.strip_suffix('"').unwrap_or(text); + return Value::Text(Arc::from(text)); + } + if arg.eq_ignore_ascii_case("TRUE") || arg.eq_ignore_ascii_case("FALSE") { + return Value::Bool(arg.eq_ignore_ascii_case("TRUE")); + } + if let Some(e) = CellError::parse(arg) { + return Value::Error(e); + } + match arg.trim().parse::() { + Ok(n) if n.is_finite() => Value::Number(n), + _ => Value::Text(Arc::from(arg)), + } +} + +/// One part of an R1C1 reference: `R`/`C` followed by an absolute number, a bracketed offset or +/// nothing (the cell's own row or column). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Part { + Absolute(u32), + Relative(i64), +} + +impl Part { + /// The 0-based index and whether it is absolute, or `None` when it falls off the sheet. + fn resolve(self, base: u32, max: u32) -> Option<(u32, bool)> { + match self { + Part::Absolute(n) => (1..=max).contains(&n).then(|| (n - 1, true)), + Part::Relative(k) => i64::from(base).checked_add(k).and_then(|v| u32::try_from(v).ok()).filter(|v| *v < max).map(|v| (v, false)), + } + } +} + +/// Parses the number after `R` or `C` at `i`: digits, `[offset]` or nothing. Returns the part and +/// the index after it, or `None` when the text isn't a reference part. +fn parse_part(chars: &[char], i: usize) -> Option<(Part, usize)> { + match chars.get(i) { + Some('[') => { + let close = chars[i..].iter().position(|&c| c == ']')? + i; + let inner: String = chars[i + 1..close].iter().collect(); + Some((Part::Relative(inner.parse().ok()?), close + 1)) + } + Some(c) if c.is_ascii_digit() => { + let end = chars[i..].iter().position(|c| !c.is_ascii_digit()).map_or(chars.len(), |p| p + i); + let n: String = chars[i..end].iter().collect(); + Some((Part::Absolute(n.parse().unwrap_or(u32::MAX)), end)) + } + _ => Some((Part::Relative(0), i)), + } +} + +fn is_word_char(c: char) -> bool { + c.is_alphanumeric() || matches!(c, '_' | '.' | '\\' | '?' | '$') +} + +/// Rewrites the R1C1 references in a SYLK formula as A1 references for the cell at `at`: +/// `RC[-1]` → `B2`, `R1C1` → `$A$1`, `R[-2]C:R[-1]C` → `D2:D3`, a whole column `C4` → `$D:$D` and +/// a whole row `R3` → `$3:$3`. Text in quotes and quoted sheet names are left alone; a reference +/// off the sheet becomes `#REF!`. +pub(crate) fn r1c1_formula_to_a1(formula: &str, at: CellRef) -> String { + let chars: Vec = formula.chars().collect(); + let mut out = String::with_capacity(formula.len()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c == '"' || c == '\'' { + // Copy the quoted run as it is; a doubled quote stays inside it. + let mut j = i + 1; + while j < chars.len() && !(chars[j] == c && chars.get(j + 1) != Some(&c)) { + j += if chars[j] == c { 2 } else { 1 }; + } + let stop = (j + 1).min(chars.len()); + out.extend(&chars[i..stop]); + i = stop; + continue; + } + let starts_word = i == 0 || !is_word_char(chars[i - 1]); + if starts_word + && matches!(c, 'R' | 'r' | 'C' | 'c') + && let Some((text, next)) = reference_at(&chars, i, at) + { + out.push_str(&text); + i = next; + continue; + } + // Copy the rest of a word as it is, so `ROUND` or `Sheet2` isn't read as a reference. + if is_word_char(c) { + let end = (i..chars.len()).find(|&j| !is_word_char(chars[j])).unwrap_or(chars.len()); + out.extend(&chars[i..end]); + i = end; + } else { + out.push(c); + i += 1; + } + } + out +} + +/// The A1 text of the R1C1 reference starting at `i`, and the index after it, or `None` when the +/// word there isn't a reference (a function or a name). +fn reference_at(chars: &[char], i: usize, at: CellRef) -> Option<(String, usize)> { + let mut j = i; + let mut row = None; + let mut col = None; + if matches!(chars.get(j), Some('R' | 'r')) { + let (part, next) = parse_part(chars, j + 1)?; + row = Some(part); + j = next; + } + if matches!(chars.get(j), Some('C' | 'c')) { + let (part, next) = parse_part(chars, j + 1)?; + col = Some(part); + j = next; + } + if row.is_none() && col.is_none() { + return None; + } + // A reference ends the word: `ROUND(`, `RATE` or `R2D2` are names. + if chars.get(j).is_some_and(|&c| is_word_char(c) || c == '(' || c == '[' || c == '!') { + return None; + } + let row_text = |p: Part| p.resolve(at.row, MAX_ROWS).map(|(r, abs)| format!("{}{}", if abs { "$" } else { "" }, r + 1)); + let col_text = |p: Part| p.resolve(at.col, MAX_COLS).map(|(c, abs)| format!("{}{}", if abs { "$" } else { "" }, col_to_letters(c))); + // One side of a range (`R2:R4`, `C1:C3`) is written alone; a lone row or column is the whole of it. + let prev = chars[..i].iter().rev().find(|c| !c.is_whitespace()); + let in_range = prev == Some(&':') || chars[j..].iter().find(|c| !c.is_whitespace()) == Some(&':'); + let text = match (row, col) { + (Some(r), Some(c)) => row_text(r).zip(col_text(c)).map(|(r, c)| format!("{c}{r}")), + (Some(r), None) => row_text(r).map(|r| if in_range { r } else { format!("{r}:{r}") }), + (None, Some(c)) => col_text(c).map(|c| if in_range { c } else { format!("{c}:{c}") }), + (None, None) => None, + }; + Some((text.unwrap_or_else(|| "#REF!".into()), j)) +} diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs new file mode 100644 index 0000000000..ae5ea88323 --- /dev/null +++ b/crates/engine/src/io/tests.rs @@ -0,0 +1,763 @@ +use super::*; + +fn book(rtl: bool, cells: &[(&str, gridcraft_core::Value, gridcraft_model::HAlign)]) -> Workbook { + let mut wb = Workbook::new(); + let ids: Vec<_> = cells.iter().map(|(_, _, h)| wb.styles.derive(gridcraft_model::StyleId::DEFAULT, |st| st.align.h = *h)).collect(); + let sh = wb.sheet_mut(0).unwrap(); + sh.right_to_left = rtl; + for ((at, value, _), id) in cells.iter().zip(ids) { + let c = CellRef::parse(at).unwrap(); + sh.set_value(c, value.clone()); + sh.set_style(c, id); + } + wb +} + +fn copied(wb: &Workbook, range: &str) -> String { + let r = RangeRef::parse(range).unwrap(); + range_html(wb, 0, r, &crate::display::range_text(wb, 0, r)).unwrap() +} + +#[cfg(not(target_arch = "wasm32"))] +#[cfg(unix)] +#[test] +fn save_fails_upfront_when_the_temp_name_is_taken() { + // Another local user who can write the directory must not be able to point the + // save's predictable temporary name at their own file: creation is exclusive. + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-temp-name-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, b"original").unwrap(); + let dest = dir.join("book.xlsx"); + std::os::unix::fs::symlink(&victim, dir.join("book.xlsx.sctmp")).unwrap(); + let err = write_file(dest.to_str().unwrap(), b"new").unwrap_err(); + assert_eq!(std::fs::read(&victim).unwrap(), b"original"); + assert!(!dir.join("book.xlsx").exists(), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[cfg(unix)] +#[test] +fn save_keeps_the_destination_access_restrictions() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-permissions-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let dest = dir.join("private.xlsx"); + std::fs::write(&dest, b"v1").unwrap(); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + write_file(dest.to_str().unwrap(), b"v2").unwrap(); + let mode = std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + // And a brand-new file is created with the restrictive, not permissive, default. + let fresh = dir.join("new.xlsx"); + write_file(fresh.to_str().unwrap(), b"v").unwrap(); + let mode = std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777; + assert!(mode & 0o022 == 0, "mode {mode:o}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn open_refuses_directories_and_unknowable_lengths() { + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-open-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert!(read_file(dir.to_str().unwrap()).is_err(), "a directory is not a regular file"); + assert!(read_file(dir.join("missing").to_str().unwrap()).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn html_export_refuses_an_outsized_grid_instead_of_growing_forever() { + // #2387: the used rectangle alone bounds the output (every row writes the whole + // column span), so a sparse sheet with one cell at A1 and another far right + // 300 rows down is 4.9M cells → refused before a byte of `` is written. + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("start".into())); + sh.set_value(CellRef::new(300, 16383), gridcraft_core::Value::Text("corner".into())); + let err = to_html(&wb, 0).unwrap_err(); + assert!(err.to_string().contains("too tall × wide"), "{err}"); + // A normal sheet is fine. + let mut ok = Workbook::new(); + ok.sheet_mut(0).unwrap().set_value(CellRef::new(5, 2), gridcraft_core::Value::Text("t".into())); + assert!(to_html(&ok, 0).is_ok()); +} + +#[test] +fn html_export_embeds_images_as_data_uris() { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().images.push(gridcraft_model::Image { + id: 1, + anchor: gridcraft_model::Anchor { cell: CellRef::new(0, 0), dx: 0.0, dy: 0.0, width: 72.0, height: 36.0, mode: Default::default() }, + data: vec![1, 2, 3].into(), + mime: "image/png".into(), + alt: "a \"logo\"".into(), + }); + let html = to_html(&wb, 0).unwrap(); + assert!( + html.contains("\"a"), + "{html}" + ); + assert!(html.contains("
"); +} + +#[test] +fn html_export_places_images_at_their_anchor_using_sheet_geometry() { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.cols.insert(1, gridcraft_model::LineInfo { size: Some(100.0), ..Default::default() }); + sh.rows.insert(1, gridcraft_model::LineInfo { size: Some(30.0), ..Default::default() }); + sh.images.push(gridcraft_model::Image { + id: 1, + anchor: gridcraft_model::Anchor { cell: CellRef::new(3, 2), dx: 5.0, dy: 7.0, width: 10.0, height: 20.0, mode: Default::default() }, + data: vec![1].into(), + mime: "image/png".into(), + alt: String::new(), + }); + sh.set_value(CellRef::new(1, 1), gridcraft_core::Value::Number(1.0)); + let html = to_html(&wb, 0).unwrap(); + // The table starts at B2; the picture is at C4: one 100 px column and two rows (30 + 20) further on. + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains("left:105px;top:57px;width:10px;height:20px"), "{html}"); +} + +fn book_with_picture(anchor: &str, cell_at: (u32, u32)) -> Workbook { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(cell_at.0, cell_at.1), gridcraft_core::Value::Number(1.0)); + sh.images.push(gridcraft_model::Image { + id: 1, + anchor: gridcraft_model::Anchor { + cell: CellRef::parse(anchor).unwrap(), + dx: 0.0, + dy: 0.0, + width: 10.0, + height: 10.0, + mode: Default::default(), + }, + data: vec![1].into(), + mime: "image/png".into(), + alt: String::new(), + }); + wb +} + +#[test] +fn html_export_places_images_past_hidden_columns_and_rows() { + let mut wb = book_with_picture("C3", (0, 0)); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(2, 2), gridcraft_core::Value::Number(2.0)); + sh.cols.insert(1, gridcraft_model::LineInfo { hidden: true, ..Default::default() }); + sh.rows.insert(1, gridcraft_model::LineInfo { hidden: true, ..Default::default() }); + let html = to_html(&wb, 0).unwrap(); + // Column B and row 2 take no room: C3 is one default column and row from A1. + assert_eq!(html.matches(""), "{html}"); + assert!(html.contains(""), "Latin text keeps its own direction: {html}"); + assert!(html.contains(""), "numbers mirror to the left and keep their sign in front: {html}"); + let clip = copied(&wb, "A1:B1"); + assert!(clip.starts_with("
Hello!-5
-5"), "{clip}"); + + let ltr = book(false, &[("A1", Value::text("Hello!"), HAlign::General)]); + assert!(to_html(<r, 0).unwrap().contains("
")); + assert!(copied(<r, "A1").starts_with("
مرحبا!"), "General Arabic text aligns by its direction: {html}"); + assert!(html.contains(""), "explicit alignment stays: {html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains("
שלוםمرحباHello
"), "a left-to-right sheet has no table direction: {html}"); + + let clip = copied(&wb, "A1:D1"); + let cells: Vec<&str> = clip.split("") && html.contains(">far")); +} + +#[test] +fn macros_are_saved_only_into_xlsm() { + let mut wb = Workbook::new(); + wb.vba_project = Some(b"vba".to_vec().into()); + let has_macros = |path: &str| { + let bytes = save_bytes(&wb, path).unwrap(); + gridcraft_xlsx::read_xlsx(&bytes).unwrap().0.vba_project.is_some() + }; + assert!(has_macros("book.xlsm")); + assert!(has_macros("BOOK.XLSM")); + assert!(!has_macros("book.xlsx"), "an .xlsx never carries a VBA project"); + assert!(has_macros("book.xltm"), "a macro-enabled template keeps the VBA project"); + assert!(!has_macros("book.xltx"), "a macro-free template never carries a VBA project"); + assert!(wb.vba_project.is_some(), "the open workbook keeps its macros"); +} + +#[test] +fn csv_named_history_does_not_get_the_reserved_sheet_name() { + for file in ["History.csv", "hIsToRy.csv", "history.tsv"] { + let (wb, _) = open_bytes(file, b"1\n").unwrap(); + let name = wb.sheets[0].name.clone(); + assert!(wb.check_sheet_name(&name, Some(0)).is_ok(), "{file} opened as {name:?}"); + } + let (wb, _) = open_bytes("Sales.csv", b"1\n").unwrap(); + assert_eq!(wb.sheets[0].name, "Sales"); +} + +#[test] +fn csv_and_text_open_read_day_first_dates_and_report_a_guessed_order() { + let may = gridcraft_core::date::serial_from_ymd(gridcraft_core::DateSystem::D1900, 2026, 5, 31).unwrap(); + let april = gridcraft_core::date::serial_from_ymd(gridcraft_core::DateSystem::D1900, 2026, 4, 3).unwrap(); + for file in ["dates.csv", "dates.txt"] { + let (wb, warnings) = open_bytes(file, b"When\n31/05/2026\n03/04/2026\n").unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(1, 0)), gridcraft_core::Value::Number(may), "{file}"); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(2, 0)), gridcraft_core::Value::Number(april), "{file}"); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + } + let (_, warnings) = open_bytes("ambiguous.csv", b"When\n03/04/2026\n12/01/2026\n").unwrap(); + assert!(warnings.iter().any(|w| w.contains("column A") && w.contains("ambiguous")), "{warnings:?}"); +} + +/// A save that can't be put in place (here a folder already has the workbook's name, as +/// with a file another app holds locked) fails without leaving `.sctmp` behind. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_save_leaves_no_temporary_file() { + let dir = std::env::temp_dir().join(format!("gridcraft-write-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let blocked = dir.join("Book1.xlsx"); + std::fs::create_dir(&blocked).unwrap(); + assert!(write_file(blocked.to_str().unwrap(), b"workbook").is_err()); + assert!(!dir.join("Book1.xlsx.sctmp").exists(), "the temporary file is removed"); + // An ordinary save still works and leaves only the workbook. + let ok = dir.join("Book2.xlsx"); + write_file(ok.to_str().unwrap(), b"workbook").unwrap(); + assert_eq!(std::fs::read(&ok).unwrap(), b"workbook"); + assert!(!dir.join("Book2.xlsx.sctmp").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// While a script runs (#2178), file reads and writes are refused whatever command or +/// parameter asked for them; nesting and dropping the sandbox restore access. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn script_sandbox_refuses_file_access_until_dropped() { + let dir = std::env::temp_dir().join(format!("gridcraft-sandbox-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let existing = dir.join("in.csv"); + std::fs::write(&existing, b"a,b\n").unwrap(); + let (existing, out) = (existing.to_string_lossy().to_string(), dir.join("out.xlsx").to_string_lossy().to_string()); + { + let _outer = ScriptSandbox::enter(); + { + let _inner = ScriptSandbox::enter(); + assert!(read_file(&existing).is_err()); + } + assert!(read_file(&existing).is_err(), "the outer sandbox still holds"); + assert!(write_file(&out, b"leak").is_err()); + assert!(!std::path::Path::new(&out).exists()); + } + assert_eq!(read_file(&existing).unwrap(), b"a,b\n"); + write_file(&out, b"ok").unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A minimal compound (CFB/OLE2) file — FAT in sector 0, directory in sector 1 — holding a +/// root entry and the given stream names. +fn cfb(streams: &[&str]) -> Vec { + let mut b = vec![0u8; 512 * 3]; + let mut put = |at: usize, v: &[u8]| b[at..at + v.len()].copy_from_slice(v); + put(0, &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]); + put(30, &9u16.to_le_bytes()); + put(44, &1u32.to_le_bytes()); + put(48, &1u32.to_le_bytes()); + put(68, &0xFFFF_FFFEu32.to_le_bytes()); + for i in 1..109 { + put(76 + i * 4, &0xFFFF_FFFFu32.to_le_bytes()); + } + put(512, &0xFFFF_FFFDu32.to_le_bytes()); + put(516, &0xFFFF_FFFEu32.to_le_bytes()); + for (k, name) in std::iter::once("Root Entry").chain(streams.iter().copied()).enumerate() { + let units: Vec = name.encode_utf16().flat_map(u16::to_le_bytes).collect(); + put(1024 + k * 128, &units); + put(1024 + k * 128 + 64, &(units.len() as u16 + 2).to_le_bytes()); + } + b +} + +/// Cut-list rows as a CAD/CAM program exports them: `;`-separated, CRLF, part codes in the last +/// two columns, a part name containing a comma. +const CUT_LIST: &str = "1;511;184;P3_L1_led;2162PE;16;1MM_2162PE;1MM_2162PE;;;1244121406FB;\r\n\ + 1;562.5;510;Komoda, lijevo;2162PE;19;1MM_2162PE;;;;12441214071A;124412140710\r\n"; + +#[test] +fn csv_save_keeps_the_separator_it_was_opened_with() { + let (wb, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap(); + assert_eq!(wb.csv_delimiter, Some(b';')); + assert_eq!(String::from_utf8(save_bytes(&wb, "cut list.csv").unwrap()).unwrap(), CUT_LIST); + // Save As another .csv name keeps it too; a comma file stays a comma file (quoting only + // fields that contain the separator in use). + assert_eq!(String::from_utf8(save_bytes(&wb, "copy.CSV").unwrap()).unwrap(), CUT_LIST); + let commas = "\"Komoda, lijevo\",b\r\n1,x;y\r\n"; + let (wb, _) = open_bytes("plain.csv", commas.as_bytes()).unwrap(); + assert_eq!(String::from_utf8(save_bytes(&wb, "plain.csv").unwrap()).unwrap(), commas); + // A tab-separated file named .csv round-trips with tabs. + let tabs = "a\tb\r\n1\t2\r\n"; + let (wb, _) = open_bytes("tabs.csv", tabs.as_bytes()).unwrap(); + assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs); +} + +#[test] +fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() { + let mut wb = Workbook::new(); + if let Some(sh) = wb.sheet_mut(0) { + sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("a")); + sh.set_value(CellRef::new(0, 1), gridcraft_core::Value::Number(1.0)); + } + assert_eq!(save_bytes(&wb, "new.csv").unwrap(), b"a,1\r\n"); + // Through .xlsx the CSV origin is gone, as in Excel. + let (from_csv, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap(); + let (reopened, _) = open_bytes("book.xlsx", &save_bytes(&from_csv, "book.xlsx").unwrap()).unwrap(); + assert_eq!(reopened.csv_delimiter, None); + assert!(String::from_utf8(save_bytes(&reopened, "again.csv").unwrap()).unwrap().starts_with("1,511,184,")); + // A .tsv/.txt saved as .csv gets commas; as .tsv it keeps tabs. + let (tsv, _) = open_bytes("list.txt", b"a\tb\r\n").unwrap(); + assert_eq!(save_bytes(&tsv, "list.csv").unwrap(), b"a,b\r\n"); + assert_eq!(save_bytes(&tsv, "list.tsv").unwrap(), b"a\tb\r\n"); +} + +#[test] +fn encrypted_workbook_is_reported_not_misread() { + let file = gridcraft_xlsx::testing::encrypt_workbook(b"package", "pw"); + let msg = open_bytes("secret.xlsx", &file).unwrap_err().to_string(); + assert!(msg.contains(PASSWORD_REQUIRED), "got: {msg}"); + assert!(!msg.contains("zip"), "must not surface the zip error: {msg}"); + // A compound file naming the streams but unreadable is damage: no password is asked for, + // and none helps. + let file = cfb(&["EncryptionInfo", "EncryptedPackage"]); + for password in [None, Some("pw")] { + let msg = open_bytes_with_password("secret.xlsx", &file, password).unwrap_err().to_string(); + assert!(msg.contains("damaged") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}"); + } +} + +#[test] +fn encryption_no_password_opens_is_reported_without_asking_for_one() { + let info: &[u8] = &[3, 0, 2, 0, 4, 0, 0, 0]; // Standard header flags: RC4, not AES + let file = gridcraft_xlsx::testing::compound_file(&[("EncryptionInfo", info), ("EncryptedPackage", &[0; 8])]); + let msg = open_bytes("rc4.xlsx", &file).unwrap_err().to_string(); + assert!(msg.contains("RC4") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}"); + let irm = gridcraft_xlsx::testing::compound_file(&[("EncryptedPackage", &[0; 8])]); + let msg = open_bytes("irm.xlsx", &irm).unwrap_err().to_string(); + assert!(msg.contains("rights-management") && !msg.contains("damaged"), "got: {msg}"); +} + +#[test] +fn other_compound_files_are_not_called_encrypted() { + let err = open_bytes("old.doc", &cfb(&["WordDocument", "\u{5}SummaryInformation"])).unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("not an Excel workbook"), "got: {msg}"); + assert!(!msg.contains("password"), "got: {msg}"); +} + +/// Save As CSV/TSV writes cells as displayed: number formats applied, formula results, +/// whole values in narrow columns (never `#####`), quoting unchanged. +#[test] +fn csv_writes_displayed_text() { + use gridcraft_core::{CellError, Value}; + use gridcraft_model::{Cell, Formula, LineInfo, NumFmt, StyleId}; + let mut wb = Workbook::new(); + let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)); + let (date, money, pct, frac, text, fixed, thousands) = + (styled("yyyy-mm-dd"), styled("$#,##0.00"), styled("0.0%"), styled("# ?/?"), styled("@"), styled("0.00"), styled("#,##0")); + let sh = wb.sheet_mut(0).unwrap(); + let cells = [ + ("A1", Cell { value: Value::Number(46023.0), formula: None, style: date, py: None }), + ("B1", Cell { value: Value::Number(1234.5), formula: None, style: money, py: None }), + ("C1", Cell { value: Value::Number(0.125), formula: None, style: pct, py: None }), + ("D1", Cell { value: Value::Number(1.5), formula: None, style: frac, py: None }), + ("E1", Cell { value: Value::text("007"), formula: None, style: text, py: None }), + ("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money, py: None }), + ("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT, py: None }), + ("A2", Cell { value: Value::Number(46024.0), style: date, ..Cell::formula(Formula::new("A1+1")) }), + ("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed, py: None }), + ("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT, py: None }), + ("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands, py: None }), + ]; + for (a, c) in cells { + sh.set_cell(CellRef::parse(a).unwrap(), c); + } + // Column B is far too narrow for its numbers: the grid shows #####, the file must not. + sh.cols.insert(1, LineInfo { size: Some(1.0), ..Default::default() }); + sh.show_formulas = true; + let csv = String::from_utf8(save_bytes(&wb, "out.csv").unwrap()).unwrap(); + assert_eq!(csv, "2026-01-01,\"$1,234.50\",12.5%,1 1/2,007,#N/A,TRUE\r\n2026-01-02,12345678.90,-0.25,\"1,234,567\",,,\r\n"); + let tsv = String::from_utf8(save_bytes(&wb, "out.tsv").unwrap()).unwrap(); + assert!(tsv.starts_with("2026-01-01\t$1,234.50\t12.5%\t"), "{tsv}"); +} + +#[test] +fn delimited_exports_preserve_general_precision_and_explicit_number_formats() { + use gridcraft_core::Value; + use gridcraft_model::{Cell, NumFmt, StyleId}; + let mut workbook = Workbook::new(); + let scientific = workbook.styles.derive(StyleId::DEFAULT, |style| style.num_fmt = NumFmt::new("0.00E+00")); + let sheet = workbook.sheet_mut(0).unwrap(); + sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() }); + sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() }); + sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() }); + for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] { + let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap(); + assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n")); + } +} + +#[test] +fn template_extension_saves_template_content_type() { + let bytes = save_bytes(&Workbook::new(), "Budget.xltx").unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut types = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut types).unwrap(); + assert!( + types.contains(r#"PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml""#), + "{types}" + ); +} + +/// Where `part`'s entry starts in the central directory of `package`. +fn central_entry(package: &[u8], part: &str) -> usize { + let mut at = 0; + while let Some(i) = package.get(at..).and_then(|rest| rest.windows(4).position(|w| w == b"PK\x01\x02")) { + let entry = at + i; + let len = u16::from_le_bytes([package[entry + 28], package[entry + 29]]) as usize; + if &package[entry + 46..entry + 46 + len] == part.as_bytes() { + return entry; + } + at = entry + 46; + } + panic!("{part} is not in the package"); +} + +/// `package` with `part` declaring `size` unpacked bytes: the reader refuses the part on the +/// declared size, so no real 512 MB part has to be built. +fn declaring(mut package: Vec, part: &str, size: u32) -> Vec { + let at = central_entry(&package, part); + package[at + 24..at + 28].copy_from_slice(&size.to_le_bytes()); + package +} + +#[test] +fn a_part_over_the_size_limit_says_how_to_get_the_data_in() { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::text("big")); + let package = save_bytes(&wb, "big.xlsx").unwrap(); + // The size reported in storytold/gridcraft#1242. + let msg = open_bytes("big.xlsx", &declaring(package.clone(), "xl/worksheets/sheet1.xml", 540_278_731)).unwrap_err().to_string(); + assert!(msg.starts_with("We can't open 'big.xlsx': "), "{msg}"); + assert!(msg.contains("xl/worksheets/sheet1.xml") && msg.contains("515 MB") && msg.contains("512 MB"), "{msg}"); + assert!(msg.contains("several sheets") && msg.contains("CSV"), "{msg}"); + assert!(!msg.contains("bytes"), "{msg}"); + // Splitting sheets doesn't shrink the shared strings, which every sheet uses: only CSV helps. + let msg = open_bytes("big.xlsx", &declaring(package.clone(), "xl/sharedStrings.xml", 540_278_731)).unwrap_err().to_string(); + assert!(msg.contains("xl/sharedStrings.xml") && msg.contains("515 MB") && msg.contains("CSV"), "{msg}"); + assert!(!msg.contains("several sheets"), "{msg}"); + // Just over the limit never reads as a size equal to it. + let msg = open_bytes("big.xlsx", &declaring(package, "xl/worksheets/sheet1.xml", 512 * 1024 * 1024 + 1)).unwrap_err().to_string(); + assert!(msg.contains("more than 512 MB"), "{msg}"); + // A package that fails for another reason keeps its own error, oversized part or not. + let mut broken = declaring(save_bytes(&wb, "big.xlsx").unwrap(), "xl/worksheets/sheet1.xml", 540_278_731); + let at = central_entry(&broken, "xl/workbook.xml"); + broken[at + 46 + "xl/workbook.xml".len() - 1] = b'x'; + let msg = open_bytes("big.xlsx", &broken).unwrap_err().to_string(); + assert!(msg.starts_with("We can't open 'big.xlsx': ") && !msg.contains("unpacks"), "{msg}"); +} + +#[test] +fn content_wins_over_a_mismatched_extension() { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Number(7.0)); + let package = save_bytes(&wb, "book.xlsx").unwrap(); + for name in ["book.xlsx", "book.ods", "book.xlsb", "book.csv"] { + let (opened, _) = open_bytes(name, &package).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 0)), gridcraft_core::Value::Number(7.0), "{name}"); + } + for name in ["data.xlsx", "data.csv"] { + let (opened, _) = open_bytes(name, b"a,b\n1,2\n").unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 1)), gridcraft_core::Value::text("b"), "{name}"); + } +} + +/// #2871: opening an XLSX reads Google Sheets' `IFERROR(__xludf.DUMMYFUNCTION("…"),cached)` +/// wrapper as the formula inside when GridCraft calculates every function it calls (including +/// the evaluator's own, such as ROW), and keeps the wrapper, and so the cached value, for a +/// Google-only function. +#[test] +fn opening_google_sheets_export_unwraps_only_formulas_gridcraft_calculates() { + use gridcraft_core::{CellRef, Value}; + let mut wb = Workbook::new(); + let sh = std::sync::Arc::make_mut(&mut wb.sheets[0]); + let wrapped = [ + ("A1", "IFERROR(__xludf.DUMMYFUNCTION(\"SUM(ROW(B1:B3))\"),6)", Value::Number(6.0)), + ("A2", "IFERROR(__xludf.DUMMYFUNCTION(\"GOOGLETRANSLATE(\"\"hi\"\",\"\"en\"\",\"\"fr\"\")\"),\"salut\")", Value::text("salut")), + ]; + for (at, text, value) in &wrapped { + let cell = gridcraft_model::Cell { + value: value.clone(), + formula: Some(std::sync::Arc::new(gridcraft_model::Formula::new(text))), + ..Default::default() + }; + sh.cells.set(CellRef::parse(at).unwrap(), cell); + } + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let (opened, _) = open_bytes("google.xlsx", &bytes).unwrap(); + let text = |at: &str| opened.sheets[0].cells.get(CellRef::parse(at).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()); + assert_eq!(text("A1").as_deref(), Some("SUM(ROW(B1:B3))")); + assert_eq!(text("A2").as_deref(), Some("IFERROR(__XLUDF.DUMMYFUNCTION(\"GOOGLETRANSLATE(\"\"hi\"\",\"\"en\"\",\"\"fr\"\")\"),\"salut\")")); + assert_eq!(opened.sheets[0].cells.get(CellRef::parse("A2").unwrap()).map(|c| c.value.clone()), Some(Value::text("salut"))); +} + +#[test] +fn a_web_page_saved_as_xls_opens_its_table() { + // #3166: a web app's "Export to Excel" is an HTML table saved as .xls; it opened as lines of + // markup. Excel opens the table: values read as typed,
"), HAlign::General), + ("B2", Value::Number(3.0), HAlign::General), + ("A3", Value::text("Total"), HAlign::Right), + ], + ); + wb.sheet_mut(0).unwrap().merges.push(RangeRef::parse("A3:B3").unwrap()); + assert_eq!( + to_html(&wb, 0).unwrap(), + "Sheet1\ + \ + \ + \ +
NameQty
Apples & <pears>3
Total
" + ); + let cell = "border:1px solid #d4d4d4;padding:2px 4px;white-space:pre-wrap;"; + assert_eq!( + copied(&wb, "A1:B2"), + format!( + "\ + \ +
NameQty
Apples & <pears>3
" + ) + ); +} + +#[test] +fn html_export_fails_instead_of_dropping_cells_past_the_row_limit() { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("near")); + sh.set_value(CellRef::new(149_999, 0), gridcraft_core::Value::text("far")); + assert!(save_bytes(&wb, "book.html").is_err()); + let sh = wb.sheet_mut(0).unwrap(); + sh.remove_cell(CellRef::new(149_999, 0)); + sh.set_value(CellRef::new(100_000, 0), gridcraft_core::Value::text("far")); + let html = String::from_utf8(save_bytes(&wb, "book.html").unwrap()).unwrap(); + assert!(html.contains(">near
bold and centred, names + // the sheet. + let page = "\u{feff}\ + \ + \ + \ +
ItemQtyCode
Kiwi &\n Lime12007
Plum4,50042
"; + let (wb, warnings) = open_bytes("orders.xls", page.as_bytes()).unwrap(); + assert!(warnings.first().is_some_and(|w| w.contains("is a web page (HTML)")), "{warnings:?}"); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.name, "Orders"); + let v = |a: &str| sh.value(CellRef::parse(a).unwrap()); + assert_eq!(v("A1"), gridcraft_core::Value::text("Item")); + assert_eq!(v("A2"), gridcraft_core::Value::text("Kiwi & Lime")); + assert_eq!(v("B2"), gridcraft_core::Value::number(12.0)); + assert_eq!(v("C2"), gridcraft_core::Value::number(7.0), "read like typed input, as Excel does"); + assert_eq!(v("B3"), gridcraft_core::Value::number(4.5), "the number the page recorded"); + let style = |a: &str| wb.styles.get(sh.style_id(CellRef::parse(a).unwrap())).clone(); + assert!(style("A1").font.bold && style("A1").align.h == gridcraft_model::HAlign::Center); + assert!(!style("A2").font.bold); + // Opened as text, codes keep their zeros; a page named .html gets no warning. + let (wb, warnings) = open_bytes_with("orders.html", page.as_bytes(), None, true).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("C2").unwrap()), gridcraft_core::Value::text("007")); + // Plain text that merely starts with a tag-like word is still read as CSV. + let (wb, _) = open_bytes("notes.csv", b",1\nx,2\n").unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()), gridcraft_core::Value::number(2.0)); +} + +#[test] +fn a_web_page_table_keeps_its_characters_text_and_header_formats() { + // A page saved in Windows-1252 keeps its accented letters (it read as replacement characters). + let mut page = b"
Caf".to_vec(); + page.push(0xE9); + page.extend_from_slice(b"2024-01-15
Plum4,50
"); + let (wb, _) = open_bytes("menu.xls", &page).unwrap(); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.value(CellRef::parse("A1").unwrap()), gridcraft_core::Value::text("Café")); + // A date in a header cell stays a date, bold and centred (its format was replaced). + let b1 = wb.styles.get(sh.style_id(CellRef::parse("B1").unwrap())); + assert!(matches!(sh.value(CellRef::parse("B1").unwrap()), gridcraft_core::Value::Number(_))); + assert!(b1.font.bold && b1.align.h == gridcraft_model::HAlign::Center); + assert_ne!(b1.num_fmt.as_str(), "General", "the date keeps its date format"); + assert_eq!(sh.value(CellRef::parse("B2").unwrap()), gridcraft_core::Value::number(4.5)); + // Opened as text, a cell keeps the text it shows, not the number the page recorded for it. + let (wb, _) = open_bytes_with("menu.xls", &page, None, true).unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()), gridcraft_core::Value::text("4,50")); +} + +#[test] +fn a_web_page_table_opens_after_a_leading_comment_and_keeps_nonbreaking_spaces() { + // An exporter's comment before still makes a web page; ` ` stays a non-breaking + // space, as Excel keeps it, while ordinary whitespace collapses. + let page = "\n
New  Yorka \n b
"; + let (wb, warnings) = open_bytes("cities.xls", page.as_bytes()).unwrap(); + assert!(warnings.first().is_some_and(|w| w.contains("is a web page (HTML)")), "{warnings:?}"); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.value(CellRef::parse("A1").unwrap()), gridcraft_core::Value::text("New\u{a0}\u{a0}York")); + assert_eq!(sh.value(CellRef::parse("B1").unwrap()), gridcraft_core::Value::text("a b")); +} + +/// A small SYLK file written the way spreadsheets export one: a header, number formats, column +/// widths, cells that carry on from the last row or column, formulas in R1C1 and a shared formula. +const SYLK: &str = "ID;PTEST;N;E\r\nP;PGeneral\r\nP;P0.00\r\nP;Pyyyy\\-mm\\-dd\r\nF;W1 1 18\r\nF;W2 3 9\r\nB;Y5;X7\r\n\ +C;Y1;X1;K\"Item\"\r\nC;X2;K\"Qty\"\r\nC;X4;K\"Total\"\r\n\ +C;Y2;X1;K\"Bolts;; small\"\r\nC;X2;K12\r\nF;P1;F$2G;X3\r\nC;X3;K0.35\r\nC;X4;K4.2;ERC[-2]*RC[-1]\r\n\ +C;X5;K52;ER2C2+R[1]C[-3]\r\nC;X6;KTRUE\r\nC;X7;K8.4;ERC[-3]*2\r\n\ +C;Y3;X1;K\"Nuts \"\"hex\"\"\"\r\nC;X2;K40\r\nC;X3;K0.12\r\nC;X4;K4.8;ERC[-2]*RC[-1]\r\nC;X5;K\"big\";EIF(R4C4>5,\"big\",\"small\")\r\nC;X7;K9.6;S;R2;C7\r\n\ +C;Y4;X1;K\"Sum\"\r\nC;X4;K9;ESUM(R[-2]C:R[-1]C)\r\nC;X5;K#DIV/0!;E1/0\r\nC;X7;K18;ESUM(C4)\r\n\ +F;P2;FG0G;Y5;X2\r\nC;Y5;X2;K45000\r\nC;X3;K\"R2C3\";E\"R2C3\"\r\nE\r\n"; + +#[test] +fn sylk_files_open_with_values_formulas_formats_and_widths() { + let (wb, warnings) = open_bytes("Parts list.slk", SYLK.as_bytes()).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.name, "Parts list", "the sheet is named after the file"); + let at = |a: &str| CellRef::parse(a).unwrap(); + let formula = |a: &str| sh.cell(at(a)).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()); + let text = |s: &str| gridcraft_core::Value::Text(s.into()); + assert_eq!(sh.value(at("A1")), text("Item")); + assert_eq!(sh.value(at("A2")), text("Bolts; small"), ";; is a semicolon"); + assert_eq!(sh.value(at("A3")), text("Nuts \"\"hex\"\""), "text is kept between the outer quotes as written"); + assert_eq!(sh.value(at("B2")), gridcraft_core::Value::Number(12.0)); + assert_eq!(sh.value(at("F2")), gridcraft_core::Value::Bool(true)); + assert_eq!(sh.value(at("E4")), gridcraft_core::Value::Error(gridcraft_core::CellError::Div0)); + assert_eq!(sh.value(at("D4")), gridcraft_core::Value::Number(9.0), "a formula keeps the value the file cached"); + assert_eq!(formula("D2").as_deref(), Some("B2*C2")); + assert_eq!(formula("E2").as_deref(), Some("$B$2+B3")); + assert_eq!(formula("E3").as_deref(), Some("IF($D$4>5,\"big\",\"small\")")); + assert_eq!(formula("D4").as_deref(), Some("SUM(D2:D3)")); + assert_eq!(formula("G3").as_deref(), Some("D3*2"), "a shared formula is the other cell's, moved"); + assert_eq!(formula("G4").as_deref(), Some("SUM($D:$D)"), "C4 alone is the whole column"); + assert_eq!(formula("C5").as_deref(), Some("\"R2C3\""), "text in quotes isn't a reference"); + // `F;P1;X3` formats the cell on the current row only. + let fmt = |a: &str| wb.styles.get(sh.style_id(at(a))).num_fmt.0.to_string(); + assert_eq!(fmt("C2"), "0.00"); + assert_eq!(fmt("C3"), "General"); + assert_eq!(fmt("B5"), "yyyy\\-mm\\-dd"); + // Widths are in characters, like the Column Width dialog's. + let chars = |c: u32| gridcraft_model::points_to_chars(f64::from(sh.col_width(c))); + assert_eq!((chars(0), chars(1), chars(2)), (18.0, 9.0, 9.0)); + assert_eq!(sh.cols.get(&3).and_then(|i| i.size), None, "column D keeps the default width"); +} + +#[test] +fn sylk_r1c1_formulas_become_a1() { + let b2 = CellRef::parse("B2").unwrap(); + for (r1c1, a1) in [ + ("RC", "B2"), + ("R[1]C[-1]", "A3"), + ("R1C1:R2C2", "$A$1:$B$2"), + ("R3", "$3:$3"), + ("R1:R[2]", "$1:4"), + ("C[1]", "C:C"), + ("SUM(C3:C4)", "SUM($C:$D)"), + ("ROUND(RC[1],2)+RATE(1,2,3)", "ROUND(C2,2)+RATE(1,2,3)"), + ("'R1C1 sheet'!R1C1", "'R1C1 sheet'!$A$1"), + ("Sheet2!RC", "Sheet2!B2"), + ("R2D2+rc", "R2D2+B2"), + ("R[-5]C", "#REF!"), + ("\"RC\"&R1C1", "\"RC\"&$A$1"), + ] { + assert_eq!(sylk::r1c1_formula_to_a1(r1c1, b2), a1, "{r1c1}"); + } +} + +#[test] +fn sylk_rejects_other_files_and_survives_damage() { + assert!(open_bytes("not.slk", b"A,B\n1,2\n").is_err(), "a SYLK file starts with ID"); + // Positions off the sheet, broken numbers, a missing end and a format past the list. + let (wb, warnings) = + open_bytes("damaged.slk", b"ID;P\nC;Y0;X1;K1\nC;Y2;X99999;K2\nC;Y3;X1;K1e999\nF;P7;Y3;X1\nF;W5 2 9\nC;Y4;X1;K5;E(((\n").unwrap(); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.cells.iter().count(), 2, "{:?}", sh.cells.iter().collect::>()); + assert_eq!(sh.value(CellRef::parse("A3").unwrap()), gridcraft_core::Value::Text("1e999".into())); + assert_eq!(warnings.len(), 1, "skipped records are reported: {warnings:?}"); +} + +#[test] +fn sylk_survives_huge_relative_offsets_and_width_floods() { + // Relative offsets at the edge of i64 fall off the sheet instead of overflowing. + let text = b"ID;P\nC;Y1;X1;K0;ER[9223372036854775807]C\nC;Y2;X1;K0;ER[-9223372036854775808]C[-9223372036854775808]\nE\n"; + assert!(open_bytes("offsets.slk", text).is_ok()); + // Width records over every column, many times over: the import keeps a bounded number. + let mut flood = b"ID;P\n".to_vec(); + for _ in 0..5000 { + flood.extend_from_slice(b"F;W1 16384 12\n"); + } + flood.extend_from_slice(b"C;Y1;X1;K1\nE\n"); + let (wb, _) = open_bytes("widths.slk", &flood).unwrap(); + assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("A1").unwrap()), gridcraft_core::Value::Number(1.0)); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f0676c7720..6f61b239e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,10 +15,12 @@ pub mod display; pub mod fill; pub mod io; pub mod links; +pub mod macros; pub mod outline; pub mod paper; pub mod pivot; pub mod pivot_calc; +pub mod recent; pub mod record; pub mod sample; pub mod selection; @@ -37,6 +39,7 @@ pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command, register_te pub use gridcraft_calc as calc; pub use gridcraft_core as core; pub use gridcraft_formula as formula; +pub use gridcraft_math as math; pub use gridcraft_model as model; pub use gridcraft_numfmt as numfmt; pub use selection::Selection; @@ -54,6 +57,12 @@ pub enum EngineError { NoDocument, #[error("{0}")] Other(String), + /// The command would replace something; run it again with `overwrite: true` to go ahead. + #[error("confirm: {0} (run again with `overwrite: true`)")] + Confirm(String), + /// Active content (a macro) asks to run; run it again with `approve: true` to allow it. + #[error("approve: {0} (run again with `approve: true`)")] + Approve(String), #[error("internal error in `{0}` (the workbook was kept as it was): {1}")] Internal(String, String), } @@ -97,6 +106,9 @@ struct OpenGroup { selection: Selection, /// The redo stack when the group began (a rollback puts it back). redo: Vec, + /// Where the recording was when the group began (`None` when nothing was recording): a + /// rollback takes back the steps recorded since, as it takes back their edits. + recorded: Option<(u64, u64)>, } /// Where the last [`Session::group_end`] or [`Session::group_rollback`] left its document: the @@ -203,6 +215,12 @@ pub struct DocState { /// workbook is opened from a file, carried by content pasted from such a workbook, and never /// changed by a trust decision. pub trust: Trust, + /// While a macro's footprint is measured: every cell a command wrote, by sheet name, even + /// where it wrote what was already there. + pub touched: Option>, + /// While a macro step runs: the structural edits its command made (the sheet's name, the + /// edit), so the macro's inputs, output and Repeat ranges follow their cells as formulas do. + pub edits: Option>, /// The references `edit.goTo` with `record: true` went to in this document, newest first, /// without names, each area written with its sheet (`Sheet1!B14:C22,Sheet1!F19:G30`). pub go_to_recent: Vec, @@ -231,6 +249,10 @@ fn history_retained_bytes(older: &Workbook, newer: &Workbook) -> usize { let next = newer.sheets.get(index).map_or(&empty, |next| &next.cells); bytes = bytes.saturating_add(sheet.cells.retained_bytes_against(next)); } + // Snapshots share the macro list until a change to it; a snapshot with its own list keeps it. + if !older.macros.shares(&newer.macros) { + bytes = bytes.saturating_add(older.macros.estimated_bytes()); + } bytes } @@ -283,7 +305,9 @@ impl DocState { calc.rebuild(&wb); Self::with_calc(wb, calc, path, title, trust) } - fn with_calc(wb: Workbook, calc: Calc, path: Option, title: String, trust: Trust) -> DocState { + fn with_calc(mut wb: Workbook, calc: Calc, path: Option, title: String, trust: Trust) -> DocState { + // Equations arrive without a layout (files never store one); painting reads only the cache. + wb.refresh_equations(); let scripts_trusted = !cmd::extra::has_scripts(&wb); let wb = Arc::new(wb); let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default()); @@ -303,6 +327,8 @@ impl DocState { content_kind: None, scripts_trusted, trust, + touched: None, + edits: None, go_to_recent: vec![], } } @@ -368,6 +394,10 @@ pub struct Prefs { pub formula_bar: bool, /// The statistics the status bar shows for a selection (right-click the status bar). pub status_bar: StatusBarStats, + /// Formulas › Recently Used: the functions most recently entered in a formula, newest first + /// (at most [`recent::MAX`]; see [`recent`]). An application list, as in Excel. + #[serde(deserialize_with = "recent::lenient")] + pub recent_functions: Vec, } /// The selection statistics shown on the status bar, set with `view.statusBar`. Excel turns on @@ -402,6 +432,7 @@ impl Default for Prefs { user_dictionary: vec![], formula_bar: true, status_bar: StatusBarStats::default(), + recent_functions: recent::defaults(), } } } @@ -446,6 +477,9 @@ pub struct Session { /// Serialized size of each journal entry, measured once when it is pushed, and their sum. journal_sizes: Vec, journal_bytes: usize, + /// While a dry run runs (the footprint, `macro.check`), its commands are not journaled: the + /// dry run is put back, and journaling it would evict the person's own oldest entries. + pub(crate) journal_paused: u32, pub ui_requests: Vec, /// Format painter source style (sticky when double-clicked). pub format_painter: Option<(Arc, usize, RangeRef, bool)>, @@ -460,6 +494,17 @@ pub struct Session { pub recorder: Option, /// How many `execute` calls are running (0 between top-level commands). depth: u32, + /// The steps the last successful `automate.runScript` or `macro.run` ran while a recorder was + /// on, for the recorder to keep with that step (see [`record::Recorder::ran`]); taken by the + /// recording hook. + pub(crate) script_ran: Option>, + /// Macros the person allowed to run in this session: (document uid, the macro's content as + /// canonical JSON, from [`macros::fingerprint`]). + pub macro_approvals: std::collections::HashSet<(u64, String)>, + /// The macro being debugged, between debugger actions. + pub macro_debug: Option, + /// Where the macro recorder started (beside `recorder`, its buffer). + pub macro_recording: Option, /// Draw tab tool: "" (select), "pen" or "eraser"; pen colour and width. pub draw_tool: String, pub draw_color: String, @@ -522,6 +567,17 @@ impl Session { pub fn doc_mut(&mut self) -> Result<&mut DocState> { self.active_mut().ok_or(EngineError::NoDocument) } + /// The warning an edit of `at` on `sheet` gets from sheet protection, or `None` when the edit + /// is allowed. Front ends ask before opening an editor, so typing into a locked cell never + /// leaves a draft that can't be entered (and so blocks saving). + pub fn locked_cell_message(&self, sheet: usize, at: CellRef) -> Option { + let d = self.active()?; + let sh = d.wb.sheet(sheet)?; + if !sh.is_protected() || !d.wb.styles.get(sh.style_id(at)).protection.locked { + return None; + } + cmd::locked_cell_error(sh, at, &d.unlocked_ranges) + } /// Opens a workbook in a new window, which becomes the active one. pub fn add_document(&mut self, d: DocState) -> usize { let uid = d.uid; @@ -535,6 +591,10 @@ impl Session { if i < self.docs.len() { let d = self.docs.remove(i); self.groups.retain(|g| g.doc != d.uid); + // A macro being debugged in this workbook ends with it; its group just went. + if self.macro_debug.as_ref().is_some_and(|m| m.doc == d.uid) { + self.macro_debug = None; + } self.windows.retain(|w| w.doc_uid != d.uid); if self.active_window.is_some_and(|w| self.window(w).is_none()) { self.activate_recent(); @@ -547,6 +607,7 @@ impl Session { pub fn new_workbook(&mut self) -> usize { let n = (1..).find(|n| !self.docs.iter().any(|d| d.title == format!("Book{n}") && d.path.is_none())).unwrap_or(1); let mut wb = Workbook::new(); + wb.props.author = self.prefs.user_name.clone(); for _ in 1..self.prefs.sheets_in_new_workbook.clamp(1, 255) { let name = wb.next_sheet_name(); wb.sheets.push(Arc::new(gridcraft_model::Sheet::new(name))); @@ -586,6 +647,16 @@ impl Session { } } + /// Cuts the journal back to its first `keep` entries, with its size bookkeeping. + pub(crate) fn truncate_journal(&mut self, keep: usize) { + if self.journal_sizes.len() == self.journal.len() { + self.journal_sizes.truncate(keep); + self.journal_bytes = self.journal_sizes.iter().sum(); + } + self.journal.truncate(keep); + self.recording = self.recording.map(|r| r.min(self.journal.len())); + } + pub fn commands(&self) -> Vec { command_specs().iter().map(|c| c.info(self)).collect() } @@ -598,7 +669,25 @@ impl Session { if let Err(why) = (spec.enabled)(self) { return Err(EngineError::Disabled(id.to_string(), why)); } + // A debugger whose undo group something else ended locks nothing any more (`macro.debug` + // itself says that the run had ended). + if id != "macro.debug" { + macros::debug::drop_if_ended(self); + } + let query = !spec.journal && !spec.undoable; + // While a macro is being debugged its undo group is open, and its workbook is locked: + // between steps only the debugger, queries and commands that look around run there + // (`macros::debug::LOOKS_AROUND`). Anything else waits, undoable or not (saving, view + // modes, stopping Record Actions, which saves a script), also when another command runs + // it. Only the run's own steps go ahead. Other workbooks stay editable. + let locked = self.active().is_some_and(|d| self.macro_debug.as_ref().is_some_and(|m| m.locks(d.uid) && !m.stepping())); + if locked && !macros::debug::runs_while_locked(id, query) { + return Err(EngineError::Disabled(id.to_string(), macros::debug::BUSY.into())); + } let before = self.active().map(|d| (d.uid, d.wb.clone(), d.selection.clone())); + // A dry run inside this command that a panic cuts short leaves journaling paused and its + // touch log open; the panic branch puts both back. + let paused_before = self.journal_paused; let params = if params.is_null() { Json::Object(Default::default()) } else { params }; let (first_group, group_epoch) = (self.next_group, self.group_epoch); // Whether a group was open on the document before the command, and how long its history was. @@ -608,7 +697,6 @@ impl Session { // because a nested `edit.undo` removes entries. A query runs nothing that changes the // history (`every_query_leaves_the_history_alone` runs each one), so it needs no // copy; front ends run queries all the time. - let query = !spec.journal && !spec.undoable; let history_before = before.as_ref().filter(|_| !query).and_then(|(uid, ..)| { #[cfg(test)] tests::HISTORY_COPIES.with(|n| n.set(n.get().saturating_add(1))); @@ -669,7 +757,16 @@ impl Session { } d.calc.rebuild(&d.wb); } + if self.journal_paused != paused_before { + self.journal_paused = paused_before; + for d in self.docs.iter_mut() { + d.touched = None; + } + } if self.depth == 0 { + // Only the `macro.debug` call itself can lose the run's place: a command nested + // in a step that panics is an error of that step, which the run handles. + macros::debug::recover(self); self.trim_history(); self.group_step = None; } @@ -687,13 +784,34 @@ impl Session { // finds no recorder. A menu-style call that only opened a dialog (`file.open` with no // file, `home.formatCells` with no style) is not recorded either: the dialog's own // call is, so playing the recording back runs the command once, with its parameters. + // A call that opened a dialog and changed the workbook too (a script with an edit before + // a menu-style step) is recorded: the edit happened, and the dialog's confirming call + // is a step of its own. let opened_dialog = self.ui_requests.get(requests_before..).is_some_and(|new| new.iter().any(|q| matches!(q, UiRequest::Dialog(..)))); - if let Some((doc, sheet, sheet_name, selection)) = place.filter(|_| !opened_dialog) + let changed = before.as_ref().is_some_and(|(uid, wb, _)| self.docs.iter().any(|d| d.uid == *uid && !Arc::ptr_eq(&d.wb, wb))); + if let Some((doc, sheet, sheet_name, selection)) = place.filter(|_| (!opened_dialog || changed) && !record::NOT_RECORDED.contains(&id)) && let Some(rec) = self.recorder.as_mut() { - rec.push(record::RecordedStep { doc, sheet, sheet_name, selection, id: id.to_string(), params: cmd::journal_params(¶ms) }); + // A toggle (Bold) is recorded with the state it set, as Excel records + // `Bold = True`: playing it back sets that state rather than flipping it again. + let params = match &result { + Ok(r) if params.is_object() => record::with_toggle_state(id, cmd::journal_params(¶ms), r), + _ => cmd::journal_params(¶ms), + }; + let kept = rec.push(record::RecordedStep { doc, sheet, sheet_name, selection, id: id.to_string(), params }); + // A script or macro run is kept with the steps it ran, so editing or deleting the + // script or macro before the recording stops does not change what was recorded. + if let Some(ran) = self.script_ran.take() + && kept + && matches!(id, "automate.runScript" | "macro.run") + { + rec.attach_ran(ran); + } + } + if self.journal_paused == 0 { + self.push_journal(id, cmd::journal_params(¶ms)); + recent::note(&mut self.prefs.recent_functions, id, ¶ms); } - self.push_journal(id, cmd::journal_params(¶ms)); } // Inside an undo group the group owns the step. A command that ended a group open before // it leaves the group its step and makes one of its own for what it changed after the end. @@ -808,6 +926,7 @@ impl Session { wb: d.wb.clone(), selection: d.selection.clone(), redo: d.redo.clone(), + recorded: self.recorder.as_ref().map(record::Recorder::mark), }; let token = GroupToken { id: g.id, doc: g.doc }; self.next_group = self.next_group.saturating_add(1); @@ -904,6 +1023,11 @@ impl Session { d.undo.truncate(g.start); d.redo = g.redo; d.revision += 1; + // The steps recorded while the group was open go with their edits (all of them when the + // recording started inside the group). + if let Some(rec) = self.recorder.as_mut() { + rec.cut_back(g.recorded.unwrap_or((0, 0)), g.doc); + } // The record of the last group step stays when the document is back exactly where that // step left it (this group began there); otherwise the rollback is where the group ended. let kept = self.group_step.as_ref().is_some_and(|st| st.doc == g.doc && st.len == g.start && Arc::ptr_eq(&st.after, &d.wb)); @@ -935,6 +1059,21 @@ impl Session { self.depth } + /// Runs a command as a command in progress would (one level deeper), for tests of what a + /// nested call may do. + #[cfg(test)] + pub(crate) fn execute_nested(&mut self, id: &str, params: Json) -> Result { + self.depth = self.depth.saturating_add(1); + let r = self.execute(id, params); + self.depth = self.depth.saturating_sub(1); + r + } + + /// Whether the token's undo group is still open (nothing has ended or rolled it back). + pub fn group_is_open(&self, token: &GroupToken) -> bool { + self.groups.iter().any(|g| g.id == token.id) + } + /// Whether an undo group is open on the document with this uid. pub fn in_group(&self, doc: u64) -> bool { self.groups.iter().any(|g| g.doc == doc) diff --git a/crates/engine/src/macros/debug.rs b/crates/engine/src/macros/debug.rs new file mode 100644 index 0000000000..7811ecb3f3 --- /dev/null +++ b/crates/engine/src/macros/debug.rs @@ -0,0 +1,694 @@ +//! The macro debugger: a run that stops between steps. +//! +//! `macro.debug` starts a run that pauses before its first step, then steps, continues to the next +//! breakpoint, runs to a chosen step, or stops. The run lives on the session between calls (one +//! action per call) inside an undo group that spans them; Stop keeps the changes as one undo step +//! or rolls them back. While a macro is being debugged its workbook is locked: only the +//! debugger, queries and the commands in [`LOOKS_AROUND`] run there, and everything else, saving +//! included, is refused ("Finish or stop the macro first"). Other workbooks stay editable. The +//! debugger runs on its own, never as a step of a script or macro, and is never recorded. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use gridcraft_model::Workbook; +use serde_json::{Value as Json, json}; + +use super::run::{Machine, StepError, rolled_back}; +use crate::{EngineError, GroupToken, Result, Selection, Session}; + +/// The most breakpoints one call sets. +pub const MAX_BREAKPOINTS: usize = 10_000; +/// The most entries `changed` lists (ranges and sheet notes), as the footprint lists ranges. +const MAX_LISTED: usize = 500; + +/// Commands that run on the debugged workbook between steps, besides `macro.debug` and queries. +/// They only look around (the selection, the active sheet, Go To, Find, zoom, copying), switch to +/// another window, close the workbook (which ends the run) or stop the run (Stop Action). The +/// debugger puts the run's active sheet and selection back before its next step runs. +pub const LOOKS_AROUND: &[&str] = &[ + "selection.set", + "selection.move", + "selection.next", + "selection.row", + "selection.column", + "selection.currentRegion", + "edit.selectAll", + "sheet.activate", + "sheet.next", + "sheet.previous", + "edit.goTo", + "edit.goToSpecial", + "edit.find", + "edit.copy", + "view.zoom", + "view.zoom100", + "view.zoomToSelection", + "window.activate", + "file.close", + "automate.stopAction", +]; + +/// Whether command `id` (a query when `query`) runs on a workbook the debugger locks. +pub fn runs_while_locked(id: &str, query: bool) -> bool { + // `macro.check` is a query, but its dry run runs the macro's steps, which the lock refuses: it + // waits too, rather than report the lock as the failure of a step. + (query && id != "macro.check") || id == "macro.debug" || LOOKS_AROUND.contains(&id) +} + +/// A macro being debugged. +pub struct Debugger { + pub name: String, + pub doc: u64, + /// Out of the session only while a step runs. + machine: Option, + token: Option, + /// Breakpoints set for this run (step paths), on top of the steps' own. + pub breakpoints: BTreeSet, + /// Only `breakpoints` stop the run; the steps' own flags are ignored (an editor that shows + /// its own breakpoints sends them all, so clearing one takes effect at once). + pub only_listed: bool, + /// The workbook when the run started, for "changed so far". + start: Arc, + /// Every step path in the macro, for checking `runTo` targets and breakpoints. + paths: BTreeSet, + /// The workbooks the run has touched (by uid). Steps run on the macro's own workbook and the + /// policy refuses window and file commands, so this is the macro's workbook unless a command + /// reaches another one some other way; edits of these wait until the run ends. + touched: BTreeSet, + /// Steps the footprint's dry runs executed before the run (they count towards the run's + /// budget, not towards `executed`). + base: u64, + /// The conflict rule that shifted the data at the start (`shiftDown`, `shiftRight`). + shifted: Option<&'static str>, + /// Where the run left its workbook after the last action. + view: Option, +} + +/// The active sheet and the selections of the debugged workbook where the run left them. +#[derive(Clone)] +struct View { + sheet: usize, + selection: Selection, + sheet_selections: Vec, +} + +impl Debugger { + /// Whether edits of the workbook with this uid wait for the run to end. + pub fn locks(&self, doc: u64) -> bool { + self.touched.contains(&doc) + } + + /// Whether one of the run's steps is running (its machine is out of the session). + pub fn stepping(&self) -> bool { + self.machine.is_none() + } + + /// The run's own steps so far. + fn executed(&self) -> u64 { + self.machine.as_ref().map_or(0, |m| m.executed.saturating_sub(self.base)) + } +} + +/// Each open workbook's uid and its current version, to see which ones a step changes. +fn versions(s: &Session) -> Vec<(u64, Arc)> { + s.docs.iter().map(|d| (d.uid, d.wb.clone())).collect() +} + +/// Adds to the run's touched log the workbooks that changed since `before`. +fn note_touched(s: &mut Session, before: &[(u64, Arc)]) { + let changed: Vec = + s.docs.iter().filter(|d| before.iter().any(|(uid, wb)| *uid == d.uid && !Arc::ptr_eq(wb, &d.wb))).map(|d| d.uid).collect(); + if let Some(dbg) = s.macro_debug.as_mut() { + dbg.touched.extend(changed); + } +} + +/// Remembers where the run left its workbook: the active sheet and the selections. +fn remember_view(s: &mut Session) { + let Some(uid) = s.macro_debug.as_ref().map(|d| d.doc) else { return }; + let view = s.docs.iter().find(|d| d.uid == uid).map(|d| View { + sheet: d.wb.active_sheet(), + selection: d.selection.clone(), + sheet_selections: d.sheet_selections.clone(), + }); + if let Some(dbg) = s.macro_debug.as_mut() { + dbg.view = view; + } +} + +/// Puts back the active sheet and the selections where the run left them, so the next step runs +/// where `macro.run` would run it, however the person looked around meanwhile. +fn put_back_view(s: &mut Session) { + let Some((uid, Some(view))) = s.macro_debug.as_ref().map(|d| (d.doc, d.view.clone())) else { return }; + let Some(d) = s.docs.iter_mut().find(|d| d.uid == uid) else { return }; + if view.sheet < d.wb.sheets.len() { + // The active sheet is view state: setting it doesn't make the workbook dirty. + d.wb.set_active_sheet(view.sheet); + } + d.selection = view.selection; + d.sheet_selections = view.sheet_selections; +} + +/// The message for edits refused while a macro is being debugged. +pub const BUSY: &str = "Finish or stop the macro first"; + +/// Ends a debugger whose undo group is no longer open (something other than the debugger ended +/// or rolled it back): its workbook is not locked any more. Returns the macro's name when it did. +pub(crate) fn drop_if_ended(s: &mut Session) -> Option { + let d = s.macro_debug.as_ref()?; + if d.stepping() || d.token.as_ref().is_some_and(|t| s.group_is_open(t)) { + return None; + } + s.macro_debug.take().map(|d| d.name) +} + +/// After Stop Action rolled back the undo groups of the workbook with uid `doc`: ends the +/// debugger if its run was there. Returns the macro's name and the files the run wrote, which stay. +pub(crate) fn end_stopped(s: &mut Session, doc: u64) -> Option<(String, Vec)> { + if !s.macro_debug.as_ref().is_some_and(|d| d.doc == doc && !d.stepping()) { + return None; + } + let d = s.macro_debug.take()?; + Some((d.name, d.machine.map(|m| m.wrote_files).unwrap_or_default())) +} + +/// Why an action finds the run already ended: its undo group was closed outside the debugger. +fn already_ended(name: &str) -> String { + format!("Macro '{name}' was no longer being debugged: its undo group had been closed outside the debugger, so nothing was kept or rolled back.") +} + +enum Mode { + Step, + Continue, + RunTo(String), +} + +const ACTIONS: [&str; 6] = ["start", "step", "continue", "runTo", "stop", "state"]; + +/// `macro.debug {name?, inputs?, action: start|step|continue|runTo|stop|state, step?, keep?, +/// breakpoints?, breakpointsOnly?}`. +pub fn debug(s: &mut Session, p: &Json) -> Result { + // A step of a script or macro that started the debugger would leave it behind when the + // script fails and rolls back its groups, the debugger's among them. + if s.depth() > 1 { + return Err(EngineError::Disabled("macro.debug".into(), "The macro debugger runs on its own, not as a step of a script or macro.".into())); + } + let ended = drop_if_ended(s); + let action = match p.get("action") { + None | Some(Json::Null) if s.macro_debug.is_some() || ended.is_some() => "state".to_string(), + None | Some(Json::Null) => "start".to_string(), + Some(Json::String(a)) => a.clone(), + // `{"action": {"runTo": {"step": "3"}}}` + Some(Json::Object(o)) if o.len() == 1 => o.keys().next().cloned().unwrap_or_default(), + Some(_) => return Err(bad("`action` must be start, step, continue, runTo, stop or state")), + }; + if !ACTIONS.contains(&action.as_str()) { + return Err(bad(format!("action must be start, step, continue, runTo, stop or state, not '{action}'"))); + } + if let Some(name) = ended + && action != "start" + { + return Err(EngineError::Other(already_ended(&name))); + } + let only = bool_param(p, "breakpointsOnly")?; + if action == "start" { + return start(s, p, only.unwrap_or(false)); + } + let keep = bool_param(p, "keep")?; + let d = s.macro_debug.as_ref().ok_or_else(not_debugging)?; + let target = if action == "runTo" { + let target = p + .get("step") + .or_else(|| p.pointer("/action/runTo/step")) + .and_then(path_of) + .ok_or_else(|| bad("`runTo` needs `step`: the path of the step to stop at"))?; + if !d.paths.contains(&target) { + return Err(bad(format!("macro '{}' has no step {target}", d.name))); + } + Some(target) + } else { + None + }; + let breakpoints = p.get("breakpoints").filter(|v| !v.is_null()).map(|v| paths_param(v, &d.paths, &d.name)).transpose()?; + if let Some(d) = s.macro_debug.as_mut() { + if let Some(bps) = breakpoints { + d.breakpoints = bps; + } + if let Some(only) = only { + d.only_listed = only; + } + } + match (action.as_str(), target) { + ("step", _) => advance(s, Mode::Step), + ("continue", _) => advance(s, Mode::Continue), + ("runTo", Some(target)) => advance(s, Mode::RunTo(target)), + ("stop", _) => stop(s, keep.unwrap_or(false)), + _ => state(s), + } +} + +fn bad(msg: impl Into) -> EngineError { + crate::cmd::bad("macro.debug", msg) +} + +fn not_debugging() -> EngineError { + EngineError::Other("No macro is being debugged. Start one with action: start.".into()) +} + +/// `true`, `false`, or not given (`null` counts as not given); anything else is refused. +fn bool_param(p: &Json, key: &str) -> Result> { + match p.get(key) { + None | Some(Json::Null) => Ok(None), + Some(Json::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(bad(format!("`{key}` must be true or false"))), + } +} + +/// A step path from JSON: `"2.1"` or `3`. +fn path_of(v: &Json) -> Option { + match v { + Json::String(t) if !t.trim().is_empty() => Some(t.trim().to_string()), + Json::Number(n) => n.as_u64().map(|n| n.to_string()), + _ => None, + } +} + +/// The `breakpoints` list: step paths of macro `name` (one of `paths`), at most +/// [`MAX_BREAKPOINTS`]. +fn paths_param(v: &Json, paths: &BTreeSet, name: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad("`breakpoints` must be a list of step paths"))?; + if list.len() > MAX_BREAKPOINTS { + return Err(bad(format!("`breakpoints` lists {} steps; at most {MAX_BREAKPOINTS} can be set", list.len()))); + } + let mut out = BTreeSet::new(); + for x in list { + let path = path_of(x).ok_or_else(|| bad("a breakpoint is a step path such as \"3\" or \"2.1\""))?; + if !paths.contains(&path) { + return Err(bad(format!("macro '{name}' has no step {path} for a breakpoint"))); + } + out.insert(path); + } + Ok(out) +} + +fn start(s: &mut Session, p: &Json, only_listed: bool) -> Result { + if let Some(d) = &s.macro_debug { + return Err(EngineError::Other(format!("Macro '{}' is being debugged. Stop it first.", d.name))); + } + let name = p.get("name").and_then(Json::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad("missing `name`"))?; + let b = super::run::begin(s, name, p)?; + let paths = all_paths(&b.mac.steps, ""); + let breakpoints = match p.get("breakpoints").filter(|v| !v.is_null()) { + Some(v) => paths_param(v, &paths, &b.mac.name)?, + None => BTreeSet::new(), + }; + let start_wb = s.doc()?.wb.clone(); + let token = s.group_begin(&format!("Run Macro: {}", b.mac.name))?; + // The run's machine: unless the rule is overwrite, it checks each step for writes over data. + let (mut machine, shifted) = match super::run::make_way(s, &b) { + Ok(made) => made, + Err(e) => { + let _ = s.group_rollback(token); + return Err(e); + } + }; + // Each action has the time limit to itself; the dry runs just had theirs. + machine.restart_clock(); + let base = machine.executed; + s.macro_debug = Some(Debugger { + name: b.mac.name.clone(), + doc: b.prepared.doc, + machine: Some(machine), + token: Some(token), + breakpoints, + only_listed, + start: start_wb, + paths, + touched: BTreeSet::from([b.prepared.doc]), + base, + shifted: shifted.then(|| b.rule.name()), + view: None, + }); + if s.macro_debug.as_ref().and_then(|d| d.machine.as_ref()).is_some_and(Machine::is_done) { + return finish(s, None); + } + remember_view(s); + state(s) +} + +fn all_paths(steps: &[gridcraft_model::Step], prefix: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + for (i, st) in steps.iter().enumerate() { + let path = if prefix.is_empty() { (i + 1).to_string() } else { format!("{prefix}.{}", i + 1) }; + match &st.kind { + gridcraft_model::StepKind::Repeat { body, .. } => out.extend(all_paths(body, &path)), + gridcraft_model::StepKind::If { then, otherwise, .. } => { + out.extend(all_paths(then, &format!("{path}.then"))); + out.extend(all_paths(otherwise, &format!("{path}.else"))); + } + _ => {} + } + out.insert(path); + } + out +} + +/// Runs one step (`Step`), or steps until a breakpoint, the target step or the end. +fn advance(s: &mut Session, mode: Mode) -> Result { + put_back_view(s); + let d = s.macro_debug.as_mut().ok_or_else(not_debugging)?; + let (name, base) = (d.name.clone(), d.base); + let breakpoints = d.breakpoints.clone(); + let only_listed = d.only_listed; + let mut machine = d.machine.take().ok_or_else(not_debugging)?; + machine.restart_clock(); + let before = versions(s); + let mut first = true; + let mut hit = false; + let mut outcome = Ok(()); + while !machine.is_done() { + if !first { + let Some((path, st)) = machine.current() else { break }; + if matches!(mode, Mode::Step) { + break; + } + if (st.breakpoint && !only_listed) || breakpoints.contains(&path) { + hit = true; + break; + } + if let Mode::RunTo(target) = &mode + && *target == path + { + break; + } + } + first = false; + outcome = machine.step(s); + if outcome.is_err() { + break; + } + } + let done = machine.is_done(); + match s.macro_debug.as_mut() { + Some(d) => d.machine = Some(machine), + // The macro.debug call panicked and `recover` has already rolled the run back. + None => { + return match outcome { + Err(e) => Ok(failed(&name, machine.executed.saturating_sub(base), &e)), + Ok(()) => Err(not_debugging()), + }; + } + } + note_touched(s, &before); + if let Err(e) = outcome { + return finish(s, Some(e)); + } + if done { + return finish(s, None); + } + remember_view(s); + let mut out = state(s)?; + out["atBreakpoint"] = json!(hit); + Ok(out) +} + +/// What every answer about the run's end or its state adds: the data shift at the start and the +/// files the run wrote (they stay, whatever happens to the workbook). +fn add_notes(out: &mut Json, d: &Debugger, wrote_files: &[String]) { + if let Some(rule) = d.shifted { + out["shifted"] = json!(rule); + } + if !wrote_files.is_empty() { + out["wroteFiles"] = json!(wrote_files); + } +} + +/// Ends the run after its last step (kept as one undo step, unless a Stop step asked for a +/// rollback) or a failed step (rolled back). +fn finish(s: &mut Session, error: Option) -> Result { + let Some(mut d) = s.macro_debug.take() else { return Err(not_debugging()) }; + let (changed, cells) = changed(s, &d); + let executed = d.executed(); + let machine = d.machine.take(); + let stopped = machine.as_ref().and_then(|m| m.stopped.clone()); + let wrote = machine.map(|m| m.wrote_files).unwrap_or_default(); + let rollback = error.is_some() || matches!(stopped, Some((_, true))); + let ended = match d.token.take() { + Some(token) if rollback => s.group_rollback(token).is_ok(), + Some(token) => s.group_end(token).is_ok(), + None => false, + }; + if !ended { + let step = error.map(|e| format!("{} ", e.describe())).unwrap_or_default(); + return Err(EngineError::Other(format!("{step}{}", already_ended(&d.name)))); + } + if let Some(e) = &error { + return Ok(failed(&d.name, executed, e)); + } + let mut out = json!({"macro": d.name, "executed": executed}); + match &stopped { + Some((msg, rolled)) => { + out["state"] = json!("stopped"); + out["stopped"] = json!(msg); + out["kept"] = json!(!rolled); + if *rolled { + out["message"] = json!(rolled_back(&wrote)); + } + } + None => out["state"] = json!("finished"), + } + if !rollback { + out["changed"] = json!(changed); + out["changedCells"] = json!(cells); + } + add_notes(&mut out, &d, &wrote); + Ok(out) +} + +/// The result of a run that a failed step rolled back. +fn failed(name: &str, executed: u64, e: &StepError) -> Json { + let mut out = json!({ + "macro": name, + "executed": executed, + "state": "failed", + "error": serde_json::to_value(e).unwrap_or(Json::Null), + "message": format!("{} {}", e.describe(), rolled_back(&e.wrote_files)), + }); + if !e.wrote_files.is_empty() { + out["wroteFiles"] = json!(e.wrote_files); + } + out +} + +/// Stops the run: keeps what it did as one undo step, or rolls it back. +fn stop(s: &mut Session, keep: bool) -> Result { + let Some(mut d) = s.macro_debug.take() else { return Err(not_debugging()) }; + let (changed, cells) = changed(s, &d); + let ended = match d.token.take() { + Some(token) if keep => s.group_end(token).is_ok(), + Some(token) => s.group_rollback(token).is_ok(), + None => false, + }; + if !ended { + return Err(EngineError::Other(already_ended(&d.name))); + } + let wrote = d.machine.as_ref().map(|m| m.wrote_files.clone()).unwrap_or_default(); + let mut out = json!({"state": "stopped", "macro": d.name, "kept": keep, "executed": d.executed()}); + if keep { + out["changed"] = json!(changed); + out["changedCells"] = json!(cells); + } else { + out["message"] = json!(rolled_back(&wrote)); + } + add_notes(&mut out, &d, &wrote); + Ok(out) +} + +/// Where the run is: the next step with its parameters as they would run, the step that just +/// ran, and what the run has changed in its workbook so far. +fn state(s: &mut Session) -> Result { + let d = s.macro_debug.as_ref().ok_or_else(not_debugging)?; + let machine = d.machine.as_ref().ok_or_else(not_debugging)?; + let wb = s.docs.iter().find(|x| x.uid == d.doc).map(|x| x.wb.clone()).ok_or(EngineError::NoDocument)?; + let (changed, cells) = changed(s, d); + let mut out = json!({ + "state": "paused", + "macro": d.name, + "current": machine.current_json(&wb), + "lastParams": machine.last_params, + "executed": d.executed(), + "breakpoints": d.breakpoints, + "changed": changed, + "changedCells": cells, + }); + add_notes(&mut out, d, &machine.wrote_files); + Ok(out) +} + +/// What the run changed in its workbook since it started: cells as `Sheet!A1:B2` ranges and the +/// sheets it added, deleted or renamed (at most [`MAX_LISTED`] entries), and how many cells +/// changed on the sheets the workbook had at the start. +fn changed(s: &Session, d: &Debugger) -> (Vec, usize) { + let Some(now) = s.docs.iter().find(|x| x.uid == d.doc).map(|x| x.wb.clone()) else { return (vec![], 0) }; + let (pairs, added) = super::run::pair_sheets(&d.start, &now); + let mut out = Vec::new(); + let mut count = 0usize; + for (bi, ai) in pairs { + let Some(before) = d.start.sheets.get(bi) else { continue }; + let Some(after) = ai.and_then(|a| now.sheets.get(a)) else { + out.push(format!("{} (deleted sheet)", before.name)); + continue; + }; + if before.name != after.name { + out.push(format!("{} (renamed from {})", after.name, before.name)); + } + if Arc::ptr_eq(before, after) { + continue; + } + let mut cells = before.cells.diff(&after.cells); + count = count.saturating_add(cells.len()); + if out.len() < MAX_LISTED { + let q = super::resolve::quote_sheet(&after.name); + out.extend(super::run::ranges(&mut cells).into_iter().map(|r| format!("{q}!{r}"))); + } + } + out.extend(added.into_iter().filter_map(|a| now.sheets.get(a)).map(|sh| format!("{} (new sheet)", sh.name))); + out.truncate(MAX_LISTED); + (out, count) +} + +/// After the `macro.debug` call itself panicked: if the run lost its place, roll it back so its +/// undo group doesn't stay open. +pub(crate) fn recover(s: &mut Session) { + if s.macro_debug.as_ref().is_some_and(Debugger::stepping) + && let Some(mut d) = s.macro_debug.take() + && let Some(token) = d.token.take() + { + let _ = s.group_rollback(token); + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::Session; + + #[test] + fn a_run_that_lost_its_place_is_rolled_back() { + let mut s = Session::new(); + s.new_workbook(); + let m = crate::macros::parse_macro(&json!({"name": "M", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"command": "cell.set", "params": {"cell": "A2", "input": "y"}} + ]})) + .unwrap(); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.push(m); + d.wb = std::sync::Arc::new(wb); + let start = s.doc().unwrap().wb.clone(); + s.execute("macro.debug", json!({"name": "M"})).unwrap(); + s.execute("macro.debug", json!({"action": "step"})).unwrap(); + // As if a step had panicked with the machine out of the session. + s.macro_debug.as_mut().unwrap().machine = None; + super::recover(&mut s); + assert!(s.macro_debug.is_none()); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert!(!s.in_group(s.doc().unwrap().uid)); + s.execute("cell.set", json!({"cell": "B1", "input": "free"})).unwrap(); + } + + #[test] + fn a_step_that_panics_reports_the_step_failure() { + crate::register_test_command("test.debugStepPanics", |_, _| panic!("boom")); + let mut s = Session::new(); + s.new_workbook(); + let m = crate::macros::parse_macro(&json!({"name": "M", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"command": "test.debugStepPanics", "params": {}} + ]})) + .unwrap(); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.push(m); + d.wb = std::sync::Arc::new(wb); + let start = s.doc().unwrap().wb.clone(); + s.execute("macro.debug", json!({"name": "M"})).unwrap(); + s.execute("macro.debug", json!({"action": "step"})).unwrap(); + let r = s.execute("macro.debug", json!({"action": "step"})).unwrap(); + assert_eq!(r["state"], "failed", "{r}"); + assert_eq!(r["macro"], "M"); + assert_eq!(r["error"]["step"], "2"); + assert!(r["message"].as_str().unwrap().contains("boom"), "{r}"); + assert!(s.macro_debug.is_none()); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert!(!s.in_group(s.doc().unwrap().uid)); + } + + #[test] + fn a_workbook_in_the_touched_log_waits_until_the_run_ends() { + let mut s = Session::new(); + s.new_workbook(); + let m = crate::macros::parse_macro(&json!({"name": "M", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"command": "cell.set", "params": {"cell": "A2", "input": "y"}} + ]})) + .unwrap(); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.push(m); + d.wb = std::sync::Arc::new(wb); + s.new_workbook(); + let other = s.doc().unwrap().uid; + s.set_active(0); + s.execute("macro.debug", json!({"name": "M"})).unwrap(); + assert!(!s.macro_debug.as_ref().unwrap().locks(other)); + // As if a step had changed the other workbook too. + let before = super::versions(&s); + let d = s.docs.iter_mut().find(|d| d.uid == other).unwrap(); + let mut wb = (*d.wb).clone(); + wb.props.title = "changed by the macro".into(); + d.wb = std::sync::Arc::new(wb); + super::note_touched(&mut s, &before); + assert!(s.macro_debug.as_ref().unwrap().locks(other)); + s.set_active(1); + assert!(s.execute("cell.set", json!({"cell": "B1", "input": "no"})).is_err()); + s.execute("macro.debug", json!({"action": "stop", "keep": true})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "free"})).unwrap(); + } + + #[test] + fn edits_run_by_another_command_wait_too() { + let mut s = Session::new(); + s.new_workbook(); + let m = crate::macros::parse_macro(&json!({"name": "M", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"command": "cell.set", "params": {"cell": "A2", "input": "y"}} + ]})) + .unwrap(); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.push(m); + d.wb = std::sync::Arc::new(wb); + s.execute("automate.recordActions", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": "1"})).unwrap(); + s.execute("macro.debug", json!({"name": "M"})).unwrap(); + s.execute("macro.debug", json!({"action": "step"})).unwrap(); + // Record Actions changes nothing itself; stopping it saves the script with a nested + // command, which would land in the run's undo group. + let e = s.execute("automate.recordActions", json!({"stop": true, "name": "S"})).unwrap_err().to_string(); + assert!(e.contains(super::BUSY), "{e}"); + assert!(s.execute("automate.allScripts", json!({})).unwrap().as_array().unwrap().is_empty()); + // The run's own steps still go ahead. + let r = s.execute("macro.debug", json!({"action": "step"})).unwrap(); + assert_eq!(r["executed"], 2, "{r}"); + assert!(s.macro_debug.is_none()); + // The recording was kept: stopping now saves it. + let saved = s.execute("automate.recordActions", json!({"stop": true, "name": "S"})).unwrap(); + assert_eq!(saved["saved"], "S", "{saved}"); + let scripts = s.execute("automate.allScripts", json!({})).unwrap(); + assert_eq!(scripts[0]["name"], "S", "{scripts}"); + } +} diff --git a/crates/engine/src/macros/mod.rs b/crates/engine/src/macros/mod.rs new file mode 100644 index 0000000000..ecbe6f6741 --- /dev/null +++ b/crates/engine/src/macros/mod.rs @@ -0,0 +1,515 @@ +//! GridCraft macros: typed, declarative command lists, not VBA. The model is plain data in +//! `gridcraft_model::Macro`; this module reads and writes it and keeps it within its limits. +//! +//! Storage: the JSON format keeps `Workbook::macros` as a field. In xlsx each macro is one item of +//! GridCraft's hidden workbook data ([`crate::cmd::stash`]), `_gc_macro__`, written when the +//! file is saved and taken back out of the names when it is opened, so the names never linger in +//! the open document. Scripts made with Automate › New Script or Record Actions are a separate, +//! older feature with their own storage; macros neither read nor change it. A recording keeps the +//! steps a script run ran while it recorded, as the run reported them. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use gridcraft_model::{DefinedName, Macro, Step, StepKind, Workbook}; +use serde_json::{Value as Json, json}; + +use crate::cmd::stash; + +pub mod debug; +pub mod policy; +pub mod recorder; +pub mod resolve; +pub mod run; + +/// The hidden-data key prefix of a stored macro (`macro_`). +const MACRO_KEY: &str = "macro_"; + +/// Reads a macro from JSON, as `macro.save` and files give it. A command step may also use the +/// short form `{"command": "cell.set", "params": {…}}`. +pub fn parse_macro(v: &Json) -> Result { + // A newer format is refused before its steps are read, so the message says why. + if let Some(found) = v.get("v").and_then(Json::as_u64) { + gridcraft_model::check_version(found)?; + } + let mut v = v.clone(); + if let Some(steps) = v.get_mut("steps") { + normalize_steps(steps, 1)?; + } + if v.get("v").is_none() + && let Some(o) = v.as_object_mut() + { + o.insert("v".into(), json!(gridcraft_model::MACRO_VERSION)); + } + let mut m: Macro = serde_json::from_value(v).map_err(|e| format!("This isn't a valid macro: {e}"))?; + m.name = m.name.trim().to_string(); + check(&m)?; + Ok(m) +} + +/// Every check a macro must pass before it is kept in a workbook: the model's limits +/// ([`Macro::check_limits`]) and the size an xlsx file can hold. Every path that adds a macro, +/// from JSON, from a file or built in code, goes through this one check. +pub fn check(m: &Macro) -> Result<(), String> { + m.check_limits()?; + check_size(m) +} + +/// Refuses a macro too large to keep in an xlsx file ([`stash::MAX_ITEM_CHARS`] characters of +/// JSON). Every command that adds or changes a macro calls [`check`], so the size of a macro kept +/// in the workbook doesn't make a save fail. (A clashing visible name doesn't either: +/// [`with_names`] stores the macro under another index.) +fn check_size(m: &Macro) -> Result<(), String> { + if macro_json(m).to_string().chars().count() > stash::MAX_ITEM_CHARS { + return Err(format!("This macro is too large to keep in the workbook ({} characters at most).", stash::MAX_ITEM_CHARS)); + } + Ok(()) +} + +/// Leaves out the last top-level steps of `m` until it fits the size [`check_size`] allows, and +/// returns how many steps it left out (a recording cut to fit, as at the step limit). Each step's +/// JSON is measured once. +pub fn fit_size(m: &mut Macro) -> usize { + let chars = |v: &Json| v.to_string().chars().count(); + let steps = std::mem::take(&mut m.steps); + // The macro without steps holds `"steps":[]`; each step adds its JSON, and a comma after the + // first. + let mut size = chars(¯o_json(m)); + let mut kept = 0usize; + for (i, st) in steps.iter().enumerate() { + let add = chars(&serde_json::to_value(st).unwrap_or(Json::Null)).saturating_add(usize::from(i > 0)); + if size.saturating_add(add) > stash::MAX_ITEM_CHARS { + break; + } + size = size.saturating_add(add); + kept = i.saturating_add(1); + } + let cut = steps.len().saturating_sub(kept); + m.steps = steps; + m.steps.truncate(kept); + cut +} + +/// How many macros the workbook holds: the readable ones and the ones kept in a newer format +/// (`Workbook::macros_unread`), which a save writes back and the next open counts too. +pub fn count(wb: &Workbook) -> usize { + wb.macros.len().saturating_add(wb.macros_unread.len()) +} + +/// Refuses one more macro in a workbook that holds [`gridcraft_model::MAX_MACROS`] already, +/// counting the kept ones, so a save never holds more than the next open keeps. +pub fn check_room(wb: &Workbook) -> Result<(), String> { + let max = gridcraft_model::MAX_MACROS; + if count(wb) < max { + return Ok(()); + } + Err(match wb.macros_unread.len() { + 0 => format!("A workbook can hold at most {max} macros."), + kept => format!( + "A workbook can hold at most {max} macros, and {kept} of the {} in this one {} made by a newer version of GridCraft and kept unchanged.", + count(wb), + if kept == 1 { "was" } else { "were" } + ), + }) +} + +/// The name of the macro kept in a newer format called `name` (compared as [`find`] compares), +/// as the file held it. Its name is taken: a new or renamed macro with it would clash when the +/// newer version reads the file. +pub fn kept_name(wb: &Workbook, name: &str) -> Option { + let name = name.trim(); + wb.macros_unread + .iter() + .filter_map(|v| v.get("name").and_then(Json::as_str)) + .map(str::trim) + .find(|k| k.eq_ignore_ascii_case(name)) + .map(str::to_string) +} + +/// Rewrites the short step form into the tagged one, in place, refusing nesting past the limit +/// before the steps are deserialized. +fn normalize_steps(steps: &mut Json, level: usize) -> Result<(), String> { + let Some(list) = steps.as_array_mut() else { return Err("`steps` must be a list.".into()) }; + for st in list { + let Some(o) = st.as_object_mut() else { return Err("Every step must be an object.".into()) }; + if !o.contains_key("type") + && let Some(id) = o.remove("command") + { + o.insert("type".into(), json!("command")); + o.insert("id".into(), id); + } + // A step with a body is a Repeat or an If: one at the top is nested 1 deep. + let nested = ["body", "then", "else"].iter().any(|key| o.contains_key(*key)); + if nested && level > gridcraft_model::MAX_MACRO_DEPTH { + return Err(format!("Repeat and If steps can nest at most {} deep.", gridcraft_model::MAX_MACRO_DEPTH)); + } + for key in ["body", "then", "else"] { + if let Some(body) = o.get_mut(key) { + normalize_steps(body, level + 1)?; + } + } + } + Ok(()) +} + +/// A macro as JSON (the shape `macro.get` returns and `macro.save` takes). +pub fn macro_json(m: &Macro) -> Json { + serde_json::to_value(m).unwrap_or(Json::Null) +} + +/// The index of the macro called `name` (case-insensitive). +pub fn find(wb: &Workbook, name: &str) -> Option { + let name = name.trim(); + wb.macros.iter().position(|m| m.name.eq_ignore_ascii_case(name)) +} + +/// A macro's content as canonical JSON text (object keys sorted): approval to run a macro holds +/// until the macro changes. It is the text itself rather than a hash, so no two different macros +/// share it. +pub fn fingerprint(m: &Macro) -> String { + macro_json(m).to_string() +} + +/// A copy of `wb` for xlsx with each macro in hidden names (`_gc_macro__`) instead of the +/// field, or `None` when there is nothing to change. The macros keep their order; the index `n` +/// is this build's choice, so it steps around any a person's own visible name already uses. +pub fn with_names(wb: &Workbook) -> crate::Result> { + // Only the numbered items are this build's: a hidden `_gc_macro__` name with some + // other key stays, as `load` leaves it. + let stored = |n: &DefinedName| macro_item(n).is_some_and(|(_, i)| i.is_some()); + if wb.macros.is_empty() && wb.macros_unread.is_empty() && !wb.names.iter().any(stored) { + return Ok(None); + } + // A macro that skipped `check` (built in code) fails the save, as the JSON save does, rather + // than being written and dropped the next time the file opens. + for m in wb.macros.iter() { + check(m).map_err(crate::EngineError::Other)?; + } + let mut out = wb.clone(); + // One pass drops the items of the last save, and one writes the macros (a file can hold a + // thousand macros and many thousands of names). + out.names.retain(|n| !stored(n)); + // A visible workbook-scope name of the storage shape is someone's own, and `set_many` won't + // write a hidden one of the same name beside it. Such a name (`_GC_MACRO_1_0`, or one a + // person defined after the file opened) blocks its item's key, in any chunk, so the macros + // take the free indices from 0 up. The keys compare as the stash reads them, so this skips + // exactly what `set_many` would refuse, and no arithmetic depends on a number from the file. + let blocked: HashSet = out.names.iter().filter(|n| !n.hidden && n.scope.is_none()).filter_map(|n| stash::item_key(&n.name)).collect(); + let free = (0..=u64::MAX).map(|i| format!("{MACRO_KEY}{i}")).filter(|key| !blocked.contains(key)); + // Macros in a newer format follow the readable ones, written back as the file held them. + let texts = wb.macros.iter().map(|m| macro_json(m).to_string()).chain(wb.macros_unread.iter().map(Json::to_string)); + let items: Vec<(String, String)> = texts.zip(free).map(|(text, key)| (key, text)).collect(); + stash::set_many(&mut out, &items)?; + // An empty list of its own, not a copy of the shared one cleared. + out.macros = gridcraft_model::Macros::default(); + out.macros_unread = std::sync::Arc::default(); + Ok(Some(out)) +} + +/// The JSON format's bytes for `wb`: the workbook, with the macros in a newer format put back into +/// the `macros` list as the file held them. +pub fn json_bytes(wb: &Workbook) -> crate::Result> { + // Every path that adds a macro checks it, so this refuses only one that skipped the check, as + // the xlsx save does, instead of writing a macro the next open would drop. + for m in &wb.macros { + check(m).map_err(crate::EngineError::Other)?; + } + let bytes = if wb.macros_unread.is_empty() { + serde_json::to_vec_pretty(wb) + } else { + serde_json::to_value(wb).and_then(|mut v| { + if let Some(list) = v.as_object_mut().map(|o| o.entry("macros").or_insert_with(|| Json::Array(vec![]))).and_then(Json::as_array_mut) { + list.extend(wb.macros_unread.iter().cloned()); + } + serde_json::to_vec_pretty(&v) + }) + }; + bytes.map_err(|e| crate::EngineError::Other(e.to_string())) +} + +/// Whether `v` is a macro in a newer format than this build reads. +fn is_newer(v: &Json) -> bool { + v.get("v").and_then(Json::as_u64).is_some_and(|found| found > u64::from(gridcraft_model::MACRO_VERSION)) +} + +/// Keeps a macro in a newer format unread, if it is small enough to save back +/// ([`stash::MAX_ITEM_CHARS`] characters of JSON, the size every xlsx save can write). +fn keep_unread(unread: &mut Vec, v: Json, bad: &mut usize) { + if v.to_string().chars().count() <= stash::MAX_ITEM_CHARS { + unread.push(v); + } else { + *bad = bad.saturating_add(1); + } +} + +/// After a file is opened: moves macros out of hidden names into `Workbook::macros`, keeps +/// macros in a newer format unread (`Workbook::macros_unread`), and drops macros that are damaged +/// or over the limits. Returns a warning for what was kept unread and one for what was dropped. +pub fn load(wb: &mut Workbook) -> Vec { + let mut warnings = Vec::new(); + let mut bad = 0usize; + let mut unread = Vec::new(); + // Entries of the JSON format's field, each read on its own so a damaged one drops alone. + let read = std::mem::take(&mut wb.macros_read); + bad = bad.saturating_add(read.len().saturating_sub(gridcraft_model::MAX_MACROS)); + for v in read.into_iter().take(gridcraft_model::MAX_MACROS) { + if is_newer(&v) { + keep_unread(&mut unread, v, &mut bad); + continue; + } + match parse_macro(&v) { + Ok(m) => wb.macros.push(m), + Err(_) => bad += 1, + } + } + // One pass takes the hidden macro names out of the workbook, grouped by macro in saved order. + let mut stored: BTreeMap<(u64, String), Vec> = BTreeMap::new(); + let mut kept = Vec::new(); + for n in std::mem::take(&mut wb.names) { + match macro_item(&n) { + None => kept.push(n), + Some((key, Some(i))) => stored.entry((i, key)).or_default().push(n), + // A `macro_` item that isn't numbered isn't one this build wrote: it stays as it is, + // unread, and a save keeps it. + Some((_, None)) => kept.push(n), + } + } + wb.names = kept; + // Past the macro limit, the rest are counted without being read. + bad = bad.saturating_add(stored.len().saturating_sub(gridcraft_model::MAX_MACROS)); + let mut found = Vec::new(); + let mut item = Workbook::new(); + for ((_, key), names) in stored.into_iter().take(gridcraft_model::MAX_MACROS) { + item.names = names; + let v = stash::get_json(&item, &key); + if let Some(v) = v.as_ref().filter(|v| is_newer(v)) { + keep_unread(&mut unread, v.clone(), &mut bad); + continue; + } + match v.ok_or_else(|| "unreadable".to_string()).and_then(|v| parse_macro(&v)) { + Ok(m) => found.push(m), + Err(_) => bad += 1, + } + } + // All of them go through the same limits, and a clashing name gets a suffix. + let mut all = std::mem::take(&mut wb.macros); + all.extend(found); + let mut taken = Taken::default(); + for m in all { + if wb.macros.len() >= gridcraft_model::MAX_MACROS { + bad += 1; + continue; + } + let mut m = m; + let checked = m.check_limits().and_then(|()| { + m.name = taken.unique(m.name.trim()); + // The macro as it is kept, renamed, must still pass, or the next save would lose it. + check(&m) + }); + match checked { + Ok(()) => { + taken.insert(&m.name); + wb.macros.push(m); + } + Err(_) => bad += 1, + } + } + // Readable and unread macros together stay within the limit, the readable ones first. + let room = gridcraft_model::MAX_MACROS.saturating_sub(wb.macros.len()); + bad = bad.saturating_add(unread.len().saturating_sub(room)); + unread.truncate(room); + if !unread.is_empty() { + let one = unread.len() == 1; + warnings.push(format!( + "{} macro{} in the workbook {} made by a newer version of GridCraft: this version can't show or run {}, and saving keeps {} unchanged.", + unread.len(), + if one { "" } else { "s" }, + if one { "was" } else { "were" }, + if one { "it" } else { "them" }, + if one { "it" } else { "them" }, + )); + } + wb.macros_unread = std::sync::Arc::new(unread); + if bad > 0 { + warnings.push(format!( + "{bad} macro{} in the workbook couldn't be opened: {} damaged or over the limits ({} macros, {} steps each, Repeat and If nested {} deep).", + if bad == 1 { "" } else { "s" }, + if bad == 1 { "it is" } else { "they are" }, + gridcraft_model::MAX_MACROS, + gridcraft_model::MAX_MACRO_STEPS, + gridcraft_model::MAX_MACRO_DEPTH + )); + } + warnings +} + +/// The item key (`macro_`, lower-cased) of a hidden macro name, and `n` when it is a number. +fn macro_item(n: &DefinedName) -> Option<(String, Option)> { + // Only a hidden workbook-scope name is macro storage: a person's own visible name that + // happens to look like one stays a name. + let key = stash::item_key(&n.name).filter(|k| n.hidden && n.scope.is_none() && k.starts_with(MACRO_KEY))?; + let i = key.strip_prefix(MACRO_KEY).and_then(|i| i.parse().ok()); + Some((key, i)) +} + +/// `name`, or `name (2)`, `name (3)`… if a macro already has it, a kept one too. A free name comes back as it is; +/// a renamed one is shortened to make room for the suffix, so it stays within +/// [`gridcraft_model::MAX_MACRO_NAME`] characters. The result still goes through [`check`]. +pub fn unique_name(wb: &Workbook, name: &str) -> String { + let mut taken = Taken::default(); + for m in &wb.macros { + taken.insert(&m.name); + } + for kept in wb.macros_unread.iter().filter_map(|v| v.get("name").and_then(Json::as_str)) { + taken.insert(kept); + } + taken.unique(name) +} + +/// Macro names in use, compared as [`find`] compares them, and the next suffix to try for each +/// shortened name and suffix width, so naming many clashing macros takes near-linear work. +#[derive(Default)] +struct Taken { + names: HashSet, + next: HashMap<(String, usize), u64>, + /// Name lookups made, for tests. + probes: usize, +} + +impl Taken { + fn key(name: &str) -> String { + name.trim().to_ascii_lowercase() + } + + fn insert(&mut self, name: &str) { + self.names.insert(Taken::key(name)); + } + + fn contains(&mut self, name: &str) -> bool { + self.probes = self.probes.saturating_add(1); + self.names.contains(&Taken::key(name)) + } + + /// The first of `name`, `name (2)`, `name (3)`… not in use. + fn unique(&mut self, name: &str) -> String { + let name = if name.is_empty() { "Macro" } else { name }; + if !self.contains(name) { + return name.to_string(); + } + let mut n: u64 = 2; + loop { + let suffix = format!(" ({n})"); + let keep = gridcraft_model::MAX_MACRO_NAME.saturating_sub(suffix.chars().count()); + let base: String = name.chars().take(keep).collect(); + let base = base.trim_end(); + // Every candidate for this base and suffix width below `next` is in use already + // (names are only added), so the search goes on from there. + let key = (Taken::key(base), suffix.len()); + let next = self.next.get(&key).copied().unwrap_or(n); + if next > n { + n = next; + continue; + } + let Some(after) = n.checked_add(1) else { return name.to_string() }; + self.next.insert(key, after); + let candidate = format!("{base}{suffix}"); + if !self.contains(&candidate) { + return candidate; + } + n = after; + } + } +} + +/// Ctrl+Shift (Cmd+Shift on a Mac) letters that GridCraft already uses, on any platform, which a +/// macro cannot take. +pub const RESERVED_SHORTCUTS: &[(char, &str)] = &[ + ('F', "Format Cells (Font) or Filter"), + ('G', "Workbook Statistics"), + ('H', "Replace"), + ('J', "Ungroup"), + ('K', "Group"), + ('L', "Filter"), + ('R', "Sort"), + ('S', "Save As"), + ('T', "AutoSum"), + ('Z', "Redo"), +]; + +/// The letter of a macro shortcut: `"Ctrl+Shift+M"`, `"Cmd+Shift+M"`, `"⌘⇧M"` and `"m"` all give +/// `'M'`. `None` when it is not one letter from A to Z, alone or after Ctrl+Shift (Cmd+Shift): +/// other modifiers (`"Ctrl+Alt+M"`) are refused rather than read as Ctrl+Shift. +pub fn parse_shortcut(s: &str) -> Option { + let letter = |t: &str| { + let mut chars = t.trim().chars(); + match (chars.next(), chars.next()) { + (Some(c), None) if c.is_ascii_alphabetic() => Some(c.to_ascii_uppercase()), + _ => None, + } + }; + let t = s.trim().to_ascii_lowercase(); + ["ctrl+shift+", "cmd+shift+", "⌘⇧"].iter().find_map(|p| t.strip_prefix(p)).map_or_else(|| letter(&t), letter) +} + +/// How a shortcut is stored and shown: `Ctrl+Shift+M`. +pub fn shortcut_text(letter: char) -> String { + format!("Ctrl+Shift+{}", letter.to_ascii_uppercase()) +} + +/// Why macro `name` cannot use Ctrl+Shift+`letter`: GridCraft uses it, or another macro has it. +pub fn shortcut_conflict(wb: &Workbook, name: &str, letter: char) -> Option { + let letter = letter.to_ascii_uppercase(); + if let Some((_, what)) = RESERVED_SHORTCUTS.iter().find(|(c, _)| *c == letter) { + return Some(format!("{} is {what}. Choose another letter.", shortcut_text(letter))); + } + wb.macros + .iter() + .find(|m| !m.name.eq_ignore_ascii_case(name.trim()) && m.shortcut.as_deref().and_then(parse_shortcut) == Some(letter)) + .map(|m| format!("{} already runs macro “{}”. Choose another letter.", shortcut_text(letter), m.name)) +} + +/// `name` trimmed, if it can name a new macro in `wb`; otherwise why not: it is empty, too long, +/// holds line breaks or another macro has it. +pub fn check_new_name(wb: &Workbook, name: &str) -> Result { + let name = name.trim(); + let probe = Macro { name: name.to_string(), ..Macro::default() }; + probe.check_limits()?; + if name.chars().any(char::is_control) { + return Err("A macro name cannot hold line breaks or other control characters.".into()); + } + if find(wb, name).is_some() { + return Err(format!("A macro called “{name}” already exists. Choose another name.")); + } + if let Some(kept) = kept_name(wb, name) { + return Err(format!("A macro called “{kept}” is kept from a newer version of GridCraft. Choose another name.")); + } + Ok(name.to_string()) +} + +/// The first free `Macro1`, `Macro2`… name, also free among the kept macros ([`kept_name`]). +pub fn next_name(wb: &Workbook) -> String { + (1..).map(|n| format!("Macro{n}")).find(|n| find(wb, n).is_none() && kept_name(wb, n).is_none()).unwrap_or_else(|| "Macro".into()) +} + +/// Every command step of `steps` (inside Repeat and If too), with its path. +pub fn command_steps(steps: &[Step]) -> Vec<(String, &str, &Json)> { + fn walk<'a>(steps: &'a [Step], prefix: &str, out: &mut Vec<(String, &'a str, &'a Json)>) { + for (i, st) in steps.iter().enumerate() { + let path = if prefix.is_empty() { (i + 1).to_string() } else { format!("{prefix}.{}", i + 1) }; + match &st.kind { + StepKind::Command { id, params } => out.push((path, id.as_str(), params)), + StepKind::Repeat { body, .. } => walk(body, &path, out), + StepKind::If { then, otherwise, .. } => { + walk(then, &format!("{path}.then"), out); + walk(otherwise, &format!("{path}.else"), out); + } + StepKind::Stop { .. } => {} + } + } + } + let mut out = Vec::new(); + walk(steps, "", &mut out); + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/macros/policy.rs b/crates/engine/src/macros/policy.rs new file mode 100644 index 0000000000..a840979869 --- /dev/null +++ b/crates/engine/src/macros/policy.rs @@ -0,0 +1,148 @@ +//! What a macro step may run. Macros run commands, so this keeps a macro from saving, opening or +//! closing files, driving the app, running other macros, or reading and writing files without the +//! person knowing. It goes by command id and the `path` parameter; the runner also runs every +//! step except an approved file step inside the scripts' file sandbox, so a command that touches a +//! file under another parameter can't either. + +use serde_json::Value as Json; + +use crate::Trust; + +/// Whether a command may run as a macro step. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Policy { + Allow, + /// Allowed once the person approves the macro; the text says why it asks ("came with a + /// workbook you opened"). + Ask(String), + /// Reads or writes files: the macro must list the command in its permissions, and the person + /// approves the macro before it runs. The text says what it does ("reads a file"). + NeedsPermission(String), + /// Never runs in a macro; the text says why. + Deny(String), +} + +/// Prefixes of commands that never run in a macro, with the reason. +const DENIED_PREFIXES: &[(&str, &str)] = &[ + ("file.", "macros don't open, save, close or create workbooks"), + ("app.", "macros don't change the app"), + ("window.", "macros don't switch windows"), + ("automate.", "macros don't record or run scripts or other macros"), + ("macro.", "macros don't record or run other macros"), +]; + +/// Single commands that never run in a macro. +const DENIED: &[(&str, &str)] = &[ + ("edit.undo", "a macro is undone as one step after it runs"), + ("edit.redo", "a macro is undone as one step after it runs"), + ("view.newWindow", "macros don't open, hide or show windows"), + ("view.hideWindow", "macros don't open, hide or show windows"), + ("view.unhideWindow", "macros don't open, hide or show windows"), +]; + +/// Commands under a denied prefix that only change the workbook. +const ALLOWED: &[&str] = &["file.properties"]; + +/// Commands that read a file when given a `path`. +const READS_FILES: &[&str] = &["data.getData", "data.fromTextCsv", "insert.picture", "pageLayout.background"]; + +/// File commands that only produce bytes unless given a `path` (then they write a file). +const EXPORTS: &[&str] = &["file.exportPdf", "file.exportCsv", "file.exportHtml", "file.print", "file.printPreview", "file.saveBytes"]; + +/// Whether command `id` with `params` writes a file (an export or print given a `path`). +pub fn writes_file(id: &str, params: &Json) -> bool { + EXPORTS.contains(&id) && params.get("path").is_some_and(|p| !p.is_null()) +} + +/// The policy for running command `id` with `params` as a macro step in a document with `trust`. +/// +/// Any `path` other than `null` counts as touching a file: a token such as `{"$ref": "Input"}` +/// becomes a path when the step runs, and exports write to `""` and `" "` as file names. The +/// runner checks the parameters both as written and as resolved. +pub fn macro_policy(id: &str, params: &Json, trust: Trust) -> Policy { + let has_path = params.get("path").is_some_and(|p| !p.is_null()); + let base = if EXPORTS.contains(&id) { + if has_path { Policy::NeedsPermission("writes a file".into()) } else { Policy::Allow } + } else if ALLOWED.contains(&id) { + Policy::Allow + } else if let Some((_, why)) = DENIED.iter().find(|(d, _)| *d == id) { + Policy::Deny((*why).into()) + } else if let Some((_, why)) = DENIED_PREFIXES.iter().find(|(p, _)| id.starts_with(p)) { + Policy::Deny((*why).into()) + } else if READS_FILES.contains(&id) && has_path { + Policy::NeedsPermission("reads a file".into()) + } else { + Policy::Allow + }; + match base { + Policy::Allow if !trust.allows_code() => Policy::Ask("came with a workbook you opened".into()), + other => other, + } +} + +/// Whether the footprint dry run can preview a command. Solver can take long, so a dry run stops +/// before it and reports the footprint as partial. +pub fn previewable(id: &str) -> bool { + id != "data.solver" +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn the_deny_and_permission_lists() { + let none = json!({}); + let path = json!({"path": "/tmp/x"}); + for id in [ + "file.saveAs", + "file.save", + "file.open", + "file.close", + "file.new", + "app.commands", + "window.activate", + "automate.runScript", + "automate.recordActions", + "macro.run", + "macro.record", + "edit.undo", + "edit.redo", + "view.newWindow", + "view.hideWindow", + "view.unhideWindow", + ] { + assert!(matches!(macro_policy(id, &none, Trust::Local), Policy::Deny(_)), "{id}"); + assert!(matches!(macro_policy(id, &path, Trust::FromFile), Policy::Deny(_)), "{id}"); + } + for id in ["data.getData", "data.fromTextCsv", "insert.picture", "pageLayout.background", "file.exportPdf", "file.print", "file.exportCsv"] { + assert!(matches!(macro_policy(id, &path, Trust::Local), Policy::NeedsPermission(_)), "{id}"); + assert!(matches!(macro_policy(id, &path, Trust::FromFile), Policy::NeedsPermission(_)), "{id}"); + } + // Without a path they touch no file. + for id in ["data.getData", "insert.picture", "file.exportPdf", "file.saveBytes", "file.printPreview"] { + assert_eq!(macro_policy(id, &none, Trust::Local), Policy::Allow, "{id}"); + assert_eq!(macro_policy(id, &json!({"path": null}), Trust::Local), Policy::Allow, "{id}"); + } + // A path that is blank or a token still touches a file once the step runs. + for path in [json!(""), json!(" "), json!({"$ref": "Input"}), json!("{{Input}}.csv"), json!(1)] { + for id in ["file.exportCsv", "data.fromTextCsv"] { + let p = json!({ "path": path }); + assert!(matches!(macro_policy(id, &p, Trust::Local), Policy::NeedsPermission(_)), "{id} {p}"); + } + } + for id in ["cell.set", "home.bold", "view.macros", "edit.copy", "file.properties"] { + assert_eq!(macro_policy(id, &none, Trust::Local), Policy::Allow, "{id}"); + assert!(matches!(macro_policy(id, &none, Trust::FromFile), Policy::Ask(_)), "{id}"); + } + assert!(!previewable("data.solver") && previewable("cell.set")); + } + + #[test] + fn every_listed_command_exists() { + for id in ALLOWED.iter().chain(READS_FILES).chain(EXPORTS).chain(DENIED.iter().map(|(id, _)| id)).chain(&["data.solver"]) { + assert!(crate::find_command(id).is_some(), "{id}"); + } + } +} diff --git a/crates/engine/src/macros/recorder.rs b/crates/engine/src/macros/recorder.rs new file mode 100644 index 0000000000..337c416618 --- /dev/null +++ b/crates/engine/src/macros/recorder.rs @@ -0,0 +1,528 @@ +//! Turning a recording into a macro. +//! +//! The recording buffer (`crate::record`) holds the top-level commands run while recording, each +//! with the sheet and selection it ran in. When recording stops: +//! +//! - commands a macro may not run (saving, opening files…) and other macros' commands are left +//! out; a macro run while recording is replaced by its steps when it has no inputs, no output +//! and only plain commands (otherwise it is left out), and an Automate script run while +//! recording by the steps it ran, leaving out the steps a macro may not run; both are the steps +//! as they ran, kept with the recording ([`crate::record::Recorder::ran`]), and a run without +//! them is left out; +//! - a `sheet.activate` or `selection.set` step is added where the sheet or selection changed +//! between commands without one, and runs of `selection.set` collapse to the last; +//! - with relative references (the default), the selection when recording started is the example +//! input: references on its sheet in, next to or near it become tokens (`Input.col(2)`, +//! `Input.below`, `Input.cell(1,4)`), also inside formulas (`{{Input.col(2)}}`), and the input's +//! shape, header and column types are inferred from it as it was when recording started; +//! - recorded text that playback would read as a token stays text: a reference parameter that +//! reads as one (a defined name called `Output`) becomes `{"$text": …}`, and `{{` in a string +//! becomes `{{{{`. + +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_model::{ColType, InputKind, MAX_MACRO_STEPS, Macro, NamedInput, Step, StepKind, Workbook}; +use serde_json::{Map, Value as Json, json}; +use std::collections::BTreeMap; + +use super::policy::{Policy, macro_policy}; +use crate::Selection; +use crate::record::RecordedStep; + +/// How far outside the example input a reference may be and still be made relative to it. +const NEAR_ROWS: u32 = 50; +const NEAR_COLS: u32 = 26; + +/// Where recording started, kept beside the buffer, with the name, shortcut and description the +/// macro is to be saved with (from the Record Macro dialog), applied when recording stops. +#[derive(Clone, Debug)] +pub struct RecordingStart { + pub doc: u64, + pub sheet: usize, + pub sheet_name: String, + pub selection: Selection, + pub relative: bool, + /// With relative references, the example input (the selection) as it was when recording + /// started: the recorded steps may change its values (text made into numbers), and the + /// macro is for data like the data it was recorded on. + pub input: Option, + /// The name, shortcut and description given when recording started (Record Macro). + pub name: Option, + pub shortcut: Option, + pub description: Option, +} + +impl RecordingStart { + /// Recording starting now in `d`. + pub fn new(d: &crate::DocState, relative: bool) -> RecordingStart { + let sheet = d.wb.active_sheet(); + RecordingStart { + doc: d.uid, + sheet, + sheet_name: d.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(), + selection: d.selection.clone(), + relative, + input: relative.then(|| infer_input(&d.wb, sheet, d.selection.current())), + name: None, + shortcut: None, + description: None, + } + } +} + +/// The steps a recording keeps for a run of `m`: its enabled command steps as written, when they +/// stand on their own (no inputs, no output and only plain commands; a Repeat, If or Stop means +/// nothing outside its macro). `None` when they don't, and the recording leaves the run out. +pub fn inline_steps(m: &Macro) -> Option> { + if !m.inputs.is_empty() || m.output.anchor.is_some() || !m.steps.iter().all(|x| matches!(x.kind, StepKind::Command { .. })) { + return None; + } + Some( + m.steps + .iter() + .filter(|x| x.enabled) + .filter_map(|x| match &x.kind { + StepKind::Command { id, params } => Some((id.clone(), params.clone())), + _ => None, + }) + .collect(), + ) +} + +/// Where a gathered command came from, which says how its parameters are written. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Origin { + /// Run while recording: plain parameters, which may become relative. + Recorded, + /// A step of a recorded script run: plain parameters, kept as they are. + Script, + /// A step of a recorded macro run: macro parameters (tokens and all), kept as written. + Macro, +} + +/// A recording turned into a macro, with what was left out. +pub struct Converted { + pub mac: Macro, + /// Commands left out (ids), in order. + pub skipped: Vec, + /// Steps not kept: past the macro's step limit (a recorded run of a long macro adds all of + /// its steps) or recorded in another workbook. + pub cut: usize, +} + +/// Builds a macro called `name` from the recorded steps. +/// `ran` is what a macro or script run ran, by step index ([`crate::record::Recorder::ran`]); a +/// run without an entry is left out and listed in `skipped`. +pub fn convert(name: &str, start: &RecordingStart, steps: &[RecordedStep], ran: &BTreeMap>) -> Converted { + let mut skipped = Vec::new(); + // Commands as they'll be played back: (id, params, sheet before, selection before, where + // they came from). At most the macro's step limit are gathered: a recording of a thousand + // runs of a long macro would otherwise expand to millions of steps before the limit cut them + // back. + let mut cmds: Vec<(String, Json, usize, String, Selection, Origin)> = Vec::new(); + let mut cut = steps.iter().filter(|st| st.doc != start.doc).count(); + let refused = |id: &str, params: &Json| matches!(macro_policy(id, params, crate::Trust::Local), Policy::Deny(_) | Policy::NeedsPermission(_)); + let mut push = |cmds: &mut Vec<(String, Json, usize, String, Selection, Origin)>, cmd: (String, Json, usize, String, Selection, Origin)| { + if cmds.len() < MAX_MACRO_STEPS { + cmds.push(cmd); + } else { + cut = cut.saturating_add(1); + } + }; + for (index, st) in steps.iter().enumerate().filter(|(_, st)| st.doc == start.doc) { + let id = st.id.as_str(); + // Another macro's steps (when they stand on their own, [`inline_steps`]) or an Automate + // script's, as they ran: what the run kept with the recording. Without them the run is + // left out; the macro or script as it stands now may not be what ran. + let origin = match id { + "macro.run" => Some(Origin::Macro), + "automate.runScript" => Some(Origin::Script), + _ => None, + }; + if let Some(origin) = origin { + match ran.get(&index) { + Some(steps) => { + for (cid, params) in steps { + if refused(cid, params) { + skipped.push(cid.clone()); + continue; + } + push(&mut cmds, (cid.clone(), params.clone(), st.sheet, st.sheet_name.clone(), st.selection.clone(), origin)); + } + } + None => skipped.push(id.to_string()), + } + continue; + } + if refused(id, &st.params) { + skipped.push(id.to_string()); + continue; + } + push(&mut cmds, (id.to_string(), st.params.clone(), st.sheet, st.sheet_name.clone(), st.selection.clone(), Origin::Recorded)); + } + + // Sheet and selection changes made without a command: where a command ran on another sheet, + // or with another selection, than the one before it, say so (a command that moved the + // selection itself does it again when played back, so the extra step is harmless). + // Each step keeps the name of the sheet it runs on. + let mut out: Vec<(String, Json, String, Origin)> = Vec::new(); + let (mut sheet, mut sel) = (start.sheet, start.selection.clone()); + for (id, params, at_sheet, sheet_name, at_sel, origin) in cmds { + if at_sheet != sheet { + out.push(("sheet.activate".into(), json!({"sheet": sheet_name}), sheet_name.clone(), Origin::Recorded)); + } + // A recorded selection.set just before already put the selection there. + let selected = matches!(out.last(), Some((last, ..)) if last == "selection.set"); + if (at_sel != sel || at_sheet != sheet) && !selected { + out.push(("selection.set".into(), selection_params(&at_sel), sheet_name.clone(), Origin::Recorded)); + } + (sheet, sel) = (at_sheet, at_sel); + out.push((id, params, sheet_name, origin)); + } + // Runs of selection.set (or sheet.activate): the last one wins. + let mut collapsed: Vec<(String, Json, String, Origin)> = Vec::new(); + for (id, params, on, origin) in out { + if matches!(id.as_str(), "selection.set" | "sheet.activate") + && let Some((last, ..)) = collapsed.last() + && *last == id + { + collapsed.pop(); + } + collapsed.push((id, params, on, origin)); + } + + // Relative references. Only references on the input's sheet become tokens: on another sheet + // `C4` is that sheet's C4. + let example = start.selection.current(); + let mut used_input = false; + let steps: Vec = collapsed + .into_iter() + .map(|(id, params, on, origin)| { + // A step that names another sheet with its `sheet` parameter runs there, whatever + // sheet was active: its unqualified references are that sheet's cells. + let names_other_sheet = params.get("sheet").is_some_and(|v| match v { + Json::String(n) => !n.eq_ignore_ascii_case(&start.sheet_name), + Json::Number(i) => i.as_u64() != Some(start.sheet as u64), + _ => false, + }); + let here = on.eq_ignore_ascii_case(&start.sheet_name) && !names_other_sheet; + // Plain text first, so the tokens added next are the only ones. + let params = if origin == Origin::Macro { params } else { literal(¶ms, None) }; + let params = if start.relative && origin == Origin::Recorded { + relative(¶ms, example, &start.sheet_name, here, &mut used_input, None) + } else { + params + }; + Step::command(id, params) + }) + .collect(); + let mut mac = Macro { name: name.to_string(), steps, ..Macro::default() }; + if start.relative && used_input { + mac.inputs = vec![start.input.clone().unwrap_or_default()]; + } + Converted { mac, skipped, cut } +} + +fn selection_params(sel: &Selection) -> Json { + let ranges: Vec = sel.ranges.iter().map(RangeRef::a1).collect(); + json!({"range": ranges.join(","), "active": sel.active.a1()}) +} + +/// Plain recorded `params` written so playback reads them as they are: a string in a reference +/// parameter that playback would read as a token, or that holds `{{`, becomes `{"$text": …}`, +/// and `{{` in any other string becomes `{{{{`. +fn literal(v: &Json, key: Option<&str>) -> Json { + match v { + Json::Object(o) => Json::Object(o.iter().map(|(k, x)| (k.clone(), literal(x, Some(k)))).collect()), + Json::Array(a) => Json::Array(a.iter().map(|x| literal(x, key)).collect()), + Json::String(t) if key.is_some_and(super::resolve::is_ref_key) && (t.contains("{{") || super::resolve::reads_as_token(t, &["Input"])) => { + json!({"$text": t}) + } + Json::String(t) if t.contains("{{") => json!(t.replace("{{", "{{{{")), + other => other.clone(), + } +} + +/// `params` with references near `example` (on `sheet`) made into tokens; `here` says whether the +/// step runs on that sheet, so its unqualified references are on it. +fn relative(v: &Json, example: RangeRef, sheet: &str, here: bool, used: &mut bool, key: Option<&str>) -> Json { + match v { + // Text kept as text ([`literal`]). + Json::Object(o) if o.len() == 1 && o.contains_key("$text") => v.clone(), + Json::Object(o) => { + // A selection of several areas stays as it is, its active cell with it: a token for + // the active cell alone would put it outside the areas on playback. + let several_areas = o.get("range").and_then(Json::as_str).is_some_and(|r| r.contains(',')); + let mut out = Map::new(); + for (k, x) in o { + let x = if several_areas && k == "active" { x.clone() } else { relative(x, example, sheet, here, used, Some(k)) }; + out.insert(k.clone(), x); + } + Json::Object(out) + } + Json::Array(a) => Json::Array(a.iter().map(|x| relative(x, example, sheet, here, used, key)).collect()), + Json::String(t) if key.is_some_and(super::resolve::is_ref_key) => { + // One area becomes a token; a list of areas ("A1:B2,D4") stays as it is. + if t.contains(',') { + return v.clone(); + } + match ref_token(t, example, sheet, here) { + Some(token) => { + *used = true; + json!(token) + } + None => v.clone(), + } + } + Json::String(t) if here && t.starts_with('=') && example.count() > 1 => { + let (f, changed) = formula_tokens(t, example); + *used |= changed; + json!(f) + } + other => other.clone(), + } +} + +/// The token for an A1 reference on the example's sheet near the example input. `here` says whether +/// an unqualified reference is on that sheet. +fn ref_token(text: &str, example: RangeRef, sheet: &str, here: bool) -> Option { + let (on, body) = crate::cmd::split_sheet(text.trim()); + match on { + Some(on) if !on.eq_ignore_ascii_case(sheet) => return None, + None if !here => return None, + _ => {} + } + let t = RangeRef::parse(body)?; + if t.is_full_cols() || t.is_full_rows() { + return None; + } + token(t, example) +} + +/// `t` as a token relative to `r`. +fn token(t: RangeRef, r: RangeRef) -> Option { + if t == r { + return Some("Input".into()); + } + let rel_row = |row: u32| i64::from(row) - i64::from(r.start.row) + 1; + let rel_col = |col: u32| i64::from(col) - i64::from(r.start.col) + 1; + let cols = |a: u32, b: u32| if a == b { format!("col({})", rel_col(a)) } else { format!("cols({}..{})", rel_col(a), rel_col(b)) }; + if r.contains_range(&t) { + let full_rows = t.start.row == r.start.row && t.end.row == r.end.row; + let full_cols = t.start.col == r.start.col && t.end.col == r.end.col; + return Some(if full_rows { + format!("Input.{}", cols(t.start.col, t.end.col)) + } else if full_cols && t.start.row == t.end.row { + format!("Input.row({})", rel_row(t.start.row)) + } else if full_cols && t.end.row == r.end.row { + format!("Input.rows({}..)", rel_row(t.start.row)) + } else if full_cols { + format!("Input.rows({}..{})", rel_row(t.start.row), rel_row(t.end.row)) + } else if t.is_single() { + format!("Input.cell({},{})", rel_row(t.start.row), rel_col(t.start.col)) + } else { + format!("Input.cell({},{}).resize({},{})", rel_row(t.start.row), rel_col(t.start.col), t.height(), t.width()) + }); + } + let near = t.start.row.saturating_add(NEAR_ROWS) >= r.start.row + && t.end.row <= r.end.row.saturating_add(NEAR_ROWS) + && t.start.col.saturating_add(NEAR_COLS) >= r.start.col + && t.end.col <= r.end.col.saturating_add(NEAR_COLS); + if !near { + return None; + } + // Just below the input, in its columns: follows the input's length. + if t.start.row == r.end.row + 1 && t.start.col >= r.start.col && t.end.col <= r.end.col { + let base = if t.start.col == r.start.col && t.end.col == r.end.col { + "Input".to_string() + } else { + format!("Input.{}", cols(t.start.col, t.end.col)) + }; + return Some(if t.height() == 1 { format!("{base}.below") } else { format!("{base}.below({})", t.height()) }); + } + // Just right of the input, in its rows: follows its width. + if t.start.col == r.end.col + 1 && t.start.row >= r.start.row && t.end.row <= r.end.row { + let base = if t.start.row == r.start.row && t.end.row == r.end.row { + "Input".to_string() + } else if t.start.row == t.end.row { + format!("Input.row({})", rel_row(t.start.row)) + } else { + format!("Input.rows({}..{})", rel_row(t.start.row), rel_row(t.end.row)) + }; + return Some(if t.width() == 1 { format!("{base}.right") } else { format!("{base}.right({})", t.width()) }); + } + let cell = format!("Input.cell({},{})", rel_row(t.start.row), rel_col(t.start.col)); + Some(if t.is_single() { cell } else { format!("{cell}.resize({},{})", t.height(), t.width()) }) +} + +/// Replaces references in a formula that are exactly the example input, one of its columns or +/// rows, or a column without its first row, with `{{token}}`. +fn formula_tokens(f: &str, r: RangeRef) -> (String, bool) { + // Each reference in the formula text is read and matched on its own, so the work is the + // formula's length whatever the example's size (an example of a whole sheet has a million + // rows, which no list of candidates may grow with). + let mut out = String::with_capacity(f.len()); + let mut changed = false; + let (mut i, mut in_text) = (0, false); + let bytes = f.as_bytes(); + while i < f.len() { + let Some(rest) = f.get(i..) else { break }; + let ch = rest.chars().next().unwrap_or(' '); + if ch == '"' { + in_text = !in_text; + } + // A reference right after `{` stays as it is: `{{` before the token would read as the + // escape of a literal `{{`. + let prev_ok = i == 0 || !bytes.get(i - 1).is_some_and(|b| b.is_ascii_alphanumeric() || matches!(b, b'$' | b'!' | b'_' | b'.' | b':' | b'{')); + if !in_text && prev_ok && ch.is_ascii_alphabetic() { + // The longest run of reference characters here: letters, digits and one `:`. + let n = rest.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b':').count(); + let text = rest.get(..n).unwrap_or(""); + let followed = rest.get(n..).and_then(|x| x.chars().next()).is_some_and(|c| matches!(c, '!' | '(' | '_' | '$')); + if !followed + && !text.contains('$') + && let Some(t) = RangeRef::parse(text) + && let Some(tok) = formula_token(t, r) + { + out.push_str("{{"); + out.push_str(&tok); + out.push_str("}}"); + i += n; + changed = true; + continue; + } + } + out.push(ch); + i += ch.len_utf8(); + } + (out, changed) +} + +/// The token for a reference inside a formula: exactly the example input, one of its columns or +/// rows, or a column without its first row. Other references stay as they are. +fn formula_token(t: RangeRef, r: RangeRef) -> Option { + if t == r { + return Some("Input".into()); + } + if !r.contains_range(&t) { + return None; + } + let col = usize::try_from(t.start.col.checked_sub(r.start.col)?).ok()?.checked_add(1)?; + let row = usize::try_from(t.start.row.checked_sub(r.start.row)?).ok()?.checked_add(1)?; + if t.start.col == t.end.col && t.start.row == r.start.row && t.end.row == r.end.row { + return Some(format!("Input.col({col})")); + } + if t.start.col == t.end.col && r.height() > 2 && t.start.row == r.start.row.checked_add(1)? && t.end.row == r.end.row { + return Some(format!("Input.rows(2..).col({col})")); + } + if r.width() > 1 && t.start.row == t.end.row && t.start.col == r.start.col && t.end.col == r.end.col { + return Some(format!("Input.row({row})")); + } + None +} + +/// The example input's shape: a header when the first row is all text over other kinds of +/// values, and each column's type when all its values agree. +pub fn infer_input(wb: &Workbook, sheet: usize, r: RangeRef) -> NamedInput { + let mut input = NamedInput::default(); + if r.is_single() { + input.kind = InputKind::Cell; + input.rows = [1, 1]; + input.cols = [1, 1]; + return input; + } + input.cols = [r.width(), r.width()]; + let Some(sh) = wb.sheet(sheet) else { return input }; + if r.count() > 100_000 { + return input; + } + let kind = |c: CellRef| -> Option { + let v = sh.value(c); + Some(match v { + Value::Empty => return None, + Value::Text(t) if t.is_empty() => return None, + Value::Number(_) if crate::display::number_format(wb.styles.get(sh.style_id(c)).num_fmt.as_str()).is_date() => ColType::Date, + Value::Number(_) => ColType::Number, + Value::Text(_) => ColType::Text, + Value::Bool(_) => ColType::Bool, + _ => ColType::Any, + }) + }; + let column = |col: u32, from: u32| -> ColType { + let mut seen: Option = None; + for row in from..=r.end.row { + match (seen, kind(CellRef::new(row, col))) { + (_, None) => {} + (None, k) => seen = k, + (Some(a), Some(b)) if a != b => return ColType::Any, + _ => {} + } + } + seen.unwrap_or(ColType::Any) + }; + let first_text = (r.start.col..=r.end.col).all(|c| kind(CellRef::new(r.start.row, c)) == Some(ColType::Text)); + let below = (r.start.col..=r.end.col).map(|c| column(c, r.start.row + 1)).collect::>(); + input.header = r.height() > 1 && first_text && below.iter().any(|k| !matches!(k, ColType::Text | ColType::Any)); + input.col_types = if input.header { below } else { (r.start.col..=r.end.col).map(|c| column(c, r.start.row)).collect() }; + if input.col_types.iter().all(|k| *k == ColType::Any) { + input.col_types.clear(); + } + input.rows = [1, 0]; + input +} + +#[cfg(test)] +mod tests { + use super::*; + + fn r(a1: &str) -> RangeRef { + RangeRef::parse(a1).unwrap() + } + + #[test] + fn references_near_the_example_become_tokens() { + let ex = r("B2:D11"); + for (t, want) in [ + ("B2:D11", Some("Input")), + ("C2:C11", Some("Input.col(2)")), + ("C2:D11", Some("Input.cols(2..3)")), + ("B2:D2", Some("Input.row(1)")), + ("B3:D11", Some("Input.rows(2..)")), + ("B3:D5", Some("Input.rows(2..4)")), + ("C4", Some("Input.cell(3,2)")), + ("C4:D5", Some("Input.cell(3,2).resize(2,2)")), + ("B12:D12", Some("Input.below")), + ("C12", Some("Input.col(2).below")), + ("C12:C13", Some("Input.col(2).below(2)")), + ("E2:E11", Some("Input.right")), + ("E5", Some("Input.row(4).right")), + ("E3:F4", Some("Input.rows(2..3).right(2)")), + ("G2", Some("Input.cell(1,6)")), + ("A1", Some("Input.cell(0,0)")), + ("Z500", None), + ("A:A", None), + ] { + assert_eq!(ref_token(t, ex, "Sheet1", true).as_deref(), want, "{t}"); + } + assert_eq!(ref_token("Sheet1!C4", ex, "Sheet1", true).as_deref(), Some("Input.cell(3,2)")); + assert_eq!(ref_token("Other!C4", ex, "Sheet1", true), None); + // On another sheet only a reference qualified with the input's sheet is on it. + assert_eq!(ref_token("C4", ex, "Sheet1", false), None); + assert_eq!(ref_token("Sheet1!C4", ex, "Sheet1", false).as_deref(), Some("Input.cell(3,2)")); + } + + #[test] + fn formulas_get_tokens_for_exact_references() { + let ex = r("B2:C5"); + for (f, want) in [ + ("=SUM(C3:C5)", "=SUM({{Input.rows(2..).col(2)}})"), + ("=SUM(C2:C5)+COUNT(B2:C5)", "=SUM({{Input.col(2)}})+COUNT({{Input}})"), + ("=SUM($C$3:$C$5)", "=SUM($C$3:$C$5)"), + ("=SUM(Other!C3:C5)", "=SUM(Other!C3:C5)"), + ("=\"C3:C5\"&C3:C5", "=\"C3:C5\"&{{Input.rows(2..).col(2)}}"), + ("=SUM(AC3:C5)", "=SUM(AC3:C5)"), + ("=B2", "=B2"), + ] { + assert_eq!(formula_tokens(f, ex).0, want, "{f}"); + } + } +} diff --git a/crates/engine/src/macros/resolve.rs b/crates/engine/src/macros/resolve.rs new file mode 100644 index 0000000000..c5c2da8d70 --- /dev/null +++ b/crates/engine/src/macros/resolve.rs @@ -0,0 +1,970 @@ +//! Macro tokens: references in step parameters that are worked out when the step runs, so a +//! macro made on one block of data works on another. +//! +//! A token is a base followed by methods: +//! +//! - bases: a declared input (`Input`, `Rates`), `Output` (the output rule's anchor), `Row` or +//! `Column` (the current item of the Repeat step around it), and `Name:Total` (a defined name or +//! a table's data; a name can hold periods, and the longest one that exists is used, so +//! `Name:Sales.Q1.cell(1,1)` is a cell of `Sales.Q1`); +//! - methods, 1-based and chainable: `.col(n)` or `.col("Amount")` (by an input's header row, +//! also after `.data`), `.row(n)`, `.cols(a..b)`, `.rows(a..)`, `.cell(r,c)` (relative to the +//! top-left cell; any whole numbers, so `cell(0,1)` is the cell above), `.offset(r,c)`, +//! `.resize(h,w)`, `.data` (without the header row), `.below(n)` and `.right(n)` (the n rows +//! below or columns right of the range). +//! +//! In parameters a token is written three ways: `{"$ref": "Input.col(2)"}` anywhere; the whole +//! string `"Input.col(2)"` in a reference parameter (`cell`, `range`, `target`, `to`, keys ending +//! in `Cell` or `Range`…); or `{{Input.col(2)}}` inside any string (`"=SUM({{Input.col(2)}})"`). +//! Each becomes A1 text before the command runs, so commands never see a token. Text that would +//! read as a token is written `{"$text": "Output"}`: it is passed as it is, never resolved or +//! interpolated (a defined name called `Output`, or `Dear {{name}}`). Plain A1 +//! references in steps are absolute: they don't follow row inserts (as in VBA); a `Name:` anchor +//! does. + +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; +use gridcraft_model::{RepeatOf, Workbook}; +use serde_json::{Map, Value as Json}; + +/// A resolved reference: a block of cells on a sheet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Place { + pub sheet: usize, + pub range: RangeRef, +} + +/// Why a reference couldn't be worked out. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ResolveError { + /// It runs past the edge of the sheet. + Edge(String), + /// Anything else (an unknown input, a malformed token). + Bad(String), +} + +impl ResolveError { + pub fn message(&self) -> &str { + match self { + ResolveError::Edge(m) | ResolveError::Bad(m) => m, + } + } +} + +impl std::fmt::Display for ResolveError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.message()) + } +} + +type R = Result; + +fn bad(msg: impl Into) -> R { + Err(ResolveError::Bad(msg.into())) +} + +/// What tokens refer to while a step runs. +#[derive(Clone, Copy, Debug)] +pub struct Env<'a> { + pub wb: &'a Workbook, + /// The sheet a reference without a sheet name is on. + pub active_sheet: usize, + /// Declared inputs, with whether each has a header row. + pub inputs: &'a [(String, Place, bool)], + pub output: Option, + /// The innermost Repeat step's current row or column. + pub item: Option<(RepeatOf, Place)>, +} + +/// Parameter keys that hold references, where a whole-string token is resolved. Elsewhere a +/// string is text (a cell may hold "Row", a chart's type is "column"), and a token needs +/// `{"$ref": …}` or `{{…}}`. +const REF_KEYS: &[&str] = &[ + "active", + "anchor", + "area", + "areas", + "at", + "cell", + "cells", + "changing", + "copyTo", + "destination", + "from", + "fromCell", + "location", + "objective", + "over", + "range", + "ranges", + "reference", + "resultCells", + "source", + "sources", + "target", + "to", + "variables", +]; + +/// Whether a parameter called `key` holds a reference. +pub fn is_ref_key(key: &str) -> bool { + let k = key.to_ascii_lowercase(); + REF_KEYS.iter().any(|r| r.eq_ignore_ascii_case(key)) || ["cell", "cells", "range", "ranges", "ref"].iter().any(|end| k.ends_with(end)) +} + +/// Reference keys that other commands use for plain words: `to` is a replacement word in +/// Review › Change Spelling, `area` is `row` or `column` in a pivot field move. Under these a +/// bare `Row` or `Column` stays text; `Row.col(2)`, `{{Row}}` or `{"$ref": "Row"}` is the token. +fn is_general_key(key: &str) -> bool { + ["area", "areas", "at", "destination", "from", "location", "source", "sources", "target", "to"].iter().any(|k| k.eq_ignore_ascii_case(key)) +} + +/// `Row` or `Column` on its own, with no method or sheet after it. +fn is_bare_item_word(text: &str) -> bool { + let t = text.trim(); + t.eq_ignore_ascii_case("row") || t.eq_ignore_ascii_case("column") +} + +/// The most nesting [`resolve_params`] walks into. +const MAX_JSON_DEPTH: usize = 64; + +/// Whether `text` starts like a token (its base is one this environment knows). A reference on a +/// sheet with such a name (`Output!A1`) is not a token. +pub fn is_token(text: &str, env: &Env) -> bool { + starts_like_token(text, |base| env.inputs.iter().any(|(n, ..)| n.eq_ignore_ascii_case(base))) +} + +/// Whether `text` would read as a token in a macro whose inputs are `inputs` (see [`is_token`]). +pub fn reads_as_token(text: &str, inputs: &[&str]) -> bool { + starts_like_token(text, |base| inputs.iter().any(|n| n.eq_ignore_ascii_case(base))) +} + +fn starts_like_token(text: &str, is_input: impl Fn(&str) -> bool) -> bool { + let t = text.trim(); + if t.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("name:")) { + return true; + } + let n: usize = t.chars().take_while(|c| c.is_alphanumeric() || *c == '_').map(char::len_utf8).sum(); + let base = t.get(..n).unwrap_or(""); + if t.get(n..).unwrap_or("").trim_start().starts_with('!') { + return false; + } + is_builtin(base) || is_input(base) +} + +fn is_builtin(base: &str) -> bool { + ["Output", "Row", "Column"].iter().any(|b| b.eq_ignore_ascii_case(base)) +} + +/// Resolves a token, or a plain reference (`B2`, `Sheet2!A1:C3`, a defined name). +pub fn resolve_ref(text: &str, env: &Env) -> R { + let t = text.trim(); + if is_token(t, env) { + return resolve_token(t, env); + } + plain_ref(t, env) +} + +/// `A1`, `'My Sheet'!A1:B2` or a defined name or table. +fn plain_ref(t: &str, env: &Env) -> R { + let (sheet, body) = crate::cmd::split_sheet(t); + let si = match &sheet { + Some(name) => env.wb.sheet_index(name).ok_or_else(|| ResolveError::Bad(format!("There is no sheet named '{name}'.")))?, + None => env.active_sheet, + }; + if let Some(range) = RangeRef::parse(body) { + return Ok(Place { sheet: si, range }); + } + if sheet.is_none() { + return named(t, env); + } + bad(format!("'{t}' isn't a reference.")) +} + +/// A defined name (by its formula) or a table (its data rows). +fn named(name: &str, env: &Env) -> R { + if let Some(n) = env.wb.name(name, env.active_sheet) { + // The sheet part keeps its characters (a sheet may be called `US$`); only the reference + // loses its `$` anchors. + let f = n.formula.trim().trim_start_matches('='); + let (sheet, body) = crate::cmd::split_sheet(f); + let si = match sheet { + Some(s) => env.wb.sheet_index(&s), + None => n.scope.or(Some(env.active_sheet)), + }; + if let (Some(sheet), Some(range)) = (si, RangeRef::parse(&body.replace('$', ""))) { + return Ok(Place { sheet, range }); + } + return bad(format!("The name '{name}' doesn't refer to a range.")); + } + if let Some((si, ti)) = env.wb.table(name) + && let Some(t) = env.wb.sheet(si).and_then(|sh| sh.tables.get(ti)) + { + // A table stands for its data rows; one with none (a header, perhaps a totals row) has + // nothing to give. + let Some(range) = t.data_range() else { + return bad(format!("The table '{name}' has no data rows.")); + }; + return Ok(Place { sheet: si, range }); + } + bad(format!("There is no name or table called '{name}'.")) +} + +/// Token method names. +const METHODS: &[&str] = &["col", "row", "cols", "rows", "cell", "offset", "resize", "data", "below", "right"]; + +/// Where the name ends in `run`, the text after `Name:` up to the first character a name can't +/// hold: at the end or at a period, the longest choice that is a defined name or table. When +/// none is, the name ends before the first method (`Nope.cell`), so the error names it. +fn name_end(run: &str, env: &Env) -> usize { + // One pass over the names and tables, as a single lookup makes. + let fits = |name: &str| { + !name.is_empty() + && run.get(..name.len()).is_some_and(|head| head.eq_ignore_ascii_case(name)) + && run.get(name.len()..).is_some_and(|rest| rest.is_empty() || rest.starts_with('.')) + }; + let names = env.wb.names.iter().filter(|n| n.scope.is_none() || n.scope == Some(env.active_sheet)).map(|n| n.name.as_str()); + let tables = env.wb.sheets.iter().flat_map(|sh| sh.tables.iter().map(|t| t.name.as_str())); + if let Some(end) = names.chain(tables).filter(|n| fits(n)).map(str::len).max() { + return end; + } + run.match_indices('.') + .map(|(i, _)| i) + .find(|&i| { + let next = run.get(i + 1..).unwrap_or("").split('.').next().unwrap_or(""); + METHODS.iter().any(|m| m.eq_ignore_ascii_case(next)) + }) + .unwrap_or(run.len()) +} + +/// Resolves a token (see the module docs). +pub fn resolve_token(text: &str, env: &Env) -> R { + let t = text.trim(); + let mut p = Parser { s: t, at: 0 }; + let (mut place, mut header) = p.base(env)?; + // The row of column names `col("…")` reads: the input's header row, kept through `data`. + let mut names_row = header.then_some(place.range.start.row); + while p.eat('.') { + let name = p.ident(); + if name.is_empty() { + return bad(format!("'{t}': expected a method name after '.'.")); + } + let args = if p.eat('(') { p.args(t)? } else { vec![] }; + let r = place.range; + let method = name.to_ascii_lowercase(); + let range = match (method.as_str(), args.as_slice()) { + ("col", [Arg::Int(n)]) => sub(r, None, Some((*n, *n)), t)?, + ("col", [Arg::Text(h)]) => { + let Some(row) = names_row else { + return bad(format!("'{t}': col(\"{h}\") needs an input with a header row; use col(n).")); + }; + let c = header_col(env, place, row, h).ok_or_else(|| ResolveError::Bad(format!("'{t}': no column is headed '{h}'.")))?; + sub(r, None, Some((c, c)), t)? + } + ("row", [Arg::Int(n)]) => sub(r, Some((*n, *n)), None, t)?, + ("cols", [Arg::Span(a, b)]) => sub(r, None, Some(span(*a, *b, i64::from(r.width()))), t)?, + ("rows", [Arg::Span(a, b)]) => sub(r, Some(span(*a, *b, i64::from(r.height()))), None, t)?, + ("cell", [Arg::Int(row), Arg::Int(col)]) => { + let c = shift(r.start, row - 1, col - 1, t)?; + RangeRef::cell(c) + } + ("offset", [Arg::Int(dr), Arg::Int(dc)]) => RangeRef::new(shift(r.start, *dr, *dc, t)?, shift(r.end, *dr, *dc, t)?), + ("resize", [Arg::Int(h), Arg::Int(w)]) => { + if *h < 1 || *w < 1 { + return bad(format!("'{t}': resize needs at least 1 row and 1 column.")); + } + RangeRef::new(r.start, shift(r.start, h - 1, w - 1, t)?) + } + ("data", []) => { + if header { + // A header row with nothing under it has no data rows to give. + if r.height() < 2 { + return bad(format!("'{t}': the range is only a header row, with no data under it.")); + } + RangeRef::new(CellRef::new(r.start.row + 1, r.start.col), r.end) + } else { + r + } + } + ("below", []) | ("below", [Arg::Int(_)]) => { + let n = count_arg(&args, t)?; + let top = shift(CellRef::new(r.end.row, r.start.col), 1, 0, t)?; + RangeRef::new(top, shift(CellRef::new(r.end.row, r.end.col), n, 0, t)?) + } + ("right", []) | ("right", [Arg::Int(_)]) => { + let n = count_arg(&args, t)?; + let left = shift(CellRef::new(r.start.row, r.end.col), 0, 1, t)?; + RangeRef::new(left, shift(r.end, 0, n, t)?) + } + _ => { + return bad(format!("'{t}': '{name}' with these arguments isn't a token method ({}).", METHODS.join(", "))); + } + }; + // After a method the result is plain cells, except that `col` and `cols` keep the input's top + // row, so a later `data` still takes the header off; only `data` keeps the header row for + // `col("…")`. + if !matches!(method.as_str(), "col" | "cols") { + header = false; + } + if method != "data" { + names_row = None; + } + place = Place { sheet: place.sheet, range }; + } + p.skip_ws(); + if p.at < p.s.len() { + return bad(format!("'{t}' isn't a token: unexpected '{}'.", p.s.get(p.at..).unwrap_or(""))); + } + Ok(place) +} + +/// The count `below(n)` and `right(n)` take: 1 when left out, and never less than 1. +fn count_arg(args: &[Arg], t: &str) -> R { + match args.first() { + Some(Arg::Int(n)) if *n < 1 => bad(format!("'{t}': the count must be at least 1.")), + Some(Arg::Int(n)) => Ok(*n), + _ => Ok(1), + } +} + +/// `a..b` with open ends filled from 1 and `len`. +fn span(a: Option, b: Option, len: i64) -> (i64, i64) { + (a.unwrap_or(1), b.unwrap_or(len)) +} + +/// Rows `rows` and columns `cols` (1-based, inclusive) of `r`; `None` keeps them all. +fn sub(r: RangeRef, rows: Option<(i64, i64)>, cols: Option<(i64, i64)>, t: &str) -> R { + let (h, w) = (i64::from(r.height()), i64::from(r.width())); + let (r0, r1) = rows.unwrap_or((1, h)); + let (c0, c1) = cols.unwrap_or((1, w)); + if r0 < 1 || c0 < 1 || r1 < r0 || c1 < c0 || r1 > h || c1 > w { + return bad(format!("'{t}' is outside the range it starts from ({} rows by {} columns).", h, w)); + } + Ok(RangeRef::new(shift(r.start, r0 - 1, c0 - 1, t)?, shift(r.start, r1 - 1, c1 - 1, t)?)) +} + +fn shift(c: CellRef, dr: i64, dc: i64, t: &str) -> R { + let row = i64::from(c.row).checked_add(dr); + let col = i64::from(c.col).checked_add(dc); + match (row, col) { + (Some(row), Some(col)) if (0..i64::from(MAX_ROWS)).contains(&row) && (0..i64::from(MAX_COLS)).contains(&col) => { + Ok(CellRef::new(row as u32, col as u32)) + } + (Some(row), Some(_)) if row < 0 => Err(ResolveError::Edge(format!("'{t}' runs past the top of the sheet."))), + (Some(row), Some(_)) if row >= i64::from(MAX_ROWS) => Err(ResolveError::Edge(format!("'{t}' runs past the last row of the sheet."))), + _ => Err(ResolveError::Edge(format!("'{t}' runs past the edge of the sheet."))), + } +} + +/// The 1-based column of `place` whose header (in sheet row `row`) reads `h`. +fn header_col(env: &Env, place: Place, row: u32, h: &str) -> Option { + let sh = env.wb.sheet(place.sheet)?; + let r = place.range; + (r.start.col..=r.end.col) + // The header's value, however the sheet shows it: with Show Formulas on, the cell's + // display text is its formula. + .position(|c| crate::display::value_text(env.wb, sh, CellRef::new(row, c)).trim().eq_ignore_ascii_case(h.trim())) + .map(|i| i as i64 + 1) +} + +#[derive(Debug)] +enum Arg { + Int(i64), + Span(Option, Option), + Text(String), +} + +struct Parser<'a> { + s: &'a str, + at: usize, +} + +impl Parser<'_> { + fn rest(&self) -> &str { + self.s.get(self.at..).unwrap_or("") + } + fn skip_ws(&mut self) { + let n = self.rest().len() - self.rest().trim_start().len(); + self.at += n; + } + fn eat(&mut self, c: char) -> bool { + self.skip_ws(); + if self.rest().starts_with(c) { + self.at += c.len_utf8(); + true + } else { + false + } + } + fn ident(&mut self) -> String { + self.skip_ws(); + let n: usize = self.rest().chars().take_while(|c| c.is_alphanumeric() || *c == '_').map(char::len_utf8).sum(); + let out = self.rest().get(..n).unwrap_or("").to_string(); + self.at += n; + out + } + fn int(&mut self) -> Option { + self.skip_ws(); + let neg = self.rest().starts_with('-'); + let start = self.at + usize::from(neg); + let digits: usize = self.s.get(start..).unwrap_or("").chars().take_while(char::is_ascii_digit).count(); + if digits == 0 || digits > 9 { + return None; + } + let n: i64 = self.s.get(start..start + digits)?.parse().ok()?; + self.at = start + digits; + Some(if neg { -n } else { n }) + } + /// The base of a token and whether it has a header row. + fn base(&mut self, env: &Env) -> R<(Place, bool)> { + self.skip_ws(); + if self.rest().get(..5).is_some_and(|h| h.eq_ignore_ascii_case("name:")) { + self.at += 5; + // A name can hold periods (`Sales.Q1`), so it is the longest part of the run, up to + // a period or the end, that names something; methods follow it. + let n: usize = self.rest().chars().take_while(|c| c.is_alphanumeric() || matches!(c, '_' | '\\' | '.')).map(char::len_utf8).sum(); + let run = self.rest().get(..n).unwrap_or("").to_string(); + let end = name_end(&run, env); + let name = run.get(..end).unwrap_or(""); + if name.is_empty() { + return bad("'Name:' needs a defined name after it."); + } + self.at += end; + return Ok((named(name, env)?, false)); + } + let base = self.ident(); + if base.eq_ignore_ascii_case("Output") { + return env.output.map(|p| (p, false)).ok_or_else(|| ResolveError::Bad("'Output' is used, but the macro has no output anchor.".into())); + } + if base.eq_ignore_ascii_case("Row") || base.eq_ignore_ascii_case("Column") { + return match env.item { + Some((_, p)) => Ok((p, false)), + None => bad(format!("'{base}' only means something inside a Repeat step.")), + }; + } + match env.inputs.iter().find(|(n, ..)| n.eq_ignore_ascii_case(&base)) { + Some((_, p, header)) => Ok((*p, *header)), + None => bad(format!("'{base}' isn't an input of this macro.")), + } + } + fn args(&mut self, t: &str) -> R> { + let mut out = Vec::new(); + if self.eat(')') { + return Ok(out); + } + loop { + self.skip_ws(); + if self.rest().starts_with('"') { + self.at += 1; + let n = self.rest().find('"').ok_or_else(|| ResolveError::Bad(format!("'{t}': a quote isn't closed.")))?; + out.push(Arg::Text(self.rest().get(..n).unwrap_or("").to_string())); + self.at += n + 1; + } else { + let a = self.int(); + self.skip_ws(); + if self.rest().starts_with("..") { + self.at += 2; + let b = self.int(); + out.push(Arg::Span(a, b)); + } else { + out.push(Arg::Int(a.ok_or_else(|| ResolveError::Bad(format!("'{t}': expected a whole number.")))?)); + } + } + if out.len() > 4 { + return bad(format!("'{t}': too many arguments.")); + } + if self.eat(')') { + return Ok(out); + } + if !self.eat(',') { + return bad(format!("'{t}': expected ',' or ')'.")); + } + } + } +} + +/// `place` as A1 text, with the sheet name when it isn't the active sheet. +pub fn a1(place: Place, env: &Env) -> String { + if place.sheet == env.active_sheet { + return place.range.a1(); + } + let name = env.wb.sheet(place.sheet).map(|s| s.name.as_str()).unwrap_or(""); + format!("{}!{}", quote_sheet(name), place.range.a1()) +} + +/// `Sheet1` or `'My Sheet'` (quotes doubled). +pub fn quote_sheet(name: &str) -> String { + // The engine's one rule: a name that reads as a cell reference, an R1C1 token or a boolean + // is quoted too, or `Q1!A1` would be read as a reference to cell Q1. + gridcraft_core::quote_sheet(name) +} + +/// Step parameters with every token replaced by A1 text. +pub fn resolve_params(params: &Json, env: &Env) -> R { + walk(params, None, env, 0) +} + +fn walk(v: &Json, key: Option<&str>, env: &Env, depth: usize) -> R { + if depth > MAX_JSON_DEPTH { + return bad("The step's parameters nest too deeply."); + } + Ok(match v { + Json::Object(o) => { + if o.len() == 1 + && let Some(Json::String(t)) = o.get("$ref") + { + return Ok(Json::String(a1(resolve_ref(t, env)?, env))); + } + // Text passed as it is: never a token, and no `{{…}}` in it is read. + if o.len() == 1 + && let Some(Json::String(t)) = o.get("$text") + { + return Ok(Json::String(t.clone())); + } + let mut out = Map::new(); + for (k, x) in o { + out.insert(k.clone(), walk(x, Some(k), env, depth + 1)?); + } + Json::Object(out) + } + // Items of a list keep their key's kind (`ranges: ["Input", …]`). + Json::Array(a) => Json::Array(a.iter().map(|x| walk(x, key, env, depth + 1)).collect::>>()?), + Json::String(s) => { + if key.is_some_and(|k| is_ref_key(k) && !(is_general_key(k) && is_bare_item_word(s))) && is_token(s, env) { + Json::String(a1(resolve_token(s, env)?, env)) + } else { + Json::String(interpolate(s, env)?) + } + } + other => other.clone(), + }) +} + +/// Replaces each `{{token}}` in `s`. `{{{{` is a literal `{{`, for text that needs the braces +/// themselves (`"Dear {{{{name}}"` writes `Dear {{name}}`). +pub fn interpolate(s: &str, env: &Env) -> R { + if !s.contains("{{") { + return Ok(s.to_string()); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find("{{") { + out.push_str(rest.get(..i).unwrap_or("")); + if rest.get(i..i + 4) == Some("{{{{") { + out.push_str("{{"); + rest = rest.get(i + 4..).unwrap_or(""); + continue; + } + let after = rest.get(i + 2..).unwrap_or(""); + let Some(j) = after.find("}}") else { + out.push_str(rest.get(i..).unwrap_or("")); + return Ok(out); + }; + let token = after.get(..j).unwrap_or(""); + out.push_str(&a1(resolve_ref(token, env)?, env)); + rest = after.get(j + 2..).unwrap_or(""); + } + out.push_str(rest); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn wb() -> Workbook { + let mut wb = Workbook::new(); + wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("My Data"))); + let sh = wb.sheet_mut(0).unwrap(); + for (i, h) in ["Name", "Amount", "Date"].iter().enumerate() { + sh.set_value(CellRef::new(1, 1 + i as u32), gridcraft_core::Value::text(*h)); + } + wb.names.push(gridcraft_model::DefinedName { + name: "Total".into(), + scope: None, + formula: "Sheet1!$F$20".into(), + comment: String::new(), + hidden: false, + }); + wb.names.push(gridcraft_model::DefinedName { + name: "Rates".into(), + scope: None, + formula: "'My Data'!$A$1:$A$5".into(), + comment: String::new(), + hidden: false, + }); + wb + } + + fn place(a1: &str) -> Place { + Place { sheet: 0, range: RangeRef::parse(a1).unwrap() } + } + + fn check(env: &Env, token: &str, want: &str) { + match resolve_ref(token, env) { + Ok(p) => assert_eq!(a1(p, env), want, "{token}"), + Err(e) => panic!("{token}: {e}"), + } + } + + #[test] + fn a_formula_header_matches_while_formulas_are_shown() { + // The header was read through the cell's display text, which is the formula while Show + // Formulas is on, so `col("Amount")` found no column headed by a formula. + let mut wb = wb(); + let sh = wb.sheet_mut(0).unwrap(); + let formula = Some(std::sync::Arc::new(gridcraft_model::Formula::new("\"Amo\"&\"unt\""))); + sh.set_cell( + CellRef::new(1, 2), + gridcraft_model::Cell { value: gridcraft_core::Value::text("Amount"), formula, style: Default::default(), py: None }, + ); + sh.show_formulas = true; + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + check(&env, "Input.col(\"Amount\")", "C2:C11"); + } + + #[test] + fn every_token_resolves() { + let wb = wb(); + // Input B2:D11 with a header row; Other on another sheet. + let inputs = vec![ + ("Input".to_string(), place("B2:D11"), true), + ("Other".to_string(), Place { sheet: 1, range: RangeRef::parse("C3:C4").unwrap() }, false), + ]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: Some(place("G2")), item: Some((RepeatOf::Rows, place("B5:D5"))) }; + for (token, want) in [ + ("Input", "B2:D11"), + ("input", "B2:D11"), + ("Input.col(2)", "C2:C11"), + ("Input.col(\"Amount\")", "C2:C11"), + ("Input.col(\"date\").data", "D3:D11"), + ("Input.cols(2..3).data", "C3:D11"), + ("Input.col(2).data.col(1)", "C3:C11"), + ("Input.data", "B3:D11"), + ("Input.data.col(2)", "C3:C11"), + ("Input.data.col(\"Amount\")", "C3:C11"), + ("Input.row(1)", "B2:D2"), + ("Input.rows(2..)", "B3:D11"), + ("Input.rows(2..4)", "B3:D5"), + ("Input.rows(..2)", "B2:D3"), + ("Input.cols(2..3)", "C2:D11"), + ("Input.cell(1,1)", "B2"), + ("Input.cell(3,2)", "C4"), + ("Input.cell(0,1)", "B1"), + ("Input.cell(12,3)", "D13"), + ("Input.offset(0,4)", "F2:H11"), + ("Input.offset(-1,-1)", "A1:C10"), + ("Input.cell(1,1).resize(2,3)", "B2:D3"), + ("Input.below()", "B12:D12"), + ("Input.below(2)", "B12:D13"), + ("Input.col(2).below", "C12"), + ("Input.right", "E2:E11"), + (" Input . col( 2 ) ", "C2:C11"), + ("Output", "G2"), + ("Output.offset(1,0)", "G3"), + ("Row", "B5:D5"), + ("Row.cell(1,2)", "C5"), + ("Column", "B5:D5"), + ("Name:Total", "F20"), + ("Name:Rates", "'My Data'!A1:A5"), + ("Name:Rates.cell(2,1)", "'My Data'!A2"), + ("Other", "'My Data'!C3:C4"), + ("B7", "B7"), + ("'My Data'!A1:B2", "'My Data'!A1:B2"), + ("Total", "F20"), + ] { + check(&env, token, want); + } + } + + #[test] + fn bad_tokens_say_why() { + let wb = wb(); + // The same cells, read with and without a header row. + let inputs = vec![("Input".to_string(), place("B2:D11"), false), ("Headed".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + for (token, needle, edge) in [ + ("Input.col(4)", "outside the range", false), + ("Input.col(0)", "outside the range", false), + ("Input.rows(5..2)", "outside the range", false), + ("Headed.col(\"Nope\")", "no column is headed", false), + ("Input.col(\"Name\")", "needs an input with a header row", false), + ("Headed.col(2).col(\"Amount\")", "needs an input with a header row", false), + ("Name:Rates.col(\"Name\")", "needs an input with a header row", false), + ("Input.colour(1)", "isn't a token method", false), + ("Input.col(1", "expected", false), + ("Input.col(x)", "whole number", false), + ("Input.col(99999999999)", "whole number", false), + ("Input.", "method name", false), + ("Input junk", "unexpected", false), + ("Input.resize(0,1)", "at least 1 row", false), + ("Output", "no output anchor", false), + ("Row", "inside a Repeat", false), + ("Name:", "needs a defined name", false), + ("Name:Nothing", "no name or table", false), + ("Nowhere!A1", "no sheet named", false), + ("Input.offset(-2,0)", "past the top", true), + ("Input.offset(0,-2)", "edge of the sheet", true), + ("Input.offset(1048570,0)", "past the last row", true), + ("Input.cell(1,16384)", "edge of the sheet", true), + ] { + let e = resolve_ref(token, &env).unwrap_err(); + assert!(e.message().contains(needle), "{token}: {e}"); + assert_eq!(matches!(e, ResolveError::Edge(_)), edge, "{token}"); + } + } + + #[test] + fn params_resolve_tokens_in_reference_keys_and_braces_anywhere() { + let wb = wb(); + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: Some(place("F2")), item: None }; + let p = json!({ + "cell": "Output", + "range": "Input.col(2)", + "ranges": ["Input.row(1)", "A1"], + "input": "Row", + "value": "Input", + "formula": "=SUM({{Input.data.col(2)}})/{{Name:Total}}", + "nested": {"target": {"$ref": "Input.cell(1,1)"}, "n": 3, "flag": true}, + "text": {"$ref": "Output"}, + "type": "column", + "sheet": "Input", + "rowInputCell": "Input.cell(1,1)", + "unclosed": "a {{b" + }); + let r = resolve_params(&p, &env).unwrap(); + assert_eq!( + r, + json!({ + "cell": "F2", + "range": "C2:C11", + "ranges": ["B2:D2", "A1"], + "input": "Row", + "value": "Input", + "formula": "=SUM(C3:C11)/F20", + "nested": {"target": "B2", "n": 3, "flag": true}, + "text": "F2", + "type": "column", + "sheet": "Input", + "rowInputCell": "B2", + "unclosed": "a {{b" + }) + ); + // Deeply nested parameters are refused, not followed. + let mut deep = json!(1); + for _ in 0..100 { + deep = json!([deep]); + } + assert!(resolve_params(&deep, &env).is_err()); + assert!(resolve_params(&json!({"cell": "Input.col(9)"}), &env).is_err()); + } + + #[test] + fn references_on_sheets_named_like_tokens_stay_references() { + // Sheets named after the built-in bases and after an input: `Output!A1` is a cell on the + // sheet Output, in a reference key, in `$ref` and in `{{…}}`. + let mut wb = Workbook::new(); + for name in ["Output", "Row", "Column", "Input", "Rates"] { + wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new(name))); + } + let inputs = vec![("Input".to_string(), place("B2:D11"), true), ("Rates".to_string(), place("F2:F5"), false)]; + for output in [None, Some(place("H2"))] { + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output, item: Some((RepeatOf::Rows, place("B5:D5"))) }; + for (sheet, i) in [("Output", 1), ("Row", 2), ("Column", 3), ("Input", 4), ("Rates", 5)] { + for text in [format!("{sheet}!A1:B2"), format!("'{sheet}'!A1:B2")] { + let want = Place { sheet: i, range: RangeRef::parse("A1:B2").unwrap() }; + assert_eq!(resolve_ref(&text, &env), Ok(want), "{text}"); + let a = a1(want, &env); + let p = json!({"range": text, "target": {"$ref": text}, "formula": format!("=SUM({{{{{text}}}}})")}); + let r = resolve_params(&p, &env).unwrap(); + // A plain reference in a reference key is passed on as written. + assert_eq!(r, json!({"range": text, "target": a, "formula": format!("=SUM({a})")}), "{text}"); + } + } + assert!(!is_token("Output !A1", &env)); + // The bare names are still tokens. + check(&env, "Input.col(2)", "C2:C11"); + check(&env, "Rates", "F2:F5"); + check(&env, "Row", "B5:D5"); + } + } + + #[test] + fn defined_names_can_hold_periods() { + // `Sales.Q1` is one defined name, beside `Sales`; `Data.row` has a segment that reads like + // a method. The longest name that exists is used, and methods follow it. + let mut wb = wb(); + for (name, formula) in [("Sales", "Sheet1!$A$1"), ("Sales.Q1", "Sheet1!$B$2:$C$5"), ("Data.row", "'My Data'!$E$1:$E$3")] { + wb.names.push(gridcraft_model::DefinedName { + name: name.into(), + scope: None, + formula: formula.into(), + comment: String::new(), + hidden: false, + }); + } + let env = Env { wb: &wb, active_sheet: 0, inputs: &[], output: None, item: None }; + for (token, want) in [ + ("Name:Sales.Q1", "B2:C5"), + ("Name:sales.q1", "B2:C5"), + ("Name:Sales.Q1.cell(1,1)", "B2"), + ("Name:Sales.Q1.col(2).row(4)", "C5"), + ("Name:Sales", "A1"), + ("Name:Sales.offset(1,0)", "A2"), + ("Name:Data.row", "'My Data'!E1:E3"), + ("Name:Data.row.row(2)", "'My Data'!E2"), + ("Name:Data.row.cell(1,1)", "'My Data'!E1"), + ("Sales.Q1", "B2:C5"), + ] { + check(&env, token, want); + } + // In a reference parameter, `$ref` and `{{…}}`, with and without a method. + let p = json!({ + "range": "Name:Sales.Q1", + "cell": "Name:Sales.Q1.cell(1,1)", + "a": {"$ref": "Name:Sales.Q1"}, + "b": {"$ref": "Name:Sales.Q1.cell(2,2)"}, + "formula": "=SUM({{Name:Sales.Q1}})+{{Name:Sales.Q1.cell(1,2)}}" + }); + let r = resolve_params(&p, &env).unwrap(); + assert_eq!(r, json!({"range": "B2:C5", "cell": "B2", "a": "B2:C5", "b": "C3", "formula": "=SUM(B2:C5)+C2"})); + // Unknown names and bad methods still fail, naming what is wrong. + for (token, needle) in [ + ("Name:Nope.Q1", "no name or table called 'Nope.Q1'"), + ("Name:Nope.cell(1,1)", "no name or table called 'Nope'"), + ("Name:Sales.Q1.bogus(1)", "'bogus' with these arguments isn't a token method"), + ("Name:Sales.Q1.cell(1", "expected"), + ("Name:Sales.Q1.", "method name"), + ("Name:.cell(1,1)", "needs a defined name"), + ] { + let e = resolve_ref(token, &env).unwrap_err(); + assert!(e.message().contains(needle), "{token}: {e}"); + let e = resolve_params(&json!({"formula": format!("={{{{{token}}}}}")}), &env).unwrap_err(); + assert!(e.message().contains(needle), "{token} in braces: {e}"); + } + } + + #[test] + fn sheet_names_are_quoted_when_needed() { + // The engine's rule: a name that reads as a cell reference, an R1C1 token or a boolean + // is quoted too, and a period on its own is not a reason to quote. + for (name, want) in [ + ("Sheet1", "Sheet1"), + ("My Data", "'My Data'"), + ("O'Hara", "'O''Hara'"), + ("2024", "'2024'"), + ("", "''"), + ("Q1", "'Q1'"), + ("R1C1", "'R1C1'"), + ("TRUE", "'TRUE'"), + ("Sales.Q1", "Sales.Q1"), + ] { + assert_eq!(quote_sheet(name), want, "{name}"); + } + } + + #[test] + fn a_bare_row_or_column_under_a_general_key_is_text() { + // `to` is a replacement word in Change Spelling and `area` is `row` or `column` in a + // pivot field move, so a bare `Row` or `Column` there stays text, inside a Repeat or not; + // the token forms still resolve there, and the bare word resolves under `range`. + let wb = wb(); + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + for item in [None, Some((RepeatOf::Rows, place("B5:D5")))] { + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: Some(place("F2")), item }; + let p = json!({"word": "Colum", "to": "Column", "area": "row", "from": "Input", "at": "Output"}); + let r = resolve_params(&p, &env).unwrap(); + assert_eq!(r, json!({"word": "Colum", "to": "Column", "area": "row", "from": "B2:D11", "at": "F2"}), "{item:?}"); + } + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: Some((RepeatOf::Rows, place("B5:D5"))) }; + let p = json!({"to": "Row.col(2)", "range": "Row", "area": {"$ref": "Row"}, "text": "{{Row}}"}); + let r = resolve_params(&p, &env).unwrap(); + assert_eq!(r, json!({"to": "C5", "range": "B5:D5", "area": "B5:D5", "text": "B5:D5"})); + } + + #[test] + fn a_header_row_alone_and_a_table_without_data_rows_are_refused() { + let mut wb = wb(); + let sh = wb.sheet_mut(0).unwrap(); + sh.tables.push(gridcraft_model::Table { + id: 1, + name: "Empty".into(), + range: RangeRef::parse("H1:J1").unwrap(), + header_row: true, + totals_row: false, + columns: Vec::new(), + style: String::new(), + banded_rows: false, + banded_cols: false, + first_col: false, + last_col: false, + filter_button: false, + filter: Vec::new(), + table_type: None, + connection_id: None, + }); + let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + assert!(resolve_ref("Input.data", &env).unwrap_err().to_string().contains("only a header row")); + assert!(resolve_ref("Input.data.col(2)", &env).unwrap_err().to_string().contains("only a header row")); + check(&env, "Plain.data", "B2:D2"); + check(&env, "Input.col(2)", "C2"); + assert!(resolve_ref("Name:Empty", &env).unwrap_err().to_string().contains("no data rows")); + } + + #[test] + fn doubled_braces_are_literal_braces() { + let wb = wb(); + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + assert_eq!(interpolate("Dear {{{{name}},", &env).unwrap(), "Dear {{name}},"); + assert_eq!(interpolate("{{{{ {{Input.cell(1,1)}} }}", &env).unwrap(), "{{ B2 }}"); + assert!(interpolate("Dear {{name}},", &env).is_err(), "an unknown token is still an error"); + } + + #[test] + fn text_marked_as_text_is_never_a_token() { + // A defined name called Output or Input in a reference parameter, a Name: prefix and + // braces: `$text` passes each as it is, in any key; unmarked, each reads as a token. + let wb = wb(); + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + for text in ["Output", "Input", "Name:Nowhere", "Row", "Dear {{name}}"] { + let p = json!({"range": {"$text": text}, "input": {"$text": text}}); + assert_eq!(resolve_params(&p, &env).unwrap(), json!({"range": text, "input": text}), "{text}"); + assert_ne!(resolve_params(&json!({"range": text}), &env).ok(), Some(json!({"range": text})), "{text}"); + assert!(reads_as_token(text, &["Input"]) || text.contains("{{"), "{text}"); + } + assert!(!reads_as_token("Output!A1", &["Input"]) && !reads_as_token("B2", &["Input"])); + } + + #[test] + fn a_defined_name_on_a_sheet_with_a_dollar_sign_resolves() { + let mut wb = wb(); + wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("US$"))); + wb.names.push(gridcraft_model::DefinedName { + name: "Dollars".into(), + scope: None, + formula: "'US$'!$F$20".into(), + comment: String::new(), + hidden: false, + }); + let env = Env { wb: &wb, active_sheet: 0, inputs: &[], output: None, item: None }; + check(&env, "Name:Dollars", "'US$'!F20"); + } + + #[test] + fn below_and_right_refuse_a_count_under_one() { + let wb = wb(); + let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; + let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; + check(&env, "Input.below", "B12:D12"); + check(&env, "Input.below(2)", "B12:D13"); + check(&env, "Input.right(1)", "E2:E11"); + for bad in ["Input.below(0)", "Input.below(-3)", "Input.right(0)"] { + assert!(resolve_ref(bad, &env).unwrap_err().to_string().contains("at least 1"), "{bad}"); + } + } +} diff --git a/crates/engine/src/macros/run.rs b/crates/engine/src/macros/run.rs new file mode 100644 index 0000000000..71c23aabef --- /dev/null +++ b/crates/engine/src/macros/run.rs @@ -0,0 +1,1666 @@ +//! Running a macro. +//! +//! 1. **Gate**: every step's command goes through [`macro_policy`]. Denied commands stop the macro +//! before anything runs; commands that touch files must be listed in the macro's permissions; +//! a macro from a file someone else made, or one that touches files, runs only once the person +//! approves it (once per macro content, for the session). +//! 2. **Inputs**: each declared input is bound to a range (given, its default, or the selection) +//! and checked against its shape and column types, with messages that name the cells. +//! 3. **Footprint**: unless the macro may overwrite, it first runs on the real workbook in dry-run +//! mode, the changes are compared with `CellStore::diff`, and everything is put back. Cells it +//! would write outside its inputs that already hold data are conflicts, handled by the output +//! rule: ask, fail, overwrite, or shift the data down or right (and check again). The +//! footprint can miss a write (a dry run stops early at a file step or Solver, and RAND or NOW +//! can send the run another way than the dry run), so the run also checks each step as it goes. +//! 4. **Run**: one undo step (`Session::grouped`); an error at any step rolls everything back and +//! names the step. +//! +//! The steps run on a small machine with an explicit frame stack, so the debugger can stop +//! between any two steps and pick up again on a later frame. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::Arc; + +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_formula::adjust::Edit; +use gridcraft_model::{Cell, CompareOp, InputKind, Macro, OnConflict, RepeatOf, Sheet, Step, StepKind, Workbook}; +use serde::Serialize; +use serde_json::{Value as Json, json}; + +use super::policy::{Policy, macro_policy, previewable, writes_file}; +use super::resolve::{self, Env, Place, ResolveError}; +use crate::{EngineError, Result, Selection, Session, Trust, UiRequest}; + +/// The most steps one run executes (counting each pass through a Repeat). +pub const MAX_EXECUTED_STEPS: u64 = 100_000; +/// How long a run may take, in milliseconds. The web build has no clock; there only the step +/// limit applies. +pub const DEFAULT_TIME_LIMIT_MS: f64 = 60_000.0; +/// The most cells an input may have for its content to be checked. +pub const MAX_INPUT_CELLS: u64 = 1_000_000; +/// The most bytes of parameters one run passes to its commands, all steps together: on the web +/// build, where there is no clock, this and the step limit bound the work a run does. +pub const MAX_PARAM_BYTES: u64 = 256 * 1024 * 1024; +/// The most ranges a footprint lists per sheet (the counts stay exact). +const MAX_LISTED_RANGES: usize = 500; + +/// An input bound to a range: name, where, whether its first row is a header. +pub type Bound = (String, Place, bool); + +/// Where and why a step failed. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct StepError { + /// The step's path: `3`, `2.1` inside a Repeat, `4.then.1` inside an If. + pub step: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + pub message: String, + /// The step ran past the edge of the sheet. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub edge: bool, + /// The step would write over data and the conflict rule is ask: overwriting answers it. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub confirm: bool, + /// Files the run wrote before the step failed ("step 1 (file.exportCsv)"): rolling back the + /// workbook leaves them written. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub wrote_files: Vec, +} + +impl StepError { + fn new(step: &str, command: Option<&str>, message: impl Into) -> StepError { + StepError { + step: step.to_string(), + command: command.map(str::to_string), + message: message.into(), + edge: false, + confirm: false, + wrote_files: Vec::new(), + } + } + + fn resolve(step: &str, command: Option<&str>, e: ResolveError) -> StepError { + let edge = matches!(e, ResolveError::Edge(_)); + StepError { edge, ..StepError::new(step, command, e.message()) } + } + + /// `Step 3 (cell.set): …` + pub fn describe(&self) -> String { + match &self.command { + Some(c) => format!("Step {} ({c}): {}", self.step, self.message), + None => format!("Step {}: {}", self.step, self.message), + } + } + + pub fn into_engine(self, name: &str) -> EngineError { + let text = format!("Macro '{name}' stopped. {} {}", self.describe(), rolled_back(&self.wrote_files)); + if self.confirm { EngineError::Confirm(text) } else { EngineError::Other(text) } + } +} + +/// What a run that rolled back leaves: "Nothing was changed.", or the files it wrote before. +pub fn rolled_back(wrote_files: &[String]) -> String { + match wrote_files { + [] => "Nothing was changed.".into(), + [one] => format!("The workbook was put back; the file {one} wrote stays."), + many => format!("The workbook was put back; the files {} wrote stay.", join_and(many)), + } +} + +/// The size of `v` as JSON text, near enough to bound how much a run passes to its commands. +fn json_bytes(v: &Json) -> u64 { + match v { + Json::String(t) => t.len() as u64 + 2, + Json::Array(a) => a.iter().map(json_bytes).fold(2, u64::saturating_add), + Json::Object(o) => o.iter().map(|(k, v)| (k.len() as u64 + 3).saturating_add(json_bytes(v))).fold(2, u64::saturating_add), + _ => 8, + } +} + +// ---------------------------------------------------------------- gate + +/// Checks every enabled step against the policy: denied commands and undeclared file access are +/// errors; otherwise returns what the person must approve (empty when nothing). +pub fn gate(m: &Macro, trust: Trust) -> Result> { + let mut asks = BTreeSet::new(); + let mut err = None; + walk_enabled(&m.steps, "", &mut |path, id, params| { + if err.is_some() { + return; + } + match macro_policy(id, params, trust) { + Policy::Allow => {} + Policy::Ask(why) => { + asks.insert(why); + } + Policy::NeedsPermission(what) => { + if m.permissions.iter().any(|p| p == id) { + asks.insert(format!("runs {id}, which {what}")); + } else { + err = Some(format!("Step {path} ({id}) {what}. Add {id} to the macro's permissions to allow it.")); + } + } + Policy::Deny(why) => err = Some(format!("Step {path} ({id}) can't run in a macro: {why}.")), + } + }); + match err { + Some(e) => Err(EngineError::Other(format!("Macro '{}' can't run. {e}", m.name))), + None => Ok(asks.into_iter().collect()), + } +} + +/// Calls `f(path, id, params)` for each enabled command step (skipping disabled steps' bodies). +fn walk_enabled(steps: &[Step], prefix: &str, f: &mut impl FnMut(&str, &str, &Json)) { + for (i, st) in steps.iter().enumerate() { + if !st.enabled { + continue; + } + let path = child_path(prefix, i); + match &st.kind { + StepKind::Command { id, params } => f(&path, id, params), + StepKind::Repeat { body, .. } => walk_enabled(body, &path, f), + StepKind::If { then, otherwise, .. } => { + walk_enabled(then, &format!("{path}.then"), f); + walk_enabled(otherwise, &format!("{path}.else"), f); + } + StepKind::Stop { .. } => {} + } + } +} + +fn child_path(prefix: &str, i: usize) -> String { + if prefix.is_empty() { (i + 1).to_string() } else { format!("{prefix}.{}", i + 1) } +} + +/// Approves the macro for this session when `approve` is set, or asks (an +/// [`EngineError::Approve`]) when it needs approval it doesn't have. +pub fn approve(s: &mut Session, m: &Macro, doc: u64, asks: &[String], approve: bool) -> Result<()> { + if asks.is_empty() { + return Ok(()); + } + let key = (doc, super::fingerprint(m)); + if s.macro_approvals.contains(&key) { + return Ok(()); + } + if approve { + s.macro_approvals.insert(key); + return Ok(()); + } + Err(EngineError::Approve(format!("Run macro '{}'? It {}.", m.name, join_and(asks)))) +} + +fn join_and(items: &[String]) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [init @ .., last] => format!("{} and {last}", init.join(", ")), + } +} + +// ---------------------------------------------------------------- inputs + +/// A macro ready to run: its inputs bound and checked, its output anchor resolved. +#[derive(Clone, Debug)] +pub struct Prepared { + pub mac: Macro, + pub doc: u64, + pub trust: Trust, + pub inputs: Vec, + pub output: Option, +} + +impl Prepared { + pub fn inputs_json(&self, wb: &Workbook) -> Json { + let env = Env { wb, active_sheet: wb.active_sheet(), inputs: &[], output: None, item: None }; + Json::Object(self.inputs.iter().map(|(n, p, _)| (n.clone(), json!(resolve::a1(*p, &env)))).collect()) + } +} + +/// Binds the macro's inputs on the active document (`given`: `{"Input": "B2:D9"}`, or a reference +/// for the first input) and checks them. Errors list every problem found. +pub fn prepare(s: &Session, m: &Macro, given: Option<&Json>) -> Result { + let d = s.doc()?; + let wb = &d.wb; + let mut inputs: Vec = Vec::new(); + let mut problems = Vec::new(); + for (i, input) in m.inputs.iter().enumerate() { + let named = given.and_then(Json::as_object).and_then(|o| o.iter().find(|(k, _)| k.eq_ignore_ascii_case(&input.name)).map(|(_, v)| v)); + let text = named.and_then(Json::as_str).or_else(|| if i == 0 { given.and_then(Json::as_str) } else { None }).or(input.default_ref.as_deref()); + let place = match text { + Some(t) => { + let env = Env { wb, active_sheet: wb.active_sheet(), inputs: &inputs, output: None, item: None }; + match resolve::resolve_ref(t, &env) { + Ok(p) => p, + Err(e) => { + problems.push(format!("{}: {}", input.name, e.message())); + continue; + } + } + } + None if i == 0 => Place { sheet: wb.active_sheet(), range: d.selection.current() }, + None => { + problems.push(format!("{0} needs a range: pass inputs: {{\"{0}\": \"A1:B5\"}}.", input.name)); + continue; + } + }; + let place = trim(wb, place); + problems.extend(check_input(wb, input, place)); + inputs.push((input.name.clone(), place, input.header)); + } + if !problems.is_empty() { + return Err(EngineError::Other(format!("Macro '{}' can't run on these inputs. {}", m.name, problems.join(" ")))); + } + let output = match &m.output.anchor { + Some(a) if !a.trim().is_empty() => { + let env = Env { wb, active_sheet: wb.active_sheet(), inputs: &inputs, output: None, item: None }; + Some( + resolve::resolve_ref(a, &env) + .map_err(|e| EngineError::Other(format!("Macro '{}': its output anchor {}", m.name, lower_first(e.message()))))?, + ) + } + _ => None, + }; + Ok(Prepared { mac: m.clone(), doc: d.uid, trust: d.trust, inputs, output }) +} + +fn lower_first(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_lowercase().chain(c).collect(), + None => String::new(), + } +} + +/// Whole rows or columns shrink to the part of the sheet in use. +fn trim(wb: &Workbook, p: Place) -> Place { + if !(p.range.is_full_cols() || p.range.is_full_rows()) { + return p; + } + let used = wb.sheet(p.sheet).and_then(Sheet::used_range); + let range = used.and_then(|u| p.range.intersection(&u)).unwrap_or(RangeRef::cell(p.range.start)); + Place { sheet: p.sheet, range } +} + +/// What is wrong with `place` as `input`, one sentence each. +fn check_input(wb: &Workbook, input: &gridcraft_model::NamedInput, place: Place) -> Vec { + let mut out = Vec::new(); + let r = place.range; + let name = &input.name; + let at = r.a1(); + if input.kind == InputKind::Cell && !r.is_single() { + out.push(format!("{name} must be a single cell; {at} is {} cells.", r.count())); + return out; + } + let header = u32::from(input.header && r.height() > 0); + let rows = r.height().saturating_sub(header); + let between = |what: &str, n: u32, [min, max]: [u32; 2]| -> Option { + let plural = |k: u32| if k == 1 { what.to_string() } else { format!("{what}s") }; + if max > 0 && min == max && n != min { + Some(format!("exactly {min} {}", plural(min))) + } else if n < min { + Some(format!("at least {min} {}", plural(min))) + } else if max > 0 && n > max { + Some(format!("at most {max} {}", plural(max))) + } else { + None + } + }; + if let Some(want) = between("data row", rows, input.rows) { + out.push(format!("{name} needs {want}; {at} has {rows}.")); + } + if let Some(want) = between("column", r.width(), input.cols) { + out.push(format!("{name} needs {want}; {at} has {}.", r.width())); + } + if r.count() > MAX_INPUT_CELLS { + out.push(format!("{name} is too large to check ({} cells; at most {}).", r.count(), MAX_INPUT_CELLS)); + return out; + } + let Some(sh) = wb.sheet(place.sheet) else { return out }; + let mut blanks = Vec::new(); + for (ci, col) in (r.start.col..=r.end.col).enumerate() { + let ty = input.col_types.get(ci).copied().unwrap_or_default(); + let mut wrong = Vec::new(); + for row in r.start.row + header..=r.end.row { + let c = CellRef::new(row, col); + let v = sh.value(c); + if v.is_empty() || v.as_text() == Some("") { + if input.non_empty { + blanks.push(c); + } + continue; + } + let date = || wb.styles.get(sh.style_id(c)).num_fmt.as_str().to_string(); + let ok = match ty { + gridcraft_model::ColType::Any => true, + gridcraft_model::ColType::Number => v.is_number(), + gridcraft_model::ColType::Text => v.is_text(), + gridcraft_model::ColType::Bool => matches!(v, Value::Bool(_)), + gridcraft_model::ColType::Date => v.is_number() && crate::display::number_format(&date()).is_date(), + }; + if !ok { + wrong.push((c, holds(&v, ty))); + } + } + if !wrong.is_empty() { + let head = if input.header { + Some(crate::display::cell_text(wb, sh, CellRef::new(r.start.row, col))).filter(|h| !h.trim().is_empty()) + } else { + None + }; + let column = match head { + Some(h) => format!("{name} column {} ({})", ci + 1, h.trim()), + None => format!("{name} column {}", ci + 1), + }; + let listed: Vec = wrong.iter().take(3).map(|(c, what)| format!("{} holds {what}", c.a1())).collect(); + let more = if wrong.len() > 3 { format!(" and {} more cells don't", wrong.len() - 3) } else { String::new() }; + out.push(format!("{column} must hold {}; {}{more}.", ty.noun(), listed.join(", "))); + } + } + if let Some(first) = blanks.first() { + let more = if blanks.len() > 1 { format!(" (and {} more)", blanks.len() - 1) } else { String::new() }; + out.push(format!("{name} must have no blank cells; {} is blank{more}.", first.a1())); + } + out +} + +/// What a cell holds, for "C7 holds text". +fn holds(v: &Value, wanted: gridcraft_model::ColType) -> &'static str { + match v { + Value::Number(_) if wanted == gridcraft_model::ColType::Date => "a number that isn't a date", + Value::Number(_) => "a number", + Value::Text(_) => "text", + Value::Bool(_) => "TRUE or FALSE", + Value::Error(_) => "an error", + Value::Array(_) => "an array", + Value::Empty => "nothing", + } +} + +// ---------------------------------------------------------------- the machine + +/// A stopwatch for the time limit. `Instant::now` traps on wasm, so there it measures nothing. +#[derive(Clone, Copy, Debug)] +pub struct Stopwatch { + #[cfg(not(target_arch = "wasm32"))] + start: std::time::Instant, +} + +impl Stopwatch { + pub fn start() -> Stopwatch { + #[cfg(not(target_arch = "wasm32"))] + #[allow(clippy::disallowed_methods)] // never on wasm (see above) + let w = Stopwatch { start: std::time::Instant::now() }; + #[cfg(target_arch = "wasm32")] + let w = Stopwatch {}; + w + } + + /// Milliseconds since the start, or `None` where there is no clock. + fn elapsed_ms(&self) -> Option { + #[cfg(not(target_arch = "wasm32"))] + let ms = Some(self.start.elapsed().as_secs_f64() * 1000.0); + #[cfg(target_arch = "wasm32")] + let ms = None; + ms + } +} + +#[derive(Clone, Debug)] +struct Frame { + steps: Arc>, + next: usize, + /// Path of the step that opened this frame (`""` at the top, `3` for a Repeat's body, + /// `4.then` for an If's branch). + prefix: String, + repeat: Option, +} + +#[derive(Clone, Copy, Debug)] +struct Loop { + of: RepeatOf, + over: Place, + /// The current item (0-based) and how many there are. + at: u32, + count: u32, +} + +impl Loop { + fn item(&self) -> Place { + let r = self.over.range; + let range = match self.of { + RepeatOf::Rows => { + let row = r.start.row.saturating_add(self.at); + RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col)) + } + RepeatOf::Columns => { + let col = r.start.col.saturating_add(self.at); + RangeRef::new(CellRef::new(r.start.row, col), CellRef::new(r.end.row, col)) + } + }; + Place { sheet: self.over.sheet, range } + } +} + +/// A macro run in progress: which step is next, and what has run. +#[derive(Clone, Debug)] +pub struct Machine { + pub name: String, + pub doc: u64, + pub inputs: Vec, + pub output: Option, + permissions: Vec, + trust: Trust, + frames: Vec, + /// Steps executed so far (each pass through a Repeat counts). + pub executed: u64, + clock: Stopwatch, + pub time_limit_ms: f64, + /// Dry run (the footprint check): steps that would touch files or can't be previewed stop + /// the run early instead of running. + pub dry_run: bool, + /// A Stop step ended the run: its message, and whether it asked for a rollback. + pub stopped: Option<(String, bool)>, + /// A dry run stopped before this step (path, reason): what follows isn't in the footprint. + pub partial: Option<(String, String)>, + /// The last step's resolved parameters (for the debugger). + pub last_params: Option, + /// Files the run wrote ("step 1 (file.exportCsv)"): rolling the run back doesn't take them back. + pub wrote_files: Vec, + /// Repeat and If bodies by the path of their frame: a body is copied the first time its step + /// runs, not on every pass. + bodies: HashMap>>, + /// Bytes of parameters passed to commands so far, against [`MAX_PARAM_BYTES`]. + param_bytes: u64, + /// Set unless the macro may overwrite: each step is checked for writes over data as it runs, + /// since the footprint can miss a write (it stopped early, or the run took another path). + guard: Option, +} + +/// Checks each step of a real run for writes over data the footprint didn't see. +#[derive(Clone, Debug)] +struct Guard { + /// The workbook when the run started, and for each sheet now, its index there (`None` for a + /// sheet the run added). + start: Arc, + origin: Vec>, + /// Where the footprint stopped, if it did: "step 2 (file.exportCsv writes a file)". + partial: Option, + /// The conflict rule is ask. + ask: bool, +} + +impl Guard { + fn new(start: Arc, partial: Option<&Json>, ask: bool) -> Guard { + let partial = partial.map(|p| { + let text = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or_default().to_string(); + format!("step {} ({})", text("step"), text("reason")) + }); + Guard { origin: (0..start.sheets.len()).map(Some).collect(), start, partial, ask } + } + + /// What one step wrote over that held data when the run started: cells outside the inputs, + /// sheets and objects it deleted ("B1 on Sheet1; 1 object"), or `""`. + fn check(&mut self, prev: &Workbook, after: &Workbook, inputs: &[Bound]) -> String { + let (pairs, _) = pair_sheets(prev, after); + let mut origin = vec![None; after.sheets.len()]; + let mut parts = Vec::new(); + let mut objects = 0usize; + for (pi, ai) in pairs { + // A sheet the run added holds nothing of the person's. + let Some(si) = self.origin.get(pi).copied().flatten() else { continue }; + let Some(ss) = self.start.sheets.get(si) else { continue }; + let Some(ai) = ai else { + parts.push(format!("the sheet {}", ss.name)); + continue; + }; + if let Some(o) = origin.get_mut(ai) { + *o = Some(si); + } + let (Some(ps), Some(sa)) = (prev.sheets.get(pi), after.sheets.get(ai)) else { continue }; + if Arc::ptr_eq(ps, sa) { + continue; + } + // The inputs have followed their cells, so they are on the sheet's index now. + let in_input = |c: CellRef| inputs.iter().any(|(_, p, _)| p.sheet == ai && p.range.contains(c)); + let mut hit: Vec = ps + .cells + .diff(&sa.cells) + .into_iter() + .filter(|&c| !in_input(c) && !recalculated_only(ps.cell(c), sa.cell(c))) + .filter(|&c| ss.cell(c).is_some_and(has_content) && content_differs(ss.cell(c), sa.cell(c))) + .collect(); + if !hit.is_empty() { + let mut listed = ranges(&mut hit); + if listed.len() > 3 { + listed.truncate(3); + listed.push("…".into()); + } + parts.push(format!("{} on {}", listed.join(", "), sa.name)); + } + objects += deleted(&ss.charts, &ps.charts, &sa.charts, |o| o.id) + + deleted(&ss.images, &ps.images, &sa.images, |o| o.id) + + deleted(&ss.shapes, &ps.shapes, &sa.shapes, |o| o.id); + } + if objects > 0 { + parts.push(format!("{objects} object{}", if objects == 1 { "" } else { "s" })); + } + self.origin = origin; + parts.join("; ") + } +} + +/// Objects of `prev` that `after` no longer has and that were there at the start. +fn deleted(start: &[T], prev: &[T], after: &[T], id: impl Fn(&T) -> u32) -> usize { + let kept: BTreeSet = after.iter().map(&id).collect(); + let had: BTreeSet = start.iter().map(&id).collect(); + prev.iter().map(&id).filter(|i| !kept.contains(i) && had.contains(i)).count() +} + +impl Machine { + pub fn new(p: &Prepared, dry_run: bool) -> Machine { + let mut m = Machine { + name: p.mac.name.clone(), + doc: p.doc, + inputs: p.inputs.clone(), + output: p.output, + permissions: p.mac.permissions.clone(), + trust: p.trust, + frames: vec![Frame { steps: Arc::new(p.mac.steps.clone()), next: 0, prefix: String::new(), repeat: None }], + executed: 0, + clock: Stopwatch::start(), + time_limit_ms: DEFAULT_TIME_LIMIT_MS, + dry_run, + stopped: None, + partial: None, + last_params: None, + wrote_files: Vec::new(), + bodies: HashMap::new(), + param_bytes: 0, + guard: None, + }; + m.settle(); + m + } + + /// Moves to the next enabled step: past disabled steps, finished frames and loop passes. + fn settle(&mut self) { + while let Some(f) = self.frames.last_mut() { + if let Some(st) = f.steps.get(f.next) { + if st.enabled { + return; + } + f.next += 1; + continue; + } + if let Some(l) = f.repeat.as_mut() + && l.at.saturating_add(1) < l.count + { + l.at += 1; + f.next = 0; + continue; + } + self.frames.pop(); + } + } + + pub fn is_done(&self) -> bool { + self.frames.is_empty() + } + + /// Starts the time limit again (the debugger gives each action its own). + pub fn restart_clock(&mut self) { + self.clock = Stopwatch::start(); + } + + /// The current step for the debugger: its path, kind, command, parameters as they would run + /// now, and the Repeat pass. + pub fn current_json(&self, wb: &Workbook) -> Json { + let Some((path, st)) = self.current() else { return Json::Null }; + let env = self.env(wb); + let mut out = json!({"step": path, "breakpoint": st.breakpoint}); + if !st.note.is_empty() { + out["note"] = json!(st.note); + } + match &st.kind { + StepKind::Command { id, params } => { + out["kind"] = json!("command"); + out["command"] = json!(id); + match resolve::resolve_params(params, &env) { + Ok(p) => out["params"] = p, + Err(e) => out["paramsError"] = json!(e.message()), + } + } + StepKind::Repeat { over, of, .. } => { + out["kind"] = json!("repeat"); + // Whole rows or columns shrink to the part in use, as when the Repeat runs. + out["over"] = + json!(resolve::resolve_ref(over, &env).map(|p| resolve::a1(trim(wb, p), &env)).unwrap_or_else(|e| e.message().to_string())); + out["of"] = json!(if *of == RepeatOf::Rows { "rows" } else { "columns" }); + } + StepKind::If { cell, .. } => { + out["kind"] = json!("if"); + out["cell"] = json!(resolve::resolve_ref(cell, &env).map(|p| resolve::a1(p, &env)).unwrap_or_else(|e| e.message().to_string())); + } + StepKind::Stop { message, .. } => { + out["kind"] = json!("stop"); + out["message"] = json!(message); + } + } + if let Some((at, count)) = self.iteration() { + out["iteration"] = json!({"at": at, "of": count}); + } + out + } + + /// The step that runs next, with its path. + pub fn current(&self) -> Option<(String, &Step)> { + let f = self.frames.last()?; + f.steps.get(f.next).map(|st| (child_path(&f.prefix, f.next), st)) + } + + /// The innermost Repeat's pass (1-based) and count. + pub fn iteration(&self) -> Option<(u32, u32)> { + self.frames.iter().rev().find_map(|f| f.repeat).map(|l| (l.at + 1, l.count)) + } + + fn item(&self) -> Option<(RepeatOf, Place)> { + self.frames.iter().rev().find_map(|f| f.repeat).map(|l| (l.of, l.item())) + } + + /// Runs every remaining step. + pub fn run_to_end(&mut self, s: &mut Session) -> std::result::Result<(), StepError> { + while !self.is_done() { + self.step(s)?; + } + Ok(()) + } + + /// Runs the current step and moves to the next one. + pub fn step(&mut self, s: &mut Session) -> std::result::Result<(), StepError> { + // The frame's steps are shared, so the step (and its bodies) isn't copied to run it. + let Some((path, steps, i)) = self.frames.last().map(|f| (child_path(&f.prefix, f.next), Arc::clone(&f.steps), f.next)) else { return Ok(()) }; + let Some(st) = steps.get(i) else { return Ok(()) }; + if let Some(f) = self.frames.last_mut() { + f.next += 1; + } + let mut r = self.exec(s, &path, st); + if let Err(e) = r.as_mut() { + e.wrote_files.clone_from(&self.wrote_files); + self.frames.clear(); + } + self.settle(); + r + } + + fn exec(&mut self, s: &mut Session, path: &str, st: &Step) -> std::result::Result<(), StepError> { + self.executed += 1; + let at = |msg: String| StepError::new(path, None, msg); + if self.executed > MAX_EXECUTED_STEPS { + return Err(at(format!("The macro ran more than {MAX_EXECUTED_STEPS} steps and was stopped."))); + } + if self.clock.elapsed_ms().is_some_and(|ms| ms > self.time_limit_ms) { + return Err(at(format!("The macro ran longer than {} seconds and was stopped.", (self.time_limit_ms / 1000.0).round()))); + } + // Steps run on the macro's workbook, whichever one is in front. + let Some(i) = s.docs.iter().position(|d| d.uid == self.doc) else { return Err(at("The workbook was closed.".into())) }; + s.set_active(i); + match &st.kind { + StepKind::Command { id, params } => self.command(s, path, id, params), + StepKind::Repeat { over, of, max, body } => { + let place = { + let wb = &s.doc().map_err(|e| at(e.to_string()))?.wb; + let env = self.env(wb); + let p = resolve::resolve_ref(over, &env).map_err(|e| StepError::resolve(path, None, e))?; + trim(wb, p) + }; + let items = match of { + RepeatOf::Rows => place.range.height(), + RepeatOf::Columns => place.range.width(), + }; + let cap = (*max).min(MAX_EXECUTED_STEPS as u32); + if items > cap { + let what = if *of == RepeatOf::Rows { "rows" } else { "columns" }; + return Err(at(format!("Repeat over {} has {items} {what}, more than its limit of {cap}.", place.range.a1()))); + } + if items > 0 && body.iter().any(|b| b.enabled) { + let repeat = Some(Loop { of: *of, over: place, at: 0, count: items }); + let steps = self.body(path.to_string(), body); + self.frames.push(Frame { steps, next: 0, prefix: path.to_string(), repeat }); + } + Ok(()) + } + StepKind::If { cell, op, value, then, otherwise } => { + let v = { + let wb = &s.doc().map_err(|e| at(e.to_string()))?.wb; + let env = self.env(wb); + let p = resolve::resolve_ref(cell, &env).map_err(|e| StepError::resolve(path, None, e))?; + if !p.range.is_single() { + return Err(at(format!("If looks at one cell; {} is {} cells.", p.range.a1(), p.range.count()))); + } + wb.sheet(p.sheet).map(|sh| sh.value(p.range.start)).unwrap_or_default() + }; + let (branch, name) = if compare(&v, *op, value) { (then, "then") } else { (otherwise, "else") }; + if branch.iter().any(|b| b.enabled) { + let prefix = format!("{path}.{name}"); + let steps = self.body(prefix.clone(), branch); + self.frames.push(Frame { steps, next: 0, prefix, repeat: None }); + } + Ok(()) + } + StepKind::Stop { message, rollback } => { + self.stopped = Some((message.clone(), *rollback)); + self.frames.clear(); + Ok(()) + } + } + } + + /// After a step that inserted, deleted or moved sheets, rows, columns or cells, moves the + /// inputs, the output and the ranges of the Repeats in progress with their cells, as the + /// references in formulas move. A step that deletes one of them, or changes the size of a + /// range a Repeat is going over, stops the run. + fn follow(&mut self, before: &Workbook, after: &Workbook, edits: &[(String, Edit)]) -> std::result::Result<(), String> { + let same_sheets = before.sheets.len() == after.sheets.len() && before.sheets.iter().zip(&after.sheets).all(|(b, a)| b.name == a.name); + if same_sheets && edits.is_empty() { + return Ok(()); + } + let (pairs, _) = pair_sheets(before, after); + let follow = |what: &str, p: Place| follow_place(before, after, &pairs, edits, p).ok_or_else(|| format!("It deleted the cells of {what}.")); + for (name, place, _) in self.inputs.iter_mut() { + *place = follow(name, *place)?; + } + if let Some(o) = self.output { + self.output = Some(follow("the output anchor", o)?); + } + for f in self.frames.iter_mut() { + let Some(l) = f.repeat.as_mut() else { continue }; + let over = follow(&format!("the range Repeat {} goes over", f.prefix), l.over)?; + if (over.range.height(), over.range.width()) != (l.over.range.height(), l.over.range.width()) { + return Err(format!("It changed the size of the range Repeat {} goes over.", f.prefix)); + } + l.over = over; + } + Ok(()) + } + + /// The shared copy of the body that runs under `prefix`. + fn body(&mut self, prefix: String, body: &[Step]) -> Arc> { + Arc::clone(self.bodies.entry(prefix).or_insert_with(|| Arc::new(body.to_vec()))) + } + + fn env<'a>(&'a self, wb: &'a Workbook) -> Env<'a> { + Env { wb, active_sheet: wb.active_sheet(), inputs: &self.inputs, output: self.output, item: self.item() } + } + + fn command(&mut self, s: &mut Session, path: &str, id: &str, params: &Json) -> std::result::Result<(), StepError> { + let fail = |msg: String| StepError::new(path, Some(id), msg); + // The policy sees the parameters the command will get, after tokens became A1 text. + let resolved = { + let wb = &s.doc().map_err(|e| fail(e.to_string()))?.wb; + resolve::resolve_params(params, &self.env(wb)).map_err(|e| StepError::resolve(path, Some(id), e))? + }; + match (macro_policy(id, params, self.trust), macro_policy(id, &resolved, self.trust)) { + (_, Policy::Deny(why)) | (Policy::Deny(why), _) => return Err(fail(format!("{id} can't run in a macro: {why}."))), + (written, Policy::NeedsPermission(what)) => { + if !self.permissions.iter().any(|p| p == id) { + return Err(fail(format!("{id} {what}. Add it to the macro's permissions to allow it."))); + } + // The gate asked the person about this step only if it saw the file access. + if !matches!(written, Policy::NeedsPermission(_)) { + return Err(fail(format!("{id} {what} only once its parameters are filled in, so it wasn't approved."))); + } + if self.dry_run { + self.partial = Some((path.to_string(), format!("{id} {what}"))); + self.frames.clear(); + return Ok(()); + } + } + (_, Policy::Allow | Policy::Ask(_)) => {} + } + if self.dry_run && !previewable(id) { + self.partial = Some((path.to_string(), format!("{id} can't be previewed"))); + self.frames.clear(); + return Ok(()); + } + self.param_bytes = self.param_bytes.saturating_add(json_bytes(&resolved)); + if self.param_bytes > MAX_PARAM_BYTES { + return Err(fail(format!( + "The macro passed more than {} MB of parameters to its steps and was stopped.", + MAX_PARAM_BYTES / (1024 * 1024) + ))); + } + let file_step = matches!(macro_policy(id, &resolved, self.trust), Policy::NeedsPermission(_)); + let writes = writes_file(id, &resolved); + self.last_params = Some(resolved.clone()); + let prev = s.docs.iter_mut().find(|d| d.uid == self.doc).map(|d| { + d.edits = Some(Vec::new()); + d.wb.clone() + }); + let queued = s.ui_requests.len(); + // Only an approved file step reaches the file system: any other step runs as a script's + // does, so a command that reads or writes a file under another parameter name can't. + let sandbox = (!file_step).then(crate::io::ScriptSandbox::enter); + let r = s.execute(id, resolved); + drop(sandbox); + let edits = s.docs.iter_mut().find(|d| d.uid == self.doc).and_then(|d| d.edits.take()).unwrap_or_default(); + // Macros never open dialogs or web pages, and never start editing a cell; messages for + // the person stay queued. + let mut blocked = None; + let asked: Vec = s.ui_requests.drain(queued.min(s.ui_requests.len())..).collect(); + for q in asked { + match q { + UiRequest::Dialog(name, _) => blocked = Some(format!("{id} would open the {name} dialog; give the step the parameters it needs.")), + UiRequest::OpenUrl(_) => blocked = Some(format!("{id} would open a web page, which macros don't do.")), + UiRequest::EditCell(_) | UiRequest::InsertName(_) => {} + m @ UiRequest::Message(_) => s.ui_requests.push(m), + } + } + r.map_err(|e| fail(e.to_string()))?; + if writes { + self.wrote_files.push(format!("step {path} ({id})")); + } + if let Some(b) = blocked { + return Err(fail(b)); + } + let after = s.docs.iter().find(|d| d.uid == self.doc).map(|d| d.wb.clone()).ok_or_else(|| fail("The workbook was closed.".into()))?; + if let Some(prev) = &prev { + self.follow(prev, &after, &edits).map_err(fail)?; + } + if let (Some(g), Some(prev)) = (self.guard.as_mut(), prev) { + let what = g.check(&prev, &after, &self.inputs); + if !what.is_empty() { + let msg = match &g.partial { + Some(at) => format!("It would write over data ({what}); the check before the run stopped at {at} and couldn't see this."), + // A value such as RAND or NOW differed from the check's, and the run went another way. + None => format!("It would write over data ({what}); the check before the run didn't see this write."), + }; + return Err(StepError { confirm: g.ask, ..fail(msg) }); + } + } + Ok(()) + } +} + +/// Where the cells of `p` are after a step: on the same sheet wherever it moved (`pairs`, from +/// [`pair_sheets`]), and moved by each structural edit the step made there, or `None` when the +/// step deleted them (or their sheet). +fn follow_place(before: &Workbook, after: &Workbook, pairs: &[(usize, Option)], edits: &[(String, Edit)], p: Place) -> Option { + let sheet = pairs.iter().find(|(b, _)| *b == p.sheet).and_then(|(_, a)| *a)?; + let mut name = after.sheet(sheet)?.name.clone(); + let old_name = before.sheet(p.sheet).map(|s| s.name.as_str()).unwrap_or_default(); + let mut text = format!("{}!{}", resolve::quote_sheet(&name), p.range.a1()); + for (target, e) in edits { + if target != &name && target != old_name { + continue; + } + let expr = gridcraft_formula::parse(&text).ok()?; + text = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, target, target, e)); + if text.contains("#REF!") { + return None; + } + // A cut and paste can take the cells to another sheet. + let env = Env { wb: after, active_sheet: usize::MAX, inputs: &[], output: None, item: None }; + name = after.sheet(resolve::resolve_ref(&text, &env).ok()?.sheet)?.name.clone(); + } + let env = Env { wb: after, active_sheet: usize::MAX, inputs: &[], output: None, item: None }; + if text.contains('$') { + text = text.replace('$', ""); + } + resolve::resolve_ref(&text, &env).ok() +} + +/// If's comparison of a cell's value with a step's `value`, the way Excel's `=`, `<`… compare. +fn compare(v: &Value, op: CompareOp, want: &Json) -> bool { + let empty = v.is_empty() || v.as_text() == Some(""); + let want_text = || match want { + Json::String(t) => t.clone(), + Json::Null => String::new(), + other => other.to_string(), + }; + let ord = || -> Option { + let w = match want { + Json::Null => Value::Empty, + Json::Bool(b) => Value::Bool(*b), + Json::Number(n) => Value::number(n.as_f64()?), + // "5" compares as a number with a number in the cell. + Json::String(t) => match (v, t.trim().parse::()) { + (Value::Number(_), Ok(n)) => Value::number(n), + _ => Value::text(t.as_str()), + }, + _ => return None, + }; + match (v, &w) { + (Value::Error(e), Value::Text(t)) => { + Some(if e.as_str().eq_ignore_ascii_case(t.trim()) { std::cmp::Ordering::Equal } else { std::cmp::Ordering::Less }) + } + (Value::Error(_), _) | (_, Value::Error(_)) | (Value::Array(_), _) => None, + _ => Some(gridcraft_core::value::compare(v, &w)), + } + }; + use std::cmp::Ordering::*; + match op { + CompareOp::Empty => empty, + CompareOp::NotEmpty => !empty, + CompareOp::Contains => v.display().to_lowercase().contains(&want_text().to_lowercase()), + CompareOp::Eq => ord() == Some(Equal), + CompareOp::Ne => ord() != Some(Equal), + CompareOp::Gt => ord() == Some(Greater), + CompareOp::Ge => matches!(ord(), Some(Greater | Equal)), + CompareOp::Lt => ord() == Some(Less), + CompareOp::Le => matches!(ord(), Some(Less | Equal)), + } +} + +// ---------------------------------------------------------------- footprint + +/// What a macro would change, from a dry run on the real workbook. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Footprint { + /// Steps executed and bytes of parameters passed by the end of the dry run that made this + /// footprint (the run's one budget). + #[serde(skip)] + pub executed: u64, + #[serde(skip)] + pub param_bytes: u64, + /// The Stop step that ended the dry run asks for the run to be rolled back. + #[serde(skip)] + pub rolls_back: bool, + /// The dry run wrote more cells than the touch log keeps, so writes that kept a cell's value + /// may be missing from `cells`: a shift cannot trust the block. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub log_full: bool, + pub sheets: Vec, + pub sheets_added: Vec, + pub sheets_removed: Vec, + pub objects_added: usize, + pub objects_changed: usize, + pub objects_removed: usize, + /// The dry run stopped early before this step; later steps aren't in the footprint. + #[serde(skip_serializing_if = "Option::is_none")] + pub partial: Option, + /// The step the run would fail at. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// A Stop step's message. + #[serde(skip_serializing_if = "Option::is_none")] + pub stopped: Option, +} + +/// The cells a macro would write on one sheet, outside its inputs. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SheetFootprint { + pub sheet: String, + #[serde(skip)] + pub index: usize, + /// The written cells as ranges (at most 500 listed), and how many cells. + pub cells: Vec, + pub changed: usize, + /// Written cells that hold data now. + pub conflicts: Vec, + pub conflict_count: usize, + /// The block that holds every written cell. + #[serde(skip_serializing_if = "Option::is_none")] + pub bounds: Option, + #[serde(skip)] + pub bounds_range: Option, +} + +impl Footprint { + /// Cells that hold data and would be written, plus sheets and objects that would go. + pub fn conflict_count(&self) -> usize { + self.sheets.iter().map(|s| s.conflict_count).sum::() + self.sheets_removed.len() + self.objects_removed + } + + /// "C2:C9 on Sheet1, the sheet Old, 2 objects". + pub fn describe_conflicts(&self) -> String { + let mut parts: Vec = self + .sheets + .iter() + .filter(|s| s.conflict_count > 0) + .map(|s| { + let mut listed = s.conflicts.iter().take(3).cloned().collect::>().join(", "); + if s.conflicts.len() > 3 { + listed.push_str(", …"); + } + format!("{listed} on {}", s.sheet) + }) + .collect(); + parts.extend(self.sheets_removed.iter().map(|n| format!("the sheet {n}"))); + if self.objects_removed > 0 { + parts.push(format!("{} object{}", self.objects_removed, if self.objects_removed == 1 { "" } else { "s" })); + } + parts.join("; ") + } +} + +/// Session state a dry run may touch, put back afterwards. The workbook, its selection and its +/// history are put back by the dry run's undo group. +struct Saved { + active: usize, + docs: Vec, + /// The workbook as last saved: `sheet.activate` and the view commands move it to the + /// current workbook on a clean document, and the rollback puts the workbook back but not this. + saved: Option>, + /// The document's revision: the rollback counts as a change, and front ends key their caches + /// on it, so a check that changed nothing leaves it as it was. + revision: Option, + sheet_selections: Vec, + unlocked_ranges: Vec<(String, String)>, + trust: Trust, + go_to_recent: Vec, + clipboard: Option, + prefs: crate::Prefs, + mode: crate::Mode, + /// The journal's length: the dry run journals nothing (`Session::journal_paused`), so nothing + /// of the person's is evicted, and the length puts back exactly what was there. + journal: usize, + recording: Option, + ui_requests: usize, + format_painter: Option<(Arc, usize, RangeRef, bool)>, + last_find: Option, + hide_ruler: bool, + windows: (Vec, Option, u64, u64), + draw: (String, String, f32), + comments_pane: bool, + show_all_notes: bool, +} + +impl Saved { + /// Takes the state and stops journaling until [`Saved::restore`]. + fn take(s: &mut Session, doc: u64) -> Saved { + let d = s.docs.iter().find(|d| d.uid == doc); + let saved = Saved { + active: s.active, + docs: s.docs.iter().map(|d| d.uid).collect(), + saved: d.map(|d| d.saved.clone()), + revision: d.map(|d| d.revision), + sheet_selections: d.map(|d| d.sheet_selections.clone()).unwrap_or_default(), + unlocked_ranges: d.map(|d| d.unlocked_ranges.clone()).unwrap_or_default(), + trust: d.map_or(Trust::Local, |d| d.trust), + go_to_recent: d.map(|d| d.go_to_recent.clone()).unwrap_or_default(), + clipboard: s.clipboard.clone(), + prefs: s.prefs.clone(), + mode: s.mode, + journal: s.journal.len(), + recording: s.recording, + ui_requests: s.ui_requests.len(), + format_painter: s.format_painter.clone(), + last_find: s.last_find.clone(), + hide_ruler: s.hide_ruler, + windows: (s.windows.clone(), s.active_window, s.next_window, s.activation), + draw: (s.draw_tool.clone(), s.draw_color.clone(), s.draw_width), + comments_pane: s.comments_pane, + show_all_notes: s.show_all_notes, + }; + s.journal_paused = s.journal_paused.saturating_add(1); + saved + } + + fn restore(self, s: &mut Session, doc: u64) { + s.docs.retain(|d| self.docs.contains(&d.uid)); + if let Some(d) = s.docs.iter_mut().find(|d| d.uid == doc) { + if let Some(saved) = self.saved { + d.saved = saved; + } + if let Some(revision) = self.revision { + d.revision = revision; + } + d.sheet_selections = self.sheet_selections; + d.unlocked_ranges = self.unlocked_ranges; + d.trust = self.trust; + d.go_to_recent = self.go_to_recent; + } + s.active = self.active.min(s.docs.len().saturating_sub(1)); + s.clipboard = self.clipboard; + s.prefs = self.prefs; + s.mode = self.mode; + s.truncate_journal(self.journal); + s.recording = self.recording; + s.journal_paused = s.journal_paused.saturating_sub(1); + s.ui_requests.truncate(self.ui_requests); + s.format_painter = self.format_painter; + s.last_find = self.last_find; + s.hide_ruler = self.hide_ruler; + (s.windows, s.active_window, s.next_window, s.activation) = self.windows; + (s.draw_tool, s.draw_color, s.draw_width) = self.draw; + s.comments_pane = self.comments_pane; + s.show_all_notes = self.show_all_notes; + } +} + +/// Runs the macro in dry-run mode on its workbook, puts everything back, and says what it would +/// change. The dry run spends from `run`'s budget: its clock and time limit, its steps and the +/// bytes of parameters it passed. +pub fn footprint(s: &mut Session, p: &Prepared, run: &Machine) -> Result { + let i = s.docs.iter().position(|d| d.uid == p.doc).ok_or(EngineError::NoDocument)?; + s.set_active(i); + let before = s.doc()?.wb.clone(); + let token = s.group_begin("Check Macro")?; + // After the calls that can fail, so nothing returns between taking and putting back. + let saved = Saved::take(s, p.doc); + if let Some(d) = s.docs.iter_mut().find(|d| d.uid == p.doc) { + d.touched = Some(Vec::new()); + } + let mut m = Machine::new(p, true); + (m.clock, m.time_limit_ms, m.executed, m.param_bytes) = (run.clock, run.time_limit_ms, run.executed, run.param_bytes); + let outcome = m.run_to_end(s); + let (after, touched) = match s.docs.iter_mut().find(|d| d.uid == p.doc) { + Some(d) => (d.wb.clone(), d.touched.take().unwrap_or_default()), + None => (before.clone(), Vec::new()), + }; + let rolled = s.group_rollback(token); + saved.restore(s, p.doc); + rolled?; + let (after, touched) = if matches!(m.stopped, Some((_, true))) { (before.clone(), Vec::new()) } else { (after, touched) }; + let mut fp = diff(&before, &after, &p.inputs, &touched); + fp.log_full = touched.len() >= crate::cmd::TOUCH_LOG_LIMIT; + (fp.executed, fp.param_bytes) = (m.executed, m.param_bytes); + fp.rolls_back = matches!(m.stopped, Some((_, true))); + fp.error = outcome.err(); + fp.stopped = m.stopped.map(|(msg, _)| msg); + fp.partial = m.partial.map(|(step, reason)| json!({"step": step, "reason": reason})); + Ok(fp) +} + +/// Compares the workbook before and after a dry run. `touched` adds the cells commands wrote +/// without changing them (a formula written again), so a shift moves everything the macro writes. +fn diff(before: &Workbook, after: &Workbook, inputs: &[Bound], touched: &[(String, CellRef)]) -> Footprint { + let mut fp = Footprint::default(); + // One pass over the touch log (up to a million writes), not one per sheet. + let mut by_sheet: HashMap<&str, BTreeSet> = HashMap::new(); + for (n, c) in touched { + by_sheet.entry(n.as_str()).or_default().insert(*c); + } + let (pairs, added) = pair_sheets(before, after); + fp.sheets_added = added.into_iter().filter_map(|a| after.sheet(a).map(|s| s.name.clone())).collect(); + for (bi, ai) in pairs { + let Some(bs) = before.sheets.get(bi) else { continue }; + let Some(ai) = ai else { + fp.sheets_removed.push(bs.name.clone()); + continue; + }; + let Some(after_sheet) = after.sheets.get(ai) else { continue }; + let rewritten = by_sheet.remove(after_sheet.name.as_str()).unwrap_or_default(); + if Arc::ptr_eq(bs, after_sheet) && rewritten.is_empty() { + continue; + } + let (added, changed, removed) = objects(bs, after_sheet); + fp.objects_added += added; + fp.objects_changed += changed; + fp.objects_removed += removed; + let in_input = |c: CellRef| inputs.iter().any(|(_, p, _)| p.sheet == bi && p.range.contains(c)); + let mut written = Vec::new(); + let mut conflicts = Vec::new(); + let mut cells: BTreeSet = bs.cells.diff(&after_sheet.cells).into_iter().collect(); + cells.extend(rewritten.iter().copied()); + for c in cells { + if in_input(c) { + continue; + } + let (b, a) = (bs.cell(c), after_sheet.cell(c)); + if recalculated_only(b, a) && !rewritten.contains(&c) { + continue; + } + written.push(c); + if b.is_some_and(has_content) && content_differs(b, a) { + conflicts.push(c); + } + } + let Some(first) = written.first() else { continue }; + let bounds = written.iter().fold(RangeRef::cell(*first), |r, c| r.union(&RangeRef::cell(*c))); + fp.sheets.push(SheetFootprint { + sheet: bs.name.clone(), + index: bi, + changed: written.len(), + conflict_count: conflicts.len(), + cells: ranges(&mut written), + conflicts: ranges(&mut conflicts), + bounds: Some(bounds.a1()), + bounds_range: Some(bounds), + }); + } + fp +} + +/// Each sheet of `before` with its index in `after` (`None` when deleted), and the sheets of +/// `after` that are new. Sheets are matched by name; what's left is matched in order (a renamed +/// sheet). +pub(crate) fn pair_sheets(before: &Workbook, after: &Workbook) -> (Vec<(usize, Option)>, Vec) { + let mut pairs: Vec<(usize, Option)> = before.sheets.iter().enumerate().map(|(bi, sh)| (bi, after.sheet_index(&sh.name))).collect(); + let matched: BTreeSet = pairs.iter().filter_map(|(_, a)| *a).collect(); + let mut spare = (0..after.sheets.len()).filter(|a| !matched.contains(a)); + for (_, a) in pairs.iter_mut().filter(|(_, a)| a.is_none()) { + *a = spare.next(); + } + (pairs, spare.collect()) +} + +/// Only a formula's (or a Python cell's) cached value changed (a recalculation, not a write): a +/// Python cell whose spill a step blocked shows #SPILL! with its code untouched. +fn recalculated_only(b: Option<&Cell>, a: Option<&Cell>) -> bool { + match (b, a) { + (Some(b), Some(a)) => match (&b.formula, &a.formula) { + (Some(x), Some(y)) => x.text == y.text && x.array == y.array && b.style == a.style, + (None, None) => match (&b.py, &a.py) { + (Some(x), Some(y)) => x.code == y.code && x.object == y.object && b.style == a.style, + _ => false, + }, + _ => false, + }, + _ => false, + } +} + +/// Python code is content, as a formula is, whatever the cell shows. +fn has_content(c: &Cell) -> bool { + c.formula.is_some() || c.py.is_some() || !(c.value.is_empty() || c.value.as_text() == Some("")) +} + +/// Whether a write changed what the person entered: the formula, the Python code and its return +/// type, or the value. A Python cell replaced by its own cached value, or by other code that +/// shows the same `#BLOCKED!`, has changed. +fn content_differs(b: Option<&Cell>, a: Option<&Cell>) -> bool { + match (b, a) { + (Some(b), Some(a)) => match (&b.formula, &a.formula) { + (Some(x), Some(y)) => x.text != y.text, + (None, None) => match (&b.py, &a.py) { + (Some(x), Some(y)) => x.code != y.code || x.object != y.object, + (None, None) => b.value != a.value, + _ => true, + }, + _ => true, + }, + (Some(b), None) => has_content(b), + _ => false, + } +} + +/// Objects added, changed and removed between two versions of a sheet. +fn objects(b: &Sheet, a: &Sheet) -> (usize, usize, usize) { + fn count(b: &[T], a: &[T], id: impl Fn(&T) -> u32) -> (usize, usize, usize) { + let added = a.iter().filter(|x| !b.iter().any(|y| id(y) == id(x))).count(); + let removed = b.iter().filter(|x| !a.iter().any(|y| id(y) == id(x))).count(); + let changed = b.iter().filter(|x| a.iter().any(|y| id(y) == id(x) && y != *x)).count(); + (added, changed, removed) + } + let parts = [count(&b.charts, &a.charts, |o| o.id), count(&b.images, &a.images, |o| o.id), count(&b.shapes, &a.shapes, |o| o.id)]; + parts.iter().fold((0, 0, 0), |t, p| (t.0 + p.0, t.1 + p.1, t.2 + p.2)) +} + +/// Cells as A1 ranges: runs along each row, then runs with the same columns on following rows. +pub(crate) fn ranges(cells: &mut [CellRef]) -> Vec { + cells.sort_unstable_by_key(|c| (c.row, c.col)); + let mut runs: Vec = Vec::new(); + for c in cells.iter() { + match runs.last_mut() { + Some(r) if r.end.row == c.row && r.end.col.checked_add(1) == Some(c.col) => r.end.col = c.col, + _ => runs.push(RangeRef::cell(*c)), + } + } + let mut merged: Vec = Vec::new(); + for r in runs { + // The block above with the same columns that ends on the row before. + match merged + .iter_mut() + .rev() + .take(64) + .find(|m| m.start.col == r.start.col && m.end.col == r.end.col && m.end.row.checked_add(1) == Some(r.start.row)) + { + Some(m) => m.end.row = r.end.row, + None => merged.push(r), + } + } + merged.iter().take(MAX_LISTED_RANGES).map(RangeRef::a1).collect() +} + +/// Inserts blank cells where the footprint lands (moving what is there down or right), so the +/// macro writes into empty cells. The block is every written cell's, so a row the macro writes +/// stays together. A shift that would move one of the macro's inputs is refused: the inputs were +/// checked and bound where they are, and only the block's columns (or rows) would move. +fn make_room(s: &mut Session, fp: &Footprint, p: &Prepared, down: bool) -> Result<()> { + let wb = s.doc()?.wb.clone(); + if let Some(why) = shift_refusal(&wb, fp, p, down) { + return Err(EngineError::Other(why)); + } + let env = Env { wb: &wb, active_sheet: usize::MAX, inputs: &[], output: None, item: None }; + let moves: Vec = fp + .sheets + .iter() + .filter(|s| s.conflict_count > 0) + .filter_map(|sh| sh.bounds_range.map(|block| resolve::a1(Place { sheet: sh.index, range: block }, &env))) + .collect(); + for range in moves { + s.execute("home.insertCells", json!({"range": range, "shift": if down { "down" } else { "right" }}))?; + } + Ok(()) +} + +/// Why shifting the data can't make room for `fp`, or `None`: the macro deletes sheets or +/// objects, the footprint couldn't follow every write, or the shift would move an input. +fn shift_refusal(wb: &Workbook, fp: &Footprint, p: &Prepared, down: bool) -> Option { + if !fp.sheets_removed.is_empty() || fp.objects_removed > 0 { + return Some("Shifting can't make room: the macro deletes sheets or objects.".into()); + } + if fp.log_full { + return Some("Shifting can't make room: the macro writes more cells than the footprint can follow.".into()); + } + let env = Env { wb, active_sheet: usize::MAX, inputs: &[], output: None, item: None }; + for sh in fp.sheets.iter().filter(|s| s.conflict_count > 0) { + let Some(block) = sh.bounds_range else { continue }; + // What the insertion moves: the block's columns from its top row down, or its rows from + // its left column rightwards. + let moved = |r: &RangeRef| { + if down { + r.start.col <= block.end.col && r.end.col >= block.start.col && r.end.row >= block.start.row + } else { + r.start.row <= block.end.row && r.end.row >= block.start.row && r.end.col >= block.start.col + } + }; + // The output is where the macro writes, so moving what is there is the point; the second + // footprint catches data the shift moved into it. + if let Some((name, pl)) = p.inputs.iter().map(|(n, pl, _)| (n.as_str(), *pl)).find(|(_, pl)| pl.sheet == sh.index && moved(&pl.range)) { + return Some(format!( + "Shifting the data would move {name} ({}). Run with onConflict overwrite or fail, or make room first.", + resolve::a1(pl, &env) + )); + } + } + None +} + +// ---------------------------------------------------------------- run + +/// A macro that passed its checks and is about to run. +pub struct Begun { + pub mac: Macro, + pub prepared: Prepared, + pub rule: OnConflict, + pub time_limit_ms: f64, + pub inputs: Json, +} + +/// The checks before a run, on the active workbook: the macro exists, the policy allows it, the +/// person approved it if it needs that, and its inputs are right. +pub fn begin(s: &mut Session, name: &str, p: &Json) -> Result { + let d = s.doc()?; + let (doc, trust) = (d.uid, d.trust); + let m = super::find(&d.wb, name) + .and_then(|i| d.wb.macros.get(i)) + .cloned() + .ok_or_else(|| EngineError::Other(format!("There is no macro called '{name}'.")))?; + check_params(p, &m)?; + let asks = gate(&m, trust)?; + approve(s, &m, doc, &asks, p.get("approve").and_then(Json::as_bool).unwrap_or(false))?; + let prepared = prepare(s, &m, p.get("inputs"))?; + let rule = conflict_rule(p, &m)?; + let time_limit_ms = time_limit(p); + let inputs = prepared.inputs_json(&s.doc()?.wb); + Ok(Begun { mac: m, prepared, rule, time_limit_ms, inputs }) +} + +/// The footprint check and the output rule, inside the run's undo group: an error when the macro +/// would fail or write over data it may not, after shifting the data if the rule says so. Returns +/// the machine for the run and whether it shifted. The dry runs count towards the run's time +/// limit. +/// +/// The footprint proves nothing about steps it didn't reach (it stopped early) or a path the run +/// takes and the dry run didn't (RAND, NOW), so the machine also checks each step as it runs and +/// stops the run at one that writes over data. +pub fn make_way(s: &mut Session, b: &Begun) -> Result<(Machine, bool)> { + let (m, rule) = (&b.mac, b.rule); + let mut machine = Machine::new(&b.prepared, false); + machine.time_limit_ms = b.time_limit_ms; + if rule == OnConflict::Overwrite { + return Ok((machine, false)); + } + // The dry runs and the run share one budget (steps, parameters) as they share one clock. + let mut fp = footprint(s, &b.prepared, &machine)?; + (machine.executed, machine.param_bytes) = (fp.executed, fp.param_bytes); + if let Some(e) = fp.error.take() { + return Err(e.into_engine(&m.name)); + } + let mut shifted = false; + if fp.conflict_count() > 0 { + let what = fp.describe_conflicts(); + match rule { + OnConflict::Ask => { + // Overwriting answers for every step, also the ones a partial footprint didn't reach. + let unseen = fp.partial.as_ref().map_or(String::new(), |p| { + let text = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or_default().to_string(); + format!( + " The check stopped at step {} ({}), so overwriting also lets the steps after it write over data unchecked.", + text("step"), + text("reason") + ) + }); + return Err(EngineError::Confirm(format!( + "Macro '{}' would write over cells that hold data ({what}).{unseen} Overwrite them, or run again with onConflict shiftDown, shiftRight or fail", + m.name + ))); + } + OnConflict::Fail | OnConflict::Overwrite => { + return Err(EngineError::Other(format!("Macro '{}' would write over cells that hold data ({what}). Nothing was changed.", m.name))); + } + OnConflict::ShiftDown | OnConflict::ShiftRight => { + make_room(s, &fp, &b.prepared, rule == OnConflict::ShiftDown)?; + fp = footprint(s, &b.prepared, &machine)?; + (machine.executed, machine.param_bytes) = (fp.executed, fp.param_bytes); + if let Some(e) = fp.error.take() { + return Err(e.into_engine(&m.name)); + } + if fp.conflict_count() > 0 { + return Err(EngineError::Other(format!( + "Macro '{}': shifting the data didn't make room ({}). Nothing was changed.", + m.name, + fp.describe_conflicts() + ))); + } + shifted = true; + } + } + } + let start = s.docs.iter().find(|d| d.uid == b.prepared.doc).ok_or(EngineError::NoDocument)?.wb.clone(); + machine.guard = Some(Guard::new(start, fp.partial.as_ref(), rule == OnConflict::Ask)); + Ok((machine, shifted)) +} + +/// Runs macro `name` on the active workbook: `{inputs?, onConflict?, overwrite?, approve?, +/// timeLimit?}` (see `macro.run`). +pub fn run(s: &mut Session, name: &str, p: &Json) -> Result { + let b = begin(s, name, p)?; + let label = format!("Run Macro: {}", b.mac.name); + s.grouped(&label, |s| { + let (mut machine, shifted) = make_way(s, &b)?; + let name = &b.mac.name; + // `ran` counts the run's own steps; the budget also holds the dry runs'. + let before_run = machine.executed; + machine.run_to_end(s).map_err(|e| e.into_engine(name))?; + match machine.stopped { + Some((msg, true)) => Err(EngineError::Other(format!("Macro '{name}' stopped: {msg} {}", rolled_back(&machine.wrote_files)))), + stopped => { + let mut out = json!({"macro": name, "ran": machine.executed.saturating_sub(before_run), "inputs": b.inputs}); + if let Some((msg, _)) = stopped { + out["stopped"] = json!(msg); + } + if shifted { + out["shifted"] = json!(b.rule.name()); + } + Ok(out) + } + } + }) +} + +/// Refuses run parameters that would otherwise be ignored: an input the macro doesn't have, an +/// input given as something other than reference text, and `onConflict`, `overwrite`, `approve` +/// or `timeLimit` of the wrong kind (`null` counts as not given). +pub fn check_params(p: &Json, m: &Macro) -> Result<()> { + let refuse = |msg: String| Err(EngineError::Other(format!("Macro '{}': {msg}", m.name))); + let names = || m.inputs.iter().map(|i| i.name.clone()).collect::>().join(", "); + match p.get("inputs") { + None | Some(Json::Null) => {} + Some(Json::String(_)) if !m.inputs.is_empty() => {} + Some(Json::String(_)) => return refuse("it takes no inputs.".into()), + Some(Json::Object(o)) => { + for (k, v) in o { + if !m.inputs.iter().any(|i| i.name.eq_ignore_ascii_case(k)) { + return refuse(if m.inputs.is_empty() { + format!("it has no input called '{k}'; it takes no inputs.") + } else { + format!("it has no input called '{k}' (its inputs: {}).", names()) + }); + } + if !v.is_string() { + return refuse(format!("give the input {k} as reference text, such as \"B2:D9\".")); + } + } + } + Some(_) => return refuse("give `inputs` as reference text, such as \"B2:D9\", or as {\"Input\": \"B2:D9\"}.".into()), + } + let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + if given("onConflict").is_some_and(|v| !v.is_string()) { + return refuse("`onConflict` must be ask, fail, overwrite, shiftDown or shiftRight.".into()); + } + for k in ["overwrite", "approve"] { + if given(k).is_some_and(|v| !v.is_boolean()) { + return refuse(format!("`{k}` must be true or false.")); + } + } + if given("timeLimit").is_some_and(|v| !v.as_f64().is_some_and(|t| t > 0.0)) { + return refuse("`timeLimit` must be a number of seconds above 0.".into()); + } + Ok(()) +} + +/// The run's `timeLimit` (seconds) in milliseconds, or the default. +fn time_limit(p: &Json) -> f64 { + p.get("timeLimit").and_then(Json::as_f64).map(|t| (t * 1000.0).clamp(1.0, 600_000.0)).unwrap_or(DEFAULT_TIME_LIMIT_MS) +} + +/// The conflict rule for this run: `onConflict`, else the macro's own. `overwrite: true` is the +/// answer to the question, so it turns `ask` into `overwrite` whichever way `ask` was given. +fn conflict_rule(p: &Json, m: &Macro) -> Result { + let rule = match p.get("onConflict").and_then(Json::as_str) { + Some(t) => OnConflict::parse(t) + .ok_or_else(|| EngineError::Other(format!("onConflict must be ask, fail, overwrite, shiftDown or shiftRight, not '{t}'.")))?, + None => m.output.on_conflict, + }; + if rule == OnConflict::Ask && p.get("overwrite").and_then(Json::as_bool) == Some(true) { + return Ok(OnConflict::Overwrite); + } + Ok(rule) +} + +/// For `macro.check`, as the run would: shifts the data, checks the footprint again, and puts +/// everything back. What still stands in the way, or `None`. +fn shifted_conflicts(s: &mut Session, fp: &Footprint, p: &Prepared, budget: &Machine, down: bool) -> Result> { + let token = s.group_begin("Check Macro")?; + let saved = Saved::take(s, p.doc); + let mut spent = budget.clone(); + (spent.executed, spent.param_bytes) = (fp.executed, fp.param_bytes); + let again = make_room(s, fp, p, down).and_then(|()| footprint(s, p, &spent)); + let rolled = s.group_rollback(token); + saved.restore(s, p.doc); + rolled?; + Ok(match again { + Err(e) => Some(e.to_string()), + Ok(again) => match (&again.error, again.conflict_count()) { + (Some(e), _) => Some(e.describe()), + (None, 0) => None, + (None, _) => Some(format!("Shifting the data doesn't make room ({}).", again.describe_conflicts())), + }, + }) +} + +/// `macro.check`: what running the macro would do, without changing anything. +pub fn check(s: &mut Session, name: &str, p: &Json) -> Result { + let d = s.doc()?; + let (doc, trust) = (d.uid, d.trust); + let m = super::find(&d.wb, name) + .and_then(|i| d.wb.macros.get(i)) + .cloned() + .ok_or_else(|| EngineError::Other(format!("There is no macro called '{name}'.")))?; + let mut out = json!({"macro": m.name, "ok": false, "onConflict": m.output.on_conflict.name()}); + let refused = |mut out: Json, e: String| { + out["errors"] = json!([e]); + Ok(out) + }; + if let Err(e) = check_params(p, &m) { + return refused(out, e.to_string()); + } + let rule = match conflict_rule(p, &m) { + Ok(r) => r, + Err(e) => return refused(out, e.to_string()), + }; + out["onConflict"] = json!(rule.name()); + let asks = match gate(&m, trust) { + Ok(a) => a, + Err(e) => return refused(out, e.to_string()), + }; + let approved = s.macro_approvals.contains(&(doc, super::fingerprint(&m))); + if !asks.is_empty() && !approved { + // Nothing from an unapproved macro runs, not even in a dry run. + out["needsApproval"] = json!(asks); + } + let prepared = match prepare(s, &m, p.get("inputs")) { + Ok(pr) => pr, + Err(e) => return refused(out, e.to_string()), + }; + out["inputs"] = prepared.inputs_json(&s.doc()?.wb); + if let Some(o) = prepared.output { + let wb = &s.doc()?.wb; + out["output"] = json!(resolve::a1(o, &Env { wb, active_sheet: wb.active_sheet(), inputs: &[], output: None, item: None })); + } + if !asks.is_empty() && !approved { + return Ok(out); + } + let mut budget = Machine::new(&prepared, false); + budget.time_limit_ms = time_limit(p); + let fp = footprint(s, &prepared, &budget)?; + // `ok`: the run would go ahead with this rule, without a question. + let mut problems = Vec::new(); + if let Some(e) = &fp.error { + problems.push(e.describe()); + } + if let (true, Some(msg)) = (fp.rolls_back, &fp.stopped) { + problems.push(format!("A Stop step ends the run and rolls it back: {msg}")); + } + let shifts = matches!(rule, OnConflict::ShiftDown | OnConflict::ShiftRight); + if fp.conflict_count() > 0 { + let what = fp.describe_conflicts(); + match rule { + OnConflict::Ask => problems.push(format!("It would write over cells that hold data ({what}); the run asks first.")), + OnConflict::Fail => problems.push(format!("It would write over cells that hold data ({what}).")), + OnConflict::Overwrite => {} + OnConflict::ShiftDown | OnConflict::ShiftRight => { + let down = rule == OnConflict::ShiftDown; + if let Some(why) = shift_refusal(&s.doc()?.wb, &fp, &prepared, down) { + problems.push(why); + } else if let Some(why) = shifted_conflicts(s, &fp, &prepared, &budget, down)? { + problems.push(why); + } + } + } + } + // The run spends its budget on the dry runs before it too: one, or two when it shifts. + let passes: u64 = match rule { + OnConflict::Overwrite => 1, + _ if shifts && fp.conflict_count() > 0 => 3, + _ => 2, + }; + if fp.executed.saturating_mul(passes) > MAX_EXECUTED_STEPS { + problems.push(format!("The run would execute more than {MAX_EXECUTED_STEPS} steps, counting the check before it ({} here).", fp.executed)); + } + if fp.param_bytes.saturating_mul(passes) > MAX_PARAM_BYTES { + problems.push(format!("The run would pass more than {} MB of parameters, counting the check before it.", MAX_PARAM_BYTES / (1024 * 1024))); + } + out["ok"] = json!(problems.is_empty()); + out["conflicts"] = json!(fp.conflict_count()); + if !problems.is_empty() { + out["errors"] = json!(problems); + } + out["footprint"] = serde_json::to_value(&fp).unwrap_or(Json::Null); + Ok(out) +} diff --git a/crates/engine/src/macros/tests.rs b/crates/engine/src/macros/tests.rs new file mode 100644 index 0000000000..52f3ba53fe --- /dev/null +++ b/crates/engine/src/macros/tests.rs @@ -0,0 +1,740 @@ +use gridcraft_model::*; +use serde_json::json; + +use super::*; + +fn sample_macro(name: &str) -> Macro { + parse_macro(&json!({ + "name": name, + "description": "Totals the amounts", + "shortcut": "Ctrl+Shift+T", + "inputs": [{"name": "Input", "rows": [1, 500], "cols": [2, 2], "header": true, "colTypes": ["text", "number"], "nonEmpty": true}], + "steps": [ + {"type": "command", "id": "cell.set", "params": {"cell": "Output", "input": "=SUM({{Input.col(2)}})"}, "breakpoint": true, "note": "the total"}, + {"type": "repeat", "over": "Input.rows(2..)", "of": "rows", "max": 100, "body": [ + {"type": "if", "cell": "Row.cell(1,2)", "op": "gt", "value": 100, "then": [ + {"command": "home.bold", "params": {"range": "Row"}} + ], "else": [{"type": "stop", "message": "done"}]} + ]}, + {"type": "command", "id": "home.italic", "enabled": false} + ], + "output": {"anchor": "Input.offset(0,3)", "onConflict": "shiftDown"}, + "permissions": ["data.getData"] + })) + .unwrap() +} + +#[test] +fn macros_read_from_json_in_both_step_forms() { + let m = sample_macro("Totals"); + assert_eq!(m.v, MACRO_VERSION); + assert_eq!(m.inputs[0].col_types, [ColType::Text, ColType::Number]); + assert_eq!(m.output.on_conflict, OnConflict::ShiftDown); + assert_eq!(m.step_count(), 6); + assert!(m.steps[0].breakpoint && m.steps[0].enabled && !m.steps[2].enabled); + let StepKind::Repeat { body, max, .. } = &m.steps[1].kind else { panic!("{:?}", m.steps[1]) }; + assert_eq!(*max, 100); + let StepKind::If { then, otherwise, op, .. } = &body[0].kind else { panic!() }; + assert_eq!(*op, CompareOp::Gt); + // The short form of earlier scripts reads as a command step. + assert_eq!(then[0].kind, StepKind::Command { id: "home.bold".into(), params: json!({"range": "Row"}) }); + assert!(matches!(&otherwise[0].kind, StepKind::Stop { message, rollback: false } if message == "done")); + // Writing and reading again gives the same macro; defaults stay out of the JSON. + let v = macro_json(&m); + assert_eq!(v["steps"][0]["type"], "command"); + assert!(v["steps"][1].get("enabled").is_none() && v["steps"][1].get("breakpoint").is_none()); + assert_eq!(v["steps"][2]["enabled"], false); + assert_eq!(parse_macro(&v).unwrap(), m); + // A minimal macro gets the defaults. + let m = parse_macro(&json!({"name": " Bare "})).unwrap(); + assert_eq!((m.name.as_str(), m.output.on_conflict, m.inputs.len()), ("Bare", OnConflict::Ask, 0)); +} + +#[test] +fn macros_over_the_limits_are_refused() { + let flat = |n: usize| json!({"name": "Big", "steps": vec![json!({"command": "cell.set"}); n]}); + assert!(parse_macro(&flat(MAX_MACRO_STEPS)).is_ok()); + assert!(parse_macro(&flat(MAX_MACRO_STEPS + 1)).unwrap_err().contains("10000 steps")); + // Nested Repeat steps: 4 Repeats one inside the other are fine (the innermost holds a + // command, or nothing), a 5th is not. + let nest = |repeats: usize| { + let mut step = json!({"command": "cell.set"}); + for _ in 0..repeats { + step = json!({"type": "repeat", "over": "Input", "body": [step]}); + } + json!({"name": "Deep", "steps": [step]}) + }; + assert!(parse_macro(&nest(MAX_MACRO_DEPTH)).is_ok()); + assert_eq!(parse_macro(&nest(MAX_MACRO_DEPTH)).unwrap().step_count(), MAX_MACRO_DEPTH + 1); + assert!(parse_macro(&nest(MAX_MACRO_DEPTH + 1)).unwrap_err().contains("4 deep")); + let mut empty = json!({"type": "repeat", "over": "Input", "body": []}); + for _ in 1..MAX_MACRO_DEPTH { + empty = json!({"type": "if", "cell": "A1", "op": "eq", "value": 1, "then": [empty], "else": []}); + } + let deep = parse_macro(&json!({"name": "Deep", "steps": [empty]})).unwrap(); + assert_eq!(deep.step_count(), MAX_MACRO_DEPTH); + assert!(deep.check_limits().is_ok(), "the model's check agrees with the parser"); + // Far deeper than serde would allow is refused before it is read. + assert!(parse_macro(&nest(200)).is_err()); + for bad in [ + json!({"name": ""}), + json!({"name": "x".repeat(256)}), + json!({"name": "a\nb"}), + json!({"name": "A", "steps": {}}), + json!({"name": "A", "steps": [1]}), + json!({"name": "A", "steps": [{"type": "nope"}]}), + json!({"name": "A", "steps": [{"type": "if", "cell": "A1", "op": "between"}]}), + json!({"name": "A", "inputs": [{"name": ""}]}), + json!({"name": "A", "inputs": [{"name": "Has space"}]}), + json!({"name": "A", "inputs": [{"name": "row"}]}), + json!({"name": "A", "inputs": [{"name": "In"}, {"name": "IN"}]}), + json!({"name": "A", "output": {"onConflict": "explode"}}), + json!([]), + ] { + assert!(parse_macro(&bad).is_err(), "{bad}"); + } +} + +fn names_of(wb: &Workbook) -> Vec { + wb.names.iter().map(|n| n.name.clone()).collect() +} + +#[test] +fn macros_round_trip_through_xlsx_and_json() { + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("Totals")); + // Large enough to need several hidden names. + let long: Vec = (0..300).map(|r| Step::command("cell.set", json!({"cell": format!("A{r}"), "input": "x\"y".repeat(10)}))).collect(); + wb.macros.push(Macro { name: "Long".into(), steps: long, ..Macro::default() }); + for file in ["book.xlsx", "book.json"] { + let bytes = crate::io::save_bytes(&wb, file).unwrap(); + let (back, warnings) = crate::io::open_bytes(file, &bytes).unwrap(); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + assert_eq!(back.macros, wb.macros, "{file}"); + assert!(back.names.is_empty(), "{file}: macros stay out of the names once opened: {:?}", names_of(&back)); + } + // In the xlsx file they are hidden names; the long one spans several. + let bytes = crate::io::save_bytes(&wb, "book.xlsx").unwrap(); + let (raw, _) = gridcraft_xlsx::read_xlsx(&bytes).unwrap(); + let names = names_of(&raw); + assert!(names.contains(&"_gc_macro_0_0".to_string()), "{names:?}"); + assert!(names.iter().filter(|n| n.starts_with("_gc_macro_1_")).count() >= 2, "{names:?}"); + assert!(raw.names.iter().all(|n| n.hidden)); + // Saving without macros writes no macro names, even if stale ones linger. + let mut empty = raw.clone(); + empty.macros.clear(); + let (again, _) = gridcraft_xlsx::read_xlsx(&crate::io::save_bytes(&empty, "x.xlsx").unwrap()).unwrap(); + assert!(again.names.iter().all(|n| !n.name.starts_with("_gc_macro_"))); + // The JSON format keeps the field (and leaves it out when there are no macros). + let json = String::from_utf8(crate::io::save_bytes(&wb, "book.json").unwrap()).unwrap(); + assert!(json.contains("\"macros\"")); + let plain = String::from_utf8(crate::io::save_bytes(&Workbook::new(), "book.json").unwrap()).unwrap(); + assert!(!plain.contains("\"macros\"")); +} + +fn hidden(name: &str, text: &str) -> DefinedName { + DefinedName { name: name.into(), scope: None, formula: format!("\"{}\"", text.replace('"', "\"\"")), comment: String::new(), hidden: true } +} + +#[test] +fn a_visible_name_that_looks_like_macro_storage_is_left_alone() { + // Macro storage is hidden workbook-scope names; a visible `_gc_macro_0_0` someone defined + // is neither read as a macro nor removed when the workbook opens. + let mut wb = Workbook::new(); + let name = DefinedName { hidden: false, ..hidden("_gc_macro_0_0", "x") }; + wb.names.push(name.clone()); + let warnings = load(&mut wb); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(wb.macros.is_empty()); + assert_eq!(wb.names, vec![name]); +} + +#[test] +fn input_names_that_read_as_cell_references_are_refused() { + // A recorded step holds plain A1 text; an input called `Q1` would take its place. + let with_input = |name: &str| json!({"name": "M", "inputs": [{"name": name}]}); + for name in ["Q1", "AB12", "Sum1", "a1"] { + let err = parse_macro(&with_input(name)).unwrap_err(); + assert!(err.contains("reads as a cell reference"), "{name}: {err}"); + } + for name in ["Amount", "Q", "Sales_Q1", "Total1a"] { + assert!(parse_macro(&with_input(name)).is_ok(), "{name}"); + } + assert!(parse_macro(&with_input("Row")).unwrap_err().contains("token of its own")); +} + +#[test] +fn a_hidden_macro_name_this_build_did_not_write_is_kept() { + // `_gc_macro_index_0` is not a numbered item: it is neither read nor dropped on open, and a + // save with macros keeps it beside the items written. + let mut wb = Workbook::new(); + let theirs = hidden("_gc_macro_index_0", "{}"); + wb.names.push(theirs.clone()); + wb.macros.push(sample_macro("Totals")); + let (raw, _) = gridcraft_xlsx::read_xlsx(&crate::io::save_bytes(&wb, "book.xlsx").unwrap()).unwrap(); + let names = names_of(&raw); + assert!(names.contains(&"_gc_macro_index_0".to_string()) && names.contains(&"_gc_macro_0_0".to_string()), "{names:?}"); + let (back, warnings) = crate::io::open_bytes("book.xlsx", &crate::io::save_bytes(&wb, "book.xlsx").unwrap()).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.macros, wb.macros); + assert_eq!(names_of(&back), ["_gc_macro_index_0"]); +} + +#[test] +fn workbook_snapshots_share_the_macro_list_until_it_changes() { + // An undo snapshot or a copy made for a cell edit holds the same list, not a copy of every + // step; the undo budget charges a list only once it is a snapshot's own. + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("Totals")); + let snapshot = wb.clone(); + assert!(wb.macros.shares(&snapshot.macros)); + assert_eq!(crate::history_retained_bytes(&snapshot, &wb), std::mem::size_of::()); + wb.macros.push(sample_macro("More")); + assert!(!wb.macros.shares(&snapshot.macros), "a write copies the list first"); + assert_eq!(snapshot.macros.len(), 1); + assert!(crate::history_retained_bytes(&snapshot, &wb) > std::mem::size_of::()); + // The copy is per list, not per workbook copy: cloning again shares the new list. + let again = wb.clone(); + assert!(wb.macros.shares(&again.macros)); + let rebuilt: Macros = wb.macros.iter().cloned().collect(); + assert_eq!(rebuilt, wb.macros); + assert_eq!(rebuilt.into_iter().count(), 2); +} + +#[test] +fn a_macro_built_in_code_goes_through_the_size_check_too() { + // `check` is the one check for every path, so a macro that passes it never makes a save fail. + let big = Macro { + name: "Big".into(), + steps: vec![Step::command("cell.set", json!({"input": "x".repeat(crate::cmd::stash::MAX_ITEM_CHARS)}))], + ..Macro::default() + }; + assert!(big.check_limits().is_ok(), "the model's limits say nothing about the size"); + assert!(check(&big).unwrap_err().contains("too large")); + // A macro that fails `check` fails the save in either format, rather than being written and + // dropped the next time the file opens: too large, or past the model's limits. + let bad_name = Macro { name: "Two\nlines".into(), ..Macro::default() }; + assert!(check(&bad_name).is_err()); + for m in [big, bad_name] { + let mut wb = Workbook::new(); + wb.macros.push(m); + for file in ["book.xlsx", "book.json"] { + assert!(crate::io::save_bytes(&wb, file).is_err(), "{file}"); + } + } +} + +fn visible(name: &str) -> DefinedName { + DefinedName { name: name.into(), scope: None, formula: "Sheet1!$A$1".into(), comment: String::new(), hidden: false } +} + +/// Saves `wb` to xlsx and returns the names in the file and the workbook opened from it. +fn xlsx_round_trip(wb: &Workbook) -> (Vec, Workbook) { + let bytes = crate::io::save_bytes(wb, "book.xlsx").unwrap(); + let raw = names_of(&gridcraft_xlsx::read_xlsx(&bytes).unwrap().0); + let (back, warnings) = crate::io::open_bytes("book.xlsx", &bytes).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + (raw, back) +} + +#[test] +fn a_visible_name_of_the_storage_shape_does_not_block_a_save() { + // The index a macro is stored under is GridCraft's choice, so a person's own visible name + // of that shape (here in capitals: names compare without case) is stepped around, not + // refused. Stale hidden items still go in the same pass. + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("A")); + wb.macros.push(sample_macro("B")); + wb.names.push(visible("_GC_MACRO_0_0")); + wb.names.push(hidden("_gc_macro_7_0", "stale")); + let (raw, back) = xlsx_round_trip(&wb); + assert_eq!(raw, ["_GC_MACRO_0_0", "_gc_macro_1_0", "_gc_macro_2_0"]); + assert_eq!(back.macros, wb.macros, "both macros, in their order"); + assert_eq!(back.names, vec![visible("_GC_MACRO_0_0")], "the person's name is kept as it was"); + assert_eq!(wb.names.len(), 2, "the open workbook is not changed by a save"); +} + +#[test] +fn a_huge_visible_index_takes_no_part_in_numbering() { + // A file can carry a visible name with any number in it. The macros take the free indices + // from 0 up, so no arithmetic depends on that number (one past the largest would overflow). + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("A")); + wb.names.push(visible(&format!("_gc_macro_{}_0", u64::MAX))); + wb.names.push(visible("_gc_macro_0_0")); + let (raw, back) = xlsx_round_trip(&wb); + assert_eq!(raw, [format!("_gc_macro_{}_0", u64::MAX), "_gc_macro_0_0".into(), "_gc_macro_1_0".into()]); + assert_eq!(back.macros, wb.macros); + assert_eq!(names_of(&back), names_of(&wb)); +} + +#[test] +fn a_visible_legacy_name_of_the_storage_shape_is_kept() { + // The stash reads a legacy `_sc_` name as data whether or not it is hidden, so writing + // key `macro_0` would remove a person's visible `_sc_macro_0`. That key is stepped around too. + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("A")); + wb.names.push(visible("_sc_macro_0")); + let (raw, back) = xlsx_round_trip(&wb); + assert_eq!(raw, ["_sc_macro_0", "_gc_macro_1_0"]); + assert_eq!(back.macros, wb.macros); + assert_eq!(back.names, vec![visible("_sc_macro_0")]); +} + +#[test] +fn a_name_defined_after_opening_does_not_block_the_next_save() { + // Once a file is open its macros are out of the names, so Define Name accepts a visible + // `_gc_macro_0_0`; the next save steps around it. + let mut s = crate::Session::new(); + s.execute("file.new", json!({})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).macros.push(sample_macro("A")); + s.execute("formulas.defineName", json!({"name": "_gc_macro_0_0", "refersTo": "=Sheet1!$A$1"})).unwrap(); + let (raw, back) = xlsx_round_trip(&s.doc().unwrap().wb); + assert_eq!(raw, ["_gc_macro_0_0", "_gc_macro_1_0"]); + assert_eq!(back.macros.len(), 1); + assert_eq!(names_of(&back), ["_gc_macro_0_0"]); +} + +#[test] +fn scripts_and_vba_stay_as_they_are() { + // Automate scripts keep their own storage, and a VBA project is carried through unchanged. + let mut wb = Workbook::new(); + let scripts = json!({"Fill": [{"command": "cell.set", "params": {"cell": "A1", "input": "x"}}]}); + wb.names.push(hidden("_sc_scripts", &scripts.to_string())); + wb.vba_project = Some(std::sync::Arc::new(b"\xd0\xcf\x11\xe0 synthetic vbaProject".to_vec())); + wb.macros.push(sample_macro("Totals")); + let bytes = crate::io::save_bytes(&wb, "book.xlsm").unwrap(); + let (back, warnings) = crate::io::open_bytes("book.xlsm", &bytes).unwrap(); + // The only warning is the reader's note that the VBA project is kept and not run. + assert!(warnings.iter().all(|w| w.contains("VBA project")), "{warnings:?}"); + assert_eq!(back.macros, wb.macros); + assert_eq!(names_of(&back), ["_sc_scripts"], "the scripts item is untouched"); + assert_eq!(back.names[0].formula, wb.names[0].formula); + assert_eq!(back.vba_project, wb.vba_project); +} + +#[test] +fn damaged_or_oversized_macros_are_dropped_with_a_warning() { + let mut wb = Workbook::new(); + wb.names.push(hidden("_gc_macro_0_0", &json!({"name": "Good"}).to_string())); + wb.names.push(hidden("_gc_macro_1_0", "{not json")); + wb.names.push(hidden("_gc_macro_2_0", &json!({"name": "Huge", "steps": vec![json!({"command": "x"}); MAX_MACRO_STEPS + 1]}).to_string())); + wb.names.push(hidden("_gc_macro_3_0", &json!({"name": "good"}).to_string())); + wb.names.push(hidden("_gc_macro_10_0", &json!({"name": "Tenth"}).to_string())); + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let (back, warnings) = crate::io::open_bytes("hostile.xlsx", &bytes).unwrap(); + let names: Vec<&str> = back.macros.iter().map(|m| m.name.as_str()).collect(); + // Saved order is by number (10 after 3); a clashing name gets a suffix. + assert_eq!(names, ["Good", "good (2)", "Tenth"]); + assert!(back.names.is_empty(), "{:?}", names_of(&back)); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].starts_with("2 macros"), "{warnings:?}"); + + // The JSON format: more than the limit, and one over the step limit. + let mut wb = Workbook::new(); + wb.macros = (0..MAX_MACROS + 5).map(|i| Macro { name: format!("M{i}"), ..Macro::default() }).collect(); + wb.macros[0].steps = vec![Step::command("x", json!({})); MAX_MACRO_STEPS + 1]; + // Written as another program would: a GridCraft save refuses a macro that fails `check`. + let bytes = serde_json::to_vec(&wb).unwrap(); + let (back, warnings) = crate::io::open_bytes("many.json", &bytes).unwrap(); + // Only the first MAX_MACROS entries are read, as in xlsx. + assert_eq!(back.macros.len(), MAX_MACROS - 1); + assert_eq!(back.macros[0].name, "M1"); + assert!(warnings[0].starts_with("6 macros"), "{warnings:?}"); + + // A macro too large for the hidden names is refused, so a save never fails on it. + let huge = "x".repeat(crate::cmd::stash::MAX_ITEM_CHARS); + let err = parse_macro(&json!({"name": "Huge", "steps": [{"command": "cell.set", "params": {"input": huge}}]})).unwrap_err(); + assert!(err.contains("too large"), "{err}"); + let mut wb = Workbook::new(); + wb.macros.push(Macro { name: "Huge".into(), steps: vec![Step::command("cell.set", json!({"input": huge}))], ..Macro::default() }); + // Written as another program would: a GridCraft save refuses a macro that fails `check`. + let bytes = serde_json::to_vec(&wb).unwrap(); + let (back, warnings) = crate::io::open_bytes("huge.json", &bytes).unwrap(); + assert!(back.macros.is_empty() && warnings[0].starts_with("1 macro "), "{warnings:?}"); +} + +#[test] +fn names() { + let mut wb = Workbook::new(); + wb.macros.push(Macro { name: "Macro1".into(), ..Macro::default() }); + assert_eq!(unique_name(&wb, "macro1"), "macro1 (2)"); + assert_eq!(unique_name(&wb, "Other"), "Other"); + assert_eq!(unique_name(&wb, ""), "Macro"); + // A long name is shortened to make room for the suffix. + let long = "y".repeat(MAX_MACRO_NAME); + wb.macros.push(Macro { name: long.clone(), ..Macro::default() }); + let renamed = unique_name(&wb, &long); + assert_eq!(renamed, format!("{} (2)", "y".repeat(MAX_MACRO_NAME - 4))); + wb.macros.push(Macro { name: renamed, ..Macro::default() }); + assert_eq!(unique_name(&wb, &long).chars().count(), MAX_MACRO_NAME); + assert_eq!(find(&wb, " MACRO1 "), Some(0)); + assert_eq!(find(&wb, "Macro2"), None); + let a = sample_macro("A"); + let mut b = a.clone(); + assert_eq!(fingerprint(&a), fingerprint(&b)); + b.steps[0].note = "changed".into(); + assert_ne!(fingerprint(&a), fingerprint(&b)); + assert_eq!(next_name(&wb), "Macro2"); + let paths: Vec<(String, &str)> = command_steps(&a.steps).into_iter().map(|(p, id, _)| (p, id)).collect(); + assert_eq!(paths, [("1".into(), "cell.set"), ("2.1.then.1".into(), "home.bold"), ("3".into(), "home.italic")]); +} + +#[test] +fn json_field_macros_get_the_name_check_too() { + // A JSON workbook can't bring in a name that macro.save and macro.rename refuse. + let mut wb = Workbook::new(); + wb.macros.push(Macro { name: "a\nb".into(), ..Macro::default() }); + wb.macros.push(Macro { name: "Fine".into(), ..Macro::default() }); + // Written as another program would: a GridCraft save refuses a macro that fails `check`. + let bytes = serde_json::to_vec(&wb).unwrap(); + let (back, warnings) = crate::io::open_bytes("ctl.json", &bytes).unwrap(); + let names: Vec<&str> = back.macros.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["Fine"]); + assert!(warnings.len() == 1 && warnings[0].starts_with("1 macro "), "{warnings:?}"); +} + +#[test] +fn duplicate_names_at_the_length_limit_survive_save_and_reopen() { + // Two macros with the same 255-character name: the second is renamed within the limit, so a + // save and a second open keep both. + let long = "é".repeat(MAX_MACRO_NAME); + for file in ["dup.json", "dup.xlsx"] { + let mut wb = Workbook::new(); + wb.macros.push(Macro { name: long.clone(), ..Macro::default() }); + wb.macros.push(Macro { name: long.clone(), description: "second".into(), ..Macro::default() }); + let (first, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(&wb, file).unwrap()).unwrap(); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + assert_eq!(first.macros.len(), 2, "{file}"); + let renamed = &first.macros[1].name; + assert_eq!(renamed.chars().count(), MAX_MACRO_NAME, "{file}"); + assert!(renamed.ends_with(" (2)") && renamed.starts_with("éé"), "{file}: {renamed}"); + let (again, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(&first, file).unwrap()).unwrap(); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + assert_eq!(again.macros, first.macros, "{file}"); + } +} + +#[test] +#[allow(clippy::disallowed_methods)] // a native-only timing test: the clock is read off wasm +fn many_hidden_macro_names_are_read_in_one_pass() { + // A hostile file with many damaged macro items: only the first MAX_MACROS are read, and the + // names are gathered and removed in one pass instead of one scan of every name per item. + let mut wb = Workbook::new(); + let items = 20_000; + for i in 0..items { + wb.names.push(hidden(&format!("_gc_macro_{i}_0"), "{not json")); + } + wb.names.push(hidden("_gc_other_0", "kept")); + let start = std::time::Instant::now(); + let warnings = load(&mut wb); + let took = start.elapsed(); + assert!(wb.macros.is_empty()); + assert_eq!(names_of(&wb), ["_gc_other_0"]); + assert!(warnings.len() == 1 && warnings[0].starts_with(&format!("{items} macros")), "{warnings:?}"); + assert!(took < std::time::Duration::from_secs(3), "{took:?}"); +} + +#[test] +fn a_damaged_json_macro_drops_alone() { + // One macro this build can't read (a newer step type, an unknown value, the wrong shape) is + // dropped with the usual warning; the workbook and its other macros open. + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(gridcraft_core::CellRef::new(0, 0), gridcraft_core::Value::text("kept")); + let mut v: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&wb, "book.json").unwrap()).unwrap(); + v["macros"] = json!([ + {"name": "Good"}, + {"name": "Newer", "steps": [{"type": "fromALaterBuild"}]}, + {"name": "Odd", "output": {"onConflict": "explode"}}, + {"name": "Short", "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "x"}}]}, + "not a macro" + ]); + let (back, warnings) = crate::io::open_bytes("book.json", v.to_string().as_bytes()).unwrap(); + let names: Vec<&str> = back.macros.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["Good", "Short"]); + assert!(matches!(&back.macros[1].steps[0].kind, StepKind::Command { id, .. } if id == "cell.set")); + assert!(back.macros_read.is_empty()); + assert!(warnings.len() == 1 && warnings[0].starts_with("3 macros"), "{warnings:?}"); + assert_eq!(back.sheet(0).unwrap().value(gridcraft_core::CellRef::new(0, 0)), gridcraft_core::Value::text("kept")); +} + +#[test] +fn a_macro_in_a_newer_format_is_kept_unread_and_saved_back_unchanged() { + // A newer build's macro (`v` 2, with a field this build doesn't know) would lose that field + // if it were read here, so it is never read: it is kept as the file held it, saved back + // unchanged, and the newer build gets it back whole. Version 1 and a missing version are + // read as before. + let future = json!({"name": "Future", "v": MACRO_VERSION + 1, "fromALaterBuild": {"x": 1}, "steps": [{"command": "cell.set"}]}); + let current = json!({"name": "Current", "v": MACRO_VERSION, "steps": [{"command": "cell.set"}]}); + let missing = json!({"name": "Missing"}); + let err = parse_macro(&future).unwrap_err(); + assert!(err.contains("newer version") && err.contains("format 2"), "{err}"); + assert!(parse_macro(&json!({"name": "Huge", "v": u64::from(u32::MAX) + 1})).unwrap_err().contains("newer version")); + // A macro built in code goes through the same check on every path. + assert!(Macro { name: "Built".into(), v: MACRO_VERSION + 1, ..Macro::default() }.check_limits().is_err()); + let check = |file: &str, back: &Workbook, warnings: &[String]| { + let names: Vec<&str> = back.macros.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["Current", "Missing"], "{file}"); + assert!(back.macros.iter().all(|m| m.v == MACRO_VERSION), "{file}"); + assert_eq!(*back.macros_unread, std::slice::from_ref(&future), "{file}"); + assert!( + warnings.len() == 1 && warnings[0].starts_with("1 macro ") && warnings[0].contains("newer version") && warnings[0].contains("unchanged"), + "{file}: {warnings:?}" + ); + // Saved and opened again, it is still there, whole, and the others are as they were. + let (again, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(back, file).unwrap()).unwrap(); + assert_eq!(warnings.len(), 1, "{file}: {warnings:?}"); + assert_eq!(again.macros, back.macros, "{file}"); + assert_eq!(again.macros_unread, back.macros_unread, "{file}"); + }; + // The JSON format's field. + let mut v: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&Workbook::new(), "book.json").unwrap()).unwrap(); + v["macros"] = json!([future, current, missing]); + let (back, warnings) = crate::io::open_bytes("book.json", v.to_string().as_bytes()).unwrap(); + check("book.json", &back, &warnings); + let saved: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&back, "book.json").unwrap()).unwrap(); + assert!(saved["macros"].as_array().unwrap().contains(&future), "the file holds it as it was"); + // Hidden names in xlsx. + let mut wb = Workbook::new(); + for (i, m) in [&future, ¤t, &missing].into_iter().enumerate() { + wb.names.push(hidden(&format!("_gc_macro_{i}_0"), &m.to_string())); + } + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let (back, warnings) = crate::io::open_bytes("book.xlsx", &bytes).unwrap(); + assert!(back.names.is_empty(), "{:?}", names_of(&back)); + check("book.xlsx", &back, &warnings); +} + +#[test] +fn kept_macros_share_the_save_limits_and_the_numbering() { + // A newer macro too large for the file is left out (keeping it would make every xlsx save + // fail), and readable and unread macros together stay within the macro limit, readable ones + // first. Kept ones are numbered after the readable ones, around a person's visible name. + let newer = |name: &str| json!({"name": name, "v": MACRO_VERSION + 1}); + let mut big = newer("Big"); + big["pad"] = json!(long(crate::cmd::stash::MAX_ITEM_CHARS)); + let mut file: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&Workbook::new(), "book.json").unwrap()).unwrap(); + let mut list = vec![big, newer("Kept"), json!({"name": "Read"})]; + file["macros"] = json!(list); + let (mut wb, warnings) = crate::io::open_bytes("book.json", file.to_string().as_bytes()).unwrap(); + assert_eq!(*wb.macros_unread, [newer("Kept")]); + assert_eq!(warnings.len(), 2, "one kept, one left out: {warnings:?}"); + wb.names.push(visible("_gc_macro_1_0")); + let (raw, back) = { + let bytes = crate::io::save_bytes(&wb, "book.xlsx").unwrap(); + let raw = names_of(&gridcraft_xlsx::read_xlsx(&bytes).unwrap().0); + (raw, crate::io::open_bytes("book.xlsx", &bytes).unwrap().0) + }; + assert_eq!(raw, ["_gc_macro_1_0", "_gc_macro_0_0", "_gc_macro_2_0"]); + assert_eq!((back.macros.len(), back.macros_unread.len()), (1, 1)); + // Past the limit the rest are left out; and when a JSON file's list is full, an unread item + // it also holds in hidden names is the one left out: readable macros come first. + list = (0..MAX_MACROS).map(|i| json!({"name": format!("M{i}")})).collect(); + let mut with_item = Workbook::new(); + with_item.names.push(hidden("_gc_macro_0_0", &newer("InNames").to_string())); + let mut file: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&with_item, "book.json").unwrap()).unwrap(); + for extra in [None, Some(newer("Over"))] { + file["macros"] = json!(list.iter().cloned().chain(extra).collect::>()); + let (wb, warnings) = crate::io::open_bytes("book.json", file.to_string().as_bytes()).unwrap(); + assert_eq!((wb.macros.len(), wb.macros_unread.len()), (MAX_MACROS, 0)); + assert!(warnings.len() == 1 && warnings[0].contains("couldn't be opened"), "{warnings:?}"); + } +} + +#[test] +fn many_macros_with_one_name_all_survive_save_and_reopen() { + // MAX_MACROS macros with the same name, at the length limit, so the suffixes run from " (2)" + // to " (1000)" and the kept part of the name shrinks as they widen. + let long = "é".repeat(MAX_MACRO_NAME); + for file in ["same.json", "same.xlsx"] { + let mut wb = Workbook::new(); + wb.macros = (0..MAX_MACROS).map(|i| Macro { name: long.clone(), description: format!("{i}"), ..Macro::default() }).collect(); + let (first, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(&wb, file).unwrap()).unwrap(); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + assert_eq!(first.macros.len(), MAX_MACROS, "{file}"); + let names: std::collections::HashSet = first.macros.iter().map(|m| m.name.to_lowercase()).collect(); + assert_eq!(names.len(), MAX_MACROS, "{file}: every name is different"); + assert!(first.macros.iter().all(|m| m.name.chars().count() <= MAX_MACRO_NAME && m.check_limits().is_ok()), "{file}"); + assert_eq!(first.macros[0].name, long); + assert_eq!(first.macros[9].name, format!("{} (10)", "é".repeat(MAX_MACRO_NAME - 5))); + assert_eq!(first.macros[MAX_MACROS - 1].name, format!("{} (1000)", "é".repeat(MAX_MACRO_NAME - 7))); + assert!(first.macros.iter().enumerate().all(|(i, m)| m.description == format!("{i}")), "{file}: order kept"); + let (again, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(&first, file).unwrap()).unwrap(); + assert!(warnings.is_empty(), "{file}: {warnings:?}"); + assert_eq!(again.macros, first.macros, "{file}"); + } +} + +#[test] +fn naming_clashing_macros_takes_linear_work() { + // Each suffix is looked up about once, not once per earlier macro with the same name. + let mut taken = Taken::default(); + // Names a file may already use, in the way of the first suffixes. + for n in 2..=500 { + taken.insert(&format!("Same ({n})")); + } + let mut out = Vec::new(); + for _ in 0..MAX_MACROS { + let name = taken.unique("SAME"); + taken.insert(&name); + out.push(name); + } + assert_eq!(out[..3], ["SAME", "SAME (501)", "SAME (502)"]); + assert!(taken.probes <= 3 * MAX_MACROS, "{} lookups", taken.probes); + // The smallest free suffix is still the one used. + let mut taken = Taken::default(); + for name in ["A", "A (3)"] { + taken.insert(name); + } + assert_eq!(taken.unique("a"), "a (2)"); + taken.insert("a (2)"); + assert_eq!(taken.unique("a"), "a (4)"); +} + +#[test] +fn a_json_workbook_with_no_sheets_keeps_its_macros() { + // A JSON file with an empty sheet list opens as a new workbook; its macros come along. + let mut wb = Workbook::new(); + wb.macros.push(sample_macro("A")); + let mut v: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&wb, "book.json").unwrap()).unwrap(); + v["sheets"] = json!([]); + let (back, warnings) = crate::io::open_bytes("book.json", v.to_string().as_bytes()).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.sheets.len(), 1); + assert_eq!(back.macros, wb.macros); +} + +fn long(n: usize) -> String { + "x".repeat(n) +} + +/// `sample_macro` as JSON with `change` made to it. +fn changed(change: fn(&mut serde_json::Value)) -> serde_json::Value { + let mut v = macro_json(&sample_macro("T")); + change(&mut v); + v +} + +#[test] +fn every_field_a_file_sets_has_a_limit() { + // A named edit to the sample file's JSON. + type Edit = (&'static str, fn(&mut serde_json::Value)); + // The sample's steps: 0 a command, 1 a Repeat whose body holds an If whose else holds a Stop. + let refused: [Edit; 14] = [ + ("shortcut", |v| v["shortcut"] = json!(long(MAX_MACRO_SHORTCUT + 1))), + ("shortcut line break", |v| v["shortcut"] = json!("Ctrl+\nM")), + ("permission count", |v| v["permissions"] = json!(vec!["data.getData"; MAX_MACRO_PERMISSIONS + 1])), + ("permission text", |v| v["permissions"] = json!(["data getData"])), + ("output anchor", |v| v["output"]["anchor"] = json!(long(MAX_MACRO_REF + 1))), + ("default range", |v| v["inputs"][0]["defaultRef"] = json!(long(MAX_MACRO_REF + 1))), + ("column types", |v| { + v["inputs"][0]["cols"] = json!([1, 0]); + v["inputs"][0]["colTypes"] = json!(vec!["any"; MAX_MACRO_COLUMNS + 1]); + }), + ("command id", |v| v["steps"][0]["id"] = json!("cell set")), + ("empty command id", |v| v["steps"][0]["id"] = json!("")), + ("Repeat range", |v| v["steps"][1]["over"] = json!(long(MAX_MACRO_REF + 1))), + ("If cell", |v| v["steps"][1]["body"][0]["cell"] = json!(long(MAX_MACRO_REF + 1))), + // As JSON the string takes its two quotes as well. + ("If value", |v| v["steps"][1]["body"][0]["value"] = json!(long(MAX_MACRO_TEXT - 1))), + ("Stop message", |v| v["steps"][1]["body"][0]["else"][0]["message"] = json!(long(MAX_MACRO_TEXT + 1))), + ("Stop message, nested", |v| v["steps"][1]["body"][0]["else"][0]["message"] = json!(long(MAX_MACRO_TEXT * 2))), + ]; + for (what, change) in refused { + assert!(parse_macro(&changed(change)).is_err(), "{what} past its limit is refused"); + } + let accepted: [Edit; 9] = [ + ("shortcut", |v| v["shortcut"] = json!(long(MAX_MACRO_SHORTCUT))), + ("permission count", |v| v["permissions"] = json!(vec!["data.getData"; MAX_MACRO_PERMISSIONS])), + ("output anchor", |v| v["output"]["anchor"] = json!(long(MAX_MACRO_REF))), + ("column types", |v| { + v["inputs"][0]["cols"] = json!([1, 0]); + v["inputs"][0]["colTypes"] = json!(vec!["any"; MAX_MACRO_COLUMNS]); + }), + ("If value", |v| v["steps"][1]["body"][0]["value"] = json!(long(MAX_MACRO_TEXT - 2))), + // Empty and NotEmpty ignore the value, which is then left out (null). + ("If with no value", |v| { + v["steps"][1]["body"][0]["op"] = json!("empty"); + v["steps"][1]["body"][0].as_object_mut().unwrap().remove("value"); + }), + // How many times a Repeat may run is the runner's to bound, not the format's. + ("Repeat max", |v| v["steps"][1]["max"] = json!(u32::MAX)), + ("Stop message", |v| v["steps"][1]["body"][0]["else"][0]["message"] = json!(long(MAX_MACRO_TEXT))), + ("no shortcut", |v| { + v.as_object_mut().unwrap().remove("shortcut"); + }), + ]; + for (what, change) in accepted { + assert!(parse_macro(&changed(change)).is_ok(), "{what} at its limit is accepted"); + } + // Every command there is passes as a step and as a permission. + for spec in crate::command_specs() { + let m = json!({"name": "T", "steps": [{"command": spec.id}], "permissions": [spec.id]}); + assert!(parse_macro(&m).is_ok(), "{}", spec.id); + } +} + +#[test] +fn an_input_declaration_is_checked_as_a_whole() { + let input = |i: serde_json::Value| json!({"name": "T", "inputs": [i]}); + for i in [ + json!({"name": "Input", "rows": [5, 2]}), + json!({"name": "Input", "cols": [3, 2]}), + json!({"name": "Input", "kind": "cell", "cols": [2, 5]}), + json!({"name": "Input", "kind": "cell", "rows": [0, 0]}), + json!({"name": "Input", "kind": "cell", "header": true}), + json!({"name": "Input", "kind": "cell", "colTypes": ["number", "text"]}), + json!({"name": "Input", "cols": [2, 2], "colTypes": ["number", "text", "any"]}), + ] { + assert!(parse_macro(&input(i.clone())).is_err(), "{i}"); + } + for i in [ + json!({"name": "Input", "rows": [5, 0]}), + json!({"name": "Input", "rows": [2, 2], "cols": [0, 3]}), + json!({"name": "Input", "kind": "cell"}), + json!({"name": "Input", "kind": "cell", "rows": [1, 1], "cols": [1, 1], "colTypes": ["number"]}), + json!({"name": "Input", "cols": [1, 2], "colTypes": ["number", "text"]}), + ] { + assert!(parse_macro(&input(i.clone())).is_ok(), "{i}"); + } + // From a file, a macro whose declaration fails is left out with the usual warning, and the + // workbook's other macros open. + let mut file: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&Workbook::new(), "book.json").unwrap()).unwrap(); + file["macros"] = json!([input(json!({"name": "Input", "rows": [5, 2]})), {"name": "Fine"}]); + let (wb, warnings) = crate::io::open_bytes("book.json", file.to_string().as_bytes()).unwrap(); + assert_eq!(wb.macros.iter().map(|m| m.name.as_str()).collect::>(), ["Fine"]); + assert_eq!(warnings.len(), 1, "{warnings:?}"); +} + +#[test] +fn the_storage_rules_hold_together_through_both_formats() { + // A visible name of the storage shape, a macro in a newer format and one whose input breaks + // the declaration rules, in one file, saved and opened again in each format and then the + // other: the visible name stays, the newer macro comes back whole, the broken one is left out + // once, and the readable one survives. + let newer = json!({"name": "Kept", "v": MACRO_VERSION + 1, "fromALaterBuild": true}); + let broken = json!({"name": "Broken", "inputs": [{"name": "Input", "rows": [5, 2]}]}); + let mut start = Workbook::new(); + start.names.push(visible("_gc_macro_0_0")); + let mut file: serde_json::Value = serde_json::from_slice(&crate::io::save_bytes(&start, "book.json").unwrap()).unwrap(); + file["macros"] = json!([newer, broken, {"name": "Good"}]); + let (wb, warnings) = crate::io::open_bytes("book.json", file.to_string().as_bytes()).unwrap(); + assert_eq!(warnings.len(), 2, "one kept, one left out: {warnings:?}"); + let expect = |wb: &Workbook, how: &str| { + assert_eq!(wb.macros.iter().map(|m| m.name.as_str()).collect::>(), ["Good"], "{how}"); + assert_eq!(*wb.macros_unread, std::slice::from_ref(&newer), "{how}"); + assert_eq!(names_of(wb), ["_gc_macro_0_0"], "{how}"); + }; + expect(&wb, "opened"); + for formats in [["book.xlsx", "book.json"], ["book.json", "book.xlsx"]] { + let mut now = wb.clone(); + for file in formats { + let (back, warnings) = crate::io::open_bytes(file, &crate::io::save_bytes(&now, file).unwrap()).unwrap(); + assert_eq!(warnings.len(), 1, "{file}: only the kept macro is reported again: {warnings:?}"); + expect(&back, file); + now = back; + } + } + let bytes = crate::io::save_bytes(&wb, "book.xlsx").unwrap(); + assert_eq!(names_of(&gridcraft_xlsx::read_xlsx(&bytes).unwrap().0), ["_gc_macro_0_0", "_gc_macro_1_0", "_gc_macro_2_0"]); +} diff --git a/crates/engine/src/paper.rs b/crates/engine/src/paper.rs index 0800f4fc76..99981fc8cb 100644 --- a/crates/engine/src/paper.rs +++ b/crates/engine/src/paper.rs @@ -10,7 +10,7 @@ //! `(gap + j·(page_w + gap), gap + i·(page_h + gap))`, and its cells start at its top-left margin. use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; -use gridcraft_model::{LineIndex, Sheet, Workbook}; +use gridcraft_model::{LineIndex, PageOrder, Sheet, Workbook}; use crate::cmd::print::{self, PX_TO_PT, PrintOptions}; @@ -45,6 +45,8 @@ pub struct PageGrid { /// Bands holding printed data: `[first, last]` row bands and column bands. pub data_rows: (usize, usize), pub data_cols: (usize, usize), + /// The sheet's page order, which numbers the printed pages. + pub page_order: PageOrder, ri: LineIndex, ci: LineIndex, } @@ -96,6 +98,7 @@ impl PageGrid { col_bands, data_rows, data_cols, + page_order: printed.settings.page_order, ri: LineIndex::new(&sh.rows, sh.default_row_height, MAX_ROWS), ci: LineIndex::new(&sh.cols, sh.default_col_width, MAX_COLS), }) @@ -206,14 +209,14 @@ impl PageGrid { pub fn is_data_page(&self, i: usize, j: usize) -> bool { (self.data_rows.0..=self.data_rows.1).contains(&i) && (self.data_cols.0..=self.data_cols.1).contains(&j) } - /// Printed page number of page `(i, j)` (down, then over) and the printed page count. + /// Printed page number of page `(i, j)` (in the sheet's page order) and the printed page count. pub fn page_number(&self, i: usize, j: usize) -> Option<(usize, usize)> { if !self.is_data_page(i, j) { return None; } let rows = self.data_rows.1 - self.data_rows.0 + 1; let cols = self.data_cols.1 - self.data_cols.0 + 1; - Some(((j - self.data_cols.0) * rows + (i - self.data_rows.0) + 1, rows * cols)) + Some((self.page_order.index(i - self.data_rows.0, j - self.data_cols.0, rows, cols) + 1, rows * cols)) } /// Page rows and columns overlapping the layout rectangle `[x0, x1] × [y0, y1]`. @@ -312,6 +315,21 @@ mod tests { assert!(g.is_data_page(0, 0) && !g.is_data_page(1, 0)); } + #[test] + fn page_numbers_follow_the_page_order() { + // Two pages tall and two wide, as printed; the pages beyond are "Click to add data" pages. + let mut wb = wb_with(60, 15); + let numbers = |wb: &Workbook| { + let g = PageGrid::build(wb, 0, 200, 60).unwrap(); + assert_eq!((g.data_rows, g.data_cols), ((0, 1), (0, 1))); + assert_eq!((g.page_number(2, 0), g.page_number(0, 2)), (None, None)); + [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(i, j)| g.page_number(i, j).unwrap()) + }; + assert_eq!(numbers(&wb), [(1, 4), (2, 4), (3, 4), (4, 4)]); + wb.sheet_mut(0).unwrap().print.page_order = PageOrder::OverThenDown; + assert_eq!(numbers(&wb), [(1, 4), (3, 4), (2, 4), (4, 4)]); + } + #[test] fn header_zones_and_text_follow_scale_with_document_and_align_with_page_margins() { let mut wb = wb_with(10, 3); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index a074f57298..bfaccace47 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -18,6 +18,21 @@ use gridcraft_model::{ use crate::pivot_calc::CalcSet; +mod charts; +mod compute; +mod items; +mod output; + +use charts::rebind_charts; +pub use charts::{chart_link, chart_series, clear_output, links_to, parse_chart_link}; +use compute::compute_from; +pub use compute::{NOT_A_VALUE_CELL, detail_cells, detail_records}; +pub use items::{distinct_labels, func_caption, item_label}; +#[cfg(test)] +use output::data_cols_exceed_sheet; +pub use output::{CellKind, OutCell, Output, RowKind}; +use output::{cell_style, look}; + /// Largest source block read (cells). pub const MAX_SOURCE_CELLS: u64 = 10_000_000; /// Largest report written (cells). @@ -171,1267 +186,12 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result, - index: HashMap, -} - -fn cmp_items(a: &Item, b: &Item) -> Ordering { - a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| a.text.cmp(&b.text)) -} - -/// (identity key, item) for a source value under a field's date grouping. -fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) { - let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item { - text: label.to_lowercase(), - value, - label, - class, - num, - first, - formatted, - }; - match v { - Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)), - Value::Number(n) => { - if group != PivotDateGroup::None - && let Some(dt) = datetime_from_serial(wb.date_system, *n) - { - let mon = MONTHS.get(dt.month.saturating_sub(1) as usize).copied().unwrap_or("Jan"); - let (label, key) = match group { - PivotDateGroup::Years => (dt.year.to_string(), dt.year as f64), - PivotDateGroup::Quarters => { - let q = (dt.month.saturating_sub(1)) / 3 + 1; - (format!("Qtr{q}"), q as f64) - } - PivotDateGroup::Months => (mon.to_string(), dt.month as f64), - _ => (format!("{}-{mon}", dt.day), (dt.month * 100 + dt.day) as f64), - }; - return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); - } - let label = crate::display::format(v, fmt, wb).text; - (format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true)) - } - Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), - Value::Bool(b) => { - let l = if *b { "TRUE" } else { "FALSE" }; - (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) - } - Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), - Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), - } -} - -impl FieldItems { - fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 { - let (key, item) = make_item(wb, v, group, fmt, first); - if let Some(i) = self.index.get(&key) { - return *i; - } - let i = self.items.len() as u32; - self.items.push(item); - self.index.insert(key, i); - i - } - fn get(&self, i: u32) -> Option<&Item> { - self.items.get(i as usize) - } - fn label(&self, i: u32) -> String { - self.get(i).map(|x| x.label.clone()).unwrap_or_default() - } -} - -/// The label of a source value under a date grouping (for filters and field lists). -pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String { - make_item(wb, v, group, fmt, 0).1.label -} - -/// Distinct item labels of a source column, sorted like the field list shows them. -pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec { - let mut fi = FieldItems::default(); - let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General"); - for (i, r) in src.rows.iter().enumerate() { - if let Some(v) = r.get(col) { - fi.intern(wb, v, group, fmt, i); - } - if fi.items.len() > 100_000 { - break; - } - } - let mut items = fi.items; - items.sort_by(cmp_items); - items.into_iter().take(limit).map(|i| i.label).collect() -} - -// ---------------------------------------------------------------- aggregation - -#[derive(Clone, Debug, Default)] -struct Acc { - count: u64, - nums: u64, - sum: f64, - prod: f64, - min: f64, - max: f64, - mean: f64, - m2: f64, - err: Option, -} - -impl Acc { - fn add(&mut self, v: &Value) { - match v { - Value::Empty => {} - Value::Number(n) => { - let n = *n; - self.count += 1; - self.nums += 1; - self.sum += n; - if self.nums == 1 { - self.prod = n; - self.min = n; - self.max = n; - } else { - self.prod *= n; - self.min = self.min.min(n); - self.max = self.max.max(n); - } - let d = n - self.mean; - self.mean += d / self.nums as f64; - self.m2 += d * (n - self.mean); - } - Value::Error(e) => { - self.count += 1; - if self.err.is_none() { - self.err = Some(*e); - } - } - _ => self.count += 1, - } - } - fn result(&self, f: PivotFunc) -> Value { - let n = self.nums as f64; - match f { - PivotFunc::Count => return Value::number(self.count as f64), - PivotFunc::CountNumbers => return Value::number(n), - _ => {} - } - if let Some(e) = self.err { - return Value::Error(e); - } - let div0 = Value::Error(CellError::Div0); - match f { - PivotFunc::Sum => Value::number(self.sum), - PivotFunc::Average => { - if self.nums == 0 { - div0 - } else { - Value::number(self.sum / n) - } - } - PivotFunc::Max => Value::number(if self.nums == 0 { 0.0 } else { self.max }), - PivotFunc::Min => Value::number(if self.nums == 0 { 0.0 } else { self.min }), - PivotFunc::Product => Value::number(if self.nums == 0 { 0.0 } else { self.prod }), - PivotFunc::StdDev | PivotFunc::Var => { - if self.nums < 2 { - div0 - } else { - let var = (self.m2 / (n - 1.0)).max(0.0); - Value::number(if f == PivotFunc::Var { var } else { var.sqrt() }) - } - } - PivotFunc::StdDevP | PivotFunc::VarP => { - if self.nums < 1 { - div0 - } else { - let var = (self.m2 / n).max(0.0); - Value::number(if f == PivotFunc::VarP { var } else { var.sqrt() }) - } - } - PivotFunc::Count | PivotFunc::CountNumbers => Value::Empty, - } - } -} - -/// Excel's caption verb for a function ("Sum of Sales"). -pub fn func_caption(f: PivotFunc) -> &'static str { - match f { - PivotFunc::Sum => "Sum", - PivotFunc::Count => "Count", - PivotFunc::Average => "Average", - PivotFunc::Max => "Max", - PivotFunc::Min => "Min", - PivotFunc::Product => "Product", - PivotFunc::CountNumbers => "Count Numbers", - PivotFunc::StdDev => "StdDev", - PivotFunc::StdDevP => "StdDevp", - PivotFunc::Var => "Var", - PivotFunc::VarP => "Varp", - } -} - -// ---------------------------------------------------------------- trees - -#[derive(Clone, Debug)] -struct Node { - item: u32, - children: Vec, -} - -fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec { - let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] }; - let mut order: Vec = Vec::new(); - let mut groups: HashMap> = HashMap::new(); - for p in paths { - if let Some(&it) = p.get(depth) { - let g = groups.entry(it).or_default(); - if g.is_empty() { - order.push(it); - } - g.push(p); - } - } - let mut nodes: Vec = order - .into_iter() - .map(|it| { - let ps = groups.remove(&it).unwrap_or_default(); - Node { item: it, children: build_tree(&ps, depth + 1, fields, items) } - }) - .collect(); - let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { - (Some(x), Some(y)) => match field.sort { - PivotSort::Asc => cmp_items(x, y), - PivotSort::Desc => cmp_items(y, x), - PivotSort::None => x.first.cmp(&y.first), - }, - _ => Ordering::Equal, - }; - nodes.sort_by(by); - nodes -} - -fn is_collapsed(field: &PivotField, label: &str) -> bool { - field.collapsed_items.iter().any(|c| c.eq_ignore_ascii_case(label)) -} - -fn collect_siblings(nodes: &[Node], prefix: &mut Vec, out: &mut HashMap, Vec>) { - out.insert(prefix.clone(), nodes.iter().map(|n| n.item).collect()); - for n in nodes { - prefix.push(n.item); - collect_siblings(&n.children, prefix, out); - prefix.pop(); - } -} - -// ---------------------------------------------------------------- output - -/// What a report cell is. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] -pub enum CellKind { - Empty, - Header, - RowLabel, - ColLabel, - Data, - Subtotal, - GrandTotal, - Filter, - Placeholder, -} - -/// What a report row is (for row-wide styling). -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] -pub enum RowKind { - Filter, - Blank, - Header, - /// Item row; `true` for a parent item (bold). - Item(bool), - Subtotal, - Grand, - Placeholder, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct OutCell { - pub value: Value, - pub kind: CellKind, - pub indent: u8, - pub num_fmt: Option, -} - -impl OutCell { - fn empty() -> OutCell { - OutCell { value: Value::Empty, kind: CellKind::Empty, indent: 0, num_fmt: None } - } -} - -/// A computed report: a dense grid relative to its top-left, with row kinds. -#[derive(Clone, Debug)] -pub struct Output { - pub grid: Vec>, - pub row_kinds: Vec, - /// Rows above the body (report filters plus a blank row). - pub body_offset: u32, - pub width: u32, - /// Grid rows of the innermost (or collapsed) items: a PivotChart's categories. - pub chart_rows: Vec, - /// Grid columns of item (not total) values with their series names: a PivotChart's series. - pub chart_cols: Vec<(u32, String)>, - /// Grid column holding the innermost row labels (`None` without row fields). - pub label_col: Option, -} - -impl Output { - pub fn height(&self) -> u32 { - self.grid.len() as u32 - } - /// Value at (row, col) relative to the top-left. - pub fn value(&self, r: usize, c: usize) -> Value { - self.grid.get(r).and_then(|row| row.get(c)).map(|x| x.value.clone()).unwrap_or_default() - } -} - -struct Grid { - rows: Vec>, - kinds: Vec, - width: usize, -} - -impl Grid { - fn push_row(&mut self, kind: RowKind) -> Result { - if (self.rows.len() as u64 + 1) * self.width.max(1) as u64 > MAX_OUTPUT_CELLS || self.rows.len() as u64 >= MAX_ROWS as u64 { - return Err("The PivotTable report is too large.".into()); - } - self.rows.push(vec![OutCell::empty(); self.width]); - self.kinds.push(kind); - Ok(self.rows.len() - 1) - } - fn set(&mut self, r: usize, c: usize, value: Value, kind: CellKind, indent: u8, fmt: Option) { - if let Some(cell) = self.rows.get_mut(r).and_then(|row| row.get_mut(c)) { - *cell = OutCell { value, kind, indent, num_fmt: fmt }; - } - } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum LineKind { - Item(bool), - Subtotal, - Grand, -} - -struct Line { - kind: LineKind, - /// A category of a PivotChart: an innermost (or collapsed) item. - leaf: bool, - path: Vec, - values: bool, - /// (column, value, indent, number format) - labels: Vec<(usize, Value, u8, Option)>, - /// The value field of the line when Σ Values sits in Rows (`None`: one per data column). - vi: Option, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum ColKind { - Leaf, - Subtotal, - Grand, -} - -struct ColSpec { - kind: ColKind, - path: Vec, -} - -struct Ctx<'a> { - pt: &'a PivotTable, - rows: Vec<&'a PivotField>, - row_items: Vec, - row_fmts: Vec, - /// Depth of Σ Values among the row fields when it sits in Rows (two or more value fields). - vpos: Option, - /// Value field captions. - val_names: Vec, -} - -impl Ctx<'_> { - fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String) { - let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) }; - let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None }; - (it.value.clone(), fmt, it.label.clone()) - } - - /// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form. - fn level_cell(&self, level: usize) -> (usize, u8) { - if self.pt.layout == PivotLayout::Outline { (level, 0) } else { (0, level.min(250) as u8) } - } - - /// Σ Values comes right here, at row field depth `depth` (`vi`: the value field already chosen above). - fn values_here(&self, depth: usize, vi: Option) -> bool { - vi.is_none() && self.vpos == Some(depth) - } - - /// Per-value subtotal lines of an item with Σ Values below it ("East Sum of Sales"). - fn value_subtotals(&self, col: usize, indent: u8, label: &str, prefix: &[u32], out: &mut Vec) { - for (vi, name) in self.val_names.iter().enumerate() { - out.push(Line { - kind: LineKind::Subtotal, - leaf: false, - path: prefix.to_vec(), - values: true, - labels: vec![(col, Value::text(format!("{label} {name}")), indent, None)], - vi: Some(vi), - }); - } - } - - /// The Σ Values level at row field depth `depth`: one item per value field, each followed by - /// the row fields below it (`nodes`) or, innermost, holding that value. - fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, out: &mut Vec) { - let (col, indent) = self.level_cell(depth); - for (vi, name) in self.val_names.iter().enumerate() { - let labels = vec![(col, Value::text(name.as_str()), indent, None)]; - let leaf = nodes.is_empty(); - out.push(Line { kind: LineKind::Item(!leaf), leaf, path: prefix.clone(), values: leaf, labels, vi: Some(vi) }); - if !leaf { - self.flatten(nodes, depth, Some(vi), prefix, out); - } - } - } - - fn flatten(&self, nodes: &[Node], depth: usize, vi: Option, prefix: &mut Vec, out: &mut Vec) { - if self.values_here(depth, vi) { - self.flatten_values(nodes, depth, prefix, out); - return; - } - let n = self.rows.len(); - // Σ Values still to come below this level: totals need one line per value field. - let values_below = vi.is_none() && self.vpos.is_some(); - let (col, indent) = self.level_cell(depth + usize::from(vi.is_some() && self.vpos.is_some())); - for node in nodes { - prefix.push(node.item); - let (v, fmt, label) = self.label_cell(depth, node.item); - let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label)); - let leaf = depth + 1 >= n || collapsed || node.children.is_empty(); - if leaf && !values_below { - out.push(Line { - kind: LineKind::Item(depth + 1 < n), - leaf: true, - path: prefix.clone(), - values: true, - labels: vec![(col, v, indent, fmt)], - vi, - }); - } else if leaf { - out.push(Line { - kind: LineKind::Item(true), - leaf: false, - path: prefix.clone(), - values: false, - labels: vec![(col, v, indent, fmt)], - vi, - }); - // Outline gives each level its own column, so the captions go in the Values - // column even when the levels between are collapsed away. - let level = if self.pt.layout == PivotLayout::Outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 }; - self.flatten_values(&[], level, prefix, out); - } else if values_below { - // Subtotals per value field, below the group (one line can't hold them all). - out.push(Line { - kind: LineKind::Item(true), - leaf: false, - path: prefix.clone(), - values: false, - labels: vec![(col, v, indent, fmt)], - vi, - }); - self.flatten(&node.children, depth + 1, None, prefix, out); - if self.pt.subtotals { - self.value_subtotals(col, indent, &label, prefix, out); - } - } else { - let top = self.pt.subtotals && self.pt.subtotals_top; - out.push(Line { - kind: LineKind::Item(true), - leaf: false, - path: prefix.clone(), - values: top, - labels: vec![(col, v, indent, fmt)], - vi, - }); - self.flatten(&node.children, depth + 1, vi, prefix, out); - if self.pt.subtotals && !self.pt.subtotals_top { - out.push(Line { - kind: LineKind::Subtotal, - leaf: false, - path: prefix.clone(), - values: true, - labels: vec![(col, Value::text(format!("{label} Total")), indent, None)], - vi, - }); - } - } - prefix.pop(); - } - } - - /// Tabular form of [`Self::flatten_values`]: the first line also carries the parents' labels. - fn flatten_tabular_values( - &self, - nodes: &[Node], - depth: usize, - prefix: &mut Vec, - pending: &[(usize, Value, u8, Option)], - out: &mut Vec, - ) { - for (vi, name) in self.val_names.iter().enumerate() { - let mut labels: Vec<(usize, Value, u8, Option)> = if vi == 0 { pending.to_vec() } else { vec![] }; - labels.push((depth, Value::text(name.as_str()), 0, None)); - if nodes.is_empty() { - out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi: Some(vi) }); - } else { - self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, out); - } - } - } - - fn flatten_tabular( - &self, - nodes: &[Node], - depth: usize, - vi: Option, - prefix: &mut Vec, - pending: &[(usize, Value, u8, Option)], - out: &mut Vec, - ) { - if self.values_here(depth, vi) { - self.flatten_tabular_values(nodes, depth, prefix, pending, out); - return; - } - let n = self.rows.len(); - let values_below = vi.is_none() && self.vpos.is_some(); - let col = depth + usize::from(vi.is_some() && self.vpos.is_some()); - for (i, node) in nodes.iter().enumerate() { - prefix.push(node.item); - let (v, fmt, label) = self.label_cell(depth, node.item); - let mut labels: Vec<(usize, Value, u8, Option)> = if i == 0 { pending.to_vec() } else { vec![] }; - labels.push((col, v, 0, fmt)); - let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label)); - if depth + 1 >= n || collapsed || node.children.is_empty() { - if values_below { - self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out); - } else { - out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi }); - } - } else { - self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, out); - if self.pt.subtotals && values_below { - self.value_subtotals(col, 0, &label, prefix, out); - } else if self.pt.subtotals { - out.push(Line { - kind: LineKind::Subtotal, - leaf: false, - path: prefix.clone(), - values: true, - labels: vec![(col, Value::text(format!("{label} Total")), 0, None)], - vi, - }); - } - } - prefix.pop(); - } - } -} - -fn flatten_cols( - nodes: &[Node], - depth: usize, - fields: &[&PivotField], - items: &[FieldItems], - subtotals: bool, - prefix: &mut Vec, - out: &mut Vec, -) { - let n = fields.len(); - for node in nodes { - prefix.push(node.item); - let label = items.get(depth).map(|fi| fi.label(node.item)).unwrap_or_default(); - let collapsed = depth + 1 < n && fields.get(depth).is_some_and(|f| is_collapsed(f, &label)); - if depth + 1 >= n || collapsed || node.children.is_empty() { - out.push(ColSpec { kind: ColKind::Leaf, path: prefix.clone() }); - } else { - flatten_cols(&node.children, depth + 1, fields, items, subtotals, prefix, out); - if subtotals { - out.push(ColSpec { kind: ColKind::Subtotal, path: prefix.clone() }); - } - } - prefix.pop(); - } -} - -type AggMap = HashMap<(Vec, Vec), Vec>; - -/// Where a value field's numbers come from. -#[derive(Clone, Copy)] -enum ValSrc { - /// A source column. - Col(usize), - /// A calculated field (index into the PivotTable's calculated fields). - Calc(usize), -} - -/// True when `col_groups` distinct column leaves (plus the grand-total column) times `values` value fields -/// (at least one data column per group) already exceed the sheet width. This is a lower bound on the final column count. -fn data_cols_exceed_sheet(col_groups: usize, grand_total: bool, values: usize) -> bool { - (col_groups + usize::from(grand_total)).saturating_mul(values.max(1)) > MAX_COLS as usize -} - /// Computes a PivotTable report from the workbook. pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result { let src = read_source(wb, &pt.source, pivot_sheet)?; compute_from(wb, pt, &src, None) } -/// Why Show Details turns a cell down when it isn't a value cell of a PivotTable (the front end -/// edits that cell instead). -pub const NOT_A_VALUE_CELL: &str = "select a value cell in a PivotTable"; - -/// Show Details: the source list and the indices of its records behind the value cell at -/// (`row`, `col`) of the report grid (relative to its top-left), in source order. `None` when -/// that cell holds no value (a label, a header, a blank). An error, for any cell, when the report -/// on the sheet is no longer what the source computes: the cell's records would be another cell's. -pub fn detail_records(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize, row: u32, col: u32) -> Result)>, String> { - let src = read_source(wb, &pt.source, pivot_sheet)?; - let mut probe = Probe { at: Some((row as usize, col as usize)), hit: None, paths: Some(Vec::new()), cells: None }; - let out = compute_from(wb, pt, &src, Some(&mut probe))?; - // Checked first: in a stale report even a cell that computes as a label may show a value. - check_current(wb, pt, pivot_sheet, &out)?; - let Some((rp, cp)) = probe.hit else { return Ok(None) }; - let records = - probe.paths.unwrap_or_default().into_iter().filter(|(_, r, c)| r.starts_with(&rp) && c.starts_with(&cp)).map(|(i, _, _)| i).collect(); - Ok(Some((src, records))) -} - -/// The cells of the report grid (relative to its top-left) where [`detail_records`] finds -/// records: its value, subtotal and grand total cells, from one computation of the report. The -/// same errors as [`detail_records`]. -pub fn detail_cells(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result, String> { - let src = read_source(wb, &pt.source, pivot_sheet)?; - let mut probe = Probe { at: None, hit: None, paths: None, cells: Some(HashSet::new()) }; - let out = compute_from(wb, pt, &src, Some(&mut probe))?; - check_current(wb, pt, pivot_sheet, &out)?; - Ok(probe.cells.unwrap_or_default().into_iter().map(|(r, c)| (r as u32, c as u32)).collect()) -} - -/// An error when the report on the sheet is not what `out` computes. Excel reads its PivotTable -/// cache; without one, the report written by the last refresh must still be what the source gives. -fn check_current(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize, out: &Output) -> Result<(), String> { - let sh = wb.sheet(pivot_sheet).ok_or("There's no such sheet.")?; - let current = pt.last_range.is_some_and(|r| { - r.height() == out.height().max(1) - && r.width() == out.width.max(1) - && out.grid.iter().enumerate().all(|(ri, line)| { - line.iter().enumerate().all(|(ci, oc)| { - sh.value_ref(CellRef::new(r.start.row + ri as u32, r.start.col + ci as u32)).unwrap_or(&Value::Empty) == &oc.value - }) - }) - }); - if !current { - return Err("The PivotTable report is out of date. Refresh it first.".into()); - } - Ok(()) -} - -/// What [`detail_records`] and [`detail_cells`] ask of a report computation: the row and column -/// item paths of the value cell at `at`, the paths of every record the filters let through (when -/// `paths` is set), and every value cell (when `cells` is set). -struct Probe { - at: Option<(usize, usize)>, - hit: Option<(Vec, Vec)>, - paths: Option, Vec)>>, - cells: Option>, -} - -fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut probe: Option<&mut Probe>) -> Result { - let fmt_of = |c: usize| src.formats.get(c).cloned().unwrap_or_else(|| "General".into()); - let rows: Vec<(usize, &PivotField)> = pt.rows.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect(); - let cols: Vec<(usize, &PivotField)> = pt.columns.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect(); - // Value fields: a source column, or a calculated field evaluated on sums (see `pivot_calc`). - let calc = CalcSet::new(pt, &src.headers); - let vals: Vec<(ValSrc, &PivotValue)> = pt - .values - .iter() - .filter_map(|v| match src.col(&v.source_col) { - Some(c) => Some((ValSrc::Col(c), v)), - None => calc.index(&v.source_col).map(|i| (ValSrc::Calc(i), v)), - }) - .collect(); - // Source columns summed for the calculated fields, accumulated after the value fields. - let mut extra: Vec = Vec::new(); - for (vs, _) in &vals { - if let ValSrc::Calc(i) = vs { - for name in calc.source_refs(*i) { - if let Some(c) = src.col(&name) - && !extra.contains(&c) - { - extra.push(c); - } - } - } - } - if rows.len() + cols.len() > MAX_AXIS_FIELDS { - return Err(format!("A PivotTable can have at most {MAX_AXIS_FIELDS} row and column fields.")); - } - if vals.len() > MAX_VALUE_FIELDS { - return Err(format!("A PivotTable can have at most {MAX_VALUE_FIELDS} value fields.")); - } - let axis_group = |name: &str| -> Option { - pt.rows.iter().chain(pt.columns.iter()).find(|f| f.source_col.eq_ignore_ascii_case(name)).map(|f| f.date_group) - }; - // (column, filter, grouping used for labels, shown as a report filter) - let filters: Vec<(usize, &PivotFilter, PivotDateGroup, bool)> = pt - .filters - .iter() - .filter_map(|f| { - let c = src.col(&f.source_col)?; - let g = axis_group(&f.source_col); - Some((c, f, g.unwrap_or_default(), g.is_none())) - }) - .collect(); - let shown_filters: Vec<&(usize, &PivotFilter, PivotDateGroup, bool)> = filters.iter().filter(|f| f.3).collect(); - - let k = vals.len(); - let empty = rows.is_empty() && cols.is_empty() && vals.is_empty(); - // Σ Values in Rows (it exists with two or more value fields): its depth among the row fields - // found in the source. - let vpos: Option = (pt.values_on_rows && k > 1).then(|| { - let p = pt.values_position.unwrap_or(pt.rows.len()); - pt.rows.iter().take(p).filter(|f| src.col(&f.source_col).is_some()).count() - }); - let on_rows = vpos.is_some(); - let row_levels = rows.len() + usize::from(on_rows); - - // ---- aggregate - let mut row_items: Vec = rows.iter().map(|_| FieldItems::default()).collect(); - let mut col_items: Vec = cols.iter().map(|_| FieldItems::default()).collect(); - let mut aggs: AggMap = HashMap::new(); - let mut row_set: HashSet> = HashSet::new(); - let mut col_set: HashSet> = HashSet::new(); - let mut col_leaves: HashSet> = HashSet::new(); - let filter_fmts: Vec = filters.iter().map(|f| fmt_of(f.0)).collect(); - let row_fmts: Vec = rows.iter().map(|(c, _)| fmt_of(*c)).collect(); - let col_fmts: Vec = cols.iter().map(|(c, _)| fmt_of(*c)).collect(); - 'rec: for (ri, rec) in src.rows.iter().enumerate() { - for ((c, f, g, _), fmt) in filters.iter().zip(filter_fmts.iter()) { - if let Some(sel) = &f.selected { - let label = item_label(wb, rec.get(*c).unwrap_or(&Value::Empty), *g, fmt); - if !sel.iter().any(|s| s.eq_ignore_ascii_case(&label)) { - continue 'rec; - } - } - } - if empty { - continue; - } - let mut rp = Vec::with_capacity(rows.len()); - for (((c, f), fi), fmt) in rows.iter().zip(row_items.iter_mut()).zip(row_fmts.iter()) { - rp.push(fi.intern(wb, rec.get(*c).unwrap_or(&Value::Empty), f.date_group, fmt, ri)); - } - let mut cp = Vec::with_capacity(cols.len()); - for (((c, f), fi), fmt) in cols.iter().zip(col_items.iter_mut()).zip(col_fmts.iter()) { - cp.push(fi.intern(wb, rec.get(*c).unwrap_or(&Value::Empty), f.date_group, fmt, ri)); - } - for a in 0..=rp.len() { - for b in 0..=cp.len() { - let e = aggs.entry((rp[..a].to_vec(), cp[..b].to_vec())).or_insert_with(|| vec![Acc::default(); k + extra.len()]); - for (acc, (vs, _)) in e.iter_mut().zip(vals.iter()) { - if let ValSrc::Col(c) = vs { - acc.add(rec.get(*c).unwrap_or(&Value::Empty)); - } - } - for (acc, c) in e.iter_mut().skip(k).zip(extra.iter()) { - acc.add(rec.get(*c).unwrap_or(&Value::Empty)); - } - } - } - // The column leaf this record lands in: its path cut after the first collapsed item (as in `flatten_cols`). - let shown = cols - .iter() - .zip(col_items.iter()) - .zip(cp.iter()) - .position(|(((_, f), fi), &it)| !f.collapsed_items.is_empty() && is_collapsed(f, &fi.label(it))) - .map_or(cp.len(), |d| d + 1); - if !col_leaves.contains(&cp[..shown]) { - col_leaves.insert(cp[..shown].to_vec()); - } - if let Some(paths) = probe.as_deref_mut().and_then(|pr| pr.paths.as_mut()) { - paths.push((ri, rp.clone(), cp.clone())); - } - row_set.insert(rp); - col_set.insert(cp); - // Refuse a report that cannot fit before the accumulators for more column groups are allocated. - if !cols.is_empty() && data_cols_exceed_sheet(col_leaves.len(), pt.grand_totals_rows, k) { - return Err("The PivotTable report will not fit on the sheet.".into()); - } - if aggs.len() > 5_000_000 { - return Err("The PivotTable report is too large.".into()); - } - } - - // ---- axes - let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect(); - let col_fields: Vec<&PivotField> = cols.iter().map(|(_, f)| *f).collect(); - let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect(); - let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect(); - let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items); - let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items); - let mut siblings: HashMap, Vec> = HashMap::new(); - collect_siblings(&row_tree, &mut Vec::new(), &mut siblings); - let level0: Vec = row_tree.iter().map(|n| n.item).collect(); - - let val_names: Vec = vals.iter().map(|(_, v)| v.name.clone()).collect(); - let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() }; - let mut lines: Vec = Vec::new(); - if row_levels == 0 { - lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None }); - } else { - if pt.layout == PivotLayout::Tabular { - ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines); - } else { - ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines); - } - // With only Σ Values in Rows its items are the totals already. - if pt.grand_totals_cols && !rows.is_empty() { - let grand = |text: String, vi: Option| Line { - kind: LineKind::Grand, - leaf: false, - path: vec![], - values: true, - labels: vec![(0, Value::text(text), 0, None)], - vi, - }; - if on_rows { - lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi)))); - } else { - lines.push(grand("Grand Total".into(), None)); - } - } - } - let mut specs: Vec = Vec::new(); - if cols.is_empty() { - specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] }); - } else { - flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs); - if pt.grand_totals_rows { - specs.push(ColSpec { kind: ColKind::Grand, path: vec![] }); - } - } - let mut data_cols: Vec<(usize, Option)> = Vec::new(); - for (si, _) in specs.iter().enumerate() { - if on_rows { - // Each line names its value field; one data column per column item. - data_cols.push((si, None)); - } else if k == 0 { - if !cols.is_empty() { - data_cols.push((si, None)); - } - } else { - for vi in 0..k { - data_cols.push((si, Some(vi))); - } - } - if data_cols.len() > MAX_COLS as usize { - return Err("The PivotTable report will not fit on the sheet.".into()); - } - } - - let compact = pt.layout == PivotLayout::Compact; - let l = if row_levels == 0 && cols.is_empty() { - 0 - } else if compact { - 1 - } else { - row_levels.max(1) - }; - let mut width = l + data_cols.len(); - if !shown_filters.is_empty() { - width = width.max(2); - } - if empty { - width = width.max(1); - } - let width = width.max(1); - let mut g = Grid { rows: vec![], kinds: vec![], width }; - - // ---- report filters - for (c, f, _, _) in &shown_filters { - let r = g.push_row(RowKind::Filter)?; - let name = src.headers.get(*c).cloned().unwrap_or_default(); - let shown = match &f.selected { - None => "(All)".to_string(), - Some(v) if v.len() == 1 => v.first().cloned().unwrap_or_default(), - Some(_) => "(Multiple Items)".to_string(), - }; - g.set(r, 0, Value::text(name), CellKind::Filter, 0, None); - g.set(r, 1, Value::text(shown), CellKind::Filter, 0, None); - } - if !shown_filters.is_empty() { - g.push_row(RowKind::Blank)?; - } - let body_offset = g.rows.len() as u32; - - if empty { - let r = g.push_row(RowKind::Placeholder)?; - g.set(r, 0, Value::text(format!("{} — choose fields", pt.name)), CellKind::Placeholder, 0, None); - return Ok(Output { - width: g.width as u32, - grid: g.rows, - row_kinds: g.kinds, - body_offset, - chart_rows: vec![], - chart_cols: vec![], - label_col: None, - }); - } - - let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default(); - let headers_on = pt.show_headers; - let row_header = |g: &mut Grid, r: usize| { - if row_levels == 0 || !headers_on { - return; - } - if compact { - g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None); - } else { - // One column per row field, Σ Values ("Values") at its place. - let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect(); - if let Some(p) = vpos { - names.insert(p.min(names.len()), "Values"); - } - for (i, name) in names.into_iter().enumerate() { - g.set(r, i, Value::text(name), CellKind::Header, 0, None); - } - } - }; - - // ---- header rows - if cols.is_empty() { - let r = g.push_row(RowKind::Header)?; - row_header(&mut g, r); - for (j, (_, vi)) in data_cols.iter().enumerate() { - match vi { - Some(vi) => g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None), - // Values on rows, no column field: the one data column is the grand total. - None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None), - None => {} - } - } - } else { - let cap = g.push_row(RowKind::Header)?; - if l > 0 && k == 1 { - g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); - } - if headers_on { - let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; - g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); - } - let levels = cols.len() + usize::from(k > 1 && !on_rows); - let first_level = g.rows.len(); - for _ in 0..levels { - g.push_row(RowKind::Header)?; - } - let mut prev: Option<&ColSpec> = None; - for (j, (si, vi)) in data_cols.iter().enumerate() { - let Some(spec) = specs.get(*si) else { continue }; - let c = l + j; - match spec.kind { - ColKind::Leaf => { - for (lv, &it) in spec.path.iter().enumerate() { - let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv)); - if !same { - let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue }; - let fmt = if item.formatted { cols.get(lv).map(|(cc, _)| fmt_of(*cc)) } else { None }; - g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt); - } - } - if k > 1 - && let Some(vi) = vi - { - g.set(first_level + cols.len(), c, Value::text(val_name(*vi)), CellKind::ColLabel, 0, None); - } - } - ColKind::Subtotal => { - let lv = spec.path.len().saturating_sub(1); - let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default(); - let text = match vi { - Some(vi) if k > 1 => format!("{label} {}", val_name(*vi)), - _ => format!("{label} Total"), - }; - g.set(first_level + lv, c, Value::text(text), CellKind::ColLabel, 0, None); - } - ColKind::Grand => { - let text = match vi { - Some(vi) if k > 1 => format!("Total {}", val_name(*vi)), - _ => "Grand Total".to_string(), - }; - g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None); - } - } - prev = Some(spec); - } - let last = g.rows.len() - 1; - row_header(&mut g, last); - } - - // ---- body - let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option { - let (vs, v) = vals.get(vi)?; - let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?; - match vs { - ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)), - ValSrc::Calc(i) => { - let sum = |name: &str| -> Value { - src.col(name) - .and_then(|c| extra.iter().position(|x| *x == c)) - .and_then(|j| accs.get(k + j)) - .map(|a| a.result(PivotFunc::Sum)) - .unwrap_or(Value::Number(0.0)) - }; - Some(calc.value(wb, *i, &sum)) - } - } - }; - let num = |v: &Option| v.as_ref().and_then(Value::as_f64); - let ratio = |a: Value, b: Option| -> Value { - match (a, b) { - (Value::Error(e), _) => Value::Error(e), - (_, Some(Value::Error(e))) => Value::Error(e), - (Value::Number(x), Some(Value::Number(y))) => { - if y == 0.0 { - Value::Error(CellError::Div0) - } else { - Value::number(x / y) - } - } - (v, _) => v, - } - }; - let data_fmt: Vec> = vals - .iter() - .map(|(vs, v)| match v.show_as { - PivotShowAs::PercentOfGrandTotal | PivotShowAs::PercentOfColumnTotal | PivotShowAs::PercentOfRowTotal => { - Some(v.number_format.clone().unwrap_or_else(|| "0.00%".into())) - } - PivotShowAs::Rank => v.number_format.clone(), - _ => v.number_format.clone().or_else(|| match v.func { - PivotFunc::Count | PivotFunc::CountNumbers => None, - _ => { - let f = match vs { - ValSrc::Col(c) => fmt_of(*c), - ValSrc::Calc(_) => "General".to_string(), - }; - (f != "General").then_some(f) - } - }), - }) - .collect(); - let mut chart_rows: Vec = Vec::new(); - let chart_cols: Vec<(u32, String)> = data_cols - .iter() - .enumerate() - .filter_map(|(j, (si, vi))| { - let spec = specs.get(*si)?; - if spec.kind != ColKind::Leaf { - return None; - } - let mut parts: Vec = - spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect(); - if let Some(vi) = vi - && (k > 1 || parts.is_empty()) - { - parts.push(val_name(*vi)); - } else if parts.is_empty() { - parts.push("Total".into()); - } - Some(((l + j) as u32, parts.join(" - "))) - }) - .filter(|_| k > 0) - .collect(); - let label_col = if row_levels == 0 { - None - } else if compact { - Some(0) - } else { - Some(row_levels.saturating_sub(1) as u32) - }; - for line in &lines { - let rk = match line.kind { - LineKind::Item(b) => RowKind::Item(b), - LineKind::Subtotal => RowKind::Subtotal, - LineKind::Grand => RowKind::Grand, - }; - let ck = match line.kind { - LineKind::Item(_) => (CellKind::RowLabel, CellKind::Data), - LineKind::Subtotal => (CellKind::Subtotal, CellKind::Subtotal), - LineKind::Grand => (CellKind::GrandTotal, CellKind::GrandTotal), - }; - let r = g.push_row(rk)?; - if line.leaf && k > 0 { - chart_rows.push(r as u32); - } - for (c, v, indent, fmt) in &line.labels { - g.set(r, *c, v.clone(), ck.0, *indent, fmt.clone()); - } - if !line.values { - continue; - } - let rp = line.path.as_slice(); - for (j, (si, col_vi)) in data_cols.iter().enumerate() { - let line_vi = col_vi.or(line.vi); - let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue }; - let Some((_, vdef)) = vals.get(*vi) else { continue }; - let cp = spec.path.as_slice(); - let Some(raw) = get(rp, cp, *vi) else { continue }; - let shown = match vdef.show_as { - PivotShowAs::Normal => raw, - PivotShowAs::PercentOfGrandTotal => ratio(raw, get(&[], &[], *vi)), - PivotShowAs::PercentOfColumnTotal => ratio(raw, get(&[], cp, *vi)), - PivotShowAs::PercentOfRowTotal => ratio(raw, get(rp, &[], *vi)), - PivotShowAs::RunningTotal => match (rp.first(), &raw) { - (Some(first), Value::Number(_)) => { - let mut acc = 0.0; - for it in &level0 { - let mut p = rp.to_vec(); - if let Some(x) = p.first_mut() { - *x = *it; - } - acc += num(&get(&p, cp, *vi)).unwrap_or(0.0); - if it == first { - break; - } - } - Value::number(acc) - } - _ => raw, - }, - PivotShowAs::Rank => match (rp.split_last(), raw.as_f64()) { - (Some((_, parent)), Some(me)) => { - let sibs = siblings.get(parent).cloned().unwrap_or_default(); - let mut rank = 1u64; - for sib in sibs { - let mut p = parent.to_vec(); - p.push(sib); - if num(&get(&p, cp, *vi)).is_some_and(|x| x > me) { - rank += 1; - } - } - Value::number(rank as f64) - } - (None, _) => Value::Empty, - _ => raw, - }, - }; - if let Some(pr) = probe.as_deref_mut() { - if pr.at == Some((r, l + j)) { - pr.hit = Some((rp.to_vec(), cp.to_vec())); - } - if let Some(cells) = pr.cells.as_mut() { - cells.insert((r, l + j)); - } - } - g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten()); - } - } - Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col }) -} - -// ---------------------------------------------------------------- styling and writing - -/// Colours for a PivotTable style name (our own palette, keyed by the familiar -/// `PivotStyleLight1…28 / Medium1…28 / Dark1…28` names). -struct Look { - header_fill: Color, - header_font: Color, - line: Color, - filter_fill: Color, -} - -fn look(style: &str) -> Look { - let rest = style.strip_prefix("PivotStyle").unwrap_or(style); - let (fam, n) = ["Light", "Medium", "Dark"] - .iter() - .find_map(|f| rest.strip_prefix(f).map(|num| (*f, num.parse::().unwrap_or(16)))) - .unwrap_or(("Light", 16)); - let k = n.saturating_sub(1) % 7; - let acc = if k == 0 { None } else { Some(3 + k as u8) }; - let tone = |tint: i16| match acc { - Some(a) => Color::Theme(a, tint), - None => Color::Theme(1, tint.clamp(-1000, 1000)), - }; - match fam { - "Dark" => Look { header_fill: Color::Theme(1, 0), header_font: Color::Theme(0, 0), line: tone(0), filter_fill: tone(600) }, - "Medium" => Look { header_fill: tone(0), header_font: Color::Theme(0, 0), line: tone(0), filter_fill: tone(800) }, - _ => Look { header_fill: tone(800), header_font: Color::Auto, line: tone(400), filter_fill: tone(800) }, - } -} - -fn cell_style(lk: &Look, rk: RowKind, cell: &OutCell, last_header: bool) -> Style { - let mut s = Style::default(); - match rk { - RowKind::Header => { - s.font.bold = true; - s.fill = Fill::solid(lk.header_fill); - s.font.color = lk.header_font; - if last_header { - s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: lk.line }; - } - } - RowKind::Filter => { - s.fill = Fill::solid(lk.filter_fill); - s.font.bold = last_header; - } - RowKind::Item(parent) => s.font.bold = parent, - RowKind::Subtotal => s.font.bold = true, - RowKind::Grand => { - s.font.bold = true; - s.borders.top = BorderLine { style: BorderStyle::Thin, color: lk.line }; - } - RowKind::Placeholder => { - s.font.italic = true; - s.font.color = Color::Theme(1, 500); - } - RowKind::Blank => {} - } - if matches!(cell.kind, CellKind::RowLabel | CellKind::ColLabel | CellKind::Subtotal | CellKind::GrandTotal) && !cell.value.is_number() { - s.align.h = HAlign::Left; - } - if matches!(cell.kind, CellKind::RowLabel | CellKind::ColLabel) && cell.value.is_number() { - s.align.h = HAlign::Left; - } - s.align.indent = cell.indent.min(15); - if let Some(f) = &cell.num_fmt { - s.num_fmt = NumFmt::new(f); - } - s -} - /// Recomputes a pivot and writes its report. With `replace` false, refuses when the target area /// holds other data. Returns the written area. pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Result { @@ -1468,7 +228,7 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re } if !replace { for (c, cell) in sh.cells.iter_range(area) { - if (!cell.value.is_empty() || cell.formula.is_some()) && !pt.last_range.is_some_and(|r| r.contains(c)) { + if cell.has_content() && !pt.last_range.is_some_and(|r| r.contains(c)) { return Err(format!( "There's already data in {}!{}. Do you want to replace it? (Run again with replace: true to overwrite.)", quote_sheet(&sh.name), @@ -1518,7 +278,10 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re if oc.value.is_empty() && id == StyleId::default() { continue; } - cells.push((CellRef::new(origin.row + ri as u32, origin.col + ci as u32), Cell { value: oc.value.clone(), formula: None, style: id })); + cells.push(( + CellRef::new(origin.row + ri as u32, origin.col + ci as u32), + Cell { value: oc.value.clone(), formula: None, style: id, py: None }, + )); } } // Column widths that fit the labels. @@ -1554,112 +317,6 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re Ok(area) } -// ---------------------------------------------------------------- PivotCharts - -/// The link a PivotChart stores to its PivotTable: `Sheet2!PivotTable1`. -pub fn chart_link(sheet: &str, pivot: &str) -> String { - format!("{}!{pivot}", quote_sheet(sheet)) -} - -/// (sheet, PivotTable name) of a PivotChart link; a leading `[Book.xlsx]` is ignored. -pub fn parse_chart_link(link: &str) -> Option<(String, String)> { - let t = link.trim(); - let t = match t.strip_prefix('[') { - Some(rest) => rest.split_once(']').map(|(_, r)| r).unwrap_or(rest), - None => t, - }; - let (sheet, name) = t.rsplit_once('!')?; - let sheet = sheet.trim(); - let sheet = gridcraft_core::unquote_sheet(sheet); - let name = name.trim(); - if sheet.is_empty() || name.is_empty() { - return None; - } - Some((sheet, name.to_string())) -} - -/// Whether a PivotChart link points at `pivot` on `sheet`. -pub fn links_to(link: &str, sheet: &str, pivot: &str) -> bool { - parse_chart_link(link).is_some_and(|(s, n)| s.eq_ignore_ascii_case(sheet) && n.eq_ignore_ascii_case(pivot)) -} - -/// An absolute reference to `col` over grid `rows` (contiguous runs joined into a union). -fn rows_ref(sheet: &str, origin: CellRef, col: u32, rows: &[u32]) -> Option { - let q = quote_sheet(sheet); - let c = origin.col.checked_add(col)?; - let letters = gridcraft_core::col_to_letters(c); - let mut parts: Vec = Vec::new(); - let mut i = 0; - while let Some(&start) = rows.get(i) { - let mut end = start; - while rows.get(i + 1).is_some_and(|n| Some(*n) == end.checked_add(1)) { - end += 1; - i += 1; - } - i += 1; - let (a, b) = (origin.row.checked_add(start)? + 1, origin.row.checked_add(end)? + 1); - parts.push(if a == b { format!("{q}!${letters}${a}") } else { format!("{q}!${letters}${a}:${letters}${b}") }); - } - match parts.len() { - 0 => None, - 1 => parts.pop(), - _ => Some(format!("({})", parts.join(","))), - } -} - -/// Most category rows a PivotChart plots. -const MAX_CHART_ROWS: usize = 10_000; - -/// A PivotChart's series for a report written at `origin`: categories are the innermost row -/// items, one series per item column (column items × value fields); totals are left out. -pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec { - let rows: Vec = out.chart_rows.iter().copied().take(MAX_CHART_ROWS).collect(); - let categories = out.label_col.and_then(|c| rows_ref(sheet, origin, c, &rows)); - out.chart_cols - .iter() - .filter_map(|(c, name)| { - Some(Series { - name: Some(format!("\"{}\"", name.replace('"', "\"\""))), - categories: categories.clone(), - values: rows_ref(sheet, origin, *c, &rows)?, - bubble_sizes: None, - color: None, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: false, - trendlines: Vec::new(), - }) - }) - .collect() -} - -/// Rebuilds the series of every PivotChart of a PivotTable after its report was written. -fn rebind_charts(wb: &mut Workbook, sheet: &str, pivot: &str, origin: CellRef, out: &Output) { - let linked = |ch: &Chart| ch.pivot.as_deref().is_some_and(|l| links_to(l, sheet, pivot)); - let hits: Vec = (0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|sh| sh.charts.iter().any(linked))).collect(); - if hits.is_empty() { - return; - } - let series = chart_series(sheet, origin, out); - for i in hits { - let Some(sh) = wb.sheet_mut(i) else { continue }; - for ch in sh.charts.iter_mut().filter(|c| linked(c)) { - ch.series = series.clone(); - } - } -} - -/// Clears a pivot's last output area. -pub fn clear_output(wb: &mut Workbook, sheet: usize, idx: usize) { - let Some(shm) = wb.sheet_mut(sheet) else { return }; - let Some(r) = shm.pivots.get(idx).and_then(|p| p.last_range) else { return }; - shm.take_cells(r); - if let Some(p) = shm.pivots.get_mut(idx) { - p.last_range = None; - } -} - #[cfg(test)] mod fit_tests { use super::data_cols_exceed_sheet; diff --git a/crates/engine/src/pivot/charts.rs b/crates/engine/src/pivot/charts.rs new file mode 100644 index 0000000000..bc5d8e5971 --- /dev/null +++ b/crates/engine/src/pivot/charts.rs @@ -0,0 +1,108 @@ +use super::output::Output; +use super::{CellRef, Chart, Series, Workbook, quote_sheet}; + +// ---------------------------------------------------------------- PivotCharts + +/// The link a PivotChart stores to its PivotTable: `Sheet2!PivotTable1`. +pub fn chart_link(sheet: &str, pivot: &str) -> String { + format!("{}!{pivot}", quote_sheet(sheet)) +} + +/// (sheet, PivotTable name) of a PivotChart link; a leading `[Book.xlsx]` is ignored. +pub fn parse_chart_link(link: &str) -> Option<(String, String)> { + let t = link.trim(); + let t = match t.strip_prefix('[') { + Some(rest) => rest.split_once(']').map(|(_, r)| r).unwrap_or(rest), + None => t, + }; + let (sheet, name) = t.rsplit_once('!')?; + let sheet = sheet.trim(); + let sheet = gridcraft_core::unquote_sheet(sheet); + let name = name.trim(); + if sheet.is_empty() || name.is_empty() { + return None; + } + Some((sheet, name.to_string())) +} + +/// Whether a PivotChart link points at `pivot` on `sheet`. +pub fn links_to(link: &str, sheet: &str, pivot: &str) -> bool { + parse_chart_link(link).is_some_and(|(s, n)| s.eq_ignore_ascii_case(sheet) && n.eq_ignore_ascii_case(pivot)) +} + +/// An absolute reference to `col` over grid `rows` (contiguous runs joined into a union). +fn rows_ref(sheet: &str, origin: CellRef, col: u32, rows: &[u32]) -> Option { + let q = quote_sheet(sheet); + let c = origin.col.checked_add(col)?; + let letters = gridcraft_core::col_to_letters(c); + let mut parts: Vec = Vec::new(); + let mut i = 0; + while let Some(&start) = rows.get(i) { + let mut end = start; + while rows.get(i + 1).is_some_and(|n| Some(*n) == end.checked_add(1)) { + end += 1; + i += 1; + } + i += 1; + let (a, b) = (origin.row.checked_add(start)? + 1, origin.row.checked_add(end)? + 1); + parts.push(if a == b { format!("{q}!${letters}${a}") } else { format!("{q}!${letters}${a}:${letters}${b}") }); + } + match parts.len() { + 0 => None, + 1 => parts.pop(), + _ => Some(format!("({})", parts.join(","))), + } +} + +/// Most category rows a PivotChart plots. +const MAX_CHART_ROWS: usize = 10_000; + +/// A PivotChart's series for a report written at `origin`: categories are the innermost row +/// items, one series per item column (column items × value fields); totals are left out. +pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec { + let rows: Vec = out.chart_rows.iter().copied().take(MAX_CHART_ROWS).collect(); + let categories = out.label_col.and_then(|c| rows_ref(sheet, origin, c, &rows)); + out.chart_cols + .iter() + .filter_map(|(c, name)| { + Some(Series { + name: Some(format!("\"{}\"", name.replace('"', "\"\""))), + categories: categories.clone(), + values: rows_ref(sheet, origin, *c, &rows)?, + bubble_sizes: None, + color: None, + secondary: false, + kind: None, + quartiles: Default::default(), + smooth: false, + trendlines: Vec::new(), + }) + }) + .collect() +} + +/// Rebuilds the series of every PivotChart of a PivotTable after its report was written. +pub(super) fn rebind_charts(wb: &mut Workbook, sheet: &str, pivot: &str, origin: CellRef, out: &Output) { + let linked = |ch: &Chart| ch.pivot.as_deref().is_some_and(|l| links_to(l, sheet, pivot)); + let hits: Vec = (0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|sh| sh.charts.iter().any(linked))).collect(); + if hits.is_empty() { + return; + } + let series = chart_series(sheet, origin, out); + for i in hits { + let Some(sh) = wb.sheet_mut(i) else { continue }; + for ch in sh.charts.iter_mut().filter(|c| linked(c)) { + ch.series = series.clone(); + } + } +} + +/// Clears a pivot's last output area. +pub fn clear_output(wb: &mut Workbook, sheet: usize, idx: usize) { + let Some(shm) = wb.sheet_mut(sheet) else { return }; + let Some(r) = shm.pivots.get(idx).and_then(|p| p.last_range) else { return }; + shm.take_cells(r); + if let Some(p) = shm.pivots.get_mut(idx) { + p.last_range = None; + } +} diff --git a/crates/engine/src/pivot/compute.rs b/crates/engine/src/pivot/compute.rs new file mode 100644 index 0000000000..0ffa8cae5d --- /dev/null +++ b/crates/engine/src/pivot/compute.rs @@ -0,0 +1,711 @@ +use super::items::{Acc, FieldItems, build_tree, collect_siblings, is_collapsed, item_label}; +use super::output::{AggMap, CellKind, ColKind, ColSpec, Ctx, Grid, Line, LineKind, Output, RowKind, ValSrc, data_cols_exceed_sheet, flatten_cols}; +use super::{ + CalcSet, CellError, CellRef, HashMap, HashSet, MAX_AXIS_FIELDS, MAX_COLS, MAX_VALUE_FIELDS, PivotDateGroup, PivotField, PivotFilter, PivotFunc, + PivotLayout, PivotShowAs, PivotTable, PivotValue, Source, Value, Workbook, read_source, +}; + +/// Why Show Details turns a cell down when it isn't a value cell of a PivotTable (the front end +/// edits that cell instead). +pub const NOT_A_VALUE_CELL: &str = "select a value cell in a PivotTable"; + +/// Show Details: the source list and the indices of its records behind the value cell at +/// (`row`, `col`) of the report grid (relative to its top-left), in source order. `None` when +/// that cell holds no value (a label, a header, a blank). An error, for any cell, when the report +/// on the sheet is no longer what the source computes: the cell's records would be another cell's. +pub fn detail_records(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize, row: u32, col: u32) -> Result)>, String> { + let src = read_source(wb, &pt.source, pivot_sheet)?; + let mut probe = Probe { at: Some((row as usize, col as usize)), hit: None, paths: Some(Vec::new()), cells: None }; + let out = compute_from(wb, pt, &src, Some(&mut probe))?; + // Checked first: in a stale report even a cell that computes as a label may show a value. + check_current(wb, pt, pivot_sheet, &out)?; + let Some((rp, cp)) = probe.hit else { return Ok(None) }; + let records = + probe.paths.unwrap_or_default().into_iter().filter(|(_, r, c)| r.starts_with(&rp) && c.starts_with(&cp)).map(|(i, _, _)| i).collect(); + Ok(Some((src, records))) +} + +/// The cells of the report grid (relative to its top-left) where [`detail_records`] finds +/// records: its value, subtotal and grand total cells, from one computation of the report. The +/// same errors as [`detail_records`]. +pub fn detail_cells(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result, String> { + let src = read_source(wb, &pt.source, pivot_sheet)?; + let mut probe = Probe { at: None, hit: None, paths: None, cells: Some(HashSet::new()) }; + let out = compute_from(wb, pt, &src, Some(&mut probe))?; + check_current(wb, pt, pivot_sheet, &out)?; + Ok(probe.cells.unwrap_or_default().into_iter().map(|(r, c)| (r as u32, c as u32)).collect()) +} + +/// An error when the report on the sheet is not what `out` computes. Excel reads its PivotTable +/// cache; without one, the report written by the last refresh must still be what the source gives. +fn check_current(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize, out: &Output) -> Result<(), String> { + let sh = wb.sheet(pivot_sheet).ok_or("There's no such sheet.")?; + let current = pt.last_range.is_some_and(|r| { + r.height() == out.height().max(1) + && r.width() == out.width.max(1) + && out.grid.iter().enumerate().all(|(ri, line)| { + line.iter().enumerate().all(|(ci, oc)| { + sh.value_ref(CellRef::new(r.start.row + ri as u32, r.start.col + ci as u32)).unwrap_or(&Value::Empty) == &oc.value + }) + }) + }); + if !current { + return Err("The PivotTable report is out of date. Refresh it first.".into()); + } + Ok(()) +} + +type ProbePath = (usize, Vec, Vec); + +/// What [`detail_records`] and [`detail_cells`] ask of a report computation: the row and column +/// item paths of the value cell at `at`, the paths of every record the filters let through (when +/// `paths` is set), and every value cell (when `cells` is set). +pub(super) struct Probe { + at: Option<(usize, usize)>, + hit: Option<(Vec, Vec)>, + paths: Option>, + cells: Option>, +} + +struct AggregateInput<'a> { + wb: &'a Workbook, + pt: &'a PivotTable, + src: &'a Source, + rows: &'a [(usize, &'a PivotField)], + cols: &'a [(usize, &'a PivotField)], + vals: &'a [(ValSrc, &'a PivotValue)], + extra: &'a [usize], + filters: &'a [(usize, &'a PivotFilter, PivotDateGroup, bool)], + filter_fmts: &'a [String], + row_fmts: &'a [String], + col_fmts: &'a [String], + empty: bool, +} + +#[derive(Default)] +struct AggregateData { + row_items: Vec, + col_items: Vec, + aggs: AggMap, + row_set: HashSet>, + col_set: HashSet>, + col_leaves: HashSet>, +} + +fn aggregate_record( + input: &AggregateInput<'_>, + data: &mut AggregateData, + probe: &mut Option<&mut Probe>, + ri: usize, + rec: &[Value], +) -> Result<(), String> { + for ((c, field, group, _), fmt) in input.filters.iter().zip(input.filter_fmts) { + if let Some(selected) = &field.selected { + let label = item_label(input.wb, rec.get(*c).unwrap_or(&Value::Empty), *group, fmt); + if !selected.iter().any(|value| value.eq_ignore_ascii_case(&label)) { + return Ok(()); + } + } + } + if input.empty { + return Ok(()); + } + let mut row_path = Vec::with_capacity(input.rows.len()); + for (((column, field), items), fmt) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts) { + row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri)); + } + let mut col_path = Vec::with_capacity(input.cols.len()); + for (((column, field), items), fmt) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts) { + col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri)); + } + for row_depth in 0..=row_path.len() { + for col_depth in 0..=col_path.len() { + let accs = data + .aggs + .entry((row_path[..row_depth].to_vec(), col_path[..col_depth].to_vec())) + .or_insert_with(|| vec![Acc::default(); input.vals.len() + input.extra.len()]); + for (acc, (source, _)) in accs.iter_mut().zip(input.vals) { + if let ValSrc::Col(column) = source { + acc.add(rec.get(*column).unwrap_or(&Value::Empty)); + } + } + for (acc, column) in accs.iter_mut().skip(input.vals.len()).zip(input.extra) { + acc.add(rec.get(*column).unwrap_or(&Value::Empty)); + } + } + } + let shown_depth = input + .cols + .iter() + .zip(data.col_items.iter()) + .zip(col_path.iter()) + .position(|(((_, field), items), &item)| !field.collapsed_items.is_empty() && is_collapsed(field, &items.label(item))) + .map_or(col_path.len(), |depth| depth + 1); + data.col_leaves.insert(col_path[..shown_depth].to_vec()); + if let Some(paths) = probe.as_deref_mut().and_then(|value| value.paths.as_mut()) { + paths.push((ri, row_path.clone(), col_path.clone())); + } + data.row_set.insert(row_path); + data.col_set.insert(col_path); + if !input.cols.is_empty() && data_cols_exceed_sheet(data.col_leaves.len(), input.pt.grand_totals_rows, input.vals.len()) { + return Err("The PivotTable report will not fit on the sheet.".into()); + } + if data.aggs.len() > 5_000_000 { + return Err("The PivotTable report is too large.".into()); + } + Ok(()) +} + +fn aggregate_source(input: AggregateInput<'_>, probe: &mut Option<&mut Probe>) -> Result { + let mut data = AggregateData { + row_items: input.rows.iter().map(|_| FieldItems::default()).collect(), + col_items: input.cols.iter().map(|_| FieldItems::default()).collect(), + ..AggregateData::default() + }; + for (ri, record) in input.src.rows.iter().enumerate() { + aggregate_record(&input, &mut data, probe, ri, record)?; + } + Ok(data) +} + +struct HeaderInput<'a> { + vals: &'a [(ValSrc, &'a PivotValue)], + row_fields: &'a [&'a PivotField], + col_fields: &'a [&'a PivotField], + col_items: &'a [FieldItems], + col_fmts: &'a [String], + vpos: Option, + data_cols: &'a [(usize, Option)], + specs: &'a [ColSpec], + row_levels: usize, + compact: bool, + on_rows: bool, + k: usize, + l: usize, + headers_on: bool, +} + +fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { + let HeaderInput { vals, row_fields, col_fields, col_items, col_fmts, vpos, data_cols, specs, row_levels, compact, on_rows, k, l, headers_on } = + input; + let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default(); + let row_header = |g: &mut Grid, r: usize| { + if row_levels == 0 || !headers_on { + return; + } + if compact { + g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None); + } else { + // One column per row field, Σ Values ("Values") at its place. + let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect(); + if let Some(p) = vpos { + names.insert(p.min(names.len()), "Values"); + } + for (i, name) in names.into_iter().enumerate() { + g.set(r, i, Value::text(name), CellKind::Header, 0, None); + } + } + }; + + // ---- header rows + if col_fields.is_empty() { + let r = g.push_row(RowKind::Header)?; + row_header(g, r); + for (j, (_, vi)) in data_cols.iter().enumerate() { + match vi { + Some(vi) => g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None), + // Values on rows, no column field: the one data column is the grand total. + None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None), + None => {} + } + } + } else { + let cap = g.push_row(RowKind::Header)?; + if l > 0 && k == 1 { + g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); + } + if headers_on { + let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; + g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); + } + let levels = col_fields.len() + usize::from(k > 1 && !on_rows); + let first_level = g.rows.len(); + for _ in 0..levels { + g.push_row(RowKind::Header)?; + } + let mut prev: Option<&ColSpec> = None; + for (j, (si, vi)) in data_cols.iter().enumerate() { + let Some(spec) = specs.get(*si) else { continue }; + let c = l + j; + match spec.kind { + ColKind::Leaf => { + for (lv, &it) in spec.path.iter().enumerate() { + let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv)); + if !same { + let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue }; + let fmt = if item.formatted { col_fmts.get(lv).cloned() } else { None }; + g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt); + } + } + if k > 1 + && let Some(vi) = vi + { + g.set(first_level + col_fields.len(), c, Value::text(val_name(*vi)), CellKind::ColLabel, 0, None); + } + } + ColKind::Subtotal => { + let lv = spec.path.len().saturating_sub(1); + let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default(); + let text = match vi { + Some(vi) if k > 1 => format!("{label} {}", val_name(*vi)), + _ => format!("{label} Total"), + }; + g.set(first_level + lv, c, Value::text(text), CellKind::ColLabel, 0, None); + } + ColKind::Grand => { + let text = match vi { + Some(vi) if k > 1 => format!("Total {}", val_name(*vi)), + _ => "Grand Total".to_string(), + }; + g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None); + } + } + prev = Some(spec); + } + let last = g.rows.len() - 1; + row_header(g, last); + } + + Ok(()) +} + +struct ValueLookup<'a> { + wb: &'a Workbook, + source: &'a Source, + calc: &'a CalcSet, + vals: &'a [(ValSrc, &'a PivotValue)], + extra: &'a [usize], + aggs: &'a AggMap, + value_count: usize, +} + +impl ValueLookup<'_> { + fn get(&self, row_path: &[u32], col_path: &[u32], value_index: usize) -> Option { + let (source, definition) = self.vals.get(value_index)?; + let accumulators = self.aggs.get(&(row_path.to_vec(), col_path.to_vec()))?; + match source { + ValSrc::Col(_) => accumulators.get(value_index).map(|acc| acc.result(definition.func)), + ValSrc::Calc(index) => { + let sum = |name: &str| -> Value { + self.source + .col(name) + .and_then(|column| self.extra.iter().position(|extra_column| *extra_column == column)) + .and_then(|index| accumulators.get(self.value_count + index)) + .map(|acc| acc.result(PivotFunc::Sum)) + .unwrap_or(Value::Number(0.0)) + }; + Some(self.calc.value(self.wb, *index, &sum)) + } + } + } +} + +struct ShowContext<'a> { + row_path: &'a [u32], + col_path: &'a [u32], + value_index: usize, + level0: &'a [u32], + siblings: &'a HashMap, Vec>, +} + +fn number(value: &Option) -> Option { + value.as_ref().and_then(Value::as_f64) +} + +fn ratio(a: Value, b: Option) -> Value { + match (a, b) { + (Value::Error(error), _) => Value::Error(error), + (_, Some(Value::Error(error))) => Value::Error(error), + (Value::Number(_), Some(Value::Number(0.0))) => Value::Error(CellError::Div0), + (Value::Number(x), Some(Value::Number(y))) => Value::number(x / y), + (value, _) => value, + } +} + +fn running_total(raw: Value, lookup: &ValueLookup<'_>, context: &ShowContext<'_>) -> Value { + let Some((first, _)) = context.row_path.split_first() else { return raw }; + if !matches!(raw, Value::Number(_)) { + return raw; + } + let mut total = 0.0; + for item in context.level0 { + let mut path = context.row_path.to_vec(); + if let Some(first_item) = path.first_mut() { + *first_item = *item; + } + total += number(&lookup.get(&path, context.col_path, context.value_index)).unwrap_or(0.0); + if item == first { + break; + } + } + Value::number(total) +} + +fn ranked_value(raw: Value, lookup: &ValueLookup<'_>, context: &ShowContext<'_>) -> Value { + let Some((_, parent)) = context.row_path.split_last() else { return Value::Empty }; + let Some(me) = raw.as_f64() else { return raw }; + let siblings = context.siblings.get(parent).cloned().unwrap_or_default(); + // Excel's ranks are dense: ties share a rank and the next value takes the next one + // (5, 4, 3, 3, 4 rank 1, 2, 3, 3, 2), so count the distinct larger values. + let mut larger: Vec = siblings + .into_iter() + .filter_map(|sibling| { + let mut path = parent.to_vec(); + path.push(sibling); + number(&lookup.get(&path, context.col_path, context.value_index)).filter(|value| *value > me) + }) + .collect(); + larger.sort_by(f64::total_cmp); + larger.dedup(); + Value::number(larger.len() as f64 + 1.0) +} + +fn show_value(definition: &PivotValue, raw: Value, lookup: &ValueLookup<'_>, context: &ShowContext<'_>) -> Value { + match definition.show_as { + PivotShowAs::Normal => raw, + PivotShowAs::PercentOfGrandTotal => ratio(raw, lookup.get(&[], &[], context.value_index)), + PivotShowAs::PercentOfColumnTotal => ratio(raw, lookup.get(&[], context.col_path, context.value_index)), + PivotShowAs::PercentOfRowTotal => ratio(raw, lookup.get(context.row_path, &[], context.value_index)), + PivotShowAs::RunningTotal => running_total(raw, lookup, context), + PivotShowAs::Rank => ranked_value(raw, lookup, context), + } +} + +type ReportFilter<'a> = (usize, &'a PivotFilter, PivotDateGroup, bool); + +fn report_filters<'a>(pt: &'a PivotTable, src: &Source) -> (Vec>, Vec>) { + let axis_group = + |name: &str| pt.rows.iter().chain(pt.columns.iter()).find(|field| field.source_col.eq_ignore_ascii_case(name)).map(|field| field.date_group); + let filters: Vec<_> = pt + .filters + .iter() + .filter_map(|filter| { + let column = src.col(&filter.source_col)?; + let group = axis_group(&filter.source_col); + Some((column, filter, group.unwrap_or_default(), group.is_none())) + }) + .collect(); + let shown = filters.iter().copied().filter(|filter| filter.3).collect(); + (filters, shown) +} + +fn values_position(pt: &PivotTable, src: &Source, value_count: usize) -> Option { + if !pt.values_on_rows || value_count <= 1 { + return None; + } + let position = pt.values_position.unwrap_or(pt.rows.len()); + Some(pt.rows.iter().take(position).filter(|field| src.col(&field.source_col).is_some()).count()) +} + +fn calculated_source_columns(vals: &[(ValSrc, &PivotValue)], calc: &CalcSet, src: &Source) -> Vec { + let mut columns = Vec::new(); + for (source, _) in vals { + let ValSrc::Calc(index) = source else { continue }; + for name in calc.source_refs(*index) { + if let Some(column) = src.col(&name) + && !columns.contains(&column) + { + columns.push(column); + } + } + } + columns +} + +fn data_columns(specs: &[ColSpec], has_column_fields: bool, on_rows: bool, value_count: usize) -> Result)>, String> { + let mut columns = Vec::new(); + for (spec_index, _) in specs.iter().enumerate() { + if on_rows { + columns.push((spec_index, None)); + } else if value_count == 0 { + if has_column_fields { + columns.push((spec_index, None)); + } + } else { + columns.extend((0..value_count).map(|value_index| (spec_index, Some(value_index)))); + } + if columns.len() > MAX_COLS as usize { + return Err("The PivotTable report will not fit on the sheet.".into()); + } + } + Ok(columns) +} + +pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut probe: Option<&mut Probe>) -> Result { + let fmt_of = |c: usize| src.formats.get(c).cloned().unwrap_or_else(|| "General".into()); + let rows: Vec<(usize, &PivotField)> = pt.rows.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect(); + let cols: Vec<(usize, &PivotField)> = pt.columns.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect(); + // Value fields: a source column, or a calculated field evaluated on sums (see `pivot_calc`). + let calc = CalcSet::new(pt, &src.headers); + let vals: Vec<(ValSrc, &PivotValue)> = pt + .values + .iter() + .filter_map(|v| match src.col(&v.source_col) { + Some(c) => Some((ValSrc::Col(c), v)), + None => calc.index(&v.source_col).map(|i| (ValSrc::Calc(i), v)), + }) + .collect(); + // Source columns summed for the calculated fields, accumulated after the value fields. + let extra = calculated_source_columns(&vals, &calc, src); + if rows.len() + cols.len() > MAX_AXIS_FIELDS { + return Err(format!("A PivotTable can have at most {MAX_AXIS_FIELDS} row and column fields.")); + } + if vals.len() > MAX_VALUE_FIELDS { + return Err(format!("A PivotTable can have at most {MAX_VALUE_FIELDS} value fields.")); + } + let (filters, shown_filters) = report_filters(pt, src); + + let k = vals.len(); + let empty = rows.is_empty() && cols.is_empty() && vals.is_empty(); + // Σ Values in Rows (it exists with two or more value fields): its depth among the row fields + // found in the source. + let vpos = values_position(pt, src, k); + let on_rows = vpos.is_some(); + let row_levels = rows.len() + usize::from(on_rows); + + // ---- aggregate + let filter_fmts: Vec = filters.iter().map(|f| fmt_of(f.0)).collect(); + let row_fmts: Vec = rows.iter().map(|(c, _)| fmt_of(*c)).collect(); + let col_fmts: Vec = cols.iter().map(|(c, _)| fmt_of(*c)).collect(); + let aggregate = aggregate_source( + AggregateInput { + wb, + pt, + src, + rows: &rows, + cols: &cols, + vals: &vals, + extra: &extra, + filters: &filters, + filter_fmts: &filter_fmts, + row_fmts: &row_fmts, + col_fmts: &col_fmts, + empty, + }, + &mut probe, + )?; + let AggregateData { row_items, col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate; + + // ---- axes + let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect(); + let col_fields: Vec<&PivotField> = cols.iter().map(|(_, f)| *f).collect(); + let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect(); + let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect(); + let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items); + let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items); + let mut siblings: HashMap, Vec> = HashMap::new(); + collect_siblings(&row_tree, &mut Vec::new(), &mut siblings); + let level0: Vec = row_tree.iter().map(|n| n.item).collect(); + + let val_names: Vec = vals.iter().map(|(_, v)| v.name.clone()).collect(); + let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() }; + let mut lines: Vec = Vec::new(); + if row_levels == 0 { + lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None }); + } else { + if pt.layout == PivotLayout::Tabular { + ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines); + } else { + ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines); + } + // With only Σ Values in Rows its items are the totals already. + if pt.grand_totals_cols && !rows.is_empty() { + let grand = |text: String, vi: Option| Line { + kind: LineKind::Grand, + leaf: false, + path: vec![], + values: true, + labels: vec![(0, Value::text(text), 0, None)], + vi, + }; + if on_rows { + lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi)))); + } else { + lines.push(grand("Grand Total".into(), None)); + } + } + } + let mut specs: Vec = Vec::new(); + if cols.is_empty() { + specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] }); + } else { + flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs); + if pt.grand_totals_rows { + specs.push(ColSpec { kind: ColKind::Grand, path: vec![] }); + } + } + let data_cols = data_columns(&specs, !cols.is_empty(), on_rows, k)?; + + let compact = pt.layout == PivotLayout::Compact; + let l = if row_levels == 0 && cols.is_empty() { + 0 + } else if compact { + 1 + } else { + row_levels.max(1) + }; + let mut width = l + data_cols.len(); + if !shown_filters.is_empty() { + width = width.max(2); + } + if empty { + width = width.max(1); + } + let width = width.max(1); + let mut g = Grid { rows: vec![], kinds: vec![], width }; + + // ---- report filters + for (c, f, _, _) in &shown_filters { + let r = g.push_row(RowKind::Filter)?; + let name = src.headers.get(*c).cloned().unwrap_or_default(); + let shown = match &f.selected { + None => "(All)".to_string(), + Some(v) if v.len() == 1 => v.first().cloned().unwrap_or_default(), + Some(_) => "(Multiple Items)".to_string(), + }; + g.set(r, 0, Value::text(name), CellKind::Filter, 0, None); + g.set(r, 1, Value::text(shown), CellKind::Filter, 0, None); + } + if !shown_filters.is_empty() { + g.push_row(RowKind::Blank)?; + } + let body_offset = g.rows.len() as u32; + + if empty { + let r = g.push_row(RowKind::Placeholder)?; + g.set(r, 0, Value::text(format!("{} — choose fields", pt.name)), CellKind::Placeholder, 0, None); + return Ok(Output { + width: g.width as u32, + grid: g.rows, + row_kinds: g.kinds, + body_offset, + chart_rows: vec![], + chart_cols: vec![], + label_col: None, + }); + } + + write_headers( + &mut g, + HeaderInput { + vals: &vals, + row_fields: &row_fields, + col_fields: &col_fields, + col_items: &col_items, + col_fmts: &col_fmts, + vpos, + data_cols: &data_cols, + specs: &specs, + row_levels, + compact, + on_rows, + k, + l, + headers_on: pt.show_headers, + }, + )?; + let val_name = |vi: usize| vals.get(vi).map(|(_, value)| value.name.clone()).unwrap_or_default(); + + // ---- body + let data_fmt: Vec> = vals + .iter() + .map(|(vs, v)| match v.show_as { + PivotShowAs::PercentOfGrandTotal | PivotShowAs::PercentOfColumnTotal | PivotShowAs::PercentOfRowTotal => { + Some(v.number_format.clone().unwrap_or_else(|| "0.00%".into())) + } + PivotShowAs::Rank => v.number_format.clone(), + _ => v.number_format.clone().or_else(|| match v.func { + PivotFunc::Count | PivotFunc::CountNumbers => None, + _ => { + let f = match vs { + ValSrc::Col(c) => fmt_of(*c), + ValSrc::Calc(_) => "General".to_string(), + }; + (f != "General").then_some(f) + } + }), + }) + .collect(); + let lookup = ValueLookup { wb, source: src, calc: &calc, vals: &vals, extra: &extra, aggs: &aggs, value_count: k }; + let mut chart_rows: Vec = Vec::new(); + let chart_cols: Vec<(u32, String)> = data_cols + .iter() + .enumerate() + .filter_map(|(j, (si, vi))| { + let spec = specs.get(*si)?; + if spec.kind != ColKind::Leaf { + return None; + } + let mut parts: Vec = + spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect(); + if let Some(vi) = vi + && (k > 1 || parts.is_empty()) + { + parts.push(val_name(*vi)); + } else if parts.is_empty() { + parts.push("Total".into()); + } + Some(((l + j) as u32, parts.join(" - "))) + }) + .filter(|_| k > 0) + .collect(); + let label_col = if row_levels == 0 { + None + } else if compact { + Some(0) + } else { + Some(row_levels.saturating_sub(1) as u32) + }; + for line in &lines { + let rk = match line.kind { + LineKind::Item(b) => RowKind::Item(b), + LineKind::Subtotal => RowKind::Subtotal, + LineKind::Grand => RowKind::Grand, + }; + let ck = match line.kind { + LineKind::Item(_) => (CellKind::RowLabel, CellKind::Data), + LineKind::Subtotal => (CellKind::Subtotal, CellKind::Subtotal), + LineKind::Grand => (CellKind::GrandTotal, CellKind::GrandTotal), + }; + let r = g.push_row(rk)?; + if line.leaf && k > 0 { + chart_rows.push(r as u32); + } + for (c, v, indent, fmt) in &line.labels { + g.set(r, *c, v.clone(), ck.0, *indent, fmt.clone()); + } + if !line.values { + continue; + } + let rp = line.path.as_slice(); + for (j, (si, col_vi)) in data_cols.iter().enumerate() { + let line_vi = col_vi.or(line.vi); + let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue }; + let Some((_, vdef)) = vals.get(*vi) else { continue }; + let cp = spec.path.as_slice(); + let Some(raw) = lookup.get(rp, cp, *vi) else { continue }; + let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0: &level0, siblings: &siblings }; + let shown = show_value(vdef, raw, &lookup, &context); + if let Some(pr) = probe.as_deref_mut() { + if pr.at == Some((r, l + j)) { + pr.hit = Some((rp.to_vec(), cp.to_vec())); + } + if let Some(cells) = pr.cells.as_mut() { + cells.insert((r, l + j)); + } + } + g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten()); + } + } + Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col }) +} diff --git a/crates/engine/src/pivot/items.rs b/crates/engine/src/pivot/items.rs new file mode 100644 index 0000000000..79b74da1ab --- /dev/null +++ b/crates/engine/src/pivot/items.rs @@ -0,0 +1,269 @@ +use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial}; + +// ---------------------------------------------------------------- items + +#[derive(Clone, Debug)] +pub(super) struct Item { + pub(super) value: Value, + pub(super) label: String, + class: u8, + num: f64, + text: String, + first: usize, + /// The value is a number shown with the source format. + pub(super) formatted: bool, +} + +#[derive(Default)] +pub(super) struct FieldItems { + items: Vec, + index: HashMap, +} + +fn cmp_items(a: &Item, b: &Item) -> Ordering { + a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| a.text.cmp(&b.text)) +} + +/// (identity key, item) for a source value under a field's date grouping. +fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) { + let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item { + text: label.to_lowercase(), + value, + label, + class, + num, + first, + formatted, + }; + match v { + Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)), + Value::Number(n) => { + if group != PivotDateGroup::None + && let Some(dt) = datetime_from_serial(wb.date_system, *n) + { + let mon = MONTHS.get(dt.month.saturating_sub(1) as usize).copied().unwrap_or("Jan"); + let (label, key) = match group { + PivotDateGroup::Years => (dt.year.to_string(), dt.year as f64), + PivotDateGroup::Quarters => { + let q = (dt.month.saturating_sub(1)) / 3 + 1; + (format!("Qtr{q}"), q as f64) + } + PivotDateGroup::Months => (mon.to_string(), dt.month as f64), + _ => (format!("{}-{mon}", dt.day), (dt.month * 100 + dt.day) as f64), + }; + return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); + } + let label = crate::display::format(v, fmt, wb).text; + (format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true)) + } + Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), + Value::Bool(b) => { + let l = if *b { "TRUE" } else { "FALSE" }; + (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) + } + Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), + Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), + } +} + +impl FieldItems { + pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 { + let (key, item) = make_item(wb, v, group, fmt, first); + if let Some(i) = self.index.get(&key) { + return *i; + } + let i = self.items.len() as u32; + self.items.push(item); + self.index.insert(key, i); + i + } + pub(super) fn get(&self, i: u32) -> Option<&Item> { + self.items.get(i as usize) + } + pub(super) fn label(&self, i: u32) -> String { + self.get(i).map(|x| x.label.clone()).unwrap_or_default() + } +} + +/// The label of a source value under a date grouping (for filters and field lists). +pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String { + make_item(wb, v, group, fmt, 0).1.label +} + +/// Distinct item labels of a source column, sorted like the field list shows them. +pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec { + let mut fi = FieldItems::default(); + let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General"); + for (i, r) in src.rows.iter().enumerate() { + if let Some(v) = r.get(col) { + fi.intern(wb, v, group, fmt, i); + } + if fi.items.len() > 100_000 { + break; + } + } + let mut items = fi.items; + items.sort_by(cmp_items); + items.into_iter().take(limit).map(|i| i.label).collect() +} + +// ---------------------------------------------------------------- aggregation + +#[derive(Clone, Debug, Default)] +pub(super) struct Acc { + count: u64, + nums: u64, + sum: f64, + prod: f64, + min: f64, + max: f64, + mean: f64, + m2: f64, + err: Option, +} + +impl Acc { + pub(super) fn add(&mut self, v: &Value) { + match v { + Value::Empty => {} + Value::Number(n) => { + let n = *n; + self.count += 1; + self.nums += 1; + self.sum += n; + if self.nums == 1 { + self.prod = n; + self.min = n; + self.max = n; + } else { + self.prod *= n; + self.min = self.min.min(n); + self.max = self.max.max(n); + } + let d = n - self.mean; + self.mean += d / self.nums as f64; + self.m2 += d * (n - self.mean); + } + Value::Error(e) => { + self.count += 1; + if self.err.is_none() { + self.err = Some(*e); + } + } + _ => self.count += 1, + } + } + pub(super) fn result(&self, f: PivotFunc) -> Value { + let n = self.nums as f64; + match f { + PivotFunc::Count => return Value::number(self.count as f64), + PivotFunc::CountNumbers => return Value::number(n), + _ => {} + } + if let Some(e) = self.err { + return Value::Error(e); + } + let div0 = Value::Error(CellError::Div0); + match f { + PivotFunc::Sum => Value::number(self.sum), + PivotFunc::Average => { + if self.nums == 0 { + div0 + } else { + Value::number(self.sum / n) + } + } + PivotFunc::Max => Value::number(if self.nums == 0 { 0.0 } else { self.max }), + PivotFunc::Min => Value::number(if self.nums == 0 { 0.0 } else { self.min }), + PivotFunc::Product => Value::number(if self.nums == 0 { 0.0 } else { self.prod }), + PivotFunc::StdDev | PivotFunc::Var => { + if self.nums < 2 { + div0 + } else { + let var = (self.m2 / (n - 1.0)).max(0.0); + Value::number(if f == PivotFunc::Var { var } else { var.sqrt() }) + } + } + PivotFunc::StdDevP | PivotFunc::VarP => { + if self.nums < 1 { + div0 + } else { + let var = (self.m2 / n).max(0.0); + Value::number(if f == PivotFunc::VarP { var } else { var.sqrt() }) + } + } + PivotFunc::Count | PivotFunc::CountNumbers => Value::Empty, + } + } +} + +/// Excel's caption verb for a function ("Sum of Sales"). Count Numbers is captioned "Count of +/// Sales", as Excel names it and as the XLSX reader names a value field saved without a name. +pub fn func_caption(f: PivotFunc) -> &'static str { + match f { + PivotFunc::Sum => "Sum", + PivotFunc::Count => "Count", + PivotFunc::Average => "Average", + PivotFunc::Max => "Max", + PivotFunc::Min => "Min", + PivotFunc::Product => "Product", + PivotFunc::CountNumbers => "Count", + PivotFunc::StdDev => "StdDev", + PivotFunc::StdDevP => "StdDevp", + PivotFunc::Var => "Var", + PivotFunc::VarP => "Varp", + } +} + +// ---------------------------------------------------------------- trees + +#[derive(Clone, Debug)] +pub(super) struct Node { + pub(super) item: u32, + pub(super) children: Vec, +} + +pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec { + let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] }; + let mut order: Vec = Vec::new(); + let mut groups: HashMap> = HashMap::new(); + for p in paths { + if let Some(&it) = p.get(depth) { + let g = groups.entry(it).or_default(); + if g.is_empty() { + order.push(it); + } + g.push(p); + } + } + let mut nodes: Vec = order + .into_iter() + .map(|it| { + let ps = groups.remove(&it).unwrap_or_default(); + Node { item: it, children: build_tree(&ps, depth + 1, fields, items) } + }) + .collect(); + let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { + (Some(x), Some(y)) => match field.sort { + PivotSort::Asc => cmp_items(x, y), + PivotSort::Desc => cmp_items(y, x), + PivotSort::None => x.first.cmp(&y.first), + }, + _ => Ordering::Equal, + }; + nodes.sort_by(by); + nodes +} + +pub(super) fn is_collapsed(field: &PivotField, label: &str) -> bool { + field.collapsed_items.iter().any(|c| c.eq_ignore_ascii_case(label)) +} + +pub(super) fn collect_siblings(nodes: &[Node], prefix: &mut Vec, out: &mut HashMap, Vec>) { + out.insert(prefix.clone(), nodes.iter().map(|n| n.item).collect()); + for n in nodes { + prefix.push(n.item); + collect_siblings(&n.children, prefix, out); + prefix.pop(); + } +} diff --git a/crates/engine/src/pivot/output.rs b/crates/engine/src/pivot/output.rs new file mode 100644 index 0000000000..c3d6ee88d5 --- /dev/null +++ b/crates/engine/src/pivot/output.rs @@ -0,0 +1,440 @@ +use super::items::{Acc, FieldItems, Node, is_collapsed}; +use super::{ + BorderLine, BorderStyle, Color, Fill, HAlign, HashMap, MAX_COLS, MAX_OUTPUT_CELLS, MAX_ROWS, NumFmt, PivotField, PivotLayout, PivotTable, Style, + Value, +}; + +// ---------------------------------------------------------------- output + +/// What a report cell is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] +pub enum CellKind { + Empty, + Header, + RowLabel, + ColLabel, + Data, + Subtotal, + GrandTotal, + Filter, + Placeholder, +} + +/// What a report row is (for row-wide styling). +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] +pub enum RowKind { + Filter, + Blank, + Header, + /// Item row; `true` for a parent item (bold). + Item(bool), + Subtotal, + Grand, + Placeholder, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct OutCell { + pub value: Value, + pub kind: CellKind, + pub indent: u8, + pub num_fmt: Option, +} + +impl OutCell { + fn empty() -> OutCell { + OutCell { value: Value::Empty, kind: CellKind::Empty, indent: 0, num_fmt: None } + } +} + +/// A computed report: a dense grid relative to its top-left, with row kinds. +#[derive(Clone, Debug)] +pub struct Output { + pub grid: Vec>, + pub row_kinds: Vec, + /// Rows above the body (report filters plus a blank row). + pub body_offset: u32, + pub width: u32, + /// Grid rows of the innermost (or collapsed) items: a PivotChart's categories. + pub chart_rows: Vec, + /// Grid columns of item (not total) values with their series names: a PivotChart's series. + pub chart_cols: Vec<(u32, String)>, + /// Grid column holding the innermost row labels (`None` without row fields). + pub label_col: Option, +} + +impl Output { + pub fn height(&self) -> u32 { + self.grid.len() as u32 + } + /// Value at (row, col) relative to the top-left. + pub fn value(&self, r: usize, c: usize) -> Value { + self.grid.get(r).and_then(|row| row.get(c)).map(|x| x.value.clone()).unwrap_or_default() + } +} + +pub(super) struct Grid { + pub(super) rows: Vec>, + pub(super) kinds: Vec, + pub(super) width: usize, +} + +impl Grid { + pub(super) fn push_row(&mut self, kind: RowKind) -> Result { + if (self.rows.len() as u64 + 1) * self.width.max(1) as u64 > MAX_OUTPUT_CELLS || self.rows.len() as u64 >= MAX_ROWS as u64 { + return Err("The PivotTable report is too large.".into()); + } + self.rows.push(vec![OutCell::empty(); self.width]); + self.kinds.push(kind); + Ok(self.rows.len() - 1) + } + pub(super) fn set(&mut self, r: usize, c: usize, value: Value, kind: CellKind, indent: u8, fmt: Option) { + if let Some(cell) = self.rows.get_mut(r).and_then(|row| row.get_mut(c)) { + *cell = OutCell { value, kind, indent, num_fmt: fmt }; + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum LineKind { + Item(bool), + Subtotal, + Grand, +} + +pub(super) struct Line { + pub(super) kind: LineKind, + /// A category of a PivotChart: an innermost (or collapsed) item. + pub(super) leaf: bool, + pub(super) path: Vec, + pub(super) values: bool, + /// (column, value, indent, number format) + pub(super) labels: Vec<(usize, Value, u8, Option)>, + /// The value field of the line when Σ Values sits in Rows (`None`: one per data column). + pub(super) vi: Option, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ColKind { + Leaf, + Subtotal, + Grand, +} + +pub(super) struct ColSpec { + pub(super) kind: ColKind, + pub(super) path: Vec, +} + +pub(super) struct Ctx<'a> { + pub(super) pt: &'a PivotTable, + pub(super) rows: Vec<&'a PivotField>, + pub(super) row_items: Vec, + pub(super) row_fmts: Vec, + /// Depth of Σ Values among the row fields when it sits in Rows (two or more value fields). + pub(super) vpos: Option, + /// Value field captions. + pub(super) val_names: Vec, +} + +impl Ctx<'_> { + fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String) { + let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) }; + let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None }; + (it.value.clone(), fmt, it.label.clone()) + } + + /// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form. + fn level_cell(&self, level: usize) -> (usize, u8) { + if self.pt.layout == PivotLayout::Outline { (level, 0) } else { (0, level.min(250) as u8) } + } + + /// Σ Values comes right here, at row field depth `depth` (`vi`: the value field already chosen above). + fn values_here(&self, depth: usize, vi: Option) -> bool { + vi.is_none() && self.vpos == Some(depth) + } + + /// Per-value subtotal lines of an item with Σ Values below it ("East Sum of Sales"). + fn value_subtotals(&self, col: usize, indent: u8, label: &str, prefix: &[u32], out: &mut Vec) { + for (vi, name) in self.val_names.iter().enumerate() { + out.push(Line { + kind: LineKind::Subtotal, + leaf: false, + path: prefix.to_vec(), + values: true, + labels: vec![(col, Value::text(format!("{label} {name}")), indent, None)], + vi: Some(vi), + }); + } + } + + /// The Σ Values level at row field depth `depth`: one item per value field, each followed by + /// the row fields below it (`nodes`) or, innermost, holding that value. + fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, out: &mut Vec) { + let (col, indent) = self.level_cell(depth); + for (vi, name) in self.val_names.iter().enumerate() { + let labels = vec![(col, Value::text(name.as_str()), indent, None)]; + let leaf = nodes.is_empty(); + out.push(Line { kind: LineKind::Item(!leaf), leaf, path: prefix.clone(), values: leaf, labels, vi: Some(vi) }); + if !leaf { + self.flatten(nodes, depth, Some(vi), prefix, out); + } + } + } + + pub(super) fn flatten(&self, nodes: &[Node], depth: usize, vi: Option, prefix: &mut Vec, out: &mut Vec) { + if self.values_here(depth, vi) { + self.flatten_values(nodes, depth, prefix, out); + return; + } + let n = self.rows.len(); + // Σ Values still to come below this level: totals need one line per value field. + let values_below = vi.is_none() && self.vpos.is_some(); + let (col, indent) = self.level_cell(depth + usize::from(vi.is_some() && self.vpos.is_some())); + for node in nodes { + prefix.push(node.item); + let (v, fmt, label) = self.label_cell(depth, node.item); + let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label)); + let leaf = depth + 1 >= n || collapsed || node.children.is_empty(); + if leaf && !values_below { + out.push(Line { + kind: LineKind::Item(depth + 1 < n), + leaf: true, + path: prefix.clone(), + values: true, + labels: vec![(col, v, indent, fmt)], + vi, + }); + } else if leaf { + out.push(Line { + kind: LineKind::Item(true), + leaf: false, + path: prefix.clone(), + values: false, + labels: vec![(col, v, indent, fmt)], + vi, + }); + // Outline gives each level its own column, so the captions go in the Values + // column even when the levels between are collapsed away. + let level = if self.pt.layout == PivotLayout::Outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 }; + self.flatten_values(&[], level, prefix, out); + } else if values_below { + // Subtotals per value field, below the group (one line can't hold them all). + out.push(Line { + kind: LineKind::Item(true), + leaf: false, + path: prefix.clone(), + values: false, + labels: vec![(col, v, indent, fmt)], + vi, + }); + self.flatten(&node.children, depth + 1, None, prefix, out); + if self.pt.subtotals { + self.value_subtotals(col, indent, &label, prefix, out); + } + } else { + let top = self.pt.subtotals && self.pt.subtotals_top; + out.push(Line { + kind: LineKind::Item(true), + leaf: false, + path: prefix.clone(), + values: top, + labels: vec![(col, v, indent, fmt)], + vi, + }); + self.flatten(&node.children, depth + 1, vi, prefix, out); + if self.pt.subtotals && !self.pt.subtotals_top { + out.push(Line { + kind: LineKind::Subtotal, + leaf: false, + path: prefix.clone(), + values: true, + labels: vec![(col, Value::text(format!("{label} Total")), indent, None)], + vi, + }); + } + } + prefix.pop(); + } + } + + /// Tabular form of [`Self::flatten_values`]: the first line also carries the parents' labels. + fn flatten_tabular_values( + &self, + nodes: &[Node], + depth: usize, + prefix: &mut Vec, + pending: &[(usize, Value, u8, Option)], + out: &mut Vec, + ) { + for (vi, name) in self.val_names.iter().enumerate() { + let mut labels: Vec<(usize, Value, u8, Option)> = if vi == 0 { pending.to_vec() } else { vec![] }; + labels.push((depth, Value::text(name.as_str()), 0, None)); + if nodes.is_empty() { + out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi: Some(vi) }); + } else { + self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, out); + } + } + } + + pub(super) fn flatten_tabular( + &self, + nodes: &[Node], + depth: usize, + vi: Option, + prefix: &mut Vec, + pending: &[(usize, Value, u8, Option)], + out: &mut Vec, + ) { + if self.values_here(depth, vi) { + self.flatten_tabular_values(nodes, depth, prefix, pending, out); + return; + } + let n = self.rows.len(); + let values_below = vi.is_none() && self.vpos.is_some(); + let col = depth + usize::from(vi.is_some() && self.vpos.is_some()); + for (i, node) in nodes.iter().enumerate() { + prefix.push(node.item); + let (v, fmt, label) = self.label_cell(depth, node.item); + let mut labels: Vec<(usize, Value, u8, Option)> = if i == 0 { pending.to_vec() } else { vec![] }; + labels.push((col, v, 0, fmt)); + let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label)); + if depth + 1 >= n || collapsed || node.children.is_empty() { + if values_below { + self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out); + } else { + out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi }); + } + } else { + self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, out); + if self.pt.subtotals && values_below { + self.value_subtotals(col, 0, &label, prefix, out); + } else if self.pt.subtotals { + out.push(Line { + kind: LineKind::Subtotal, + leaf: false, + path: prefix.clone(), + values: true, + labels: vec![(col, Value::text(format!("{label} Total")), 0, None)], + vi, + }); + } + } + prefix.pop(); + } + } +} + +pub(super) fn flatten_cols( + nodes: &[Node], + depth: usize, + fields: &[&PivotField], + items: &[FieldItems], + subtotals: bool, + prefix: &mut Vec, + out: &mut Vec, +) { + let n = fields.len(); + for node in nodes { + prefix.push(node.item); + let label = items.get(depth).map(|fi| fi.label(node.item)).unwrap_or_default(); + let collapsed = depth + 1 < n && fields.get(depth).is_some_and(|f| is_collapsed(f, &label)); + if depth + 1 >= n || collapsed || node.children.is_empty() { + out.push(ColSpec { kind: ColKind::Leaf, path: prefix.clone() }); + } else { + flatten_cols(&node.children, depth + 1, fields, items, subtotals, prefix, out); + if subtotals { + out.push(ColSpec { kind: ColKind::Subtotal, path: prefix.clone() }); + } + } + prefix.pop(); + } +} + +pub(super) type AggMap = HashMap<(Vec, Vec), Vec>; + +/// Where a value field's numbers come from. +#[derive(Clone, Copy)] +pub(super) enum ValSrc { + /// A source column. + Col(usize), + /// A calculated field (index into the PivotTable's calculated fields). + Calc(usize), +} + +/// True when `col_groups` distinct column leaves (plus the grand-total column) times `values` value fields +/// (at least one data column per group) already exceed the sheet width. This is a lower bound on the final column count. +pub(super) fn data_cols_exceed_sheet(col_groups: usize, grand_total: bool, values: usize) -> bool { + (col_groups + usize::from(grand_total)).saturating_mul(values.max(1)) > MAX_COLS as usize +} + +// ---------------------------------------------------------------- styling and writing + +/// Colours for a PivotTable style name (our own palette, keyed by the familiar +/// `PivotStyleLight1…28 / Medium1…28 / Dark1…28` names). +pub(super) struct Look { + header_fill: Color, + header_font: Color, + line: Color, + filter_fill: Color, +} + +pub(super) fn look(style: &str) -> Look { + let rest = style.strip_prefix("PivotStyle").unwrap_or(style); + let (fam, n) = ["Light", "Medium", "Dark"] + .iter() + .find_map(|f| rest.strip_prefix(f).map(|num| (*f, num.parse::().unwrap_or(16)))) + .unwrap_or(("Light", 16)); + let k = n.saturating_sub(1) % 7; + let acc = if k == 0 { None } else { Some(3 + k as u8) }; + let tone = |tint: i16| match acc { + Some(a) => Color::Theme(a, tint), + None => Color::Theme(1, tint.clamp(-1000, 1000)), + }; + match fam { + "Dark" => Look { header_fill: Color::Theme(1, 0), header_font: Color::Theme(0, 0), line: tone(0), filter_fill: tone(600) }, + "Medium" => Look { header_fill: tone(0), header_font: Color::Theme(0, 0), line: tone(0), filter_fill: tone(800) }, + _ => Look { header_fill: tone(800), header_font: Color::Auto, line: tone(400), filter_fill: tone(800) }, + } +} + +pub(super) fn cell_style(lk: &Look, rk: RowKind, cell: &OutCell, last_header: bool) -> Style { + let mut s = Style::default(); + match rk { + RowKind::Header => { + s.font.bold = true; + s.fill = Fill::solid(lk.header_fill); + s.font.color = lk.header_font; + if last_header { + s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: lk.line }; + } + } + RowKind::Filter => { + s.fill = Fill::solid(lk.filter_fill); + s.font.bold = last_header; + } + RowKind::Item(parent) => s.font.bold = parent, + RowKind::Subtotal => s.font.bold = true, + RowKind::Grand => { + s.font.bold = true; + s.borders.top = BorderLine { style: BorderStyle::Thin, color: lk.line }; + } + RowKind::Placeholder => { + s.font.italic = true; + s.font.color = Color::Theme(1, 500); + } + RowKind::Blank => {} + } + if matches!(cell.kind, CellKind::RowLabel | CellKind::ColLabel | CellKind::Subtotal | CellKind::GrandTotal) && !cell.value.is_number() { + s.align.h = HAlign::Left; + } + if matches!(cell.kind, CellKind::RowLabel | CellKind::ColLabel) && cell.value.is_number() { + s.align.h = HAlign::Left; + } + s.align.indent = cell.indent.min(15); + if let Some(f) = &cell.num_fmt { + s.num_fmt = NumFmt::new(f); + } + s +} diff --git a/crates/engine/src/recent.rs b/crates/engine/src/recent.rs new file mode 100644 index 0000000000..0a1bba2dc2 --- /dev/null +++ b/crates/engine/src/recent.rs @@ -0,0 +1,205 @@ +//! Formulas › Recently Used: the functions most recently entered in a formula. +//! +//! The list is [`crate::Prefs::recent_functions`], an application list like Excel's, saved with +//! the other preferences. [`crate::Session::execute`] calls [`note`] for each `cell.*` and +//! `range.*` command it journals, from any source (the interface, the control channel, MCP or a +//! script), so the list never depends on the journal, which drops its oldest entries. + +use std::collections::HashSet; +use std::sync::OnceLock; + +use crate::cmd::edit::is_formula_input; +use gridcraft_formula::lexer::{Tok, tokenize}; +use gridcraft_formula::normalize_function_name; +use serde::Deserialize; +use serde_json::Value as Json; + +/// How many functions the list keeps. +pub const MAX: usize = 10; +/// The longest formula read (Excel's formula length limit): a longer one was not typed. +const FORMULA_MAX: usize = 8_192; +/// The most formulas read from one command: a large paste needs only its last few. +const SCAN_BUDGET: usize = 2_000; + +/// What the list holds before any function has been used. +pub fn defaults() -> Vec { + ["SUM", "AVERAGE", "IF", "COUNT", "MAX", "MIN", "SUMIF", "XLOOKUP", "PMT", "TODAY"].map(String::from).to_vec() +} + +/// Whether `name` (upper case, without `_xlfn.`) is a function of the catalog. +fn known(name: &str) -> bool { + static NAMES: OnceLock> = OnceLock::new(); + NAMES + .get_or_init(|| crate::cmd::formulas::function_list().iter().filter_map(|f| f["name"].as_str().map(str::to_ascii_uppercase)).collect()) + .contains(name) +} + +/// The functions a formula calls, outermost first, known functions only. A formula is what a +/// cell takes as one (`=…`, or `+…`/`-…` as Excel takes `+SUM(1)`). +pub fn functions_in_formula(text: &str) -> Vec { + if !is_formula_input(text) { + return vec![]; + } + let body = text.strip_prefix('=').unwrap_or(text); + if body.len() > FORMULA_MAX { + return vec![]; + } + let mut out: Vec = Vec::new(); + for t in tokenize(body).unwrap_or_default() { + if let Tok::Func(name) = t.tok { + let name = normalize_function_name(&name); + if known(&name) && !out.contains(&name) { + out.push(name); + } + } + } + out +} + +/// The formula texts a command's params enter, the last first, at most `budget` of them. +fn formulas_newest_first<'a>(id: &str, params: &'a Json, budget: usize) -> Vec<&'a str> { + fn walk<'a>(v: &'a Json, out: &mut Vec<&'a str>, depth: usize, budget: usize) { + match v { + Json::String(s) if is_formula_input(s) && out.len() < budget => out.push(s), + // A range's values are rows of cells; anything deeper is not a cell value. + Json::Array(a) if depth < 2 => { + for x in a.iter().rev() { + if out.len() >= budget { + return; + } + walk(x, out, depth + 1, budget); + } + } + _ => {} + } + } + let mut out = Vec::new(); + if id.starts_with("cell.") || id.starts_with("range.") { + for key in ["formula", "values", "value", "input"] { + if let Some(v) = params.get(key) { + walk(v, &mut out, 0, budget); + } + } + } + out +} + +/// Moves `names` (most recent first) to the front of `recent`, keeping at most [`MAX`]. +pub fn push(recent: &mut Vec, names: &[String]) { + let mut next: Vec = Vec::with_capacity(MAX); + for n in names.iter().chain(recent.iter()) { + if next.len() == MAX { + break; + } + if !next.contains(n) { + next.push(n.clone()); + } + } + *recent = next; +} + +/// Moves the functions that the formulas a command entered call to the front of `recent`. The +/// last formulas are read first (they are the most recent), within [`SCAN_BUDGET`]. +pub(crate) fn note(recent: &mut Vec, id: &str, params: &Json) { + let mut names: Vec = Vec::new(); + for f in formulas_newest_first(id, params, SCAN_BUDGET) { + for n in functions_in_formula(f) { + if !names.contains(&n) { + names.push(n); + } + } + if names.len() >= MAX { + break; + } + } + if !names.is_empty() { + push(recent, &names); + } +} + +/// Reads a saved list leniently: known function names only, at most [`MAX`]. A value that is not +/// a list gives the default list, so a hand-edited or hostile `prefs.json` loses this list, never +/// the other preferences. +pub(crate) fn lenient<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let raw = Json::deserialize(d)?; + let Some(list) = raw.as_array() else { return Ok(defaults()) }; + let mut out = Vec::new(); + for name in list.iter().filter_map(Json::as_str) { + if out.len() == MAX { + break; + } + let name = name.to_ascii_uppercase(); + if known(&name) && !out.contains(&name) { + out.push(name); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn formulas_name_their_functions_outermost_first() { + assert_eq!(functions_in_formula("=IF(SUM(A1:A3)>2,_xlfn.XLOOKUP(1,B:B,C:C),sum(1))"), ["IF", "SUM", "XLOOKUP"]); + assert!(functions_in_formula("=MYLAMBDA(1)+A1").is_empty(), "only known functions"); + assert!(functions_in_formula("SUM(1)").is_empty(), "not a formula"); + assert!(functions_in_formula("=\"SUM(\"").is_empty(), "inside a string"); + assert!(functions_in_formula(&format!("=SUM({})", "1+".repeat(9000))).is_empty(), "too long"); + assert!(functions_in_formula("=((((").is_empty()); + assert!(functions_in_formula("=").is_empty()); + // A formula may be typed with + or - instead of =, as input_to_cell takes it. + 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("- SUM(1)").is_empty(), "not formulas"); + } + + #[test] + fn commands_give_their_formulas_newest_first() { + let read = |id: &str, params: Json| formulas_newest_first(id, ¶ms, SCAN_BUDGET).into_iter().map(String::from).collect::>(); + assert_eq!(read("range.setValues", json!({"values": [["=SUM(1)", 2], ["x", "=PMT(1,2,3)"]]})), ["=PMT(1,2,3)", "=SUM(1)"]); + assert_eq!(read("cell.set", json!({"input": "=NPV(1,2)"})), ["=NPV(1,2)"]); + assert_eq!(read("range.setValues", json!({"values": [["+SUM(1)", "-5", "-ABS(2)"]]})), ["-ABS(2)", "+SUM(1)"]); + assert!(read("home.bold", json!({"input": "=IRR(1)"})).is_empty(), "only cell.* and range.* enter formulas"); + assert!(read("range.setValues", json!({"values": [[["=FV(1,2,3)"]]]})).is_empty(), "deeper than rows of cells"); + // A large paste is read from its end, within the budget. + let rows: Vec = (0..5_000).map(|i| json!([format!("=ABS({i})")])).collect(); + let paste = json!({ "values": rows }); + let last = formulas_newest_first("range.setValues", &paste, 3); + assert_eq!(last, ["=ABS(4999)", "=ABS(4998)", "=ABS(4997)"]); + } + + #[test] + fn recent_keeps_ten_distinct_newest_first() { + let mut r = defaults(); + assert!(r.iter().all(|n| known(n)), "the default list names known functions"); + push(&mut r, &["PMT".into(), "NPV".into()]); + assert_eq!(r.len(), MAX); + assert_eq!(&r[..3], ["PMT", "NPV", "SUM"]); + assert_eq!(r.iter().filter(|n| *n == "PMT").count(), 1); + let many: Vec = + ["ABS", "ACOS", "AND", "CHOOSE", "DATE", "EXP", "FIND", "INDEX", "LEFT", "LN", "MOD", "NOW"].map(String::from).to_vec(); + push(&mut r, &many); + assert_eq!(r, many[..MAX]); + } + + #[test] + fn a_saved_list_is_read_leniently() { + let prefs = |v: Json| serde_json::from_value::(v).unwrap(); + assert_eq!(prefs(json!({"r1c1": true})).recent_functions, defaults(), "a prefs.json from before the list gets the default"); + // A hostile value loses only itself, never the other preferences. + let bad = prefs(json!({"r1c1": true, "recentFunctions": 5})); + assert!(bad.r1c1); + assert_eq!(bad.recent_functions, defaults()); + let mut odd: Vec = ["npv", "NOT_A_FUNCTION", "SUM", "NPV"].iter().map(|n| json!(n)).chain([json!(3), json!(null)]).collect(); + odd.extend(crate::cmd::formulas::function_list().into_iter().take(40).map(|f| f["name"].clone())); + let odd = prefs(json!({ "recentFunctions": odd })); + assert_eq!(&odd.recent_functions[..2], ["NPV", "SUM"]); + assert_eq!(odd.recent_functions.len(), MAX); + let back = prefs(serde_json::to_value(&odd).unwrap()); + assert_eq!(back.recent_functions, odd.recent_functions, "the list survives a save and reload"); + } +} diff --git a/crates/engine/src/record.rs b/crates/engine/src/record.rs index 7804be6c9e..a970823309 100644 --- a/crates/engine/src/record.rs +++ b/crates/engine/src/record.rs @@ -8,6 +8,7 @@ use serde::Serialize; use serde_json::Value as Json; +use std::collections::BTreeMap; use crate::Selection; @@ -18,6 +19,11 @@ pub const RECORD_LIMIT: usize = 100_000; /// without a size cap a recording of a few opens of a large workbook keeps tens of MB alive. pub const RECORD_MAX_BYTES: usize = 64 * 1024 * 1024; +/// Commands never recorded: recovery actions and the debugger, not steps of the person's work. A +/// recording that replayed Stop Action would stop the run it is a step of, and the debugger runs +/// on its own, never as a step of a script or macro. +pub const NOT_RECORDED: [&str; 2] = ["automate.stopAction", "macro.debug"]; + /// One recorded command and where it ran. #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -34,33 +40,126 @@ pub struct RecordedStep { pub params: Json, } +/// Numbers each recording, so an undo group's mark from an earlier one isn't read as this one's. +static NEXT_RECORDING: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + /// The steps recorded since recording started. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub struct Recorder { pub steps: Vec, /// Steps not kept because the recording reached [`RECORD_LIMIT`] or [`RECORD_MAX_BYTES`]. /// Once a step is dropped, every later one is too, so `steps` is always the beginning of /// what ran, never a sequence with gaps. pub dropped: usize, - /// The size of `steps` serialized as JSON. + /// The size of `steps` and `ran` serialized as JSON. bytes: usize, + /// What a step ran, by its index in `steps`, for a command that runs steps stored in the + /// workbook (`automate.runScript`, `macro.run`): the commands as they ran, so a recording + /// keeps them even when the script or macro is edited or deleted before the recording stops. + /// A run without an entry is left out when the recording is used. + pub ran: BTreeMap>, + /// Which recording this is, and the number the next kept step gets: each step's number is in + /// `seqs`, beside it, so a mark stays right however many steps rollbacks take out. + generation: u64, + next_seq: u64, + seqs: Vec, +} + +impl Default for Recorder { + fn default() -> Self { + let generation = NEXT_RECORDING.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Recorder { steps: Vec::new(), dropped: 0, bytes: 0, ran: BTreeMap::new(), generation, next_seq: 0, seqs: Vec::new() } + } +} + +/// `params` with the state a toggle set (Bold's `on`, from the command's result), as Excel +/// records `Bold = True`: playing the step back sets that state rather than flipping it again. +/// `python.output` without `mode` is a toggle too: it keeps the return type it set (the result's +/// `output`) as its `mode`. +pub(crate) fn with_toggle_state(id: &str, mut params: Json, result: &Json) -> Json { + let state = match id { + "python.output" => result.get("output").filter(|o| o.is_string()).map(|o| ("mode", o)), + _ => result.get("on").filter(|o| o.is_boolean()).map(|o| ("on", o)), + }; + if let Some((key, state)) = state { + if params.is_null() { + params = Json::Object(serde_json::Map::new()); + } + if let Json::Object(p) = &mut params + && p.get(key).is_none_or(Json::is_null) + { + p.insert(key.into(), state.clone()); + } + } + params } impl Recorder { - /// Adds a step, or counts it as dropped once the buffer is full. - pub fn push(&mut self, step: RecordedStep) { + /// Adds a step, or counts it as dropped once the buffer is full; `true` when it was kept. + pub fn push(&mut self, step: RecordedStep) -> bool { // Once a step has been dropped, or the step count is full, the rest are counted without // being serialized (a `file.open` step holds a whole file). if self.dropped > 0 || self.steps.len() >= RECORD_LIMIT { self.dropped = self.dropped.saturating_add(1); - return; + return false; } let size = serde_json::to_vec(&step).map_or(0, |v| v.len()); if self.bytes.saturating_add(size) <= RECORD_MAX_BYTES { self.bytes = self.bytes.saturating_add(size); self.steps.push(step); + self.seqs.push(self.next_seq); + self.next_seq = self.next_seq.saturating_add(1); + true } else { self.dropped = self.dropped.saturating_add(1); + false } } + + /// Attaches what the last kept step ran ([`Recorder::ran`]), within the byte budget: past it, + /// the step stays without it, and the recording leaves the run out and lists it as skipped. + pub fn attach_ran(&mut self, steps: Vec<(String, Json)>) { + let Some(index) = self.steps.len().checked_sub(1) else { return }; + let size = serde_json::to_vec(&steps).map_or(0, |v| v.len()); + if self.bytes.saturating_add(size) <= RECORD_MAX_BYTES { + self.bytes = self.bytes.saturating_add(size); + self.ran.insert(index, steps); + } + } + + /// Where the recording is now, for [`Recorder::cut_back`]: this recording and the number its + /// next step gets. + pub(crate) fn mark(&self) -> (u64, u64) { + (self.generation, self.next_seq) + } + + /// Takes back the steps recorded in the document with uid `doc` since `mark` (an undo group + /// on it was rolled back, so playing them back would make edits it no longer has). Steps in + /// other documents stay: their edits do too. Steps the buffer dropped stay counted. + /// What a step ran ([`Recorder::ran`]) goes with its step, and stays with a kept one under its + /// new index. A mark from another recording (the recording started again inside the group) + /// means every step of this one came after it. + pub(crate) fn cut_back(&mut self, (generation, seq): (u64, u64), doc: u64) { + let from = if generation == self.generation { seq } else { 0 }; + let gone = |i: usize, step: &RecordedStep| step.doc == doc && self.seqs.get(i).is_some_and(|&n| n >= from); + if !self.steps.iter().enumerate().any(|(i, s)| gone(i, s)) { + return; + } + let mut ran = std::mem::take(&mut self.ran); + let (mut steps, mut seqs) = (Vec::with_capacity(self.steps.len()), Vec::with_capacity(self.seqs.len())); + for (i, step) in self.steps.iter().enumerate() { + if gone(i, step) { + continue; + } + if let Some(r) = ran.remove(&i) { + self.ran.insert(steps.len(), r); + } + steps.push(step.clone()); + seqs.push(self.seqs.get(i).copied().unwrap_or(0)); + } + (self.steps, self.seqs) = (steps, seqs); + let size = |v: Result, serde_json::Error>| v.map_or(0, |v| v.len()); + self.bytes = self.steps.iter().map(|s| size(serde_json::to_vec(s))).sum::() + + self.ran.values().map(|r| size(serde_json::to_vec(r))).sum::(); + } } diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 4df6fbe4ab..3f3feee9dc 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -128,6 +128,32 @@ impl Selection { } } +impl Selection { + /// Ctrl+. (Next Corner of Selection): the active cell moves clockwise to the next corner of + /// the current area (top-left, top-right, bottom-right, bottom-left) and becomes the anchor, + /// so Shift+arrows then move the opposite corner. The area stays selected. From a cell that + /// isn't a corner the next corner is the top-left one; a single cell stays where it is. + pub fn next_corner(&mut self) { + self.next_corner_by(Some); + } + + /// [`Selection::next_corner`] where `stop` says where each corner takes the active cell: the + /// top-left cell of a merged cell the corner is in, or `None` for a corner that can't be + /// selected (it is skipped). Corners that end up on the active cell are one stop with it. + pub fn next_corner_by(&mut self, stop: impl Fn(CellRef) -> Option) { + let r = self.current(); + let corners = [r.start, CellRef::new(r.start.row, r.end.col), r.end, CellRef::new(r.end.row, r.start.col)]; + let next = match corners.iter().rposition(|c| stop(*c) == Some(self.active)) { + Some(i) => (1..=4).filter_map(|k| corners.get((i + k) % 4)).filter_map(|c| stop(*c)).find(|c| *c != self.active), + None => corners.iter().find_map(|c| stop(*c)), + }; + if let Some(next) = next { + self.active = next; + self.anchor = next; + } + } +} + /// Ctrl+arrow: jump to the edge of the current data region (Excel's End mode). pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef { if dr == 0 && dc == 0 { @@ -190,7 +216,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 { - let filled = |c: CellRef| sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&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))); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a4..fe42b6977b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1081,6 +1081,48 @@ fn sort_and_filter() { assert_eq!(r["hiddenRows"], 1); } +/// Delete and the Clear commands on a filtered selection clear only the rows showing, as in +/// Excel (#1419); rows hidden by hand are cleared with the rest. +#[test] +fn clearing_a_filtered_selection_leaves_the_rows_the_filter_hides() { + let mut s = s(); + let rows = [["Name", "Status"], ["John", "Active"], ["Mary", "Inactive"], ["David", "Active"], ["Sarah", "Inactive"], ["Michael", "Active"]]; + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + s.execute("home.bold", json!({"range": "A2:A6", "on": true})).unwrap(); + s.execute("review.newNote", json!({"cell": "A3", "text": "note", "author": "Example"})).unwrap(); + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + s.execute("data.filter", json!({})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["Active"]})).unwrap(); + let bold = |s: &Session, a: &str| { + let d = s.doc().unwrap(); + d.wb.styles.get(d.wb.active().unwrap().style_id(CellRef::parse(a).unwrap())).font.bold + }; + + s.execute("edit.clearContents", json!({"range": "A2:A6"})).unwrap(); + for a in ["A2", "A4", "A6"] { + assert_eq!(v(&s, a), Value::Empty, "{a} shows and is cleared"); + } + assert_eq!(v(&s, "A3"), Value::from("Mary")); + assert_eq!(v(&s, "A5"), Value::from("Sarah")); + + s.execute("edit.clearFormats", json!({"range": "A2:A6"})).unwrap(); + assert!(!bold(&s, "A2")); + assert!(bold(&s, "A3"), "a filtered-out row keeps its format"); + + s.execute("edit.clearAll", json!({"range": "A2:B6"})).unwrap(); + assert_eq!(v(&s, "B2"), Value::Empty); + assert_eq!(v(&s, "B3"), Value::from("Inactive")); + assert_eq!(v(&s, "A5"), Value::from("Sarah")); + assert!(s.doc().unwrap().wb.active().unwrap().comments.contains_key(&CellRef::parse("A3").unwrap())); + + // Without the filter, a row hidden by hand is cleared like the rows around it. + s.execute("data.clearFilter", json!({})).unwrap(); + s.execute("home.hideRows", json!({"rows": "5:5"})).unwrap(); + s.execute("edit.clearContents", json!({"range": "A3:A5"})).unwrap(); + assert_eq!(v(&s, "A3"), Value::Empty); + assert_eq!(v(&s, "A5"), Value::Empty); +} + /// Top 10 keeps the top or bottom N items or percent, ties at the threshold included. #[test] fn filter_top10_items_and_percent() { @@ -1358,6 +1400,17 @@ fn protection_refuses_edits_of_locked_cells() { assert_eq!(v(&s, "A1"), Value::Number(1.0)); } +#[test] +fn locked_cell_message_matches_what_an_edit_would_be_refused_with() { + let s = protected(json!({})); + let locked = CellRef::parse("A1").unwrap(); + let unlocked = CellRef::parse("D1").unwrap(); + + assert!(s.locked_cell_message(0, locked).is_some_and(|m| m.contains("protected sheet"))); + assert_eq!(s.locked_cell_message(0, unlocked), None, "an unlocked cell stays editable"); + assert_eq!(s.locked_cell_message(9, locked), None, "no such sheet"); +} + #[test] fn protection_allows_permitted_row_and_column_edits() { let mut s = protected(json!({"insertRows": true, "deleteRows": true, "insertColumns": true})); @@ -1965,6 +2018,15 @@ fn a_whole_column_table_without_headers_stays_on_the_sheet() { assert!(e.to_string().contains("pushed off the end"), "{e}"); } +#[test] +fn inserting_a_column_next_to_far_right_data_names_gridcraft_in_the_refusal() { + let mut sess = s(); + sess.execute("cell.set", json!({"cell": "XFD1", "input": "2"})).unwrap(); + let e = sess.execute("home.insertColumns", json!({"cols": "A:A"})).unwrap_err(); + assert!(e.to_string().contains("GridCraft cannot shift nonblank cells"), "{e}"); + assert!(!e.to_string().contains("Excel"), "{e}"); +} + #[test] fn inserting_cells_refuses_to_push_values_off_the_sheet() { for (shift, edge, last_fit, last_ok) in [("right", "XFD1", "XFC1", "XFD1"), ("down", "A1048576", "A1048575", "A1048576")] { @@ -1973,6 +2035,7 @@ fn inserting_cells_refuses_to_push_values_off_the_sheet() { sess.execute("cell.set", json!({"cell": edge, "input": "2"})).unwrap(); let e = sess.execute("home.insertCells", json!({"range": "A1", "shift": shift})).unwrap_err(); assert!(e.to_string().contains("loss of data"), "{e}"); + assert!(e.to_string().contains("GridCraft") && !e.to_string().contains("Excel"), "{e}"); assert_eq!(v(&sess, "A1"), Value::Number(1.0)); assert_eq!(v(&sess, edge), Value::Number(2.0)); // A value that still fits moves to the last valid cell. @@ -2351,6 +2414,36 @@ fn deleting_a_3d_span_end_sheet_keeps_the_rest() { } } +#[test] +fn workbook_view_roundtrips_after_sheet_deletion_and_reordering() { + let view = gridcraft_model::WorkbookView { show_sheet_tabs: false, show_horizontal_scroll: true, show_vertical_scroll: false, tab_ratio: 350 }; + for (initial_active, command, params, expected_order, expected_active) in [ + ("Third", "home.deleteSheet", json!({"sheet": "First"}), vec!["Second", "Third"], 1), + ("Third", "home.deleteSheet", json!({"sheet": "Third"}), vec!["First", "Second"], 1), + ("First", "home.deleteSheet", json!({"sheet": "Third"}), vec!["First", "Second"], 0), + ("Third", "sheet.move", json!({"sheet": "Third", "to": 0}), vec!["Third", "First", "Second"], 0), + ("Third", "sheet.move", json!({"sheet": "First", "to": 2}), vec!["Second", "Third", "First"], 2), + ] { + let mut session = s(); + session.execute("sheet.rename", json!({"name": "First"})).unwrap(); + for name in ["Second", "Third"] { + session.execute("home.insertSheet", json!({"name": name})).unwrap(); + } + std::sync::Arc::make_mut(&mut session.doc_mut().unwrap().wb).view = view; + session.execute("sheet.activate", json!({"sheet": initial_active})).unwrap(); + session.execute(command, params).unwrap(); + + let wb = &session.doc().unwrap().wb; + assert_eq!(wb.active_sheet(), expected_active, "{command}"); + assert_eq!(wb.sheets.iter().map(|s| s.name.as_str()).collect::>(), expected_order, "{command}"); + let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(wb).unwrap()).unwrap(); + assert_eq!(back.sheets.iter().map(|s| s.name.as_str()).collect::>(), expected_order, "{command} after reopening"); + assert_eq!(back.active_sheet(), expected_active, "activeTab follows {command}"); + assert_eq!(back.active().unwrap().name, expected_order[expected_active], "the active sheet is not a stale index"); + assert_eq!(back.view, view, "workbook display settings survive {command}"); + } +} + #[test] fn xlsx_roundtrip_through_engine() { let mut s = s(); @@ -2406,8 +2499,7 @@ fn ods_import_keeps_cached_values_and_reports_limits() { #[test] #[cfg(not(target_arch = "wasm32"))] fn ods_import_never_reuses_source_as_save_target() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-ods-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let bytes = ods_fixture(); @@ -2437,8 +2529,7 @@ fn ods_import_never_reuses_source_as_save_target() { #[test] #[cfg(not(target_arch = "wasm32"))] fn saving_an_opened_semicolon_csv_keeps_semicolons() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-csv-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let path = dir.join("cut list.csv"); @@ -2460,6 +2551,53 @@ fn saving_an_opened_semicolon_csv_keeps_semicolons() { std::fs::remove_dir_all(dir).unwrap(); } +/// `file.exportCsv` writes displayed text by default (Excel's Save As CSV); `values: true` writes the +/// raw values for automation: full precision, ISO dates and times. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn export_csv_values_writes_raw_values_and_the_default_stays_displayed_text() { + let mut s = s(); + for (cell, input, code) in [ + ("A1", "1234.5", "$#,##0.00"), + ("B1", "0.123456789", "0.00"), + ("C1", "46023", "d-mmm-yy"), + ("D1", "46023.5", "yyyy-mm-dd hh:mm"), + ("E1", "0.75", "h:mm"), + ("F1", "TRUE", "General"), + ("G1", "a,b", "General"), + ("H1", "=1/0", "General"), + ("I1", "1", "h:mm"), + ("J1", "1.5", "h:mm"), + ("K1", "46023", "yyyy-mm-dd hh:mm"), + ("L1", "1.5", "[h]:mm"), + ("M1", "2.5", "[>=3]yyyy-mm-dd;[<3]hh:mm"), + ] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + s.execute("home.numberFormat", json!({"range": cell, "code": code})).unwrap(); + } + #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("gridcraft-csv-values-{}-{nonce}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let displayed = dir.join("displayed.csv"); + s.execute("file.exportCsv", json!({"path": displayed})).unwrap(); + s.execute("file.exportCsv", json!({"path": dir.join("off.csv"), "values": false})).unwrap(); + let raw = dir.join("raw.csv"); + s.execute("file.exportCsv", json!({"path": raw, "values": true})).unwrap(); + let saved = s.execute("file.saveBytes", json!({"format": "csv"})).unwrap(); + let default = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap(); + // The default export is byte for byte what Save As CSV writes, and `values: false` is the default. + assert_eq!(std::fs::read(&displayed).unwrap(), default); + assert_eq!(std::fs::read(dir.join("off.csv")).unwrap(), default); + let default = String::from_utf8(default).unwrap(); + assert!(default.starts_with("\"$1,234.50\",0.12,1-Jan-26,"), "{default}"); + assert_eq!( + std::fs::read_to_string(&raw).unwrap(), + "1234.5,0.123456789,2026-01-01,2026-01-01T12:00:00,18:00:00,TRUE,\"a,b\",#DIV/0!,00:00:00,12:00:00,2026-01-01T00:00:00,1.5,12:00:00\r\n" + ); + std::fs::remove_dir_all(dir).unwrap(); +} + /// A workbook whose B1 is `=[1]Sheet1!A1`, linked to `link` (an external relationship target). fn linked_workbook(link: &str) -> Vec { use std::io::{Cursor, Write}; @@ -2512,8 +2650,7 @@ fn link_target(path: &std::path::Path) -> String { #[test] #[cfg(not(target_arch = "wasm32"))] fn save_as_into_another_folder_keeps_linked_workbooks_on_the_same_file() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let a = std::env::temp_dir().join(format!("gridcraft-links-{}-{nonce}", std::process::id())); let b = a.join("b"); std::fs::create_dir_all(&b).unwrap(); @@ -2541,8 +2678,7 @@ fn save_as_into_another_folder_keeps_linked_workbooks_on_the_same_file() { #[test] #[cfg(not(target_arch = "wasm32"))] fn saving_to_an_unknown_extension_is_refused() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-unknown-ext-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let mut s = s(); @@ -2566,8 +2702,7 @@ fn saving_to_an_unknown_extension_is_refused() { #[test] #[cfg(not(target_arch = "wasm32"))] fn an_xlsx_opened_under_an_unknown_extension_saves_back_as_xlsx() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-dat-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let path = dir.join("budget.dat"); @@ -2608,6 +2743,78 @@ fn validation_formulas_are_relative_and_see_the_new_value() { assert!(!ok(&mut s, "C1", "50")); } +#[test] +fn multi_area_rule_formulas_are_relative_to_the_top_left_cell_of_all_areas() { + // Issue #3152: Excel writes the formula for the top-left cell of all the areas (H26), whatever + // order they are listed in, not for the first area listed (H62). + let mut s = s(); + s.execute("range.setValues", json!({"range": "F26:F27", "values": [[4], [5]]})).unwrap(); + s.execute("data.validation", json!({"range": "H62:H68,H26:H27,H93:H95", "type": "custom", "formula1": "=MOD($H26,$F26)=0"})).unwrap(); + let ok = |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == true; + assert!(ok(&mut s, "H26", "4")); + assert!(ok(&mut s, "H26", "8")); + assert!(!ok(&mut s, "H26", "3")); + assert!(ok(&mut s, "H27", "10")); + assert!(!ok(&mut s, "H27", "4")); + + // Conditional formats anchor on the same cell: `=D2>0` on D5:D6,D2:D3 checks D2 at D2. + s.execute("range.setValues", json!({"range": "D2:D6", "values": [[1], [0], [0], [1], [0]]})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "D5:D6,D2:D3", "rule": {"type": "expression", "formula": "=D2>0", "preset": "greenFill"}})) + .unwrap(); + let wb = s.doc().unwrap().wb.clone(); + let mut cache = crate::cf::CfCache::new(); + let mut styled = |c: &str| cache.look(&wb, 0, CellRef::parse(c).unwrap()).and_then(|l| l.style).is_some(); + assert_eq!([styled("D2"), styled("D3"), styled("D5"), styled("D6")], [true, false, true, false]); +} + +#[test] +fn removing_a_rules_top_left_cell_rewrites_its_formulas_for_the_new_one() { + let mut s = s(); + let ok = |s: &mut Session, cell: &str, input: &str| s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == true; + let f1 = |s: &Session| s.doc().unwrap().wb.active().unwrap().validations[0].f1.clone(); + + // One area: clearing A1 off A1:A9 leaves A2:A9, whose cells still check themselves. + s.execute("data.validation", json!({"range": "A1:A9", "type": "custom", "formula1": "=A1>10"})).unwrap(); + s.execute("data.validation", json!({"range": "A1", "clear": true})).unwrap(); + assert_eq!(f1(&s), "A2>10"); + assert!(ok(&mut s, "A2", "20")); + assert!(!ok(&mut s, "A2", "5")); + s.execute("data.validation", json!({"range": "A1:A9", "clear": true})).unwrap(); + + // Several areas: clearing H26 moves the top-left cell to H27, where `$H27,$F27` is checked. + s.execute("range.setValues", json!({"range": "F26:F27", "values": [[4], [5]]})).unwrap(); + s.execute("data.validation", json!({"range": "H62:H68,H26:H27", "type": "custom", "formula1": "=MOD($H26,$F26)=0"})).unwrap(); + s.execute("data.validation", json!({"range": "H26", "clear": true})).unwrap(); + assert_eq!(f1(&s), "MOD($H27,$F27)=0"); + assert!(ok(&mut s, "H27", "10")); + assert!(!ok(&mut s, "H27", "4")); + // Absolute and literal formulas don't move. + s.execute("data.validation", json!({"range": "J1:J3", "type": "list", "formula1": "=$B$1:$B$2"})).unwrap(); + s.execute("data.validation", json!({"range": "J1", "clear": true})).unwrap(); + let dv = s.doc().unwrap().wb.active().unwrap().validations.iter().find(|d| d.ranges[0].a1() == "J2:J3").unwrap().f1.clone(); + assert_eq!(dv, "$B$1:$B$2"); + + // Conditional formats: Clear Rules on D2 drops the D2:D3 area, and D5:D6 keeps reading itself. + s.execute("range.setValues", json!({"range": "D2:D6", "values": [[1], [0], [0], [0], [1]]})).unwrap(); + s.execute("home.conditionalFormat", json!({"range": "D5:D6,D2:D3", "rule": {"type": "expression", "formula": "=D2>0", "preset": "greenFill"}})) + .unwrap(); + s.execute("range.setValues", json!({"range": "E2:E6", "values": [[1], [0], [0], [0], [1]]})).unwrap(); + s.execute("range.setValues", json!({"range": "G2:G6", "values": [[0], [9], [9], [9], [0]]})).unwrap(); + s.execute( + "home.conditionalFormat", + json!({"range": "E5:E6,E2:E3", "rule": {"type": "cellIs", "operator": "greater", "value": "=G2", "preset": "lightRedFill"}}), + ) + .unwrap(); + s.execute("home.clearRules", json!({"range": "D2,E2"})).unwrap(); + let rules: Vec = s.doc().unwrap().wb.active().unwrap().cond_formats.iter().map(|c| c.rule.clone()).collect(); + assert!(rules.iter().any(|r| matches!(r, gridcraft_model::CfRule::Expression { formula, .. } if formula == "D5>0")), "{rules:?}"); + assert!(rules.iter().any(|r| matches!(r, gridcraft_model::CfRule::CellIs { a, .. } if a == "G5")), "{rules:?}"); + let wb = s.doc().unwrap().wb.clone(); + let mut cache = crate::cf::CfCache::new(); + let mut styled = |c: &str| cache.look(&wb, 0, CellRef::parse(c).unwrap()).and_then(|l| l.style).is_some(); + assert_eq!([styled("D5"), styled("D6"), styled("E5"), styled("E6")], [false, true, false, true]); +} + #[test] fn samples_build() { for (name, _) in crate::sample::SAMPLES { @@ -2841,6 +3048,24 @@ fn checkboxes_keep_values_toggle_and_delete_in_two_passes() { assert_ne!(fmt_of(&s, "B2"), "checkbox"); } +/// A checked box in a row the filter hides doesn't hold back Delete on the boxes showing, and +/// stays as it is (#1419). +#[test] +fn delete_on_filtered_checkboxes_skips_the_hidden_rows() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Status"], ["on"], ["off"], ["on"]]})).unwrap(); + s.execute("insert.checkbox", json!({"range": "B2:B4"})).unwrap(); + s.execute("cell.toggleCheckbox", json!({"cell": "B3"})).unwrap(); + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + s.execute("data.filter", json!({})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["on"]})).unwrap(); + s.execute("edit.clearContents", json!({"range": "B2:B4"})).unwrap(); + assert_ne!(fmt_of(&s, "B2"), "checkbox", "the unchecked boxes showing are removed at once"); + assert_ne!(fmt_of(&s, "B4"), "checkbox"); + assert_eq!(fmt_of(&s, "B3"), "checkbox"); + assert_eq!(v(&s, "B3"), Value::Bool(true)); +} + #[test] fn checkboxes_survive_xlsx_as_cell_controls() { let mut s = s(); @@ -3240,8 +3465,7 @@ fn xlsb_import_keeps_cached_values_and_reports_limits() { #[test] #[cfg(not(target_arch = "wasm32"))] fn xlsb_import_never_reuses_source_as_save_target() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-xlsb-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let bytes = xlsb_fixture(); @@ -4410,8 +4634,7 @@ fn encrypted_workbooks_open_with_their_password() { #[cfg(not(target_arch = "wasm32"))] fn a_decrypted_workbook_never_overwrites_its_encrypted_original() { const PW: &str = "synthetic-pw-5522"; - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-encrypted-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let path = dir.join("Secret.xlsx"); @@ -4544,8 +4767,7 @@ fn csv_as_text_keeps_identifier_columns_as_written() { #[test] #[cfg(not(target_arch = "wasm32"))] fn cell_filename_follows_the_file_the_workbook_lives_in() { - #[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name - let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nonce = unique_nonce(); let dir = std::env::temp_dir().join(format!("gridcraft-cellname-{}-{nonce}", std::process::id())); std::fs::create_dir(&dir).unwrap(); let name = "=CELL(\"filename\",A1)"; @@ -5075,6 +5297,42 @@ fn move_columns_checks_the_protection_of_the_named_sheet() { assert_eq!(v(&s, "A1"), Value::text("A")); } +#[test] +fn move_columns_checks_the_protection_of_a_sheet_named_by_its_range() { + // A `Sheet!` range or cell picks the sheet the move modifies; the protection checks must + // authorize that sheet too, not the active one. + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "P"})).unwrap(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4]]})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + for key in ["range", "cell"] { + let err = s.execute("sheet.moveColumns", json!({key: "P!A1", "cols": "B:C", "before": 4})).expect_err("moving columns on a protected sheet"); + assert!(err.to_string().contains("protected"), "{err}"); + } + let d = s.doc().unwrap(); + let sh = &d.wb.sheets[d.wb.sheet_index("P").unwrap()]; + let pv: Vec = (0..4).map(|c| sh.value(CellRef::new(0, c))).collect(); + assert_eq!(pv, vec![Value::number(1.0), Value::number(2.0), Value::number(3.0), Value::number(4.0)]); +} + +#[test] +fn sorting_cannot_unlock_a_locked_cell_by_moving_equal_content_onto_it() { + // An unlocked 2 sorted onto a locked 2 leaves the content as it was, but would make the cell + // editable; the sort is refused instead. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[2], [2], [1]]})).unwrap(); + s.execute("home.lockCell", json!({"range": "A1", "on": false})).unwrap(); + s.execute("home.lockCell", json!({"range": "A3", "on": false})).unwrap(); + s.execute("review.protectSheet", json!({"sort": true})).unwrap(); + let before = s.doc().unwrap().wb.clone(); + let err = + s.execute("data.sort", json!({"range": "A1:A3", "header": false, "keys": [{"column": "A", "order": "asc"}]})).expect_err("sort unlocking A2"); + assert!(err.to_string().contains("protected sheet"), "{err}"); + assert_eq!(*s.doc().unwrap().wb, *before); + assert!(s.execute("cell.set", json!({"cell": "A2", "input": "9"})).is_err(), "A2 stays locked"); +} + #[test] fn a_script_cannot_switch_windows() { // Stored scripts are scoped to their workbook: a step that activates another window would @@ -5093,6 +5351,12 @@ fn a_script_cannot_switch_windows() { assert_eq!(v(&s, "A1"), Value::number(2.0)); } +mod equation; +mod macros; +mod objects; +mod python_cells; +mod python_commands; +mod python_files; mod seams; #[test] @@ -5117,3 +5381,194 @@ fn a_saved_workbook_keeps_its_values_until_an_edit_reaches_them() { assert_eq!(v(&saved, "B1"), Value::Number(6.0)); assert_eq!(v(&saved, "C1"), Value::Number(7.0)); } + +/// A per-test unique suffix for temp dir names. +#[cfg(not(target_arch = "wasm32"))] +fn unique_nonce() -> u64 { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +/// Normal, Page Layout and Page Break Preview are not undo steps (as in Excel), so undoing or +/// redoing an edit keeps each sheet in the view it is in now, instead of putting back the view +/// of the snapshot it swaps in. Found through the command-sequence fuzz (seed 177). +#[test] +fn undo_and_redo_keep_each_sheets_view() { + use gridcraft_model::SheetViewMode; + let view = |s: &Session, i: usize| s.doc().unwrap().wb.sheet(i).unwrap().view; + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("view.pageBreakPreview", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Empty); + assert_eq!(view(&s, 0), SheetViewMode::PageBreakPreview, "undo leaves the view alone"); + s.execute("view.pageLayout", json!({})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(1.0)); + assert_eq!(view(&s, 0), SheetViewMode::PageLayout, "redo leaves the view alone"); + + // Undoing a rename: the sheet is found at its position under the restored name. + s.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap(); + s.execute("view.normal", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_ne!(s.doc().unwrap().wb.sheet(0).unwrap().name, "Renamed"); + assert_eq!(view(&s, 0), SheetViewMode::Normal); + + // Undoing a new sheet: the other sheets keep theirs. + s.execute("view.pageBreakPreview", json!({})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Extra"})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets.len(), 1); + assert_eq!(view(&s, 0), SheetViewMode::PageBreakPreview); +} + +#[test] +fn a_multi_step_undo_keeps_views_through_each_step() { + // A rename and a new sheet undone in one call: neither the name nor the sheet count matches + // between the first and last workbook, so the view is carried step by step. + let mut s = s(); + let first = s.doc().unwrap().wb.sheet(0).unwrap().name.clone(); + s.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap(); + s.execute("view.pageBreakPreview", json!({"sheet": 0})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Extra"})).unwrap(); + s.execute("edit.undo", json!({"steps": 2})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.wb.sheets.len(), 1); + assert_eq!(d.wb.sheet(0).unwrap().name, first); + assert_eq!(d.wb.sheet(0).unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview); + s.execute("edit.redo", json!({"steps": 2})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!((d.wb.sheets.len(), d.wb.sheet(0).unwrap().name.as_str()), (2, "Renamed")); + assert_eq!(d.wb.sheet(0).unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview); +} + +#[test] +fn a_view_kept_through_redo_doesnt_make_the_saved_workbook_dirty() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + d.saved = d.wb.clone(); + } + s.execute("edit.undo", json!({})).unwrap(); + s.execute("view.pageBreakPreview", json!({})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.wb.active().unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview); + assert!(!d.is_dirty(), "back at the saved edits, the view alone isn't a change"); +} + +#[test] +fn workbook_display_options_are_commands() { + // #3101: Show sheet tabs / horizontal / vertical scroll bar, toggling without `on`, saved with + // the workbook and undoable. + let mut s = Session::new(); + s.new_workbook(); + let view = |s: &Session| s.doc().unwrap().wb.view; + assert_eq!(s.execute("view.showSheetTabs", json!({})).unwrap()["on"], json!(false)); + assert_eq!(s.execute("view.showHorizontalScrollBar", json!({"on": false})).unwrap()["on"], json!(false)); + assert_eq!(s.execute("view.showVerticalScrollBar", json!({"on": false})).unwrap()["on"], json!(false)); + let v = view(&s); + assert!(!v.show_sheet_tabs && !v.show_horizontal_scroll && !v.show_vertical_scroll); + let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap()).unwrap(); + assert_eq!(back.view, v, "saved with the workbook"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(view(&s).show_vertical_scroll); + assert_eq!(s.execute("view.showSheetTabs", json!({})).unwrap()["on"], json!(true), "toggles back"); +} + +/// A link from a file can sit on a cell with nothing stored in it, past the used range (or on a +/// sheet with no cells at all). Clear Hyperlinks, and Remove Hyperlink in the cell menu, must +/// still remove it. +#[test] +fn clear_hyperlinks_removes_links_on_cells_with_nothing_stored() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + let link = || gridcraft_model::Hyperlink { target: "https://example.com".into(), tooltip: None, external: true }; + let (a1, c5) = (CellRef::parse("A1").unwrap(), CellRef::parse("C5").unwrap()); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().hyperlinks.insert(c5, link()); + s.execute("edit.clearHyperlinks", json!({"range": "C5"})).unwrap(); + assert!(!s.doc().unwrap().wb.active().unwrap().hyperlinks.contains_key(&c5), "the link past the used range is removed"); + + // No cells at all. + s.execute("edit.clearAll", json!({"range": "A1"})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().hyperlinks.insert(a1, link()); + s.execute("edit.clearHyperlinks", json!({"range": "A1"})).unwrap(); + assert!(!s.doc().unwrap().wb.active().unwrap().hyperlinks.contains_key(&a1), "the link on an empty sheet is removed"); +} + +/// Notes and links aren't cell contents, so the cell comparison that guards a protected sheet +/// doesn't see them go: Clear Hyperlinks and Clear Comments refuse locked cells themselves, +/// stored or not. +#[test] +fn clearing_links_and_notes_respects_sheet_protection() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + let link = || gridcraft_model::Hyperlink { target: "https://example.com".into(), tooltip: None, external: true }; + let (a1, c5) = (CellRef::parse("A1").unwrap(), CellRef::parse("C5").unwrap()); + { + let sh = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.hyperlinks.insert(a1, link()); + sh.hyperlinks.insert(c5, link()); + } + s.execute("review.newNote", json!({"cell": "C5", "text": "note", "author": "Example"})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + for (cmd, range) in [("edit.clearHyperlinks", "A1"), ("edit.clearHyperlinks", "C5"), ("edit.clearComments", "C5")] { + assert!(s.execute(cmd, json!({"range": range})).is_err(), "{cmd} on locked {range}"); + } + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + assert!(sh.hyperlinks.contains_key(&a1) && sh.hyperlinks.contains_key(&c5) && sh.comments.contains_key(&c5), "nothing removed"); + + s.execute("review.unprotectSheet", json!({})).unwrap(); + s.execute("edit.clearHyperlinks", json!({"range": "A1:C5"})).unwrap(); + s.execute("edit.clearComments", json!({"range": "C5"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + assert!(sh.hyperlinks.is_empty() && sh.comments.is_empty()); +} + +/// A removed link or note is a change to its cell even when nothing is stored there, so a +/// recorded macro's footprint lists it. +#[test] +fn clearing_links_and_notes_records_their_cells() { + let mut s = s(); + let c5 = CellRef::parse("C5").unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb) + .sheet_mut(0) + .unwrap() + .hyperlinks + .insert(c5, gridcraft_model::Hyperlink { target: "https://example.com".into(), tooltip: None, external: true }); + s.execute("review.newNote", json!({"cell": "D7", "text": "note", "author": "Example"})).unwrap(); + s.doc_mut().unwrap().touched = Some(Vec::new()); + s.execute("edit.clearHyperlinks", json!({"range": "C5"})).unwrap(); + s.execute("edit.clearComments", json!({"range": "D7"})).unwrap(); + let touched: Vec = s.doc().unwrap().touched.clone().unwrap_or_default().into_iter().map(|(_, c)| c.a1()).collect(); + assert!(touched.contains(&"C5".to_string()) && touched.contains(&"D7".to_string()), "{touched:?}"); +} + +/// The locked-cell check for notes and links keeps Allow Edit Ranges: a range without a password +/// allows them at once, one with a password once it's unlocked in this session. +#[test] +fn clearing_links_and_notes_keeps_allow_edit_ranges() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + let link = || gridcraft_model::Hyperlink { target: "https://example.com".into(), tooltip: None, external: true }; + let (a1, c5) = (CellRef::parse("A1").unwrap(), CellRef::parse("C5").unwrap()); + { + let sh = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.hyperlinks.insert(a1, link()); + sh.hyperlinks.insert(c5, link()); + } + s.execute("review.newNote", json!({"cell": "C5", "text": "note", "author": "Example"})).unwrap(); + // Ranges are added before protecting: a protected sheet refuses `add`. + s.execute("review.allowEditRanges", json!({"action": "add", "title": "Open", "range": "A1"})).unwrap(); + s.execute("review.allowEditRanges", json!({"action": "add", "title": "Kept", "range": "C5", "password": "example"})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + + s.execute("edit.clearHyperlinks", json!({"range": "A1"})).unwrap(); + assert!(s.execute("edit.clearComments", json!({"range": "C5"})).is_err(), "a password range stays locked until unlocked"); + s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Kept", "password": "example"})).unwrap(); + s.execute("edit.clearHyperlinks", json!({"range": "C5"})).unwrap(); + s.execute("edit.clearComments", json!({"range": "C5"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap().clone(); + assert!(sh.hyperlinks.is_empty() && sh.comments.is_empty()); +} diff --git a/crates/engine/src/tests/equation.rs b/crates/engine/src/tests/equation.rs new file mode 100644 index 0000000000..6b544b2acc --- /dev/null +++ b/crates/engine/src/tests/equation.rs @@ -0,0 +1,227 @@ +//! Equations: insert, edit, the layout cache and its rebuild on load. + +use gridcraft_model::{Color, Shape, ShapeKind}; +use serde_json::json; + +use super::s; +use crate::Session; + +fn equation(s: &Session, id: u32) -> Shape { + s.doc().unwrap().wb.active().unwrap().shapes.iter().find(|x| x.id == id).cloned().unwrap() +} + +fn insert(s: &mut Session, p: serde_json::Value) -> u32 { + s.execute("insert.equation", p).unwrap()["equation"].as_u64().unwrap() as u32 +} + +#[test] +fn insert_lays_the_equation_out_and_sizes_its_frame() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}", "cell": "C3"})); + let e = equation(&s, id); + assert_eq!(e.kind, ShapeKind::Equation); + assert_eq!(e.anchor.cell.a1(), "C3"); + assert_eq!(e.line, Color::Auto, "Automatic ink"); + let list = e.math.get(&e.text).unwrap().unwrap(); + let scale = crate::cmd::equation::fit_scale(list, e.anchor.width, e.anchor.height); + assert!((scale - 11.0 * 96.0 / 72.0).abs() < 0.01, "11 pt: {scale}"); + // A bigger size makes a bigger frame; `at` works like `cell`. + let big = insert(&mut s, json!({"latex": "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}", "at": "H3", "size": 22, "color": "#1F4E79"})); + let b = equation(&s, big); + assert!((b.anchor.width - 8.0) > 1.9 * (e.anchor.width - 8.0)); + assert_eq!(b.line, Color::Rgb(0x1F4E79)); + assert_eq!(b.anchor.cell.a1(), "H3"); + // One undo step each. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().shapes.iter().all(|x| x.id != big)); +} + +#[test] +fn insert_refuses_missing_bad_or_hostile_source() { + let mut s = s(); + for p in [ + json!({}), + json!({"latex": ""}), + json!({"latex": " "}), + json!({"latex": 5}), + json!({"latex": "x", "size": 0}), + json!({"latex": "x", "size": f64::MAX}), + json!({"latex": "x", "color": "nope"}), + ] { + assert!(s.execute("insert.equation", p.clone()).is_err(), "{p}"); + } + let e = s.execute("insert.equation", json!({"latex": "a + \\foo"})).unwrap_err().to_string(); + assert!(e.contains("character 5") && e.contains("\\foo"), "{e}"); + let e = s.execute("insert.equation", json!({"latex": "x".repeat(5000)})).unwrap_err().to_string(); + assert!(e.contains("4096"), "{e}"); + let e = s.execute("insert.equation", json!({"latex": format!("{}x{}", "{".repeat(40), "}".repeat(40))})).unwrap_err().to_string(); + assert!(e.contains("nest"), "{e}"); + assert!(s.doc().unwrap().wb.active().unwrap().shapes.is_empty()); + // `equation.edit` is the other way a source reaches the layout engine; it has the same caps, + // and a refused edit leaves the equation as it was. + let id = insert(&mut s, json!({"latex": "x"})); + let e = s.execute("equation.edit", json!({"id": id, "latex": "x".repeat(5000)})).unwrap_err().to_string(); + assert!(e.contains("4096"), "{e}"); + let e = s.execute("equation.edit", json!({"id": id, "latex": format!("{}x{}", "{".repeat(40), "}".repeat(40))})).unwrap_err().to_string(); + assert!(e.contains("nest"), "{e}"); + assert_eq!(equation(&s, id).text, "x"); +} + +#[test] +fn edit_keeps_the_scale_and_fits_the_frame() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x", "size": 20})); + let before = equation(&s, id); + s.execute("equation.edit", json!({"id": id, "latex": "x + y + z"})).unwrap(); + let after = equation(&s, id); + assert_eq!(after.text, "x + y + z"); + let list = after.math.get(&after.text).unwrap().unwrap(); + let scale = crate::cmd::equation::fit_scale(list, after.anchor.width, after.anchor.height); + assert!((scale - 20.0 * 96.0 / 72.0).abs() < 0.05, "{scale}"); + assert!(after.anchor.width > before.anchor.width); + // A frame the user resized keeps its new scale through an edit. + s.execute("object.move", json!({"kind": "equation", "id": id, "width": after.anchor.width * 2.0, "height": after.anchor.height * 2.0})).unwrap(); + s.execute("equation.edit", json!({"id": id, "latex": "x + y"})).unwrap(); + let e = equation(&s, id); + let scale = crate::cmd::equation::fit_scale(e.math.get(&e.text).unwrap().unwrap(), e.anchor.width, e.anchor.height); + assert!(scale > 2.0 * 20.0 * 96.0 / 72.0 * 0.95, "{scale}"); + // Undo restores the source and its layout. + s.execute("edit.undo", json!({})).unwrap(); + let e = equation(&s, id); + assert_eq!(e.text, "x + y + z"); + assert!(e.math.get(&e.text).unwrap().is_ok()); + // Same source: nothing to do. Bad source: refused, nothing changes. + let depth = s.doc().unwrap().undo.len(); + s.execute("equation.edit", json!({"id": id, "latex": "x + y + z"})).unwrap(); + assert_eq!(s.doc().unwrap().undo.len(), depth); + assert!(s.execute("equation.edit", json!({"id": id, "latex": "\\frac{"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": id, "latex": ""})).is_err()); + assert_eq!(equation(&s, id).text, "x + y + z"); +} + +#[test] +fn the_source_excerpt_is_at_most_the_cap_and_whole_chars() { + use crate::cmd::equation::source_excerpt; + use gridcraft_math::MAX_SOURCE_BYTES as CAP; + assert_eq!(source_excerpt(""), ""); + assert_eq!(source_excerpt("x+y"), "x+y"); + let at = "x".repeat(CAP); + assert_eq!(source_excerpt(&at), at, "a source at the cap is whole"); + assert_eq!(source_excerpt(&format!("{at}tail")), at); + // A three-byte character straddling the cap is left out rather than cut in two. + let s = format!("{}\u{20AC}", "x".repeat(CAP - 1)); + assert_eq!(source_excerpt(&s), "x".repeat(CAP - 1)); + let s = format!("{}\u{20AC}\u{20AC}", "x".repeat(CAP - 2)); + assert_eq!(source_excerpt(&s).len(), CAP - 2); + assert_eq!(source_excerpt(&"\u{1F600}".repeat(2000)).len(), CAP); +} + +#[test] +fn edit_refuses_what_is_not_an_equation() { + let mut s = s(); + let tb = s.execute("insert.textBox", json!({"text": "hi"})).unwrap()["shape"].as_u64().unwrap(); + assert!(s.execute("equation.edit", json!({"id": tb, "latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": 999, "latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": -1, "latex": "x"})).is_err()); +} + +#[test] +fn layouts_are_rebuilt_on_load_and_not_saved() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "e^{i\\pi} + 1 = 0"})); + let wb = s.doc().unwrap().wb.clone(); + let bytes = serde_json::to_vec(&*wb).unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("\"math\""), "the cache is not saved"); + let (opened, _) = crate::io::open_bytes("book.json", &bytes).unwrap(); + let raw = opened.active().unwrap().shapes.iter().find(|x| x.id == id).cloned().unwrap(); + assert!(raw.math.get(&raw.text).is_none(), "a freshly read shape has no layout"); + let mut t = Session::new(); + t.add_document(crate::DocState::new(opened, None, "Book".into(), crate::Trust::FromFile)); + let e = equation(&t, id); + assert!(e.math.get(&e.text).unwrap().is_ok(), "opening lays it out"); +} + +#[test] +fn a_bad_source_from_a_file_keeps_its_error() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + sh.shapes.iter_mut().for_each(|x| x.text = "\\frac{".into()); + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let e = equation(&t, id); + assert!(e.math.get(&e.text).unwrap().is_err()); +} + +#[test] +fn equations_on_a_protected_sheet_are_locked() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x"})); + s.execute("review.protectSheet", json!({})).unwrap(); + assert!(s.execute("equation.edit", json!({"id": id, "latex": "y"})).is_err()); + assert!(s.execute("insert.equation", json!({"latex": "y"})).is_err()); +} + +#[test] +fn a_file_with_too_many_equations_lays_out_a_bounded_amount() { + // About 1 KB each: past the budget, equations are refused without running the layout engine, + // so opening the file takes bounded time. + let source = format!("x{}", "+x".repeat(500)); + let count = gridcraft_model::MAX_EQUATION_LAYOUT_BYTES / source.len() + 40; + let mut s = s(); + let first = insert(&mut s, json!({"latex": "x", "cell": "A1"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + let template = sh.shapes.iter().find(|x| x.id == first).cloned().unwrap(); + sh.shapes.clear(); + for i in 0..count { + let mut e = template.clone(); + e.id = 100 + i as u32; + e.text = source.clone(); + e.math = Default::default(); + sh.shapes.push(e); + } + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let shapes = t.doc().unwrap().wb.active().unwrap().shapes.clone(); + let laid = shapes.iter().filter(|x| matches!(x.math.get(&x.text), Some(Ok(_)))).count(); + let refused: Vec<&Shape> = + shapes.iter().filter(|x| matches!(x.math.get(&x.text), Some(Err(e)) if e.message == gridcraft_model::EQUATION_BUDGET_MESSAGE)).collect(); + assert_eq!(laid + refused.len(), count, "every equation has a layout or the budget's error"); + assert!(laid * source.len() <= gridcraft_model::MAX_EQUATION_LAYOUT_BYTES, "{laid} laid out"); + assert!(refused.len() >= 40, "{} refused", refused.len()); + // A later edit does not retry them all, and OK on one, unchanged, lays it out. + let id = refused[0].id; + t.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + assert!(matches!(equation(&t, id).math.get(&source), Some(Err(_)))); + t.execute("equation.edit", json!({"id": id, "latex": source})).unwrap(); + assert!(matches!(equation(&t, id).math.get(&source), Some(Ok(_))), "editing lays it out"); +} + +#[test] +fn ids_stay_unique_when_a_file_used_the_largest_id() { + // A workbook (from a JSON file, say) whose shape has id u32::MAX: new equations and the + // objects of a copied sheet still get ids no other object has. + let mut s = s(); + let first = insert(&mut s, json!({"latex": "x", "cell": "A1"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + sh.shapes.iter_mut().filter(|x| x.id == first).for_each(|x| x.id = u32::MAX); + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let a = insert(&mut t, json!({"latex": "y", "cell": "C1"})); + let b = insert(&mut t, json!({"latex": "z", "cell": "E1"})); + t.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &t.doc().unwrap().wb; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| sh.shapes.iter().map(|x| x.id)).collect(); + assert_eq!(ids.len(), 6, "three equations on each sheet"); + assert!(a != u32::MAX && b != u32::MAX && a != b, "{a} {b}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 6, "every id is distinct: {ids:?}"); +} diff --git a/crates/engine/src/tests/macros.rs b/crates/engine/src/tests/macros.rs new file mode 100644 index 0000000000..aa17080fac --- /dev/null +++ b/crates/engine/src/tests/macros.rs @@ -0,0 +1,2436 @@ +//! Macros: running, input checks, the footprint dry run, the policy and the limits. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use gridcraft_core::CellRef; +use serde_json::{Value as Json, json}; + +use super::{s, v}; +use crate::{EngineError, Session}; + +fn undo_labels(s: &Session) -> Vec { + s.doc().unwrap().undo.iter().map(|e| e.label.clone()).collect() +} + +fn set(s: &mut Session, cell: &str, input: &str) { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); +} + +/// Puts a macro into the active workbook (replacing one with the same name). +pub(super) fn put(s: &mut Session, m: Json) { + let m = crate::macros::parse_macro(&m).unwrap(); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.retain(|x| !x.name.eq_ignore_ascii_case(&m.name)); + wb.macros.push(m); + d.wb = Arc::new(wb); + d.saved = d.wb.clone(); +} + +/// Names in B2:B5 and amounts in C2:C5 under a header row. +fn data(s: &mut Session) { + for (cell, input) in [("B2", "Name"), ("C2", "Amount"), ("B3", "Ann"), ("C3", "120"), ("B4", "Bo"), ("C4", "80"), ("B5", "Cy"), ("C5", "200")] { + set(s, cell, input); + } +} + +/// A macro that writes a label and a total next to its input and bolds the header. +fn totals() -> Json { + json!({ + "name": "Totals", + "inputs": [{"name": "Input", "header": true, "cols": [2, 2], "colTypes": ["text", "number"]}], + "output": {"anchor": "Input.right(2).cell(1,2)"}, + "steps": [ + {"command": "cell.set", "params": {"cell": "Output", "input": "Total"}}, + {"command": "cell.set", "params": {"cell": "Output.offset(1,0)", "input": "=SUM({{Input.data.col(2)}})"}}, + {"command": "home.bold", "params": {"range": "Input.row(1)"}} + ] + }) +} + +fn bold(s: &Session, a: &str) -> bool { + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + d.wb.styles.get(sh.style_id(gridcraft_core::CellRef::parse(a).unwrap())).font.bold +} + +#[test] +fn a_run_resolves_tokens_and_is_one_undo_step() { + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + let before = undo_labels(&s); + let r = s.execute("macro.run", json!({"name": "totals", "inputs": {"Input": "B2:C5"}})).unwrap(); + assert_eq!(r["ran"], 3); + assert_eq!(r["inputs"], json!({"Input": "B2:C5"})); + assert_eq!(v(&s, "E2").display(), "Total"); + assert_eq!(v(&s, "E3").display(), "400"); + assert_eq!(s.doc().unwrap().wb.active().unwrap().input_text(gridcraft_core::CellRef::parse("E3").unwrap()), "=SUM(C3:C5)"); + assert!(bold(&s, "B2") && bold(&s, "C2")); + let after = undo_labels(&s); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().unwrap(), "Run Macro: Totals"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(v(&s, "E2").is_empty() && v(&s, "E3").is_empty() && !bold(&s, "B2")); + assert_eq!(undo_labels(&s), before); + // The selection is the default input. + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.run", json!({"name": "Totals"})).unwrap(); + assert_eq!(v(&s, "E3").display(), "400"); +} + +#[test] +fn inputs_are_checked_with_messages_that_name_the_cells() { + let mut s = s(); + data(&mut s); + set(&mut s, "C4", "eighty"); + set(&mut s, "C5", "TRUE"); + put(&mut s, totals()); + let start = s.doc().unwrap().wb.clone(); + let err = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5"})).unwrap_err().to_string(); + assert!(err.contains("Input column 2 (Amount) must hold numbers; C4 holds text, C5 holds TRUE or FALSE."), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "nothing ran"); + + // Shape: width, rows, a single cell, blanks, dates. + let mut m = totals(); + m["inputs"][0] = json!({"name": "Input", "header": true, "rows": [1, 2], "cols": [3, 3], "nonEmpty": true, "colTypes": ["any", "date"]}); + put(&mut s, m); + set(&mut s, "B4", ""); + let err = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5"})).unwrap_err().to_string(); + for needle in [ + "Input needs at most 2 data rows; B2:C5 has 3.", + "Input needs exactly 3 columns; B2:C5 has 2.", + "Input column 2 (Amount) must hold dates; C3 holds a number that isn't a date, C4 holds text, C5 holds TRUE or FALSE.", + "Input must have no blank cells; B4 is blank.", + ] { + assert!(err.contains(needle), "missing `{needle}` in {err}"); + } + let mut m = totals(); + m["inputs"][0] = json!({"name": "Input", "kind": "cell"}); + put(&mut s, m); + let err = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5"})).unwrap_err().to_string(); + assert!(err.contains("Input must be a single cell; B2:C5 is 8 cells."), "{err}"); + // A second input with no range, and a bad reference. + put(&mut s, json!({"name": "Two", "inputs": [{"name": "Input"}, {"name": "Rates"}], "steps": []})); + let err = s.execute("macro.run", json!({"name": "Two"})).unwrap_err().to_string(); + assert!(err.contains("Rates needs a range"), "{err}"); + let err = s.execute("macro.run", json!({"name": "Two", "inputs": {"Rates": "Nowhere!A1"}})).unwrap_err().to_string(); + assert!(err.contains("Rates: There is no sheet named 'Nowhere'."), "{err}"); + // Whole columns shrink to the cells in use. + put( + &mut s, + json!({"name": "Col", "inputs": [{"name": "Input", "rows": [1, 10]}], "steps": [{"command": "cell.set", "params": {"cell": "Input.below", "input": "end"}}], "output": {"onConflict": "overwrite"}}), + ); + s.execute("macro.run", json!({"name": "Col", "inputs": "B:B"})).unwrap(); + assert_eq!(v(&s, "B6").display(), "end"); + assert!(s.execute("macro.run", json!({"name": "nope"})).unwrap_err().to_string().contains("no macro called 'nope'")); +} + +#[test] +fn an_error_rolls_everything_back_and_names_the_step() { + let mut s = s(); + data(&mut s); + let mut m = totals(); + m["output"]["onConflict"] = json!("overwrite"); + m["steps"][2] = json!({"type": "repeat", "over": "Input.data", "body": [ + {"command": "home.italic", "params": {"range": "Row"}}, + {"command": "cell.set", "params": {"cell": "Row.cell(1,9)", "input": "=1/"}} + ]}); + put(&mut s, m); + let (before, undo) = (s.doc().unwrap().wb.clone(), undo_labels(&s)); + let err = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5"})).unwrap_err().to_string(); + assert!(err.starts_with("Macro 'Totals' stopped. Step 3.2 (cell.set):"), "{err}"); + assert!(err.ends_with("Nothing was changed."), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &before)); + assert_eq!(undo_labels(&s), undo); + assert!(s.doc().unwrap().redo.is_empty()); +} + +#[test] +fn conflicts_ask_fail_or_overwrite() { + let mut s = s(); + data(&mut s); + set(&mut s, "E3", "keep me"); + // A formula that reads what the macro writes: its value changes, but it isn't written. + set(&mut s, "H1", "=E3"); + put(&mut s, totals()); + let start = s.doc().unwrap().wb.clone(); + let r = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5"})); + let Err(EngineError::Confirm(q)) = r else { panic!("{r:?}") }; + assert!(q.contains("would write over cells that hold data (E3 on Sheet1)"), "{q}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "programmatic runs default to failing"); + let err = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5", "onConflict": "fail"})).unwrap_err().to_string(); + assert!(err.contains("Nothing was changed"), "{err}"); + assert!(s.execute("macro.run", json!({"name": "Totals", "onConflict": "sideways"})).is_err()); + + // macro.check shows the footprint and the conflict, and changes nothing. + let journal = s.journal.len(); + let sel = s.doc().unwrap().selection.clone(); + let c = s.execute("macro.check", json!({"name": "Totals", "inputs": "B2:C5"})).unwrap(); + // Under ask the run would ask first, so it wouldn't go ahead as it is. + assert_eq!((&c["ok"], &c["onConflict"]), (&json!(false), &json!("ask"))); + assert_eq!(c["errors"], json!(["It would write over cells that hold data (E3 on Sheet1); the run asks first."])); + assert_eq!(c["conflicts"], 1); + assert_eq!(c["output"], "E2"); + assert_eq!(c["footprint"]["sheets"][0]["cells"], json!(["E2:E3"])); + assert_eq!(c["footprint"]["sheets"][0]["conflicts"], json!(["E3"])); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert_eq!((s.journal.len(), &s.doc().unwrap().selection), (journal, &sel)); + // With the answer given, or with the rule overwrite, it would. + for p in [json!({"overwrite": true}), json!({"onConflict": "overwrite"})] { + let mut p = p; + (p["name"], p["inputs"]) = (json!("Totals"), json!("B2:C5")); + let c = s.execute("macro.check", p.clone()).unwrap(); + assert_eq!((&c["ok"], &c["onConflict"], c.get("errors")), (&json!(true), &json!("overwrite"), None), "{p}"); + } + + // The answer to the question overwrites. + s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "E3").display(), "400"); + assert_eq!(v(&s, "H1").display(), "400"); +} + +/// The value of `cell` on the sheet called `sheet`. +fn on(s: &Session, sheet: &str, cell: &str) -> String { + let wb = &s.doc().unwrap().wb; + wb.sheet(wb.sheet_index(sheet).unwrap()).unwrap().value(CellRef::parse(cell).unwrap()).display() +} + +#[test] +fn inputs_and_the_output_follow_their_cells_when_a_step_moves_them() { + // A sheet inserted in front: the input is still on Sheet1, not on whatever sheet is first now. + let mut s = s(); + let steps = json!([ + {"command": "home.insertSheet", "params": {"name": "Summary", "before": 0}}, + {"command": "cell.set", "params": {"cell": "Input", "input": "x"}} + ]); + put( + &mut s, + json!({"name": "Front", "inputs": [{"name": "Input", "kind": "cell"}], "output": {"onConflict": "overwrite"}, "steps": steps.clone()}), + ); + s.execute("macro.run", json!({"name": "Front", "inputs": "Sheet1!B2"})).unwrap(); + assert_eq!((on(&s, "Sheet1", "B2"), on(&s, "Summary", "B2")), ("x".into(), "".into())); + + // Data in the input: the step writes into its own input, which isn't data written over, on + // the input's sheet wherever it moved. + let mut s = super::s(); + set(&mut s, "B2", "held"); + put(&mut s, json!({"name": "Front", "inputs": [{"name": "Input", "kind": "cell"}], "output": {"onConflict": "fail"}, "steps": steps})); + s.execute("macro.run", json!({"name": "Front", "inputs": "Sheet1!B2"})).unwrap(); + assert_eq!(on(&s, "Sheet1", "B2"), "x"); + + // Rows inserted above: the input and the output move down with their cells. + let mut s = super::s(); + set(&mut s, "B5", "in"); + let steps = json!([ + {"command": "home.insertRows", "params": {"rows": "2:3"}}, + {"command": "cell.set", "params": {"cell": "Input", "input": "x"}}, + {"command": "cell.set", "params": {"cell": "Output", "input": "y"}} + ]); + put( + &mut s, + json!({"name": "Down", "inputs": [{"name": "Input", "kind": "cell"}], "output": {"anchor": "D5", "onConflict": "overwrite"}, "steps": steps}), + ); + s.execute("macro.run", json!({"name": "Down", "inputs": "B5"})).unwrap(); + assert_eq!((v(&s, "B7").display(), v(&s, "D7").display()), ("x".into(), "y".into())); + assert_eq!((v(&s, "B5").display(), v(&s, "D5").display()), ("".into(), "".into())); + + // A step that deletes an input's cells stops the run. + let mut s = super::s(); + set(&mut s, "B5", "in"); + let steps = json!([{"command": "home.deleteRows", "params": {"rows": "5"}}, {"command": "cell.set", "params": {"cell": "Input", "input": "x"}}]); + put(&mut s, json!({"name": "Gone", "inputs": [{"name": "Input", "kind": "cell"}], "output": {"onConflict": "overwrite"}, "steps": steps})); + let start = s.doc().unwrap().wb.clone(); + let err = s.execute("macro.run", json!({"name": "Gone", "inputs": "B5"})).unwrap_err().to_string(); + assert!(err.contains("Step 1 (home.deleteRows): It deleted the cells of Input."), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + + // A step inside a Repeat that changes the size of the range it goes over stops the run. + let mut s = super::s(); + let body = json!([{"command": "home.insertRows", "params": {"rows": "2"}}]); + put(&mut s, json!({"name": "Grow", "output": {"onConflict": "overwrite"}, "steps": [{"type": "repeat", "over": "A1:A3", "body": body}]})); + let err = s.execute("macro.run", json!({"name": "Grow"})).unwrap_err().to_string(); + assert!(err.contains("Step 1.1 (home.insertRows): It changed the size of the range Repeat 1 goes over."), "{err}"); +} + +#[test] +fn shifting_makes_room_and_is_checked_again() { + for (rule, moved) in [("shiftDown", ["E4", "E5"]), ("shiftRight", ["F2", "F3"])] { + let mut s = s(); + data(&mut s); + set(&mut s, "E2", "old 1"); + set(&mut s, "E3", "old 2"); + put(&mut s, totals()); + let r = s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5", "onConflict": rule})).unwrap(); + assert_eq!(r["shifted"], rule); + assert_eq!((v(&s, "E2").display(), v(&s, "E3").display()), ("Total".into(), "400".into()), "{rule}"); + assert_eq!((v(&s, moved[0]).display(), v(&s, moved[1]).display()), ("old 1".into(), "old 2".into()), "{rule}"); + // The shift and the run are one undo step. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(v(&s, "E2").display(), "old 1", "{rule}"); + assert!(v(&s, moved[1]).is_empty(), "{rule}"); + } + // A cell written with what it already holds isn't a conflict, but it moves with the others, + // so rows stay together. + let mut s = super::s(); + for (cell, input) in [("F2", "x"), ("G2", "b"), ("F3", "f3"), ("G3", "g3")] { + set(&mut s, cell, input); + } + put( + &mut s, + json!({"name": "Pair", "output": {"onConflict": "shiftDown"}, "steps": [ + {"command": "cell.set", "params": {"cell": "F2", "input": "a"}}, + {"command": "cell.set", "params": {"cell": "G2", "input": "b"}} + ]}), + ); + let c = s.execute("macro.check", json!({"name": "Pair"})).unwrap(); + assert_eq!((c["conflicts"].as_u64(), &c["footprint"]["sheets"][0]["cells"]), (Some(1), &json!(["F2:G2"]))); + s.execute("macro.run", json!({"name": "Pair"})).unwrap(); + let row = |s: &Session, r: u32| (v(s, &format!("F{r}")).display(), v(s, &format!("G{r}")).display()); + assert_eq!(row(&s, 2), ("a".into(), "b".into())); + assert_eq!(row(&s, 3), ("x".into(), "b".into())); + assert_eq!(row(&s, 4), ("f3".into(), "g3".into())); + // An anchor that moves with the shifted data still lands on it: the second check refuses. + let mut s = super::s(); + data(&mut s); + set(&mut s, "E2", "old"); + s.execute("formulas.defineName", json!({"name": "Target", "refersTo": "=Sheet1!$E$2"})).unwrap(); + put( + &mut s, + json!({"name": "Named", "steps": [{"command": "cell.set", "params": {"cell": "Name:Target", "input": "new"}}], "output": {"onConflict": "shiftDown"}}), + ); + let start = s.doc().unwrap().wb.clone(); + let err = s.execute("macro.run", json!({"name": "Named"})).unwrap_err().to_string(); + assert!(err.contains("shifting the data didn't make room (E3 on Sheet1)"), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + // The check shifts and checks again as the run does, and puts everything back, the document's + // revision included. + let journal = s.journal.len(); + let revision = s.doc().unwrap().revision; + let c = s.execute("macro.check", json!({"name": "Named"})).unwrap(); + assert_eq!((&c["ok"], &c["errors"]), (&json!(false), &json!(["Shifting the data doesn't make room (E3 on Sheet1)."])), "{c}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert_eq!((s.journal.len(), s.doc().unwrap().revision), (journal, revision)); + // Where the shift does make room, the check says the run would go ahead. + let mut s = super::s(); + data(&mut s); + set(&mut s, "E2", "old 1"); + put(&mut s, totals()); + let c = s.execute("macro.check", json!({"name": "Totals", "inputs": "B2:C5", "onConflict": "shiftDown"})).unwrap(); + assert_eq!((&c["ok"], c.get("errors")), (&json!(true), None), "{c}"); +} + +#[test] +fn stop_action_stops_a_macro_being_debugged() { + // Stop Action rolls back the open undo groups, the debugger's among them; the run ends with + // its group, and the answer says so. + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + let (start, undo) = (s.doc().unwrap().wb.clone(), undo_labels(&s)); + s.execute("macro.debug", json!({"action": "start", "name": "Totals", "inputs": "B2:C5", "breakpoints": ["1"]})).unwrap(); + s.execute("macro.debug", json!({"action": "step"})).unwrap(); + assert_eq!(v(&s, "E2").display(), "Total"); + let r = s.execute("automate.stopAction", json!({})).unwrap(); + assert_eq!((r["stopped"].as_bool(), r["macro"].as_str()), (Some(true), Some("Totals")), "{r}"); + assert!(r["message"].as_str().unwrap().contains("was stopped and rolled back"), "{r}"); + assert!(s.macro_debug.is_none(), "the debugger ended with its group"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert_eq!(undo_labels(&s), undo); + assert!(!s.in_group(s.doc().unwrap().uid)); + set(&mut s, "A1", "free"); + assert!(s.execute("macro.debug", json!({"action": "step"})).unwrap_err().to_string().contains("No macro is being debugged")); + // Stop Action on another workbook leaves the debugger alone. + s.execute("macro.debug", json!({"action": "start", "name": "Totals", "inputs": "B2:C5"})).unwrap(); + s.new_workbook(); + let r = s.execute("automate.stopAction", json!({})).unwrap(); + assert_eq!(r, json!({"stopped": false})); + assert!(s.macro_debug.is_some()); +} + +#[test] +fn the_debugger_runs_on_its_own_and_is_never_recorded() { + // As a step of a script, the debugger would outlive the script's rollback of its groups. + let mut s = s(); + stepper(&mut s); + let start = s.doc().unwrap().wb.clone(); + let commands = json!([ + {"command": "macro.debug", "params": {"action": "start", "name": "Walk", "inputs": "B2:C5"}}, + {"command": "cell.set", "params": {"cell": "A1", "input": "after"}} + ]); + s.execute("automate.newScript", json!({"name": "S", "commands": commands})).unwrap(); + let after_script = s.doc().unwrap().wb.clone(); + let e = s.execute("automate.runScript", json!({"name": "S"})).unwrap_err().to_string(); + assert!(e.contains("runs on its own"), "{e}"); + assert!(s.macro_debug.is_none()); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &after_script)); + assert!(!s.in_group(s.doc().unwrap().uid)); + set(&mut s, "A1", "free"); + assert!(!Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + // Neither recorder keeps it. + s.start_recording(); + s.execute("automate.recordActions", json!({})).unwrap(); + debug(&mut s, json!({"action": "start", "name": "Walk", "inputs": "B2:C5"})); + debug(&mut s, json!({"action": "stop"})); + let saved = s.execute("automate.recordActions", json!({"stop": true, "name": "R"})).unwrap(); + assert_eq!(saved["steps"], 0, "{saved}"); + let recorded = s.stop_recording().unwrap(); + assert!(!recorded.steps.iter().any(|st| st.id == "macro.debug"), "{:?}", recorded.steps); +} + +#[test] +fn a_debugger_whose_group_was_closed_elsewhere_locks_nothing() { + let mut s = s(); + stepper(&mut s); + let uid = s.doc().unwrap().uid; + debug(&mut s, json!({"action": "start", "name": "Walk", "inputs": "B2:C5"})); + debug(&mut s, json!({"action": "step"})); + // As if a command had rolled back the open groups without telling the debugger. + assert!(s.abort_groups(uid)); + set(&mut s, "A1", "free"); + assert!(s.macro_debug.is_none(), "the lock let the edit through and ended the debugger"); + // A debugger action says the run had ended; nothing is reported as kept or rolled back. + debug(&mut s, json!({"action": "start", "name": "Walk", "inputs": "B2:C5"})); + debug(&mut s, json!({"action": "step"})); + assert!(s.abort_groups(uid)); + let e = s.execute("macro.debug", json!({"action": "stop", "keep": true})).unwrap_err().to_string(); + assert!(e.contains("no longer being debugged"), "{e}"); + assert!(s.macro_debug.is_none()); + // Starting again works at once. + debug(&mut s, json!({"action": "start", "name": "Walk", "inputs": "B2:C5"})); + assert!(s.abort_groups(uid)); + assert_eq!(debug(&mut s, json!({"action": "start", "name": "Walk", "inputs": "B2:C5"}))["state"], "paused"); +} + +/// Whether `a` on sheet `sheet` is bold. +fn bold_on(s: &Session, sheet: &str, a: &str) -> bool { + let d = s.doc().unwrap(); + let sh = d.wb.sheet(d.wb.sheet_index(sheet).unwrap()).unwrap(); + d.wb.styles.get(sh.style_id(CellRef::parse(a).unwrap())).font.bold +} + +#[test] +fn between_steps_only_looking_around_runs_and_the_run_continues_where_it_was() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + put( + &mut s, + json!({"name": "Sel", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "selection.set", "params": {"range": "C3"}}, + {"command": "home.bold", "params": {}} + ]}), + ); + debug(&mut s, json!({"action": "start", "name": "Sel"})); + debug(&mut s, json!({"action": "step"})); + // Looking around runs: another sheet, another selection, Go To, Find, Copy, zoom. + s.execute("sheet.activate", json!({"sheet": "Other"})).unwrap(); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("edit.goTo", json!({"reference": "B2"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("view.zoom", json!({"percent": 150})).unwrap(); + assert!(s.execute("selection.stats", json!({})).is_ok(), "queries run"); + // Anything else waits, undoable or not, saving included. + let path = std::env::temp_dir().join(format!("gc-macro-debug-save-{}.xlsx", std::process::id())); + let busy = |r: Result| matches!(&r, Err(EngineError::Disabled(_, why)) if why == crate::macros::debug::BUSY); + assert!(busy(s.execute("view.customViews", json!({"save": "Mine"})))); + assert!(busy(s.execute("view.pageLayout", json!({})))); + assert!(busy(s.execute("file.saveAs", json!({"path": path.to_string_lossy()})))); + assert!(busy(s.execute("file.save", json!({})))); + assert!(busy(s.execute("automate.recordActions", json!({})))); + assert!(busy(s.execute("cell.set", json!({"cell": "A1", "input": "x"})))); + // A check would dry-run the macro's steps, which the lock refuses: it waits too. + assert!(busy(s.execute("macro.check", json!({"name": "Sel"})))); + assert!(!path.exists(), "nothing was saved"); + // The next step runs on the run's sheet and selection, as macro.run would. + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!(st["state"], "finished", "{st}"); + assert!(bold_on(&s, "Sheet1", "C3")); + assert!(!bold_on(&s, "Other", "B2") && !bold_on(&s, "Other", "A1")); + let d = s.doc().unwrap(); + assert_eq!((d.wb.active_sheet(), d.selection.active), (0, CellRef::parse("C3").unwrap())); +} + +#[test] +fn a_panic_inside_a_step_is_that_steps_error_and_the_run_goes_on() { + crate::register_test_command("test.debugInnerPanics", |_, _| panic!("inner")); + // A step whose command catches a nested command's panic as an error and goes on editing. + crate::register_test_command("test.debugSwallowsPanic", |s, _| { + let _ = s.execute("test.debugInnerPanics", json!({})); + s.execute("cell.set", json!({"cell": "B1", "input": "after"})) + }); + let mut s = s(); + put( + &mut s, + json!({"name": "M", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"command": "test.debugSwallowsPanic", "params": {}} + ]}), + ); + let undo = undo_labels(&s); + debug(&mut s, json!({"action": "start", "name": "M"})); + debug(&mut s, json!({"action": "step"})); + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!(st["state"], "finished", "{st}"); + assert_eq!((v(&s, "A1").display(), v(&s, "B1").display()), ("x".into(), "after".into())); + let after = undo_labels(&s); + assert_eq!((after.len(), after.last().map(String::as_str)), (undo.len() + 1, Some("Run Macro: M")), "{after:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(v(&s, "A1").is_empty() && v(&s, "B1").is_empty()); +} + +#[test] +fn debugger_parameters_are_checked_before_anything_changes() { + let mut s = s(); + stepper(&mut s); + let start = |bps: Json| json!({"action": "start", "name": "Walk", "inputs": "B2:C5", "breakpoints": bps}); + let e = s.execute("macro.debug", start(json!(["9"]))).unwrap_err().to_string(); + assert!(e.contains("has no step 9 for a breakpoint"), "{e}"); + let many: Vec = (0..10_001).map(|_| "1".to_string()).collect(); + let e = s.execute("macro.debug", start(json!(many))).unwrap_err().to_string(); + assert!(e.contains("at most 10000"), "{e}"); + assert!(s.macro_debug.is_none() && !s.in_group(s.doc().unwrap().uid)); + debug(&mut s, start(json!([]))); + // `keep` is true or false: "true" would have read as false and rolled the run back. + assert!(s.execute("macro.debug", json!({"action": "stop", "keep": "true"})).is_err()); + assert!(s.execute("macro.debug", json!({"action": "step", "breakpointsOnly": "yes"})).is_err()); + assert!(s.execute("macro.debug", json!({"action": 5})).is_err()); + // An unknown action or step path changes nothing, breakpoints included. + assert!(s.execute("macro.debug", json!({"action": "leap", "breakpoints": ["2"]})).is_err()); + assert!(s.execute("macro.debug", json!({"action": "step", "breakpoints": ["2.x"]})).is_err()); + assert!(s.execute("macro.debug", json!({"action": "runTo", "step": "9", "breakpoints": ["2"]})).is_err()); + let st = debug(&mut s, json!({"action": "state"})); + assert_eq!((st["current"]["step"].as_str(), &st["breakpoints"]), (Some("1"), &json!([])), "{st}"); + // `breakpointsOnly` alone applies to the list the run has (none here): the flag on 3.1 no + // longer stops it. + let st = debug(&mut s, json!({"action": "continue", "breakpointsOnly": true})); + assert_eq!(st["state"], "finished", "{st}"); +} + +#[test] +fn the_debuggers_answers_count_its_own_steps_and_say_what_stays() { + // `executed` counts the run's steps, not the footprint's dry run before it. + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + let st = debug(&mut s, json!({"action": "start", "name": "Totals", "inputs": "B2:C5"})); + assert_eq!(st["executed"], 0, "{st}"); + assert_eq!(debug(&mut s, json!({"action": "step"}))["executed"], 1); + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!((st["state"].as_str(), st["executed"].as_u64()), (Some("finished"), Some(3)), "{st}"); + // A shift at the start is reported, as macro.run reports it. + let mut s = super::s(); + data(&mut s); + set(&mut s, "E2", "old"); + put(&mut s, totals()); + let st = debug(&mut s, json!({"action": "start", "name": "Totals", "inputs": "B2:C5", "onConflict": "shiftDown"})); + assert_eq!(st["shifted"], "shiftDown", "{st}"); + assert_eq!(debug(&mut s, json!({"action": "stop"}))["shifted"], "shiftDown"); + // The files the run wrote stay when the workbook is put back: a failed step, a Stop step + // that rolls back, and stopping without keeping each say so. + let dir = std::env::temp_dir().join(format!("gc-macro-debug-files-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let export = json!({"command": "file.exportCsv", "params": {"path": format!("{}/out.csv", dir.to_string_lossy())}}); + for (last, how) in [ + (json!({"command": "cell.set", "params": {"cell": "Nowhere!A2", "input": "two"}}), "failed"), + (json!({"type": "stop", "message": "undo", "rollback": true}), "stopped"), + (json!({"command": "cell.set", "params": {"cell": "A2", "input": "two"}}), "stop"), + ] { + let mut s = super::s(); + put(&mut s, json!({"name": "F", "output": {"onConflict": "overwrite"}, "permissions": ["file.exportCsv"], "steps": [export, last]})); + debug(&mut s, json!({"action": "start", "name": "F", "approve": true})); + debug(&mut s, json!({"action": "step"})); + let st = if how == "stop" { debug(&mut s, json!({"action": "stop"})) } else { debug(&mut s, json!({"action": "step"})) }; + let msg = st["message"].as_str().unwrap_or_default(); + assert!(msg.contains("the file step 1 (file.exportCsv) wrote stays") && !msg.contains("Nothing was changed"), "{how}: {st}"); + assert_eq!(st["wroteFiles"], json!(["step 1 (file.exportCsv)"]), "{how}: {st}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_debugger_lists_deleted_and_renamed_sheets_and_caps_the_list() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Sheet2"})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Sheet3"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + put( + &mut s, + json!({"name": "Sheets", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "sheet.rename", "params": {"sheet": "Sheet2", "name": "Renamed"}}, + {"command": "home.deleteSheet", "params": {"sheet": "Sheet3"}}, + {"command": "cell.set", "params": {"cell": "A1", "input": "end"}} + ]}), + ); + debug(&mut s, json!({"action": "start", "name": "Sheets"})); + debug(&mut s, json!({"action": "step"})); + let st = debug(&mut s, json!({"action": "step"})); + let changed = st["changed"].as_array().unwrap(); + assert!(changed.contains(&json!("Renamed (renamed from Sheet2)")), "{st}"); + assert!(changed.contains(&json!("Sheet3 (deleted sheet)")), "{st}"); + assert!(!changed.iter().any(|c| c.as_str().is_some_and(|c| c.contains("(new sheet)"))), "{st}"); + // As if a step had written cells that make more ranges than the answer lists, on two sheets. + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + for sh in wb.sheets.iter_mut() { + let sh = Arc::make_mut(sh); + for r in 0..600u32 { + sh.set_value(CellRef::new(r + 10, r % 2), gridcraft_core::Value::Number(1.0)); + } + } + d.wb = Arc::new(wb); + let st = debug(&mut s, json!({"action": "state"})); + assert_eq!(st["changed"].as_array().unwrap().len(), 500, "{}", st["changed"].as_array().unwrap().len()); + assert_eq!(st["changedCells"], 1200); + debug(&mut s, json!({"action": "stop"})); +} + +#[test] +fn the_debugger_shows_a_repeat_over_whole_columns_as_the_run_goes_over_them() { + let mut s = s(); + data(&mut s); + put( + &mut s, + json!({"name": "Cols", "output": {"onConflict": "overwrite"}, "steps": [ + {"type": "repeat", "over": "B:C", "of": "columns", "body": [{"command": "cell.set", "params": {"cell": "Z1", "input": "x"}}]} + ]}), + ); + let st = debug(&mut s, json!({"action": "start", "name": "Cols"})); + assert_eq!(st["current"]["over"], "B2:C5", "{st}"); + debug(&mut s, json!({"action": "stop"})); +} + +#[test] +fn closing_the_debugged_workbook_ends_the_debugger() { + // `file.close` is not an edit, so the debugger's lock lets it through; the group went with + // the document, and so must the debugger, or the next workbook could not debug anything and + // the state would report that no document is open. + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + s.execute("macro.debug", json!({"action": "start", "name": "Totals", "inputs": "B2:C5", "breakpoints": ["1"]})).unwrap(); + assert!(s.macro_debug.is_some()); + s.execute("file.close", json!({"force": true})).unwrap(); + assert!(s.macro_debug.is_none(), "the debugger ended with its workbook"); + s.new_workbook(); + data(&mut s); + put(&mut s, totals()); + s.execute("macro.debug", json!({"action": "start", "name": "Totals", "inputs": "B2:C5", "breakpoints": ["1"]})).unwrap(); + assert!(s.execute("macro.debug", json!({})).is_ok(), "the new workbook can be debugged"); + s.execute("macro.debug", json!({"action": "stop"})).unwrap(); +} + +#[test] +fn a_shift_that_would_move_an_input_is_refused() { + // A shift inserts cells over the conflicting block, which moves the block's columns (or rows) + // from there on. When one of the macro's own inputs lies in the way, its data would move and + // shear while the run keeps the old coordinates, so the shift is refused and nothing changes. + let mut s = s(); + data(&mut s); + set(&mut s, "B1", "Old title"); + put( + &mut s, + json!({"name": "Title", "inputs": [{"name": "Input", "header": true}], "steps": [ + {"command": "cell.set", "params": {"cell": "Input.cell(0,1)", "input": "Report"}} + ]}), + ); + let start = s.doc().unwrap().wb.clone(); + let err = s.execute("macro.run", json!({"name": "Title", "inputs": "B2:C5", "onConflict": "shiftDown"})).unwrap_err().to_string(); + assert!(err.contains("would move Input (") && err.contains("B2:C5"), "{err}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "nothing changed"); + assert_eq!((v(&s, "B1").display(), v(&s, "B3").display()), ("Old title".into(), "Ann".into())); + // Writing left of the input and shifting right would move it too. + put( + &mut s, + json!({"name": "Left", "inputs": [{"name": "Input", "header": true}], "steps": [ + {"command": "cell.set", "params": {"cell": "Input.offset(1,-1).cell(1,1)", "input": "x"}} + ]}), + ); + set(&mut s, "A3", "in the way"); + let err = s.execute("macro.run", json!({"name": "Left", "inputs": "B2:C5", "onConflict": "shiftRight"})).unwrap_err().to_string(); + assert!(err.contains("would move Input"), "{err}"); + // The output counts as well. + put( + &mut s, + json!({"name": "Out", "inputs": [{"name": "Input", "header": true}], "output": {"anchor": "Input.below(1)"}, "steps": [ + {"command": "cell.set", "params": {"cell": "Input.cell(0,1)", "input": "Report"}} + ]}), + ); + let err = s.execute("macro.run", json!({"name": "Out", "inputs": "B2:C5", "onConflict": "shiftDown"})).unwrap_err().to_string(); + assert!(err.contains("would move Input"), "{err}"); + // A shift that moves nothing of the macro's own still works, over the block of every written + // cell, so a row the macro writes stays together. + set(&mut s, "H1", "elsewhere"); + put( + &mut s, + json!({"name": "Wide", "inputs": [{"name": "Input", "header": true}], "steps": [ + {"command": "cell.set", "params": {"cell": "H1", "input": "over"}}, + {"command": "cell.set", "params": {"cell": "H9", "input": "far"}} + ]}), + ); + s.execute("macro.run", json!({"name": "Wide", "inputs": "B2:C5", "onConflict": "shiftDown"})).unwrap(); + assert_eq!((v(&s, "H1").display(), v(&s, "H9").display(), v(&s, "H10").display()), ("over".into(), "far".into(), "elsewhere".into())); + assert_eq!(v(&s, "B3").display(), "Ann", "the input did not move"); +} + +#[test] +fn a_shift_is_refused_when_the_footprint_cannot_follow_every_write() { + // The touch log keeps at most a million writes; past that, a write that kept a cell's value + // is missing from the footprint, so a shift could split a row the macro writes. The footprint + // says so and the shift is refused (overwrite, with no dry run, still runs). + let mut s = s(); + set(&mut s, "A1", "x"); + set(&mut s, "E2", "old"); + put( + &mut s, + json!({"name": "Flood", "steps": [ + {"command": "edit.fillDown", "params": {"range": "A1:A1000001"}}, + {"command": "cell.set", "params": {"cell": "E2", "input": "new"}} + ]}), + ); + let c = s.execute("macro.check", json!({"name": "Flood"})).unwrap(); + assert_eq!(c["footprint"]["logFull"], true, "{c}"); + let err = s.execute("macro.run", json!({"name": "Flood", "onConflict": "shiftDown"})).unwrap_err().to_string(); + assert!(err.contains("more cells than the footprint can follow"), "{err}"); + assert_eq!(v(&s, "E2").display(), "old", "nothing changed"); +} + +#[test] +fn a_dry_run_leaves_a_clean_workbook_clean() { + // `view.zoom` and `sheet.activate` move the saved mark to the current workbook on a clean + // document; the dry run's rollback puts the workbook back, so the mark must come back too. + let mut s = s(); + data(&mut s); + let d = s.doc_mut().unwrap(); + d.saved = d.wb.clone(); + assert!(!s.doc().unwrap().is_dirty()); + put(&mut s, json!({"name": "Look", "steps": [{"command": "view.zoom", "params": {"percent": 120}}]})); + s.execute("macro.check", json!({"name": "Look"})).unwrap(); + assert!(!s.doc().unwrap().is_dirty(), "a dry run changed nothing"); + // A run refused by the conflict rule changed nothing either. + put(&mut s, totals()); + set(&mut s, "E3", "taken"); + let d = s.doc_mut().unwrap(); + d.saved = d.wb.clone(); + assert!(s.execute("macro.run", json!({"name": "Totals", "inputs": "B2:C5", "onConflict": "fail"})).is_err()); + assert!(!s.doc().unwrap().is_dirty()); +} + +#[test] +fn a_dry_run_cut_short_by_a_panic_leaves_journaling_on() { + // A panic inside a command that started a dry run, nested in another command: the panic + // guard of the nested call puts the pause and the touch log back, so the session journals + // the person's commands again. + crate::cmd::register_undoable_test_command("test.dryRunThenPanic", |s, _| { + s.journal_paused = s.journal_paused.saturating_add(1); + if let Ok(d) = s.doc_mut() { + d.touched = Some(Vec::new()); + } + panic!("in a dry run"); + }); + let mut s = s(); + let err = s.execute_nested("test.dryRunThenPanic", json!({})).unwrap_err().to_string(); + assert!(err.contains("in a dry run"), "{err}"); + assert_eq!((s.journal_paused, s.doc().unwrap().touched.is_none()), (0, true)); + let n = s.journal.len(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + assert_eq!(s.journal.len(), n + 1, "journaled again"); +} + +#[test] +fn a_dry_run_leaves_the_journal_and_the_recording_start_as_they_were() { + // A dry run journals nothing: journaling its nested commands would push a full journal past + // its limit and evict the person's own oldest entries, and move Record Actions' start. + let mut s = s(); + data(&mut s); + for i in 0..crate::JOURNAL_MAX_ENTRIES { + s.execute("selection.set", json!({"range": format!("A{}", i % 50 + 1)})).unwrap(); + } + s.recording = Some(s.journal.len().saturating_sub(100)); + put( + &mut s, + json!({"name": "Long", "steps": [{"type": "repeat", "over": "A1:A200", "body": [ + {"type": "repeat", "over": "A1:A60", "body": [{"command": "cell.set", "params": {"cell": "Row.cell(1,1)", "input": "x"}}]} + ]}]}), + ); + let (journal, recording) = (s.journal.clone(), s.recording); + let c = s.execute("macro.check", json!({"name": "Long"})).unwrap(); + assert!(c.get("footprint").is_some(), "{c}"); + assert_eq!((s.journal.len(), s.recording), (journal.len(), recording)); + assert!(s.journal == journal, "the journal is as it was"); + // The check itself is a query and isn't journaled; a command after it is. + s.execute("selection.set", json!({"range": "B1"})).unwrap(); + assert_eq!(s.journal.last().map(|(id, _)| id.as_str()), Some("selection.set")); +} + +#[test] +fn each_step_is_checked_for_writes_over_data() { + let dir = std::env::temp_dir().join(format!("gc-macro-guard-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let csv = dir.join("out.csv").to_string_lossy().to_string(); + let export = json!({"command": "file.exportCsv", "params": {"path": csv}}); + let solver = json!({"command": "data.solver", "params": {"objective": "C1", "variables": "A1", "constraints": ["A1 <= 5"], "method": "simplex", "saveModel": false}}); + let late = json!({"command": "cell.set", "params": {"cell": "B1", "input": "over"}}); + // A file step or Solver, then a step that writes over B1: the run stops there. + for first in [&export, &solver] { + let mut s = super::s(); + set(&mut s, "A1", "1"); + set(&mut s, "C1", "=A1"); + set(&mut s, "B1", "keep"); + put(&mut s, json!({"name": "Late", "inputs": [{"name": "Input"}], "permissions": ["file.exportCsv"], "steps": [first, late]})); + let start = s.doc().unwrap().wb.clone(); + for rule in ["fail", "ask"] { + let r = s.execute("macro.run", json!({"name": "Late", "inputs": "A1", "onConflict": rule, "approve": true})); + let e = match (rule, r) { + ("fail", Err(EngineError::Other(e))) | ("ask", Err(EngineError::Confirm(e))) => e, + (_, r) => panic!("{first} {rule}: {r:?}"), + }; + assert!(e.contains("Step 2 (cell.set): It would write over data (B1 on Sheet1)"), "{e}"); + // The workbook is put back; a file the run wrote stays, and the message says so. + let left = + if first == &export { "The workbook was put back; the file step 1 (file.exportCsv) wrote stays." } else { "Nothing was changed." }; + assert!(e.ends_with(left), "{e}"); + assert_eq!(v(&s, "B1").display(), "keep", "{first} {rule}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "{first} {rule}: rolled back"); + } + // The answer to the question overwrites. + s.execute("macro.run", json!({"name": "Late", "inputs": "A1", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "B1").display(), "over"); + } + // A step that writes over what the macro itself wrote isn't a conflict. + let mut s = super::s(); + let again = |input: &str| json!({"command": "cell.set", "params": {"cell": "E1", "input": input}}); + put( + &mut s, + json!({"name": "Twice", "permissions": ["file.exportCsv"], "output": {"onConflict": "fail"}, "steps": [again("a"), export, again("b")]}), + ); + s.execute("macro.run", json!({"name": "Twice", "approve": true})).unwrap(); + assert_eq!(v(&s, "E1").display(), "b"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_run_that_takes_another_path_than_its_check_is_still_checked() { + // RAND gives the run other values than the dry run before it, so an If can go the other way: + // the write the footprint didn't see must still not go over data. + let mut s = s(); + let steps = json!([ + {"command": "cell.set", "params": {"cell": "A1", "input": "=RAND()"}}, + {"type": "if", "cell": "A1", "op": "gt", "value": 0.5, "then": [{"command": "cell.set", "params": {"cell": "B1", "input": "over"}}]} + ]); + put(&mut s, json!({"name": "Coin", "output": {"onConflict": "fail"}, "steps": steps})); + let mut outcomes = BTreeSet::new(); + for _ in 0..40 { + set(&mut s, "B1", "keep"); + let r = s.execute("macro.run", json!({"name": "Coin"})); + assert_eq!(v(&s, "B1").display(), "keep", "{r:?}"); + outcomes.insert(match r { + Ok(_) => "ran", + Err(e) if e.to_string().contains("would write over") => "refused", + Err(e) => panic!("{e}"), + }); + } + assert_eq!(outcomes.len(), 2, "both paths were taken: {outcomes:?}"); +} + +#[test] +fn run_parameters_that_would_be_ignored_are_refused() { + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + for (p, says) in [ + (json!({"inputs": {"Inptu": "B2:C5"}}), "it has no input called 'Inptu' (its inputs: Input)."), + (json!({"inputs": {"Input": 5}}), "give the input Input as reference text"), + (json!({"inputs": ["B2:C5"]}), "give `inputs` as reference text"), + (json!({"inputs": "B2:C5", "onConflict": 1}), "`onConflict` must be"), + (json!({"inputs": "B2:C5", "overwrite": "yes"}), "`overwrite` must be true or false."), + (json!({"inputs": "B2:C5", "approve": 1}), "`approve` must be true or false."), + (json!({"inputs": "B2:C5", "timeLimit": "30"}), "`timeLimit` must be a number of seconds above 0."), + (json!({"inputs": "B2:C5", "timeLimit": 0}), "`timeLimit` must be a number of seconds above 0."), + ] { + let mut p = p; + p["name"] = json!("Totals"); + let err = s.execute("macro.run", p.clone()).unwrap_err().to_string(); + assert!(err.contains(&format!("Macro 'Totals': {says}")), "{p}: {err}"); + } + put(&mut s, json!({"name": "None", "steps": []})); + let err = s.execute("macro.run", json!({"name": "None", "inputs": "A1"})).unwrap_err().to_string(); + assert!(err.contains("Macro 'None': it takes no inputs."), "{err}"); + // `null` is the same as not given, and an input's name matches in any case. + let p = json!({"name": "Totals", "inputs": {"input": "B2:C5"}, "onConflict": null, "overwrite": true, "timeLimit": null}); + s.execute("macro.run", p).unwrap(); +} + +#[test] +fn a_run_passes_a_bounded_amount_of_parameters() { + // A step with a 3 MB parameter in a Repeat of 100 rows would hand its command 300 MB; the run + // stops at 256 MB, which matters on the web build, where there is no time limit. + let mut s = s(); + let big = "x".repeat(3_000_000); + let body = json!([{"command": "home.bold", "params": {"range": "A1", "note": big}}]); + put(&mut s, json!({"name": "Big", "output": {"onConflict": "overwrite"}, "steps": [{"type": "repeat", "over": "A1:A100", "body": body}]})); + let err = s.execute("macro.run", json!({"name": "Big"})).unwrap_err().to_string(); + assert!(err.contains("passed more than 256 MB of parameters to its steps"), "{err}"); + // 50 rows are 150 MB: the run alone stays under the limit, the dry run and the run together + // go past it, as they share the step budget. + let body = json!([{"command": "home.bold", "params": {"range": "A1", "note": "x".repeat(3_000_000)}}]); + for (rule, ok) in [("overwrite", true), ("fail", false)] { + let repeat = json!({"type": "repeat", "over": "A1:A50", "body": body}); + put(&mut s, json!({"name": "Half", "output": {"onConflict": rule}, "steps": [repeat]})); + assert_eq!(s.execute("macro.run", json!({"name": "Half"})).is_ok(), ok, "{rule}"); + } +} + +#[test] +fn the_check_says_whether_the_run_would_go_ahead() { + let mut s = s(); + // A Stop step that rolls the run back. + put(&mut s, json!({"name": "Halt", "output": {"onConflict": "fail"}, "steps": [{"type": "stop", "message": "Not today.", "rollback": true}]})); + let c = s.execute("macro.check", json!({"name": "Halt"})).unwrap(); + assert_eq!((&c["ok"], &c["errors"]), (&json!(false), &json!(["A Stop step ends the run and rolls it back: Not today."]))); + // A shift that would move an input. + set(&mut s, "B1", "taken"); + set(&mut s, "B3", "in"); + let step = json!({"command": "cell.set", "params": {"cell": "B1", "input": "new"}}); + put(&mut s, json!({"name": "Move", "inputs": [{"name": "Input", "kind": "cell"}], "output": {"onConflict": "shiftDown"}, "steps": [step]})); + let c = s.execute("macro.check", json!({"name": "Move", "inputs": "B3"})).unwrap(); + assert_eq!(c["ok"], false); + assert!(c["errors"][0].as_str().unwrap().starts_with("Shifting the data would move Input (Sheet1!B3)."), "{c}"); + // A macro whose dry run takes 90,000 steps passes its own dry run, but the run spends the + // budget twice under fail, so the check says it wouldn't finish. + let spin = json!([{"type": "repeat", "over": "A1:A300", "body": [{"type": "repeat", "over": "A1:A300", "body": [{"type": "if", "cell": "A1", "op": "empty"}]}]}]); + for (rule, ok) in [("fail", false), ("overwrite", true)] { + put(&mut s, json!({"name": "Spin", "output": {"onConflict": rule}, "steps": spin})); + let c = s.execute("macro.check", json!({"name": "Spin"})).unwrap(); + assert_eq!(c["ok"], ok, "{rule}: {c}"); + assert_eq!(s.execute("macro.run", json!({"name": "Spin"})).is_ok(), ok, "{rule}: the run agrees"); + } + let c = s.execute("macro.check", json!({"name": "Spin", "onConflict": "fail"})).unwrap(); + assert!(c["errors"][0].as_str().unwrap().starts_with("The run would execute more than 100000 steps, counting the check before it"), "{c}"); + // Parameters the run would refuse, the check reports. + let c = s.execute("macro.check", json!({"name": "Spin", "onConflict": 5})).unwrap(); + assert!(c["errors"][0].as_str().unwrap().contains("`onConflict` must be"), "{c}"); +} + +#[test] +fn the_question_after_a_partial_footprint_says_what_the_answer_covers() { + let dir = std::env::temp_dir().join(format!("gc-macro-unseen-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let csv = dir.join("out.csv").to_string_lossy().to_string(); + let mut s = s(); + set(&mut s, "B1", "keep"); + set(&mut s, "C1", "also"); + let steps = json!([ + {"command": "cell.set", "params": {"cell": "B1", "input": "over"}}, + {"command": "file.exportCsv", "params": {"path": csv}}, + {"command": "cell.set", "params": {"cell": "C1", "input": "over"}} + ]); + put(&mut s, json!({"name": "Two", "permissions": ["file.exportCsv"], "steps": steps})); + let r = s.execute("macro.run", json!({"name": "Two", "approve": true})); + let Err(EngineError::Confirm(q)) = r else { panic!("{r:?}") }; + assert!(q.contains("(B1 on Sheet1). The check stopped at step 2 (file.exportCsv writes a file), so overwriting also lets the steps after it write over data unchecked."), "{q}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_dry_run_puts_back_the_go_to_list() { + let mut s = s(); + let step = json!({"command": "edit.goTo", "params": {"reference": "D4", "record": true}}); + put(&mut s, json!({"name": "Go", "steps": [step]})); + s.execute("macro.check", json!({"name": "Go"})).unwrap(); + assert_eq!(s.doc().unwrap().go_to_recent, Vec::::new()); +} + +#[test] +fn the_answer_to_the_question_counts_however_ask_was_given() { + let mut s = s(); + data(&mut s); + put(&mut s, totals()); + set(&mut s, "E3", "taken"); + let p = json!({"name": "Totals", "inputs": "B2:C5", "onConflict": "ask"}); + assert!(matches!(s.execute("macro.run", p.clone()), Err(EngineError::Confirm(_)))); + let mut answered = p; + answered["overwrite"] = json!(true); + s.execute("macro.run", answered).unwrap(); + assert_eq!(v(&s, "E3").display(), "400"); +} + +#[test] +fn the_step_limit_is_one_budget_across_the_dry_run_and_the_run() { + // 300 x 300 passes is under the limit for one phase; the dry run and the run together are not. + let mut s = s(); + put( + &mut s, + json!({"name": "Spin", "steps": [{"type": "repeat", "over": "A1:A300", "body": [ + {"type": "repeat", "over": "A1:A300", "body": [{"type": "if", "cell": "A1", "op": "empty"}]} + ]}]}), + ); + let err = s.execute("macro.run", json!({"name": "Spin"})).unwrap_err().to_string(); + assert!(err.contains("more than 100000 steps"), "{err}"); + // With no dry run (overwrite), the same macro fits. + s.execute("macro.run", json!({"name": "Spin", "onConflict": "overwrite"})).unwrap(); +} + +#[test] +fn the_footprint_covers_other_sheets_objects_and_edges() { + let mut s = s(); + data(&mut s); + s.execute("home.insertSheet", json!({"name": "Notes"})).unwrap(); + set(&mut s, "A1", "note"); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + s.execute("insert.chart", json!({"range": "B2:C5", "type": "column", "at": "H2"})).unwrap(); + let chart = s.doc().unwrap().wb.sheet(0).unwrap().charts[0].id; + put( + &mut s, + json!({"name": "Wide", "output": {"onConflict": "fail"}, "steps": [ + {"command": "cell.set", "params": {"cell": "Notes!A1", "input": "x"}}, + {"command": "cell.set", "params": {"cell": "Notes!B2", "input": "y"}}, + {"command": "home.insertSheet", "params": {"name": "Extra"}}, + {"command": "sheet.activate", "params": {"sheet": "Sheet1"}}, + {"command": "insert.shape", "params": {"kind": "ellipse", "at": "J2"}}, + {"command": "object.delete", "params": {"kind": "chart", "id": chart}} + ]}), + ); + let c = s.execute("macro.check", json!({"name": "Wide", "inputs": {}})).unwrap(); + let fp = &c["footprint"]; + assert_eq!( + fp["sheets"], + json!([{"sheet": "Notes", "cells": ["A1", "B2"], "changed": 2, "conflicts": ["A1"], "conflictCount": 1, "bounds": "A1:B2"}]) + ); + assert_eq!(fp["sheetsAdded"], json!(["Extra"])); + assert_eq!((fp["objectsAdded"].as_u64(), fp["objectsRemoved"].as_u64()), (Some(1), Some(1))); + assert_eq!(c["conflicts"], 2, "the deleted chart and the note"); + assert_eq!(s.doc().unwrap().wb.sheets.len(), 2, "the dry run's new sheet went away"); + let err = s.execute("macro.run", json!({"name": "Wide"})).unwrap_err().to_string(); + assert!(err.contains("(A1 on Notes; 1 object)"), "{err}"); + + // Running past the edge of the sheet fails before anything changes. + put( + &mut s, + json!({"name": "Edge", "inputs": [{"name": "Input"}], "steps": [{"command": "cell.set", "params": {"cell": "Input.offset(-3,0)", "input": "x"}}]}), + ); + let err = s.execute("macro.run", json!({"name": "Edge", "inputs": "B2"})).unwrap_err().to_string(); + assert!(err.contains("Step 1 (cell.set): 'Input.offset(-3,0)' runs past the top of the sheet."), "{err}"); + let c = s.execute("macro.check", json!({"name": "Edge", "inputs": "B2"})).unwrap(); + assert_eq!((c["ok"].as_bool(), c["footprint"]["error"]["edge"].as_bool()), (Some(false), Some(true))); +} + +#[test] +fn repeat_if_and_stop() { + let mut s = s(); + data(&mut s); + put( + &mut s, + json!({"name": "Flag", "inputs": [{"name": "Input", "header": true}], "output": {"onConflict": "overwrite"}, "steps": [ + {"type": "repeat", "over": "Input.data", "body": [ + {"type": "if", "cell": "Row.cell(1,2)", "op": "gt", "value": 100, + "then": [{"command": "cell.set", "params": {"cell": "Row.right", "input": "big"}}], + "else": [{"command": "cell.set", "params": {"cell": "Row.right", "input": "small"}}]}, + {"type": "if", "cell": "Row.cell(1,1)", "op": "eq", "value": "bo", "then": [{"type": "stop", "message": "Found Bo."}]} + ]}, + {"command": "cell.set", "params": {"cell": "A1", "input": "not reached"}} + ]}), + ); + let r = s.execute("macro.run", json!({"name": "Flag", "inputs": "B2:C5"})).unwrap(); + assert_eq!(r["stopped"], "Found Bo."); + assert_eq!((v(&s, "D3").display(), v(&s, "D4").display()), ("big".into(), "small".into())); + assert!(v(&s, "D5").is_empty() && v(&s, "A1").is_empty()); + assert_eq!(undo_labels(&s).last().unwrap(), "Run Macro: Flag", "a stop keeps the changes"); + // A Stop that rolls back is an error that changes nothing. + put( + &mut s, + json!({"name": "Guard", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, + {"type": "if", "cell": "C3", "op": "notEmpty", "then": [{"type": "stop", "message": "C3 must be empty.", "rollback": true}]} + ]}), + ); + let err = s.execute("macro.run", json!({"name": "Guard"})).unwrap_err().to_string(); + assert_eq!(err, "Macro 'Guard' stopped: C3 must be empty. Nothing was changed."); + assert!(v(&s, "A1").is_empty()); + // Comparisons. + for (op, value, want) in [ + ("eq", json!(120), true), + ("eq", json!("120"), true), + ("ne", json!(120), false), + ("ge", json!(120), true), + ("lt", json!(120.5), true), + ("le", json!(100), false), + ("contains", json!("12"), true), + ("empty", json!(null), false), + ] { + put( + &mut s, + json!({"name": "Cmp", "output": {"onConflict": "overwrite"}, "steps": [ + {"type": "if", "cell": "C3", "op": op, "value": value, "then": [{"command": "cell.set", "params": {"cell": "A9", "input": "yes"}}], "else": [{"command": "cell.set", "params": {"cell": "A9", "input": "no"}}]} + ]}), + ); + s.execute("macro.run", json!({"name": "Cmp"})).unwrap(); + assert_eq!(v(&s, "A9").display(), if want { "yes" } else { "no" }, "{op} {value}"); + } + // If needs one cell. + put(&mut s, json!({"name": "Many", "steps": [{"type": "if", "cell": "A1:A2", "op": "empty"}]})); + assert!(s.execute("macro.run", json!({"name": "Many"})).unwrap_err().to_string().contains("If looks at one cell")); + // Disabled steps are skipped. + put( + &mut s, + json!({"name": "Off", "output": {"onConflict": "overwrite"}, "steps": [{"command": "cell.set", "params": {"cell": "A8", "input": "x"}, "enabled": false}]}), + ); + assert_eq!(s.execute("macro.run", json!({"name": "Off"})).unwrap()["ran"], 0); +} + +#[test] +fn macros_are_bounded() { + let mut s = s(); + put(&mut s, json!({"name": "Long", "steps": [{"type": "repeat", "over": "A1:A20", "max": 10, "body": [{"type": "stop"}]}]})); + let err = s.execute("macro.run", json!({"name": "Long"})).unwrap_err().to_string(); + assert!(err.contains("Repeat over A1:A20 has 20 rows, more than its limit of 10."), "{err}"); + // 400 × 400 passes is over the step limit. + put( + &mut s, + json!({"name": "Spin", "output": {"onConflict": "overwrite"}, "steps": [{"type": "repeat", "over": "A1:A400", "body": [ + {"type": "repeat", "over": "A1:A400", "body": [{"type": "if", "cell": "A1", "op": "empty"}]} + ]}]}), + ); + let err = s.execute("macro.run", json!({"name": "Spin"})).unwrap_err().to_string(); + assert!(err.contains("ran more than 100000 steps"), "{err}"); + let err = s.execute("macro.run", json!({"name": "Spin", "timeLimit": 0.001})).unwrap_err().to_string(); + assert!(err.contains("ran longer than"), "{err}"); + // The footprint's dry run keeps to the time limit too, and so does the check's. + put( + &mut s, + json!({"name": "Spin", "output": {"onConflict": "fail"}, "steps": [{"type": "repeat", "over": "A1:A400", "body": [ + {"type": "repeat", "over": "A1:A400", "body": [{"type": "if", "cell": "A1", "op": "empty"}]} + ]}]}), + ); + let err = s.execute("macro.run", json!({"name": "Spin", "timeLimit": 0.001})).unwrap_err().to_string(); + assert!(err.contains("ran longer than"), "{err}"); + let c = s.execute("macro.check", json!({"name": "Spin", "timeLimit": 0.001})).unwrap(); + assert!(c["errors"][0].as_str().unwrap().contains("ran longer than"), "{c}"); +} + +#[test] +fn a_token_in_a_path_needs_the_permission_and_approval() { + let mut s = s(); + let dir = std::env::temp_dir().join(format!("gc-macro-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let files = |dir: &std::path::Path| std::fs::read_dir(dir).unwrap().count(); + let in_dir = format!("{}/{{{{Input}}}}", dir.to_string_lossy()); + for path in [json!({"$ref": "Input"}), json!(in_dir), json!(" ")] { + let step = json!({"command": "file.exportCsv", "params": {"path": path}}); + put(&mut s, json!({"name": "Export", "inputs": [{"name": "Input"}], "steps": [step]})); + // Without the permission nothing runs, not even the check's dry run. + let err = s.execute("macro.run", json!({"name": "Export"})).unwrap_err().to_string(); + assert!(err.contains("Step 1 (file.exportCsv) writes a file. Add file.exportCsv to the macro's permissions"), "{path}: {err}"); + let c = s.execute("macro.check", json!({"name": "Export"})).unwrap(); + assert!(c["errors"][0].as_str().unwrap().contains("writes a file"), "{path}: {c}"); + assert!(c.get("footprint").is_none()); + // With it, the person approves first; the check doesn't run it before then. + put(&mut s, json!({"name": "Export", "inputs": [{"name": "Input"}], "steps": [step], "permissions": ["file.exportCsv"]})); + let r = s.execute("macro.run", json!({"name": "Export"})); + let Err(EngineError::Approve(q)) = &r else { panic!("{path}: {r:?}") }; + assert!(q.contains("file.exportCsv, which writes a file"), "{q}"); + let c = s.execute("macro.check", json!({"name": "Export"})).unwrap(); + assert_eq!(c["needsApproval"], json!(["runs file.exportCsv, which writes a file"]), "{path}"); + assert!(c.get("footprint").is_none()); + assert_eq!(files(&dir), 0, "{path}"); + assert!(!std::path::Path::new("A1.csv").exists() && !std::path::Path::new(" .csv").exists()); + } + // Once approved, the check's dry run stops before the step, and only the run writes the file. + let step = json!({"command": "file.exportCsv", "params": {"path": in_dir}}); + put(&mut s, json!({"name": "Export", "inputs": [{"name": "Input"}], "steps": [step], "permissions": ["file.exportCsv"]})); + s.execute("macro.run", json!({"name": "Export", "approve": true, "inputs": "B2"})).unwrap(); + assert_eq!(files(&dir), 1); + std::fs::remove_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&dir).unwrap(); + let c = s.execute("macro.check", json!({"name": "Export", "inputs": "B2"})).unwrap(); + assert_eq!(c["footprint"]["partial"]["step"], "1", "{c}"); + assert_eq!(files(&dir), 0, "the check writes nothing"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_debugger_runs_a_token_path_only_with_the_permission_and_approval() { + let mut s = s(); + let dir = std::env::temp_dir().join(format!("gc-macro-debug-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let files = |dir: &std::path::Path| std::fs::read_dir(dir).unwrap().count(); + let step = json!({"command": "file.exportCsv", "params": {"path": format!("{}/{{{{Input}}}}", dir.to_string_lossy())}}); + put(&mut s, json!({"name": "Export", "inputs": [{"name": "Input"}], "steps": [step]})); + let err = s.execute("macro.debug", json!({"action": "start", "name": "Export"})).unwrap_err().to_string(); + assert!(err.contains("writes a file"), "{err}"); + put(&mut s, json!({"name": "Export", "inputs": [{"name": "Input"}], "steps": [step], "permissions": ["file.exportCsv"]})); + assert!(matches!(s.execute("macro.debug", json!({"action": "start", "name": "Export"})), Err(EngineError::Approve(_)))); + assert_eq!(files(&dir), 0); + // Approved, it pauses before the step and writes the file only when the step runs. + s.execute("macro.debug", json!({"action": "start", "name": "Export", "approve": true, "inputs": "B2", "breakpoints": ["1"]})).unwrap(); + assert_eq!(files(&dir), 0, "paused before the step"); + s.execute("macro.debug", json!({"action": "step"})).unwrap(); + assert_eq!(files(&dir), 1, "the debugger runs the approved step"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_policy_keeps_macros_away_from_files_and_the_app() { + let mut s = s(); + for (id, params) in [ + ("file.saveAs", json!({"path": "/tmp/x.xlsx"})), + ("file.close", json!({})), + ("app.language.set", json!({"language": "de"})), + ("automate.runScript", json!({"name": "Script 1"})), + ("edit.undo", json!({})), + ("macro.run", json!({"name": "Self"})), + ("view.newWindow", json!({})), + ("view.hideWindow", json!({})), + ] { + put( + &mut s, + json!({"name": "Bad", "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "x"}}, {"command": id, "params": params}]}), + ); + let err = s.execute("macro.run", json!({"name": "Bad"})).unwrap_err().to_string(); + assert!(err.contains(&format!("Step 2 ({id}) can't run in a macro")), "{err}"); + assert!(v(&s, "A1").is_empty(), "{id}: nothing ran"); + } + // A disabled step isn't checked. + put(&mut s, json!({"name": "Bad", "steps": [{"command": "file.close", "enabled": false}]})); + s.execute("macro.run", json!({"name": "Bad"})).unwrap(); + + // Reading a file needs the permission, then the person's approval (once per macro content). + let dir = std::env::temp_dir().join(format!("gc-macro-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let csv = dir.join("in.csv"); + std::fs::write(&csv, "a,b\n1,2\n").unwrap(); + let step = json!({"command": "data.fromTextCsv", "params": {"path": csv.to_string_lossy(), "sheet": "Imported"}}); + put(&mut s, json!({"name": "Import", "steps": [step]})); + let err = s.execute("macro.run", json!({"name": "Import"})).unwrap_err().to_string(); + assert!(err.contains("Step 1 (data.fromTextCsv) reads a file. Add data.fromTextCsv to the macro's permissions"), "{err}"); + put(&mut s, json!({"name": "Import", "steps": [step], "permissions": ["data.fromTextCsv"]})); + let r = s.execute("macro.run", json!({"name": "Import"})); + let Err(EngineError::Approve(q)) = &r else { panic!("{r:?}") }; + assert_eq!(q, "Run macro 'Import'? It runs data.fromTextCsv, which reads a file."); + assert_eq!(s.doc().unwrap().wb.sheets.len(), 1); + let c = s.execute("macro.check", json!({"name": "Import"})).unwrap(); + assert_eq!(c["needsApproval"], json!(["runs data.fromTextCsv, which reads a file"])); + assert!(c.get("footprint").is_none(), "nothing unapproved runs, even dry"); + s.execute("macro.run", json!({"name": "Import", "approve": true})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets.len(), 2); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("macro.run", json!({"name": "Import"})).unwrap(); + // The dry run skips the file step and says so. + let c = s.execute("macro.check", json!({"name": "Import"})).unwrap(); + assert_eq!(c["footprint"]["partial"]["step"], "1"); + // Changing the macro asks again. + put(&mut s, json!({"name": "Import", "description": "changed", "steps": [step], "permissions": ["data.fromTextCsv"]})); + assert!(matches!(s.execute("macro.run", json!({"name": "Import"})), Err(EngineError::Approve(_)))); + let _ = std::fs::remove_dir_all(&dir); + + // Steps that would open a dialog fail instead. + put(&mut s, json!({"name": "Pic", "output": {"onConflict": "overwrite"}, "steps": [{"command": "insert.picture"}]})); + let err = s.execute("macro.run", json!({"name": "Pic"})).unwrap_err().to_string(); + assert!(err.contains("would open the insertPicture dialog"), "{err}"); + assert!(s.ui_requests.is_empty()); + // A step that would start editing a cell, or put a name in the edit, runs without it. + let (use_name, insert) = (json!({"name": "Rate"}), json!({"name": "SUM"})); + let steps = json!([{"command": "formulas.useInFormula", "params": use_name}, {"command": "formulas.insertFunction", "params": insert}]); + put(&mut s, json!({"name": "Edit", "output": {"onConflict": "overwrite"}, "steps": steps})); + s.execute("macro.run", json!({"name": "Edit"})).unwrap(); + assert!(s.ui_requests.is_empty()); +} + +#[test] +fn macros_from_a_file_ask_before_running() { + let mut s = s(); + let mut wb = gridcraft_model::Workbook::new(); + wb.macros.push(crate::macros::parse_macro(&json!({"name": "Theirs", "output": {"onConflict": "overwrite"}, "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "ran"}}]})).unwrap()); + let bytes = serde_json::to_vec(&wb).unwrap(); + s.execute("file.open", json!({"name": "theirs.json", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + assert_eq!(s.doc().unwrap().trust, crate::Trust::FromFile); + let r = s.execute("macro.run", json!({"name": "Theirs"})); + let Err(EngineError::Approve(q)) = &r else { panic!("{r:?}") }; + assert_eq!(q, "Run macro 'Theirs'? It came with a workbook you opened."); + assert!(v(&s, "A1").is_empty()); + s.execute("macro.run", json!({"name": "Theirs", "approve": true})).unwrap(); + assert_eq!(v(&s, "A1").display(), "ran"); + // Approved once per macro content: the second run doesn't ask. + s.execute("macro.run", json!({"name": "Theirs"})).unwrap(); + // The approval holds the macro's whole content, not a hash two macros could share. + let m = s.doc().unwrap().wb.macros[0].clone(); + let doc = s.doc().unwrap().uid; + let key: (u64, String) = (doc, crate::macros::macro_json(&m).to_string()); + assert!(s.macro_approvals.contains(&key)); + // The JSON is canonical: the same macro with its keys in another order is the same macro. + let a = crate::macros::parse_macro(&json!({"name": "M", "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "x"}}]})).unwrap(); + let b = crate::macros::parse_macro(&json!({"steps": [{"params": {"input": "x", "cell": "A1"}, "command": "cell.set"}], "name": "M"})).unwrap(); + assert_eq!(crate::macros::fingerprint(&a), crate::macros::fingerprint(&b)); +} + +#[test] +fn a_partial_footprint_doesnt_clear_later_writes() { + let dir = std::env::temp_dir().join(format!("gc-macro-partial-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let csv = dir.join("out.csv").to_string_lossy().to_string(); + let export = json!({"command": "file.exportCsv", "params": {"path": csv}}); + let solver = json!({"command": "data.solver", "params": {"objective": "C1", "variables": "A1", "constraints": ["A1 <= 5"], "method": "simplex", "saveModel": false}}); + let late = json!({"command": "cell.set", "params": {"cell": "B1", "input": "over"}}); + // The dry run stops at an approved file step or at Solver; the step after it writes over B1. + for first in [&export, &solver] { + let mut s = super::s(); + set(&mut s, "A1", "1"); + set(&mut s, "C1", "=A1"); + set(&mut s, "B1", "keep"); + put(&mut s, json!({"name": "Late", "inputs": [{"name": "Input"}], "permissions": ["file.exportCsv"], "steps": [first, late]})); + let start = s.doc().unwrap().wb.clone(); + let c = s.execute("macro.check", json!({"name": "Late", "inputs": "A1"})).unwrap(); + if c.get("needsApproval").is_none() { + assert_eq!((c["conflicts"].as_u64(), &c["footprint"]["partial"]["step"]), (Some(0), &json!("1")), "{c}"); + } + for rule in ["fail", "ask"] { + let r = s.execute("macro.run", json!({"name": "Late", "inputs": "A1", "onConflict": rule, "approve": true})); + let e = match (rule, r) { + ("fail", Err(EngineError::Other(e))) | ("ask", Err(EngineError::Confirm(e))) => e, + (_, r) => panic!("{first} {rule}: {r:?}"), + }; + assert!(e.contains("Step 2 (cell.set): It would write over data (B1 on Sheet1)"), "{e}"); + assert_eq!(v(&s, "B1").display(), "keep", "{first} {rule}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "{first} {rule}: rolled back"); + } + // The answer to the question overwrites. + s.execute("macro.run", json!({"name": "Late", "inputs": "A1", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "B1").display(), "over"); + } + // A step that writes over what the macro itself wrote isn't a conflict. + let mut s = super::s(); + let again = |input: &str| json!({"command": "cell.set", "params": {"cell": "E1", "input": input}}); + put( + &mut s, + json!({"name": "Twice", "permissions": ["file.exportCsv"], "output": {"onConflict": "fail"}, "steps": [again("a"), export, again("b")]}), + ); + s.execute("macro.run", json!({"name": "Twice", "approve": true})).unwrap(); + assert_eq!(v(&s, "E1").display(), "b"); + // After a shift, the steps past the file step are checked too. + let mut s = super::s(); + set(&mut s, "C1", "old"); + set(&mut s, "D1", "keep"); + let step = |cell: &str| json!({"command": "cell.set", "params": {"cell": cell, "input": "new"}}); + put( + &mut s, + json!({"name": "Shift", "permissions": ["file.exportCsv"], "output": {"onConflict": "shiftDown"}, "steps": [step("C1"), export, step("D1")]}), + ); + let start = s.doc().unwrap().wb.clone(); + let err = s.execute("macro.run", json!({"name": "Shift", "approve": true})).unwrap_err().to_string(); + assert!(err.contains("Step 3 (cell.set): It would write over data (D1 on Sheet1)"), "{err}"); + assert_eq!((v(&s, "C1").display(), v(&s, "D1").display()), ("old".into(), "keep".into())); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start), "the shift is rolled back too"); + let _ = std::fs::remove_dir_all(&dir); +} + +// ---------------------------------------------------------------- debugger + +fn debug(s: &mut Session, p: Json) -> Json { + s.execute("macro.debug", p).unwrap() +} + +/// Four steps: two plain ones, a Repeat over the data rows (with a breakpoint on its body), and +/// a final one. +fn stepper(s: &mut Session) { + data(s); + put( + s, + json!({"name": "Walk", "inputs": [{"name": "Input", "header": true}], "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "E1", "input": "start"}}, + {"command": "cell.set", "params": {"cell": "Input.right.cell(1,1)", "input": "flag"}}, + {"type": "repeat", "over": "Input.data", "body": [ + {"command": "cell.set", "params": {"cell": "Row.right", "input": "seen"}, "breakpoint": true} + ]}, + {"command": "cell.set", "params": {"cell": "E9", "input": "end"}} + ]}), + ); +} + +#[test] +fn the_debugger_steps_continues_and_runs_to_a_step_as_one_undo_step() { + let mut s = s(); + stepper(&mut s); + let undo = undo_labels(&s); + let st = debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5", "action": "start"})); + assert_eq!(st["state"], "paused"); + assert_eq!( + st["current"], + json!({"step": "1", "kind": "command", "command": "cell.set", "params": {"cell": "E1", "input": "start"}, "breakpoint": false}) + ); + assert_eq!(st["executed"], 0); + + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!(st["current"]["step"], "2"); + assert_eq!(st["current"]["params"]["cell"], "D2", "tokens resolve for the next step"); + assert_eq!(st["lastParams"], json!({"cell": "E1", "input": "start"})); + assert_eq!(st["changed"], json!(["Sheet1!E1"])); + assert_eq!(v(&s, "E1").display(), "start"); + + // Other edits wait; selecting cells and queries don't. + let r = s.execute("cell.set", json!({"cell": "A1", "input": "x"})); + assert!(matches!(&r, Err(EngineError::Disabled(_, why)) if why == "Finish or stop the macro first"), "{r:?}"); + assert!(s.execute("macro.run", json!({"name": "Walk"})).is_err()); + assert!(s.execute("edit.undo", json!({})).is_err()); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + assert!(s.execute("macro.debug", json!({"name": "Walk", "action": "start"})).unwrap_err().to_string().contains("is being debugged")); + + // Continue stops at the breakpoint inside the Repeat, once per row. + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!((st["current"]["step"].as_str(), st["atBreakpoint"].as_bool()), (Some("3.1"), Some(true))); + assert_eq!(st["current"]["iteration"], json!({"at": 1, "of": 3})); + assert_eq!(st["current"]["params"]["cell"], "D3"); + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!(st["current"]["iteration"], json!({"at": 2, "of": 3})); + // Run To stops at a breakpoint on the way, then at its step. + let st = debug(&mut s, json!({"action": "runTo", "step": "4", "breakpoints": []})); + assert_eq!((st["current"]["step"].as_str(), st["atBreakpoint"].as_bool()), (Some("3.1"), Some(true))); + assert_eq!(st["current"]["iteration"], json!({"at": 3, "of": 3})); + let st = debug(&mut s, json!({"action": "runTo", "step": "4"})); + assert_eq!((st["current"]["step"].as_str(), st["atBreakpoint"].as_bool()), (Some("4"), Some(false))); + assert_eq!((v(&s, "D4").display(), v(&s, "D5").display()), ("seen".into(), "seen".into())); + // Breakpoints from the call: none left before the end. + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!(st["state"], "finished"); + assert_eq!(st["executed"], 7); + assert!(st["changed"].as_array().unwrap().contains(&json!("Sheet1!E9"))); + assert_eq!(v(&s, "E9").display(), "end"); + let after = undo_labels(&s); + assert_eq!(after.len(), undo.len() + 1, "{after:?}"); + assert_eq!(after.last().unwrap(), "Run Macro: Walk"); + // Edits work again; one undo takes the whole run back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(v(&s, "E1").is_empty() && v(&s, "D3").is_empty() && v(&s, "E9").is_empty()); + set(&mut s, "A1", "free"); +} + +#[test] +fn a_breakpoint_list_can_replace_the_steps_own() { + let mut s = s(); + stepper(&mut s); + // Only step 4 stops the run: the flag on 3.1 is ignored. + let st = debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5", "breakpoints": ["4"], "breakpointsOnly": true})); + assert_eq!(st["current"]["step"], "1"); + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!((st["current"]["step"].as_str(), st["atBreakpoint"].as_bool()), (Some("4"), Some(true))); + debug(&mut s, json!({"action": "stop"})); + // Clearing the list mid-run (an editor removing its last breakpoint) runs to the end. + debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5", "breakpoints": ["3.1"], "breakpointsOnly": true})); + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!(st["current"]["step"], "3.1"); + let st = debug(&mut s, json!({"action": "continue", "breakpoints": [], "breakpointsOnly": true})); + assert_eq!(st["state"], "finished"); +} + +#[test] +fn stopping_the_debugger_keeps_or_rolls_back() { + for keep in [false, true] { + let mut s = s(); + stepper(&mut s); + let (start, undo) = (s.doc().unwrap().wb.clone(), undo_labels(&s)); + debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5", "breakpoints": ["2"]})); + let st = debug(&mut s, json!({"action": "continue"})); + assert_eq!((st["current"]["step"].as_str(), st["atBreakpoint"].as_bool()), (Some("2"), Some(true))); + let st = debug(&mut s, json!({"action": "stop", "keep": keep})); + assert_eq!((st["state"].as_str(), st["kept"].as_bool()), (Some("stopped"), Some(keep))); + if keep { + assert_eq!(v(&s, "E1").display(), "start"); + assert_eq!(undo_labels(&s).len(), undo.len() + 1); + assert_eq!(st["changed"], json!(["Sheet1!E1"])); + } else { + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + assert_eq!(undo_labels(&s), undo); + } + set(&mut s, "A1", "free"); + assert!(s.execute("macro.debug", json!({"action": "step"})).unwrap_err().to_string().contains("No macro is being debugged")); + } +} + +#[test] +fn a_debugged_run_after_a_partial_footprint_stops_before_writing_over_data() { + let mut s = s(); + set(&mut s, "A1", "1"); + set(&mut s, "C1", "=A1"); + set(&mut s, "B1", "keep"); + let solver = json!({"command": "data.solver", "params": {"objective": "C1", "variables": "A1", "constraints": ["A1 <= 5"], "method": "simplex", "saveModel": false}}); + let late = json!({"command": "cell.set", "params": {"cell": "B1", "input": "over"}}); + put(&mut s, json!({"name": "Late", "inputs": [{"name": "Input"}], "output": {"onConflict": "fail"}, "steps": [solver, late]})); + let start = s.doc().unwrap().wb.clone(); + debug(&mut s, json!({"name": "Late", "action": "start", "inputs": "A1"})); + debug(&mut s, json!({"action": "step"})); + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!(st["state"], "failed", "{st}"); + assert!(st["message"].as_str().unwrap().contains("It would write over data (B1 on Sheet1)"), "{st}"); + assert_eq!(v(&s, "B1").display(), "keep"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); +} + +#[test] +fn a_failing_step_ends_the_debugged_run_and_rolls_it_back() { + let mut s = s(); + data(&mut s); + put( + &mut s, + json!({"name": "Breaks", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "A1", "input": "one"}}, + {"command": "cell.set", "params": {"cell": "Nowhere!A2", "input": "two"}}, + {"type": "stop", "message": "never"} + ]}), + ); + let start = s.doc().unwrap().wb.clone(); + debug(&mut s, json!({"name": "Breaks"})); + assert!(s.execute("macro.debug", json!({"action": "runTo", "step": "9"})).unwrap_err().to_string().contains("has no step 9")); + assert!(s.execute("macro.debug", json!({"action": "leap"})).is_err()); + debug(&mut s, json!({"action": "step"})); + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!(st["state"], "failed"); + assert_eq!(st["error"]["step"], "2"); + assert!(st["message"].as_str().unwrap().starts_with("Step 2 (cell.set):"), "{st}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().wb, &start)); + set(&mut s, "B1", "free again"); + // A run that ends at once (a Stop first) finishes on start. + put(&mut s, json!({"name": "Quick", "steps": [{"type": "stop", "message": "bye"}]})); + let st = debug(&mut s, json!({"name": "Quick"})); + assert_eq!(st["state"], "paused"); + let st = debug(&mut s, json!({"action": "step"})); + assert_eq!((st["state"].as_str(), st["stopped"].as_str()), (Some("stopped"), Some("bye"))); + put(&mut s, json!({"name": "Empty", "steps": []})); + assert_eq!(debug(&mut s, json!({"name": "Empty"}))["state"], "finished"); +} + +// ---------------------------------------------------------------- commands and the recorder + +#[test] +fn macros_are_saved_listed_renamed_and_deleted() { + let mut s = s(); + s.execute("macro.save", json!({"macro": totals()})).unwrap(); + // The fields can also come at the top level. + let r = s + .execute("macro.save", json!({"name": "Second", "description": "two", "shortcut": "Ctrl+Shift+Q", "steps": [{"command": "home.bold"}]})) + .unwrap(); + assert_eq!(r, json!({"name": "Second", "steps": 1})); + let list = s.execute("macro.list", json!({})).unwrap(); + assert_eq!(list[0], json!({"name": "Totals", "description": "", "steps": 3, "inputs": ["Input"], "onConflict": "ask", "permissions": []})); + assert_eq!(list[1]["shortcut"], "Ctrl+Shift+Q"); + let got = s.execute("macro.get", json!({"name": "totals"})).unwrap(); + assert_eq!(crate::macros::parse_macro(&got).unwrap(), crate::macros::parse_macro(&totals()).unwrap()); + assert!(s.execute("macro.save", json!({"macro": totals(), "replace": false})).unwrap_err().to_string().contains("already exists")); + assert!(s.execute("macro.save", json!({"macro": {"name": "Bad", "steps": [{"type": "warp"}]}})).is_err()); + assert!(s.execute("macro.rename", json!({"name": "Second", "to": "TOTALS"})).unwrap_err().to_string().contains("already exists")); + s.execute("macro.rename", json!({"name": "Second", "to": "Third"})).unwrap(); + s.execute("macro.rename", json!({"name": "third", "to": "THIRD"})).unwrap(); + s.execute("macro.delete", json!({"name": "Totals"})).unwrap(); + let names: Vec = + s.execute("macro.list", json!({})).unwrap().as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap().to_string()).collect(); + assert_eq!(names, ["THIRD"]); + assert!(s.execute("macro.delete", json!({"name": "Totals"})).unwrap_err().to_string().contains("no macro called")); + // Saving, renaming and deleting are undoable. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.execute("macro.list", json!({})).unwrap().as_array().unwrap().len(), 2); + // Macros are kept apart from Automate scripts: View › Macros still lists the scripts. + assert_eq!(s.execute("view.macros", json!({})).unwrap(), json!([])); + assert!(s.execute("macro.rename", json!({"name": "THIRD", "to": "a\nb"})).is_err()); +} + +#[test] +fn macros_and_automate_scripts_live_side_by_side() { + let mut s = s(); + let steps = json!([{"command": "cell.set", "params": {"cell": "B1", "input": "from script"}}]); + s.execute("automate.newScript", json!({"name": "Inner", "commands": steps})).unwrap(); + s.execute("macro.save", json!({"name": "Inner", "steps": [{"command": "cell.set", "params": {"cell": "C1", "input": "from macro"}}], "output": {"onConflict": "overwrite"}})).unwrap(); + // Recording a script run keeps the script's steps, so the macro stands on its own. + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "typed"); + s.execute("automate.runScript", json!({"name": "Inner"})).unwrap(); + s.execute("automate.recordActions", json!({})).unwrap(); + s.execute("automate.recordActions", json!({"stop": true, "name": "Empty"})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Recorded"})).unwrap(); + assert_eq!(r["skipped"], json!(["automate.recordActions", "automate.recordActions"])); + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Recorded"})).unwrap()).unwrap(); + let ids: Vec = crate::macros::command_steps(&m.steps).iter().map(|(_, id, p)| format!("{id} {p}")).collect(); + assert_eq!(ids, ["cell.set {\"cell\":\"A1\",\"input\":\"typed\"}", "cell.set {\"cell\":\"B1\",\"input\":\"from script\"}"]); + // Both lists keep their own entries, under the same name if need be. + let scripts = s.execute("automate.allScripts", json!({})).unwrap(); + assert_eq!(scripts, json!([{"name": "Empty", "steps": 0, "trusted": true}, {"name": "Inner", "steps": 1, "trusted": true}])); + let macros: Vec = s.execute("macro.list", json!({})).unwrap().as_array().unwrap().iter().map(|m| m["name"].clone()).collect(); + assert_eq!(macros, [json!("Inner"), json!("Recorded")]); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("automate.runScript", json!({"name": "Inner"})).unwrap(); + s.execute("macro.run", json!({"name": "Inner"})).unwrap(); + assert_eq!((v(&s, "B1").display(), v(&s, "C1").display()), ("from script".into(), "from macro".into())); + // Both survive an xlsx round trip unchanged. + let b64 = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap()["base64"].as_str().unwrap().to_string(); + s.execute("file.open", json!({"name": "both.xlsx", "base64": b64})).unwrap(); + // Opened from a file, the scripts are not trusted yet (#2178); their names and steps are the same. + let names_and_steps = |v: &Json| v.as_array().unwrap().iter().map(|s| (s["name"].clone(), s["steps"].clone())).collect::>(); + assert_eq!(names_and_steps(&s.execute("automate.allScripts", json!({})).unwrap()), names_and_steps(&scripts)); + assert_eq!(s.execute("macro.list", json!({})).unwrap().as_array().unwrap().len(), 2); +} + +#[test] +fn a_relative_recording_plays_back_on_another_block() { + let mut s = s(); + data(&mut s); + put( + &mut s, + json!({"name": "Plain", "steps": [{"command": "cell.set", "params": {"cell": "A20", "input": "plain"}}], "output": {"onConflict": "overwrite"}}), + ); + put(&mut s, json!({"name": "Shaped", "inputs": [{"name": "Input"}], "steps": []})); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + let r = s.execute("macro.record", json!({})).unwrap(); + assert_eq!(r, json!({"recording": true, "relative": true, "input": "B2:C5"})); + // Clicking a cell and typing, a formula over the amounts, bold header, italic on a selection. + s.execute("selection.set", json!({"cell": "E2"})).unwrap(); + set(&mut s, "E2", "Total"); + set(&mut s, "E3", "=SUM(C3:C5)"); + s.execute("home.bold", json!({"range": "B2:C2"})).unwrap(); + s.execute("selection.set", json!({"cell": "C3"})).unwrap(); + s.execute("selection.set", json!({"cell": "C4"})).unwrap(); + s.execute("home.italic", json!({})).unwrap(); + set(&mut s, "C6", "end"); + // Not kept: commands macros don't run, and a macro with inputs; a plain macro's steps are + // inlined. + s.execute("window.activate", json!({"index": 0})).unwrap(); + s.execute("macro.run", json!({"name": "Plain"})).unwrap(); + s.execute("macro.run", json!({"name": "Shaped", "inputs": "A1"})).unwrap(); + // The journal can be trimmed meanwhile. + s.journal.clear(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Sum it", "description": "made by recording"})).unwrap(); + assert!(!s.is_recording()); + assert_eq!(r["saved"], "Sum it"); + assert_eq!(r["skipped"], json!(["window.activate", "macro.run"])); + assert_eq!(r["inputs"], json!(["Input"])); + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Sum it"})).unwrap()).unwrap(); + assert_eq!(m.description, "made by recording"); + let input = &m.inputs[0]; + assert!(input.header); + assert_eq!((input.cols, input.col_types.clone()), ([2, 2], vec![gridcraft_model::ColType::Text, gridcraft_model::ColType::Number])); + let steps: Vec<(String, Json)> = m + .steps + .iter() + .map(|st| match &st.kind { + gridcraft_model::StepKind::Command { id, params } => (id.clone(), params.clone()), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!( + steps, + vec![ + ("selection.set".to_string(), json!({"cell": "Input.cell(1,4)"})), + ("cell.set".into(), json!({"cell": "Input.cell(1,4)", "input": "Total"})), + ("cell.set".into(), json!({"cell": "Input.cell(2,4)", "input": "=SUM({{Input.rows(2..).col(2)}})"})), + ("home.bold".into(), json!({"range": "Input.row(1)", "on": true})), + ("selection.set".into(), json!({"cell": "Input.cell(3,2)"})), + ("home.italic".into(), json!({"on": true})), + ("cell.set".into(), json!({"cell": "Input.col(2).below", "input": "end"})), + ("cell.set".into(), json!({"cell": "A20", "input": "plain"})), + ] + ); + // Play it back on a longer block somewhere else. + for (cell, input) in [ + ("G10", "Who"), + ("H10", "Paid"), + ("G11", "A"), + ("H11", "1"), + ("G12", "B"), + ("H12", "2"), + ("G13", "C"), + ("H13", "3"), + ("G14", "D"), + ("H14", "4"), + ] { + set(&mut s, cell, input); + } + s.execute("macro.run", json!({"name": "Sum it", "inputs": "G10:H14", "onConflict": "overwrite"})).unwrap(); + assert_eq!((v(&s, "J10").display(), v(&s, "J11").display()), ("Total".into(), "10".into())); + assert!(bold(&s, "G10") && bold(&s, "H10")); + assert_eq!(v(&s, "H15").display(), "end"); + // Toggles were recorded with the state they set: a second run keeps the header bold. + s.execute("macro.run", json!({"name": "Sum it", "inputs": "G10:H14", "onConflict": "overwrite"})).unwrap(); + assert!(bold(&s, "G10") && bold(&s, "H10")); + let d = s.doc().unwrap(); + assert!(d.wb.styles.get(d.wb.active().unwrap().style_id(gridcraft_core::CellRef::parse("H12").unwrap())).font.italic); + // The input is checked like any other: text in the amounts is refused. + set(&mut s, "H12", "two"); + let err = s.execute("macro.run", json!({"name": "Sum it", "inputs": "G10:H14"})).unwrap_err().to_string(); + assert!(err.contains("Input column 2 (Paid) must hold numbers; H12 holds text."), "{err}"); +} + +#[test] +fn an_absolute_recording_keeps_its_references() { + let mut s = s(); + s.execute("selection.set", json!({"range": "B2:C3"})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + set(&mut s, "B2", "x"); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + set(&mut s, "C3", "y"); + let r = s.execute("macro.record", json!({})).unwrap(); + assert_eq!(r["saved"], "Macro1"); + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Macro1"})).unwrap()).unwrap(); + assert!(m.inputs.is_empty()); + let ids: Vec = crate::macros::command_steps(&m.steps).iter().map(|(_, id, p)| format!("{id} {p}")).collect(); + assert_eq!( + ids, + [ + "home.insertSheet {\"name\":\"Two\"}", + "sheet.activate {\"sheet\":\"Two\"}", + "selection.set {\"active\":\"A1\",\"range\":\"A1\"}", + "cell.set {\"cell\":\"B2\",\"input\":\"x\"}", + "sheet.activate {\"sheet\":\"Sheet1\"}", + "selection.set {\"active\":\"A1\",\"range\":\"A1\"}", + "cell.set {\"cell\":\"C3\",\"input\":\"y\"}", + ] + ); + // Stopping when nothing records says so. + assert_eq!(s.execute("macro.record", json!({"stop": true})).unwrap(), json!({"recording": false})); +} + +#[test] +fn only_the_workbooks_a_debugged_run_touched_wait() { + let mut s = s(); + stepper(&mut s); + debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5"})); + debug(&mut s, json!({"action": "step"})); + // Another workbook stays editable, macros included. + s.new_workbook(); + set(&mut s, "A1", "elsewhere"); + put( + &mut s, + json!({"name": "Here", "output": {"onConflict": "overwrite"}, "steps": [{"command": "cell.set", "params": {"cell": "A2", "input": "ran"}}]}), + ); + s.execute("macro.run", json!({"name": "Here"})).unwrap(); + assert_eq!(v(&s, "A2").display(), "ran"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(v(&s, "A2").is_empty()); + // The debugged one waits. + s.set_active(0); + let r = s.execute("cell.set", json!({"cell": "A1", "input": "x"})); + assert!(matches!(&r, Err(EngineError::Disabled(_, why)) if why == "Finish or stop the macro first"), "{r:?}"); + // The run carries on in its own workbook whichever one is in front. + s.set_active(1); + let st = debug(&mut s, json!({"action": "continue", "breakpoints": []})); + assert_eq!(st["state"], "paused"); + assert_eq!(s.active_index(), 0); + debug(&mut s, json!({"action": "stop"})); + set(&mut s, "A1", "free"); +} + +/// The commands of saved macro `name`, as `id params`. +fn recorded(s: &mut Session, name: &str) -> Vec { + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": name})).unwrap()).unwrap(); + crate::macros::command_steps(&m.steps).iter().map(|(_, id, p)| format!("{id} {p}")).collect() +} + +#[test] +fn a_recording_is_kept_when_saving_it_fails() { + let mut s = s(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "typed"); + // A name the macro check refuses: still recording, and a good name saves what was recorded. + assert!(s.execute("macro.record", json!({"stop": true, "name": "Bad\u{1}name"})).is_err()); + assert!(s.is_recording()); + set(&mut s, "A2", "more"); + let r = s.execute("macro.record", json!({"stop": true, "name": "Good"})).unwrap(); + assert_eq!(r["saved"], "Good"); + assert!(!s.is_recording()); + assert_eq!(recorded(&mut s, "Good"), ["cell.set {\"cell\":\"A1\",\"input\":\"typed\"}", "cell.set {\"cell\":\"A2\",\"input\":\"more\"}"]); + + // A workbook at its macro limit: freeing a slot and stopping again saves it. + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "B1", "full"); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + let filler = wb.macros[0].clone(); + while wb.macros.len() < gridcraft_model::MAX_MACROS { + let mut m = filler.clone(); + m.name = format!("Filler{}", wb.macros.len()); + wb.macros.push(m); + } + d.wb = Arc::new(wb); + let err = s.execute("macro.record", json!({"stop": true, "name": "Late"})).unwrap_err().to_string(); + assert!(err.contains("at most"), "{err}"); + assert!(s.is_recording()); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + wb.macros.pop(); + d.wb = Arc::new(wb); + s.execute("macro.record", json!({"stop": true, "name": "Late"})).unwrap(); + assert_eq!(recorded(&mut s, "Late"), ["cell.set {\"cell\":\"B1\",\"input\":\"full\"}"]); +} + +#[test] +fn a_relative_recording_keeps_references_on_another_sheet() { + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + data(&mut s); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + s.execute("home.bold", json!({"range": "B2:C2"})).unwrap(); + // On the other sheet, C4 and C3:C5 are that sheet's cells, not the input's. + s.execute("sheet.activate", json!({"sheet": "Two"})).unwrap(); + set(&mut s, "C4", "x"); + set(&mut s, "D2", "=SUM(C3:C5)"); + s.execute("macro.record", json!({"stop": true, "name": "Both"})).unwrap(); + let steps = recorded(&mut s, "Both"); + assert!(steps.contains(&"cell.set {\"cell\":\"C4\",\"input\":\"x\"}".to_string()), "{steps:?}"); + assert!(steps.contains(&"cell.set {\"cell\":\"D2\",\"input\":\"=SUM(C3:C5)\"}".to_string()), "{steps:?}"); + // Played back on another block of Sheet1, it writes Two's cells. + set(&mut s, "C4", ""); + set(&mut s, "D2", ""); + set(&mut s, "C3", "5"); + set(&mut s, "C5", "7"); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + for (cell, input) in [("G10", "Who"), ("H10", "Paid"), ("G11", "A"), ("H11", "100"), ("G12", "B"), ("H12", "200"), ("G13", "C"), ("H13", "300")] { + set(&mut s, cell, input); + } + s.execute("macro.run", json!({"name": "Both", "inputs": "G10:H13", "onConflict": "overwrite"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + assert!(bold(&s, "G10") && bold(&s, "H10")); + // Nothing was written into or beside the input. + assert_eq!((v(&s, "H12").display(), v(&s, "I10").display()), ("200".into(), String::new())); + s.execute("sheet.activate", json!({"sheet": "Two"})).unwrap(); + assert_eq!((v(&s, "C4").display(), v(&s, "D2").display()), ("x".into(), "12".into())); +} + +#[test] +fn a_step_that_names_another_sheet_keeps_its_references() { + // `sheet` names where the step runs whatever sheet is active, so its C4 is that sheet's C4. + let mut s = s(); + s.execute("home.insertSheet", json!({"name": "Two"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + data(&mut s); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + s.execute("cell.set", json!({"sheet": "Two", "cell": "C4", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"sheet": "Sheet1", "cell": "C4", "input": "90"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Named"})).unwrap(); + let steps = recorded(&mut s, "Named"); + assert!(steps.contains(&"cell.set {\"cell\":\"C4\",\"input\":\"x\",\"sheet\":\"Two\"}".to_string()), "{steps:?}"); + assert!(steps.contains(&"cell.set {\"cell\":\"Input.cell(3,2)\",\"input\":\"90\",\"sheet\":\"Sheet1\"}".to_string()), "{steps:?}"); +} + +#[test] +fn inlining_recorded_runs_stops_at_the_step_limit() { + // A recorded run of a long macro adds all of its steps; the conversion gathers at most the + // macro's step limit and counts the rest, instead of expanding every run first. + let mut s = s(); + let steps: Vec = (0..6_000).map(|_| json!({"command": "cell.set", "params": {"cell": "A1", "input": "x"}})).collect(); + put(&mut s, json!({"name": "Big", "output": {"onConflict": "overwrite"}, "steps": steps})); + s.execute("macro.record", json!({})).unwrap(); + s.execute("macro.run", json!({"name": "Big"})).unwrap(); + s.execute("macro.run", json!({"name": "Big"})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Twice"})).unwrap(); + assert_eq!((r["steps"].as_u64(), r["dropped"].as_u64()), (Some(10_000), Some(2_000)), "{r}"); +} + +#[test] +fn a_recording_can_be_cancelled() { + let mut s = s(); + data(&mut s); + let before = s.execute("macro.list", json!({})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "E2", "x"); + let r = s.execute("macro.record", json!({"cancel": true})).unwrap(); + assert_eq!(r, json!({"recording": false, "cancelled": true})); + assert!(!s.is_recording() && s.macro_recording.is_none()); + assert_eq!(s.execute("macro.list", json!({})).unwrap(), before, "nothing was saved"); + assert_eq!(s.execute("macro.record", json!({"cancel": true})).unwrap()["cancelled"], false); + // Recording works again afterwards. + s.execute("macro.record", json!({})).unwrap(); + assert!(s.is_recording()); + s.execute("macro.record", json!({"cancel": true})).unwrap(); +} + +#[test] +fn formulas_are_tokenized_by_reading_their_references() { + // An example as large as a sheet has a million rows: each reference in the formula is read + // and matched on its own, instead of a list of every column and row of the example. + let mut s = s(); + s.execute("selection.set", json!({"range": "A1:Z1000000"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "AB1", "input": "=SUM(A1:A1000000)+SUM(A1:A3)+B2"})).unwrap(); + s.execute("cell.set", json!({"cell": "AB2", "input": "=SUM(A1:Z1000000)&\"A1:A1000000\""})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Wide"})).unwrap(); + let steps = recorded(&mut s, "Wide"); + // A single cell inside a formula stays as it is: only the input, its columns and its rows + // become tokens there. + assert!(steps.iter().any(|st| st.contains("=SUM({{Input.col(1)}})+SUM(A1:A3)+B2")), "{steps:?}"); + assert!(steps.iter().any(|st| st.contains("=SUM({{Input}})&\\\"A1:A1000000\\\"")), "{steps:?}"); +} + +#[test] +fn a_selection_of_several_areas_keeps_its_active_cell_as_it_is() { + let mut s = s(); + data(&mut s); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + // Several areas picked with the mouse: no command, so the recording adds a selection.set + // with the active cell before the next step. + let (a, b) = (gridcraft_core::RangeRef::parse("B2:C5").unwrap(), gridcraft_core::RangeRef::parse("E2:E5").unwrap()); + s.doc_mut().unwrap().selection = crate::Selection { active: b.start, anchor: b.start, ranges: vec![a, b] }; + s.execute("home.bold", json!({})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Areas"})).unwrap(); + let steps = recorded(&mut s, "Areas"); + assert!(steps.contains(&"selection.set {\"active\":\"E2\",\"range\":\"B2:C5,E2:E5\"}".to_string()), "{steps:?}"); + assert!(steps.iter().all(|st| !st.contains("\"active\":\"Input")), "{steps:?}"); +} + +#[test] +fn steps_recorded_in_another_workbook_are_counted() { + let mut s = s(); + data(&mut s); + let home = s.active_index(); + s.execute("macro.record", json!({})).unwrap(); + s.new_workbook(); + set(&mut s, "A1", "elsewhere"); + set(&mut s, "A2", "too"); + s.set_active(home); + set(&mut s, "E2", "here"); + let r = s.execute("macro.record", json!({"stop": true, "name": "Home"})).unwrap(); + assert_eq!((r["steps"].as_u64(), r["dropped"].as_u64()), (Some(1), Some(2)), "{r}"); +} + +#[test] +fn a_recorded_macro_run_is_inlined_only_when_its_steps_stand_alone() { + let mut s = s(); + put( + &mut s, + json!({"name": "Branchy", "output": {"onConflict": "overwrite"}, "steps": [ + {"type": "if", "cell": "A1", "op": "empty", + "then": [{"command": "cell.set", "params": {"cell": "B1", "input": "empty"}}], + "else": [{"command": "cell.set", "params": {"cell": "B1", "input": "full"}}]} + ]}), + ); + put( + &mut s, + json!({"name": "Placed", "output": {"anchor": "D1", "onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "Output", "input": "out"}} + ]}), + ); + put( + &mut s, + json!({"name": "Plain", "output": {"onConflict": "overwrite"}, "steps": [ + {"command": "cell.set", "params": {"cell": "C1", "input": "plain"}}, + {"command": "cell.set", "params": {"cell": "C2", "input": "off"}, "enabled": false} + ]}), + ); + s.execute("macro.record", json!({"relative": false})).unwrap(); + for name in ["Branchy", "Placed", "Plain"] { + s.execute("macro.run", json!({"name": name})).unwrap(); + } + let r = s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(r["skipped"], json!(["macro.run", "macro.run"])); + assert_eq!(recorded(&mut s, "Rec"), ["cell.set {\"cell\":\"C1\",\"input\":\"plain\"}"]); +} + +#[test] +fn a_recorded_script_run_leaves_out_the_steps_a_macro_may_not_run() { + let mut s = s(); + let steps = json!([ + {"command": "cell.set", "params": {"cell": "B1", "input": "kept"}}, + {"command": "app.commands", "params": {}}, + {"command": "macro.list", "params": {}} + ]); + s.execute("automate.newScript", json!({"name": "Mixed", "commands": steps})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Mixed"})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(r["skipped"], json!(["app.commands", "macro.list"])); + assert_eq!(recorded(&mut s, "Rec"), ["cell.set {\"cell\":\"B1\",\"input\":\"kept\"}"]); + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); +} + +#[test] +fn a_recorded_script_run_keeps_the_steps_that_ran() { + // One script is edited and another deleted before the recording stops: the macro holds the + // steps as they ran, not the scripts as they stand when the recording is saved. + let mut s = s(); + let step = |input: &str| json!([{"command": "cell.set", "params": {"cell": "B1", "input": input}}]); + s.execute("automate.newScript", json!({"name": "Edited", "commands": step("first")})).unwrap(); + s.execute("automate.newScript", json!({"name": "Gone", "commands": step("kept")})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Edited"})).unwrap(); + s.execute("automate.runScript", json!({"name": "Gone"})).unwrap(); + s.execute("automate.newScript", json!({"name": "Edited", "commands": step("changed")})).unwrap(); + s.execute("automate.deleteScript", json!({"name": "Gone"})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + let steps = recorded(&mut s, "Rec"); + assert_eq!( + steps.get(..2), + Some(&["cell.set {\"cell\":\"B1\",\"input\":\"first\"}".to_string(), "cell.set {\"cell\":\"B1\",\"input\":\"kept\"}".to_string()][..]), + "{steps:?}" + ); + assert!(!r["skipped"].as_array().unwrap().contains(&json!("automate.runScript")), "{r}"); +} + +#[test] +fn a_recording_is_saved_in_the_workbook_where_it_started() { + let mut s = s(); + data(&mut s); + let first = s.doc().unwrap().uid; + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "E2", "Total"); + s.new_workbook(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Here"})).unwrap(); + assert_eq!(r["saved"], "Here"); + // The active workbook stays active and gets nothing. + assert_ne!(s.doc().unwrap().uid, first); + assert!(s.doc().unwrap().wb.macros.is_empty()); + s.set_active(0); + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Here"})).unwrap()).unwrap(); + // The input's shape comes from the workbook where recording started. + assert!(m.inputs[0].header); + assert_eq!(recorded(&mut s, "Here"), ["cell.set {\"cell\":\"Input.cell(1,4)\",\"input\":\"Total\"}"]); + + // When that workbook was closed, stopping says so and ends the recording. + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "E3", "x"); + s.set_active(1); + s.close_document(0); + let err = s.execute("macro.record", json!({"stop": true, "name": "Gone"})).unwrap_err().to_string(); + assert!(err.contains("was closed"), "{err}"); + assert!(!s.is_recording()); + assert!(s.doc().unwrap().wb.macros.is_empty()); +} + +#[test] +fn a_name_given_when_recording_stops_never_replaces_a_macro() { + let mut s = s(); + let original = json!({"command": "cell.set", "params": {"cell": "Z9", "input": "mine"}}); + put(&mut s, json!({"name": "Tidy", "description": "keep me", "steps": [original]})); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "recorded"); + let r = s.execute("macro.record", json!({"stop": true, "name": "tidy"})).unwrap(); + assert_eq!(r["saved"], "tidy (2)"); + let kept = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Tidy"})).unwrap()).unwrap(); + assert_eq!((kept.name.as_str(), kept.description.as_str(), kept.steps.len()), ("Tidy", "keep me", 1)); + assert_eq!(recorded(&mut s, "Tidy"), ["cell.set {\"cell\":\"Z9\",\"input\":\"mine\"}"]); + assert_eq!(recorded(&mut s, "tidy (2)"), ["cell.set {\"cell\":\"A1\",\"input\":\"recorded\"}"]); +} + +#[test] +fn steps_past_the_macro_limit_are_counted_as_dropped() { + let mut s = s(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + let (doc, selection) = (s.doc().unwrap().uid, s.doc().unwrap().selection.clone()); + let rec = s.recorder.as_mut().unwrap(); + for i in 0..gridcraft_model::MAX_MACRO_STEPS + 5 { + rec.push(crate::record::RecordedStep { + doc, + sheet: 0, + sheet_name: "Sheet1".into(), + selection: selection.clone(), + id: "cell.set".into(), + params: json!({"cell": "A1", "input": i.to_string()}), + }); + } + rec.dropped = 3; + let r = s.execute("macro.record", json!({"stop": true, "name": "Long"})).unwrap(); + assert_eq!(r["steps"], gridcraft_model::MAX_MACRO_STEPS); + assert_eq!(r["dropped"], 8, "{r}"); +} + +#[test] +fn a_recording_waits_while_a_macro_in_its_workbook_is_debugged() { + let mut s = s(); + stepper(&mut s); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "Z1", "typed"); + debug(&mut s, json!({"name": "Walk", "inputs": "B2:C5"})); + debug(&mut s, json!({"action": "step"})); + // Saved now, the macro would go into the run's undo group, and stopping the run without + // keeping its changes would delete it again. + let r = s.execute("macro.record", json!({"stop": true, "name": "Typed"})); + assert!(matches!(&r, Err(EngineError::Disabled(id, why)) if id == "macro.record" && why == crate::macros::debug::BUSY), "{r:?}"); + assert!(s.is_recording()); + debug(&mut s, json!({"action": "stop"})); + let r = s.execute("macro.record", json!({"stop": true, "name": "Typed"})).unwrap(); + assert_eq!(r["saved"], "Typed"); + assert_eq!(recorded(&mut s, "Typed"), ["cell.set {\"cell\":\"Z1\",\"input\":\"typed\"}"]); +} + +/// Opens a JSON workbook whose `macros` field holds `macros`, as a file the person opened. +fn open_with_macros(s: &mut Session, macros: Vec) -> Vec { + let mut file = serde_json::to_value(gridcraft_model::Workbook::new()).unwrap(); + file["macros"] = json!(macros); + let r = s.execute("file.open", json!({"name": "kept.json", "base64": crate::io::base64_encode(file.to_string().as_bytes())})).unwrap(); + r["warnings"].as_array().map(|w| w.iter().map(|x| x.as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default() +} + +#[test] +fn kept_macros_count_toward_the_limit_and_keep_their_names() { + // Macros in a newer format count toward the limit when the file opens again, so they count + // when one is added; their names are taken. + let mut s = s(); + let newer = |name: &str| json!({"name": name, "v": gridcraft_model::MACRO_VERSION + 1}); + let mut list: Vec = (0..gridcraft_model::MAX_MACROS - 2).map(|i| json!({"name": format!("M{i}")})).collect(); + list.extend([newer("Future"), newer("Macro1")]); + open_with_macros(&mut s, list); + assert_eq!((s.doc().unwrap().wb.macros.len(), s.doc().unwrap().wb.macros_unread.len()), (gridcraft_model::MAX_MACROS - 2, 2)); + let err = s.execute("macro.save", json!({"name": "New"})).unwrap_err().to_string(); + assert!(err.contains("at most 1000 macros") && err.contains("2 of the 1000"), "{err}"); + s.execute("macro.delete", json!({"name": "M0"})).unwrap(); + for (cmd, p) in [("macro.save", json!({"name": " future "})), ("macro.rename", json!({"name": "M1", "to": "MACRO1"}))] { + let err = s.execute(cmd, p).unwrap_err().to_string(); + assert!(err.contains("newer version"), "{cmd}: {err}"); + } + // Record Macro refuses a kept macro's name when recording starts. + let err = s.execute("macro.record", json!({"name": "future"})).unwrap_err().to_string(); + assert!(err.contains("newer version") && !s.is_recording(), "{err}"); + // A recording takes the next free name, around the kept one, and fills the last place. + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "typed"); + assert_eq!(s.execute("macro.record", json!({"stop": true})).unwrap()["saved"], "Macro2"); + assert_eq!(crate::macros::unique_name(&s.doc().unwrap().wb, "Future"), "Future (2)"); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A2", "more"); + let err = s.execute("macro.record", json!({"stop": true, "name": "Late"})).unwrap_err().to_string(); + assert!(err.contains("2 of the 1000"), "{err}"); + s.execute("macro.record", json!({"cancel": true})).unwrap(); + // Saved and opened again: every macro, the kept ones too, is still there. + for format in ["xlsx", "json"] { + let b64 = s.execute("file.saveBytes", json!({"format": format})).unwrap()["base64"].as_str().unwrap().to_string(); + s.execute("file.open", json!({"name": format!("again.{format}"), "base64": b64})).unwrap(); + let wb = &s.doc().unwrap().wb; + assert_eq!((wb.macros.len(), wb.macros_unread.len()), (gridcraft_model::MAX_MACROS - 2, 2), "{format}"); + assert_eq!(*wb.macros_unread, [newer("Future"), newer("Macro1")], "{format}"); + } +} + +#[test] +fn re_saving_a_large_macro_keeps_the_undo_history_within_its_budget() { + // Each save keeps a copy of the macro list in the undo step before it. The budget counts + // the copies' parameters, so it trims the history instead of keeping every copy. + let mut s = s(); + let big = "x".repeat(3_900_000); + let saves = 36; + for i in 0..saves { + let m = json!({"name": "Big", "description": i.to_string(), "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": big}}]}); + s.execute("macro.save", json!({"macro": m, "replace": true})).unwrap(); + } + let d = s.doc().unwrap(); + let kept: usize = d.undo.iter().map(|e| e.retained_bytes).sum(); + assert!(kept <= crate::UNDO_BYTES_LIMIT, "{kept}"); + assert!(d.undo.len() < saves, "{} undo steps", d.undo.len()); + assert!(d.undo.iter().skip(1).all(|e| e.retained_bytes > big.len()), "each kept copy is charged for its parameters"); +} + +#[test] +fn the_recorded_input_is_inferred_as_it_was_when_recording_started() { + // The recording turns text numbers into numbers; the macro is for data like the data it was + // recorded on, so the input's column types are the ones it had when recording started. + let mut s = s(); + for (cell, input) in [("B2", "Name"), ("C2", "Amount"), ("B3", "Ann"), ("C3", "'120"), ("B4", "Bo"), ("C4", "'80")] { + set(&mut s, cell, input); + } + s.execute("selection.set", json!({"range": "B2:C4"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "C3", "120"); + set(&mut s, "C4", "80"); + s.execute("macro.record", json!({"stop": true, "name": "Numbers"})).unwrap(); + let m = crate::macros::parse_macro(&s.execute("macro.get", json!({"name": "Numbers"})).unwrap()).unwrap(); + assert!(!m.inputs[0].col_types.contains(&gridcraft_model::ColType::Number), "{:?}", m.inputs[0]); + // Played back on data like the original, text numbers and all. + for (cell, input) in [("G10", "Who"), ("H10", "Paid"), ("G11", "A"), ("H11", "'1"), ("G12", "B"), ("H12", "'2")] { + set(&mut s, cell, input); + } + s.execute("macro.run", json!({"name": "Numbers", "inputs": "G10:H12", "onConflict": "overwrite"})).unwrap(); + assert_eq!(v(&s, "H11"), gridcraft_core::Value::Number(120.0)); +} + +#[test] +fn a_script_step_that_only_opened_a_dialog_is_left_out_of_the_recording() { + // Played back, a menu-style step with no parameters would stop the run at its dialog; the + // script's edit is kept. A run whose steps the recording couldn't keep is left out, not read + // from the workbook as the script stands at the end. + let mut s = s(); + let steps = json!([{"command": "cell.set", "params": {"cell": "B1", "input": "1"}}, {"command": "home.formatCells", "params": {}}]); + s.execute("automate.newScript", json!({"name": "EditThenAsk", "commands": steps})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "EditThenAsk"})).unwrap(); + assert!(s.take_ui_requests().iter().any(|q| matches!(q, crate::UiRequest::Dialog(..)))); + s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(recorded(&mut s, "Rec"), ["cell.set {\"cell\":\"B1\",\"input\":\"1\"}"]); + set(&mut s, "B1", ""); + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); + assert_eq!(v(&s, "B1").display(), "1"); + assert!(!s.take_ui_requests().iter().any(|q| matches!(q, crate::UiRequest::Dialog(..)))); + + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "EditThenAsk"})).unwrap(); + s.recorder.as_mut().unwrap().ran.clear(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Without"})).unwrap(); + assert_eq!(r["skipped"], json!(["automate.runScript"])); + assert!(recorded(&mut s, "Without").is_empty()); +} + +#[test] +fn a_rolled_back_script_run_takes_what_it_ran_out_of_the_recording() { + // What a recorded script run ran goes with its step when a group rollback takes the step + // back, and a kept run keeps what it ran under its new place. + let mut s = s(); + s.execute("automate.newScript", json!({"name": "Mark", "commands": [{"command": "cell.set", "params": {"cell": "A1", "input": "m"}}]})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Mark"})).unwrap(); + let _left = s.group_begin("Left open").unwrap(); + set(&mut s, "B1", "gone"); + s.execute("automate.runScript", json!({"name": "Mark"})).unwrap(); + s.execute("automate.stopAction", json!({})).unwrap(); + let rec = s.recorder.as_ref().unwrap(); + assert_eq!((rec.steps.len(), rec.ran.keys().copied().collect::>()), (1, vec![0])); + s.execute("automate.runScript", json!({"name": "Mark"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + let a1 = "cell.set {\"cell\":\"A1\",\"input\":\"m\"}"; + assert_eq!(recorded(&mut s, "Rec"), [a1, a1]); +} + +#[test] +fn a_script_run_records_the_state_its_toggles_set() { + let mut s = s(); + s.execute( + "automate.newScript", + json!({"name": "Bolder", "commands": [{"command": "home.bold", "params": {"range": "A1"}}, {"command": "home.italic"}]}), + ) + .unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Bolder"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(recorded(&mut s, "Rec"), ["home.bold {\"on\":true,\"range\":\"A1\"}", "home.italic {\"on\":true}"]); + // Played back twice, A1 stays bold: the step sets the state rather than flipping it. + for _ in 0..2 { + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); + assert!(bold(&s, "A1")); + } +} + +#[test] +fn renaming_checks_the_macro_size() { + // A longer name can take a macro past the size a file holds: renaming is refused, as saving is. + let mut s = s(); + let mut m = json!({"name": "A", "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": ""}}]}); + let size = |m: &Json| crate::macros::macro_json(&crate::macros::parse_macro(m).unwrap()).to_string().chars().count(); + let pad = crate::cmd::stash::MAX_ITEM_CHARS - size(&m); + m["steps"][0]["params"]["input"] = json!("x".repeat(pad)); + assert_eq!(size(&m), crate::cmd::stash::MAX_ITEM_CHARS); + s.execute("macro.save", json!({"macro": m})).unwrap(); + let err = s.execute("macro.rename", json!({"name": "A", "to": "Longer"})).unwrap_err().to_string(); + assert!(err.contains("too large"), "{err}"); + s.execute("macro.rename", json!({"name": "A", "to": "B"})).unwrap(); + crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); +} + +#[test] +fn a_recorded_macro_run_keeps_the_steps_that_ran() { + // The macro is changed and another deleted before the recording stops: the recording holds + // the steps as they ran. + let mut s = s(); + let one = |cell: &str, input: &str| json!({"output": {"onConflict": "overwrite"}, "steps": [{"command": "cell.set", "params": {"cell": cell, "input": input}}]}); + for (name, cell, input) in [("Changed", "C1", "first"), ("Gone", "C2", "kept")] { + let mut m = one(cell, input); + m["name"] = json!(name); + put(&mut s, m); + } + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("macro.run", json!({"name": "Changed"})).unwrap(); + s.execute("macro.run", json!({"name": "Gone"})).unwrap(); + let mut changed = one("C1", "changed"); + changed["name"] = json!("Changed"); + s.execute("macro.save", json!({"macro": changed, "replace": true})).unwrap(); + s.execute("macro.delete", json!({"name": "Gone"})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(r["skipped"], json!(["macro.save", "macro.delete"]), "{r}"); + assert_eq!(recorded(&mut s, "Rec"), ["cell.set {\"cell\":\"C1\",\"input\":\"first\"}", "cell.set {\"cell\":\"C2\",\"input\":\"kept\"}"]); +} + +#[test] +fn recorded_text_that_reads_as_a_token_plays_back_as_text() { + // Braces typed into a cell and a defined name called Output are text and a name when + // recorded; played back they stay so, instead of being read as tokens. + let mut s = s(); + data(&mut s); + s.execute("formulas.defineName", json!({"name": "Output", "refersTo": "=Sheet1!$H$1"})).unwrap(); + s.execute("selection.set", json!({"range": "B2:C5"})).unwrap(); + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "A1", "Dear {{name}}"); + set(&mut s, "E3", "=SUM(C3:C5)&\"{{x\""); + s.execute("edit.goTo", json!({"reference": "Output"})).unwrap(); + s.execute("home.bold", json!({})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Letters"})).unwrap(); + for cell in ["A1", "E3"] { + set(&mut s, cell, ""); + } + s.execute("home.bold", json!({"range": "H1"})).unwrap(); + assert!(!bold(&s, "H1")); + s.execute("macro.run", json!({"name": "Letters", "inputs": "B2:C5", "onConflict": "overwrite"})).unwrap(); + assert_eq!(v(&s, "A1").display(), "Dear {{name}}"); + assert_eq!(v(&s, "E3").display(), "400{{x"); + assert!(bold(&s, "H1")); + let steps = recorded(&mut s, "Letters"); + assert!(steps.contains(&"edit.goTo {\"reference\":{\"$text\":\"Output\"}}".to_string()), "{steps:?}"); + assert!( + steps.iter().any(|st| st.contains("=SUM({{Input.rows(2..).col(2)}})&\\\"{{{{x\\\"")), + "the formula's own reference is still a token: {steps:?}" + ); +} + +#[test] +fn a_macro_recorded_in_a_workbook_from_a_file_runs_without_asking() { + // The person recorded it: it doesn't ask as a macro that came with the file does. + let mut s = s(); + open_with_macros(&mut s, vec![]); + assert_eq!(s.doc().unwrap().trust, crate::Trust::FromFile); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "mine"); + s.execute("macro.record", json!({"stop": true, "name": "Mine"})).unwrap(); + set(&mut s, "A1", ""); + s.execute("macro.run", json!({"name": "Mine", "onConflict": "overwrite"})).unwrap(); + assert_eq!(v(&s, "A1").display(), "mine"); + // Changed, it asks again. + s.execute("macro.save", json!({"name": "Mine", "replace": true, "steps": [{"command": "cell.set", "params": {"cell": "A1", "input": "x"}}]})) + .unwrap(); + assert!(matches!(s.execute("macro.run", json!({"name": "Mine"})), Err(EngineError::Approve(_)))); +} + +#[test] +fn a_recording_past_the_macro_size_is_cut_and_counted() { + // Three steps of 1.5 million characters each don't fit one macro: the third is left out and + // counted in `dropped`, and the rest is saved. + let mut s = s(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + let (doc, selection) = (s.doc().unwrap().uid, s.doc().unwrap().selection.clone()); + let rec = s.recorder.as_mut().unwrap(); + for i in 0..3 { + rec.push(crate::record::RecordedStep { + doc, + sheet: 0, + sheet_name: "Sheet1".into(), + selection: selection.clone(), + id: "cell.set".into(), + params: json!({"cell": format!("A{}", i + 1), "input": "x".repeat(1_500_000)}), + }); + } + let r = s.execute("macro.record", json!({"stop": true, "name": "Large"})).unwrap(); + assert_eq!((r["steps"].as_u64(), r["dropped"].as_u64()), (Some(2), Some(1)), "{r}"); + assert!(!s.is_recording()); + crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); +} + +#[test] +fn record_refuses_parameters_it_would_ignore() { + let mut s = s(); + // `name`, `description` and `shortcut` count when starting (Record Macro); wrong kinds don't. + for p in [json!({"name": 5}), json!({"shortcut": true}), json!({"relative": "no"}), json!({"stop": 1})] { + assert!(s.execute("macro.record", p.clone()).is_err(), "{p}"); + assert!(!s.is_recording(), "{p}"); + } + s.execute("macro.record", json!({"relative": false, "name": null})).unwrap(); + for p in [json!({"relative": true}), json!({"shortcut": "K"}), json!({"stop": false}), json!({"cancel": true, "name": "x"}), json!({"name": 3})] { + assert!(s.execute("macro.record", p.clone()).is_err(), "{p}"); + assert!(s.is_recording(), "{p}"); + } + assert_eq!(s.execute("macro.record", json!({"cancel": true})).unwrap()["cancelled"], true); +} + +#[test] +fn saving_over_a_macro_needs_replace() { + let mut s = s(); + s.execute("macro.save", json!({"name": "Tidy", "description": "first"})).unwrap(); + let err = s.execute("macro.save", json!({"name": "TIDY", "description": "second"})).unwrap_err().to_string(); + assert!(err.contains("'Tidy' already exists") && err.contains("replace: true"), "{err}"); + assert!(s.execute("macro.save", json!({"name": "Tidy", "replace": "yes"})).is_err()); + assert_eq!(s.execute("macro.get", json!({"name": "Tidy"})).unwrap()["description"], "first"); + s.execute("macro.save", json!({"name": "TIDY", "description": "second", "replace": true})).unwrap(); + assert_eq!(s.execute("macro.get", json!({"name": "Tidy"})).unwrap()["description"], "second"); +} + +#[test] +fn undo_while_recording_keeps_the_undone_step_as_excel_does() { + let mut s = s(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + set(&mut s, "A1", "typed"); + s.execute("edit.undo", json!({})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(r["skipped"], json!(["edit.undo"]), "{r}"); + assert_eq!(recorded(&mut s, "Rec"), ["cell.set {\"cell\":\"A1\",\"input\":\"typed\"}"]); + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); + assert_eq!(v(&s, "A1").display(), "typed"); +} + +#[test] +fn record_checks_a_name_shortcut_and_description_when_it_starts() { + let mut s = s(); + s.execute("macro.save", json!({"name": "Taken", "shortcut": "Ctrl+Shift+P", "steps": []})).unwrap(); + for (p, needle) in [ + (json!({"name": "taken"}), "already exists"), + (json!({"name": "a\nb"}), "line breaks"), + (json!({"name": "x".repeat(300)}), "at most"), + (json!({"name": "New", "shortcut": "p"}), "already runs macro"), + (json!({"name": "New", "shortcut": "Ctrl+Shift+Z"}), "Redo"), + (json!({"name": "New", "shortcut": "F5"}), "one letter"), + (json!({"name": "New", "description": "d".repeat(100_000)}), "at most"), + ] { + let e = s.execute("macro.record", p.clone()).unwrap_err().to_string(); + assert!(e.contains(needle), "{p}: {e}"); + assert!(!s.is_recording(), "{p}"); + } + let r = s.execute("macro.record", json!({"name": " Tidy ", "shortcut": "j", "description": "Tidies"})); + // J is Ungroup on a Mac, so it is reserved; M is free. + assert!(r.is_err_and(|e| e.to_string().contains("Ungroup"))); + let r = s.execute("macro.record", json!({"name": " Tidy ", "shortcut": "m", "description": "Tidies"})).unwrap(); + assert_eq!(r["name"], json!("Tidy")); + set(&mut s, "A1", "1"); + let r = s.execute("macro.record", json!({"stop": true})).unwrap(); + assert_eq!(r["saved"], json!("Tidy")); + let m = s.execute("macro.get", json!({"name": "Tidy"})).unwrap(); + assert_eq!((m["shortcut"].clone(), m["description"].clone()), (json!("Ctrl+Shift+M"), json!("Tidies"))); + // Empty params record under the next MacroN, as before, and never open a dialog. + s.execute("macro.record", json!({})).unwrap(); + set(&mut s, "A2", "2"); + let r = s.execute("macro.record", json!({})).unwrap(); + assert!(r["saved"].as_str().is_some_and(|n| n.starts_with("Macro")), "{r}"); + assert!(s.take_ui_requests().is_empty(), "no dialog"); +} + +#[test] +fn shortcuts_parse_to_one_letter_and_avoid_reserved_and_taken_ones() { + use crate::macros::{parse_shortcut, shortcut_conflict, shortcut_text}; + assert_eq!(parse_shortcut("Ctrl+Shift+M"), Some('M')); + assert_eq!(parse_shortcut("⌘⇧k"), Some('K')); + assert_eq!(parse_shortcut(" q "), Some('Q')); + assert_eq!(parse_shortcut("cmd+shift+r"), Some('R')); + // Other modifiers are refused, not read as Ctrl+Shift. + for bad in ["Ctrl+Shift+F5", "Ctrl+Shift+", "", "Ctrl+Shift+é", "Ctrl+Alt+M", "Shift+M", "Alt+M", "Ctrl+M"] { + assert_eq!(parse_shortcut(bad), None, "{bad}"); + } + assert_eq!(shortcut_text('m'), "Ctrl+Shift+M"); + let mut wb = gridcraft_model::Workbook::default(); + wb.macros.push(gridcraft_model::Macro { name: "A".into(), shortcut: Some("Ctrl+Shift+M".into()), ..Default::default() }); + wb.macros.push(gridcraft_model::Macro { name: "B".into(), ..Default::default() }); + assert!(shortcut_conflict(&wb, "B", 's').is_some_and(|m| m.contains("Save As"))); + assert!(shortcut_conflict(&wb, "B", 'm').is_some_and(|m| m.contains("“A”"))); + // A macro keeps its own letter. + assert_eq!(shortcut_conflict(&wb, "a", 'M'), None); + assert_eq!(shortcut_conflict(&wb, "B", 'Q'), None); +} + +#[test] +fn a_shortcut_taken_while_recording_is_reported_when_it_is_left_off() { + let mut s = s(); + s.execute("macro.record", json!({"name": "Tidy", "shortcut": "m"})).unwrap(); + set(&mut s, "A1", "1"); + // Another macro takes Ctrl+Shift+M before recording stops. + s.execute("macro.save", json!({"name": "Other", "shortcut": "Ctrl+Shift+M", "steps": []})).unwrap(); + let r = s.execute("macro.record", json!({"stop": true})).unwrap(); + assert_eq!(r["saved"], "Tidy"); + assert_eq!(r["shortcutDropped"], "Ctrl+Shift+M", "{r}"); + assert!(s.execute("macro.get", json!({"name": "Tidy"})).unwrap()["shortcut"].is_null()); + // A free one is kept and not reported. + s.execute("macro.record", json!({"name": "Keep", "shortcut": "q"})).unwrap(); + set(&mut s, "A2", "2"); + let r = s.execute("macro.record", json!({"stop": true})).unwrap(); + assert!(r.get("shortcutDropped").is_none(), "{r}"); + assert_eq!(s.execute("macro.get", json!({"name": "Keep"})).unwrap()["shortcut"], "Ctrl+Shift+Q"); +} diff --git a/crates/engine/src/tests/objects.rs b/crates/engine/src/tests/objects.rs new file mode 100644 index 0000000000..2274f04131 --- /dev/null +++ b/crates/engine/src/tests/objects.rs @@ -0,0 +1,476 @@ +//! Floating objects of every kind: found, moved, listed, stacked and deleted by `{kind, id}`. + +use gridcraft_core::CellRef; +use gridcraft_model::{Anchor, AnchorMode, ObjKind, ObjRef, Sheet}; +use serde_json::json; + +use super::s; +use crate::Session; + +fn at(a: &str) -> CellRef { + CellRef::parse(a).unwrap() +} + +fn sheet(s: &Session, i: usize) -> &Sheet { + s.doc().unwrap().wb.sheet(i).unwrap() +} + +fn id_of(v: &serde_json::Value, key: &str) -> u32 { + v[key].as_u64().unwrap() as u32 +} + +/// A table with one object of each kind on the first sheet: a chart, a picture, a shape, a +/// slicer and an equation, in `ObjKind::ALL` order. +fn every_kind(s: &mut Session) -> [ObjRef; 5] { + s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Qty"], ["East", 3], ["West", 5], ["East", 2], ["North", 8]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:B5", "name": "Sales"})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "B1:B5", "type": "column", "at": "D2"})).unwrap(), "chart"); + let image = super::add_image(s, "D18", AnchorMode::MoveAndSize); + let shape = id_of(&s.execute("insert.shape", json!({"kind": "ellipse", "at": "H18"})).unwrap(), "shape"); + s.execute("selection.set", json!({"cell": "A2"})).unwrap(); + let slicer = id_of(&s.execute("insert.slicer", json!({"column": "Region", "at": "L2"})).unwrap(), "slicer"); + let equation = id_of(&s.execute("insert.equation", json!({"latex": "x^2", "cell": "L18"})).unwrap(), "equation"); + [ + ObjRef::new(ObjKind::Chart, chart), + ObjRef::new(ObjKind::Image, image), + ObjRef::new(ObjKind::Shape, shape), + ObjRef::new(ObjKind::Slicer, slicer), + ObjRef::new(ObjKind::Equation, equation), + ] +} + +#[test] +fn every_kind_is_found_moved_and_deleted_by_kind_and_id() { + let mut s = s(); + let objs = every_kind(&mut s); + for o in objs { + assert_eq!(sheet(&s, 0).object_ref(o.id), Some(o), "the id finds its kind"); + assert_eq!(ObjKind::parse(o.kind.name()), Some(o.kind)); + s.execute("object.move", json!({"kind": o.kind.name(), "id": o.id, "at": "M20", "width": 50, "height": 30})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert_eq!((a.cell, a.width, a.height), (at("M20"), 50.0, 30.0)); + s.execute("object.setAnchorMode", json!({"kind": o.kind.name(), "id": o.id, "mode": "absolute"})).unwrap(); + assert_eq!(sheet(&s, 0).object_anchor(o).unwrap().mode, AnchorMode::Absolute); + } + // An equation is a shape too; a plain shape is not an equation. + assert!(sheet(&s, 0).has_object(ObjRef::new(ObjKind::Shape, objs[4].id))); + assert!(s.execute("object.delete", json!({"kind": "equation", "id": objs[2].id})).is_err()); + // A kind that does not match the id, an unknown id or kind, and a missing kind are refused. + assert!(s.execute("object.delete", json!({"kind": "slicer", "id": objs[0].id})).is_err()); + assert!(s.execute("object.delete", json!({"kind": "chart", "id": 9999})).is_err()); + assert!(s.execute("object.delete", json!({"kind": "widget", "id": objs[0].id})).is_err()); + assert!(s.execute("object.delete", json!({"id": objs[0].id})).is_err(), "kind is required"); + for (n, o) in objs.into_iter().enumerate() { + let out = s.execute("object.delete", json!({"kind": o.kind.name(), "id": o.id})).unwrap(); + assert_eq!(out["deleted"], json!({"kind": o.kind.name(), "id": o.id})); + assert!(!sheet(&s, 0).has_object(o)); + for later in &objs[n + 1..] { + assert!(sheet(&s, 0).has_object(*later), "deleting {o:?} leaves {later:?}"); + } + } + // One undo step per delete brings the equation back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(sheet(&s, 0).has_object(objs[4])); +} + +#[test] +fn selection_pane_lists_and_stacks_slicers() { + let mut s = s(); + let objs = every_kind(&mut s); + let second = id_of(&s.execute("insert.slicer", json!({"column": "Qty", "at": "P2"})).unwrap(), "slicer"); + let list = s.execute("arrange.selectionPane", json!({})).unwrap(); + let items = list.as_array().unwrap(); + let kinds: Vec<&str> = items.iter().map(|o| o["kind"].as_str().unwrap()).collect(); + for k in ObjKind::ALL { + assert!(kinds.contains(&k.name()), "{k:?} listed in {kinds:?}"); + } + assert_eq!(kinds.last(), Some(&"slicer"), "slicers stack on top"); + let names: Vec<&str> = items.iter().map(|o| o["name"].as_str().unwrap()).collect(); + assert!(names.contains(&"Region") && names.contains(&"Qty"), "{names:?}"); + assert_eq!(sheet(&s, 0).slicers.first().map(|c| c.id), Some(objs[3].id)); + s.execute("arrange.sendBackward", json!({"kind": "slicer", "id": second, "toBack": true})).unwrap(); + assert_eq!(sheet(&s, 0).slicers.first().map(|c| c.id), Some(second)); +} + +#[test] +fn hostile_object_params_are_refused() { + let mut s = s(); + let objs = every_kind(&mut s); + for p in [ + json!({}), + json!({"kind": "chart"}), + json!({"kind": "chart", "id": -1}), + json!({"kind": "chart", "id": u64::MAX}), + json!({"kind": 7, "id": objs[0].id}), + json!({"kind": null, "id": objs[0].id}), + ] { + for cmd in ["object.delete", "object.move", "object.setAnchorMode"] { + assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p}"); + } + } + let o = objs[3]; + s.execute("object.move", json!({"kind": o.kind.name(), "id": o.id, "dx": 1e300, "dy": -1e300, "width": 1e300, "height": -5})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert!(a.dx.is_finite() && a.dy.is_finite() && a.width <= 10000.0 && a.height >= 0.0, "{a:?}"); +} + +fn cell_of(s: &Session, o: ObjRef) -> String { + sheet(s, 0).object_anchor(o).unwrap().cell.a1() +} + +#[test] +fn every_kind_follows_row_and_column_edits_and_sorts() { + let mut s = s(); + let objs = every_kind(&mut s); + // Anchors: chart D2, picture D18, shape H18, slicer L2, equation L18. + s.execute("object.setAnchorMode", json!({"kind": "shape", "id": objs[2].id, "mode": "absolute"})).unwrap(); + let cells = |s: &Session| objs.map(|o| cell_of(s, o)); + assert_eq!(cells(&s), ["D2", "D18", "H18", "L2", "L18"]); + s.execute("home.insertRows", json!({"rows": "10:11"})).unwrap(); + assert_eq!(cells(&s), ["D2", "D20", "H18", "L2", "L20"], "rows inserted above move the objects below them; an absolute shape stays"); + s.execute("home.insertColumns", json!({"cols": "C:C"})).unwrap(); + assert_eq!(cells(&s), ["E2", "E20", "H18", "M2", "M20"]); + s.execute("home.deleteColumns", json!({"cols": "C:C"})).unwrap(); + s.execute("home.deleteRows", json!({"rows": "10:11"})).unwrap(); + assert_eq!(cells(&s), ["D2", "D18", "H18", "L2", "L18"]); + // Sorting moves a picture anchored inside the sorted block with its row. + s.execute("range.setValues", json!({"range": "T1", "values": [["k"], [3], [1], [2]]})).unwrap(); + let pic = ObjRef::new(ObjKind::Image, super::add_image(&mut s, "T2", AnchorMode::MoveAndSize)); + s.execute("selection.set", json!({"range": "T1:T4"})).unwrap(); + s.execute("data.sortAscending", json!({"header": true, "column": "T"})).unwrap(); + assert_eq!(cell_of(&s, pic), "T4", "the row holding 3 sorts last"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(cell_of(&s, pic), "T2"); +} + +/// A picture at `cell` with anchor `mode`, offset `(dx, dy)` and size `(width, height)`, added +/// straight to the model like `add_image`, so a sort that follows is the only step to undo. +fn picture(s: &mut Session, cell: &str, mode: AnchorMode, dx: f32, dy: f32, width: f32, height: f32) -> ObjRef { + let id = super::add_image(s, cell, mode); + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + if let Some(img) = wb.sheet_mut(0).unwrap().images.iter_mut().find(|i| i.id == id) { + img.anchor = Anchor { dx, dy, width, height, ..img.anchor }; + } + ObjRef::new(ObjKind::Image, id) +} + +/// The anchor of `o` as (cell, dx, dy, width, height). +fn anchor_of(s: &Session, o: ObjRef) -> (String, f32, f32, f32, f32) { + let a = sheet(s, 0).object_anchor(o).unwrap(); + (a.cell.a1(), a.dx, a.dy, a.width, a.height) +} + +/// Sorting rows under a picture follows its anchor mode, as Excel's "Move and size with cells", +/// "Move but don't size with cells" and "Don't move or size with cells" do. +#[test] +fn sorting_rows_under_a_picture_follows_its_anchor_mode() { + let mut s = s(); + // Rows 2..5 hold 3, 1, 4, 2; sorted ascending they read 1, 2, 3, 4, so row 2 moves to row 4, + // row 3 to row 2, row 4 to row 5 and row 5 to row 3. Default rows are 20 pt tall. + s.execute("range.setValues", json!({"range": "A1", "values": [["k"], [3], [1], [4], [2]]})).unwrap(); + // Three pictures inside one row each (3 pt down, 12 pt tall), one per anchor mode. + let sized = picture(&mut s, "A2", AnchorMode::MoveAndSize, 5.0, 3.0, 30.0, 12.0); + let moved = picture(&mut s, "A3", AnchorMode::MoveOnly, 5.0, 3.0, 30.0, 12.0); + let pinned = picture(&mut s, "A4", AnchorMode::Absolute, 5.0, 3.0, 30.0, 12.0); + // A "move and size" picture spanning rows 2 and 3: its top is 10 pt into row 2 (y 30) and + // its bottom 15 pt into row 3 (y 55). The sort puts row 3 above row 2. + let tall = picture(&mut s, "A2", AnchorMode::MoveAndSize, 5.0, 10.0, 30.0, 25.0); + let before: Vec<_> = [sized, moved, pinned, tall].iter().map(|&o| anchor_of(&s, o)).collect(); + s.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + s.execute("data.sortAscending", json!({"header": true, "column": "A"})).unwrap(); + assert_eq!( + anchor_of(&s, sized), + ("A4".into(), 5.0, 3.0, 30.0, 12.0), + "move and size: travels with row 2 to row 4, re-fitted to the same 20 pt row" + ); + assert_eq!(anchor_of(&s, moved), ("A2".into(), 5.0, 3.0, 30.0, 12.0), "move only: travels with row 3 to row 2 at its own size"); + assert_eq!(anchor_of(&s, pinned), ("A4".into(), 5.0, 3.0, 30.0, 12.0), "absolute: stays while the cells move under it"); + // The tall picture's bottom row now sorts above its top row, so there is nothing to stretch + // it between: it travels with its top-left row and keeps its size instead of collapsing. + assert_eq!(anchor_of(&s, tall), ("A4".into(), 5.0, 10.0, 30.0, 25.0), "two rows swapped: moves with its top row at its old size"); + s.execute("edit.undo", json!({})).unwrap(); + let after: Vec<_> = [sized, moved, pinned, tall].iter().map(|&o| anchor_of(&s, o)).collect(); + assert_eq!(after, before, "undo restores every anchor"); +} + +/// A sort by columns follows the anchor mode the same way. +#[test] +fn sorting_columns_under_a_picture_follows_its_anchor_mode() { + let mut s = s(); + // Row 10 holds a header in A and 3, 1, 2 in B..D; sorted ascending, column B moves to D, + // C to B and D to C. Default columns are 64 pt wide. + s.execute("range.setValues", json!({"range": "A10", "values": [["k", 3, 1, 2]]})).unwrap(); + let sized = picture(&mut s, "B10", AnchorMode::MoveAndSize, 5.0, 3.0, 30.0, 12.0); + let moved = picture(&mut s, "C10", AnchorMode::MoveOnly, 5.0, 3.0, 30.0, 12.0); + let pinned = picture(&mut s, "D10", AnchorMode::Absolute, 5.0, 3.0, 30.0, 12.0); + // A "move and size" picture spanning columns B and C: from x 104 (40 pt into B) to x 154 + // (26 pt into C). The sort puts column C before column B. + let wide = picture(&mut s, "B10", AnchorMode::MoveAndSize, 40.0, 3.0, 50.0, 12.0); + let before: Vec<_> = [sized, moved, pinned, wide].iter().map(|&o| anchor_of(&s, o)).collect(); + s.execute("data.sort", json!({"range": "A10:D10", "header": true, "orientation": "columns", "keys": [{"row": 10}]})).unwrap(); + assert_eq!(anchor_of(&s, sized), ("D10".into(), 5.0, 3.0, 30.0, 12.0), "move and size: travels with column B to D at the same width"); + assert_eq!(anchor_of(&s, moved), ("B10".into(), 5.0, 3.0, 30.0, 12.0), "move only: travels with column C to B at its own size"); + assert_eq!(anchor_of(&s, pinned), ("D10".into(), 5.0, 3.0, 30.0, 12.0), "absolute: stays"); + assert_eq!(anchor_of(&s, wide), ("D10".into(), 40.0, 3.0, 50.0, 12.0), "two columns swapped: moves with its left column at its old size"); + s.execute("edit.undo", json!({})).unwrap(); + let after: Vec<_> = [sized, moved, pinned, wide].iter().map(|&o| anchor_of(&s, o)).collect(); + assert_eq!(after, before, "undo restores every anchor"); +} + +#[test] +fn slicers_follow_inserted_rows_like_other_objects() { + let mut s = s(); + let objs = every_kind(&mut s); + s.execute("home.insertRows", json!({"rows": "1:2"})).unwrap(); + assert_eq!(cell_of(&s, objs[3]), "L4"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(cell_of(&s, objs[3]), "L2"); +} + +#[test] +fn chart_series_follow_cut_moves_renames_and_sheet_deletes() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[3], [5], [2], [8]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:A4", "type": "column"})).unwrap(), "chart"); + let values = |s: &Session| sheet(s, 0).charts.iter().find(|c| c.id == chart).map(|c| c.series[0].values.clone()).unwrap_or_default(); + s.execute("edit.cut", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert!(values(&s).contains("$F$2:$F$5"), "a cut-move takes the series with the cells: {}", values(&s)); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts[0].series[0].values = "Other!$A$1:$A$3".into(); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Inputs"})).unwrap(); + assert_eq!(values(&s), "Inputs!$A$1:$A$3"); + s.execute("home.deleteSheet", json!({"sheet": 1})).unwrap(); + assert!(values(&s).contains("#REF!"), "a series into a deleted sheet becomes #REF!: {}", values(&s)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(values(&s), "Inputs!$A$1:$A$3"); +} + +#[test] +fn a_copied_sheet_gives_its_objects_fresh_ids() { + let mut s = s(); + let objs = every_kind(&mut s); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let ids_of = |sh: &Sheet| -> Vec { + sh.charts + .iter() + .map(|c| c.id) + .chain(sh.images.iter().map(|c| c.id)) + .chain(sh.shapes.iter().map(|c| c.id)) + .chain(sh.slicers.iter().map(|c| c.id)) + .collect() + }; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| ids_of(sh)).collect(); + assert_eq!(ids.len(), 2 * objs.len()); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 2 * objs.len(), "every object id stays unique across the workbook"); + let copy = sheet(&s, 1); + let mut kinds: Vec<&str> = ids_of(copy).into_iter().filter_map(|id| copy.object_ref(id)).map(|o| o.kind.name()).collect(); + let mut want: Vec<&str> = objs.iter().map(|o| o.kind.name()).collect(); + kinds.sort_unstable(); + want.sort_unstable(); + assert_eq!(kinds, want, "the copies keep their kinds"); + assert!(s.doc().unwrap().wb.next_object_id() > *ids.last().unwrap_or(&0)); +} + +#[test] +fn bubble_sizes_follow_edits_like_the_other_series_references() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 3, 10], [2, 5, 20], [3, 2, 30]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:B3", "type": "bubble"})).unwrap(), "chart"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap().series[0] + .bubble_sizes = Some("Sheet1!$C$1:$C$3".into()); + let sizes = |s: &Session| sheet(s, 0).charts.iter().find(|c| c.id == chart).and_then(|c| c.series[0].bubble_sizes.clone()).unwrap_or_default(); + s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap(); + assert_eq!(sizes(&s), "Sheet1!$C$2:$C$4", "an inserted row moves the bubble sizes with their cells"); + s.execute("edit.cut", json!({"range": "C2:C4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(sizes(&s), "Sheet1!$F$2:$F$4", "a cut-move takes the bubble sizes with the cells"); + s.execute("sheet.rename", json!({"sheet": 0, "name": "Data"})).unwrap(); + assert_eq!(sizes(&s), "Data!$F$2:$F$4", "a renamed sheet is renamed in the bubble sizes"); +} + +/// A file can carry an object with the largest id. New objects and a copied sheet's objects then +/// take free ids instead of the largest one again, so `{kind, id}` still names one object. +#[test] +fn object_ids_stay_unique_when_a_file_used_the_largest_id() { + let mut s = s(); + let first = id_of(&s.execute("insert.shape", json!({"kind": "rectangle", "at": "B2"})).unwrap(), "shape"); + // The file's shape carries the largest id (set on the model, as a loaded file would). + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().shapes.iter_mut().find(|o| o.id == first).unwrap().id = u32::MAX; + let second = id_of(&s.execute("insert.shape", json!({"kind": "ellipse", "at": "D2"})).unwrap(), "shape"); + let third = id_of(&s.execute("insert.shape", json!({"kind": "triangle", "at": "F2"})).unwrap(), "shape"); + assert!(second != u32::MAX && third != u32::MAX && second != third, "new shapes take free ids, not the largest again: {second}, {third}"); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| sh.shapes.iter().map(|o| o.id)).collect(); + assert_eq!(ids.len(), 6); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 6, "every shape id is distinct across both sheets"); +} + +/// A file's anchors are not held to the 10,000 points `object.move` gives a new size. A picture +/// a file made 12,000 wide keeps that width when it is moved, shrinks by what a resize asks +/// (11,990 stays 11,990, no jump to 10,000) and never grows further; a dimension the file kept +/// within the limit is still capped there. +#[test] +fn an_oversized_imported_object_keeps_its_size_when_moved_and_shrinks_only_by_a_resize() { + let mut s = s(); + let image = super::add_image(&mut s, "B2", AnchorMode::MoveOnly); + // The file's picture is 12,000 by 300: set on the model, then written and read back as a file. + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let a = wb.sheet_mut(0).unwrap().object_anchor_mut(ObjRef::new(ObjKind::Image, image)).unwrap(); + a.width = 12_000.0; + a.height = 300.0; + } + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + s.execute("file.open", json!({"name": "wide.xlsx", "base64": saved["base64"]})).unwrap(); + let o = ObjRef::new(ObjKind::Image, sheet(&s, 0).images[0].id); + let size = |s: &Session| { + let a = sheet(s, 0).object_anchor(o).unwrap(); + (a.width.round(), a.height.round()) + }; + assert_eq!(size(&s), (12_000.0, 300.0), "the reader keeps the file's size"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "at": "D5", "dx": 3, "dy": 4})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert_eq!((a.cell, a.dx, a.dy), (at("D5"), 3.0, 4.0)); + assert_eq!(size(&s), (12_000.0, 300.0), "a move without a size keeps the file's size"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 12_010})).unwrap(); + assert_eq!(size(&s), (12_000.0, 300.0), "the object does not grow past what the file gave"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 11_990})).unwrap(); + assert_eq!(size(&s), (11_990.0, 300.0), "a resize shrinks by what it asks, with no jump to 10,000"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 50_000, "height": 50_000})).unwrap(); + assert_eq!(size(&s), (11_990.0, 10_000.0), "hostile sizes are capped: at the current width, and at 10,000 for a height the file kept within it"); +} + +/// `chart.set` follows the same rule: the Format Chart pane's Size fields send the unchanged +/// dimension back with the edited one, so a chart a file made 12,000 wide keeps that width when +/// its height is edited, shrinks by what is asked and never grows further. +#[test] +fn chart_set_keeps_a_chart_size_a_file_made_larger_than_the_limit() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:A3", "type": "column", "at": "C2"})).unwrap(), "chart"); + // The file's chart is 12,000 wide (set on the model, as a loaded file would). + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + wb.sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap().anchor.width = 12_000.0; + let size = |s: &Session| { + let c = sheet(s, 0).charts.iter().find(|c| c.id == chart).unwrap(); + (c.anchor.width, c.anchor.height) + }; + s.execute("chart.set", json!({"chart": chart, "width": 12_000, "height": 250})).unwrap(); + assert_eq!(size(&s), (12_000.0, 250.0), "the unchanged width sent back with a new height stays"); + s.execute("chart.set", json!({"chart": chart, "width": 11_990})).unwrap(); + assert_eq!(size(&s), (11_990.0, 250.0), "a resize shrinks by what it asks"); + s.execute("chart.set", json!({"chart": chart, "width": 50_000, "height": 50_000})).unwrap(); + assert_eq!(size(&s), (11_990.0, 10_000.0), "hostile sizes are capped at the current width and at 10,000"); +} + +#[test] +fn arrange_and_align_match_a_shape_id_to_its_kind() { + // `arrange.*` and `arrange.align` under `kind: "equation"` act on equations only: an + // ordinary shape's id given as an equation is refused by `arrange` and left in place by + // `align`, as `object.delete` refuses it. An equation is a shape too, so its id works under + // `shape`, as for the other object commands; an unknown kind, and an id of no object of the + // kind, are refused instead of acting on whatever shape has the id. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let order = |s: &Session| -> Vec { sheet(s, 0).shapes.iter().map(|c| c.id).collect() }; + assert_eq!(order(&s), vec![shape.id, equation.id]); + assert!(s.execute("arrange.bringForward", json!({"kind": "equation", "id": shape.id, "toFront": true})).is_err()); + assert_eq!(order(&s), vec![shape.id, equation.id], "the shape is not reordered as an equation"); + s.execute("arrange.sendBackward", json!({"kind": "equation", "id": equation.id, "toBack": true})).unwrap(); + assert_eq!(order(&s), vec![equation.id, shape.id]); + s.execute("arrange.bringForward", json!({"kind": "shape", "id": equation.id, "toFront": true})).unwrap(); + assert_eq!(order(&s), vec![shape.id, equation.id], "an equation is a shape too"); + assert!(s.execute("arrange.bringForward", json!({"kind": "widget", "id": shape.id})).is_err()); + assert!(s.execute("arrange.bringForward", json!({"kind": "chart", "id": 9999})).is_err()); + assert!(s.execute("arrange.bringForward", json!({"kind": "shape", "id": objs[0].id})).is_err(), "a chart's id is not a shape"); + // Align: the shape's id given as an equation is refused and nothing moves; the two equations + // line up on their own. + let second = ObjRef::new(ObjKind::Equation, id_of(&s.execute("insert.equation", json!({"latex": "y", "cell": "B30"})).unwrap(), "equation")); + let before = (anchor_of(&s, shape), anchor_of(&s, equation)); + assert!(s.execute("arrange.align", json!({"kind": "equation", "ids": [shape.id, equation.id, second.id], "align": "left"})).is_err()); + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation)), before, "nothing is aligned with a refused id"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id, second.id], "align": "left"})).unwrap(); + let (a, b) = (sheet(&s, 0).object_anchor(equation).unwrap(), sheet(&s, 0).object_anchor(second).unwrap()); + assert_eq!((a.cell.col, a.dx), (b.cell.col, b.dx), "the equations line up"); + assert!(s.execute("arrange.align", json!({"kind": "widget", "ids": [shape.id, equation.id], "align": "left"})).is_err()); +} + +#[test] +fn arrange_refuses_a_kind_that_is_present_but_not_a_name() { + // `kind` is `shape` only when the parameter is absent: `null`, a number or another non-name + // is refused, so a shape's id is not reordered or aligned under it. The `object.*` commands + // refuse the same values, their kind being required. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let order = |s: &Session| -> Vec { sheet(s, 0).shapes.iter().map(|c| c.id).collect() }; + let before = (order(&s), anchor_of(&s, shape)); + for kind in [json!(null), json!(7), json!(["shape"]), json!({"kind": "shape"}), json!(true)] { + assert!(s.execute("arrange.bringForward", json!({"kind": kind, "id": shape.id, "toFront": true})).is_err(), "{kind}"); + assert!(s.execute("arrange.align", json!({"kind": kind, "ids": [shape.id, equation.id], "align": "left"})).is_err(), "{kind}"); + assert!(s.execute("object.move", json!({"kind": kind, "id": shape.id, "at": "A1"})).is_err(), "{kind}"); + } + assert_eq!((order(&s), anchor_of(&s, shape)), before, "nothing moved"); + // Absent, the kind is `shape`, as before. + s.execute("arrange.bringForward", json!({"id": shape.id, "toFront": true})).unwrap(); + assert_eq!(order(&s).last(), Some(&shape.id)); +} + +#[test] +fn align_refuses_an_id_that_is_not_an_object_of_the_kind() { + // `arrange.align` and `arrange.group` refuse an id in `ids` that is not an object of the + // kind, or not a number, as `arrange` and the `object.*` commands refuse it, instead of + // aligning the rest and reporting success; nothing moves. With fewer than two ids they + // change nothing and succeed. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let second = ObjRef::new(ObjKind::Equation, id_of(&s.execute("insert.equation", json!({"latex": "y", "cell": "B30"})).unwrap(), "equation")); + let before = (anchor_of(&s, shape), anchor_of(&s, equation), anchor_of(&s, second)); + for ids in [ + json!([shape.id, equation.id, second.id]), + json!([equation.id, second.id, 9999]), + json!([equation.id, second.id, -1]), + json!([equation.id, second.id, "x"]), + json!([equation.id, second.id, 1e12]), + json!([equation.id, second.id, null]), + ] { + assert!(s.execute("arrange.align", json!({"kind": "equation", "ids": ids, "align": "left"})).is_err(), "{ids}"); + assert!(s.execute("arrange.group", json!({"kind": "equation", "ids": ids})).is_err(), "{ids}"); + } + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation), anchor_of(&s, second)), before, "nothing moved"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id], "align": "left"})).unwrap(); + s.execute("arrange.align", json!({"kind": "equation", "align": "left"})).unwrap(); + assert_eq!(anchor_of(&s, equation), before.1, "fewer than two ids change nothing"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id, second.id], "align": "left"})).unwrap(); + let (a, b) = (sheet(&s, 0).object_anchor(equation).unwrap(), sheet(&s, 0).object_anchor(second).unwrap()); + assert_eq!((a.cell.col, a.dx), (b.cell.col, b.dx), "the equations line up"); +} + +#[test] +fn align_refuses_ids_that_are_not_an_array() { + // `ids` may be absent (nothing to align) but, present, must be an array of object ids: `null`, + // a number, a string or an object is refused by `arrange.align` and `arrange.group`, and + // nothing moves. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let before = (anchor_of(&s, shape), anchor_of(&s, equation)); + for ids in [json!(null), json!(7), json!("x"), json!({"ids": [1]})] { + assert!(s.execute("arrange.align", json!({"kind": "shape", "ids": ids, "align": "left"})).is_err(), "{ids}"); + assert!(s.execute("arrange.group", json!({"kind": "shape", "ids": ids})).is_err(), "{ids}"); + } + s.execute("arrange.align", json!({"kind": "shape", "align": "left"})).unwrap(); + s.execute("arrange.group", json!({"kind": "shape"})).unwrap(); + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation)), before, "nothing moved"); +} diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs new file mode 100644 index 0000000000..63cf1d92b8 --- /dev/null +++ b/crates/engine/src/tests/python_cells.rs @@ -0,0 +1,532 @@ +//! Python cells under edits: what keeps, moves, rewrites or removes their code. + +use std::sync::Arc; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{Cell, PyCode}; +use serde_json::json; + +use super::s; +use crate::Session; + +/// Makes `cell` on sheet `sheet` a Python cell with `code` and a cached value. +fn plant(s: &mut Session, sheet: usize, cell: &str, code: &str) { + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + let sh = wb.sheet_mut(sheet).unwrap(); + let at = CellRef::parse(cell).unwrap(); + let style = sh.style_id(at); + sh.set_cell(at, Cell { value: Value::Number(1.0), formula: None, style, py: Some(Arc::new(PyCode::new(code))) }); + d.wb = Arc::new(wb); +} + +fn code(s: &Session, sheet: usize, cell: &str) -> Option { + let d = s.doc().unwrap(); + d.wb.sheet(sheet).unwrap().cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_ref()).map(|p| p.code.clone()) +} + +#[test] +fn typing_py_formulas_points_to_python_set() { + let mut s = s(); + let e = s.execute("cell.set", json!({"cell": "A1", "input": "=PY(\"1+1\",0)"})).unwrap_err(); + assert!(e.to_string().contains("python.set"), "{e}"); + assert!(s.execute("cell.set", json!({"cell": "A1", "input": "=py"})).is_err()); + // Other functions starting with PY are not affected. + s.execute("cell.set", json!({"cell": "A2", "input": "=PI()"})).unwrap(); +} + +#[test] +fn entering_or_clearing_a_python_cell_removes_its_code() { + let mut s = s(); + plant(&mut s, 0, "A1", "1 + 1"); + plant(&mut s, 0, "A2", "2 + 2"); + plant(&mut s, 0, "A3", "3 + 3"); + let got = s.execute("cell.get", json!({"cell": "A1"})).unwrap(); + assert_eq!(got["input"], "1 + 1"); + assert_eq!(got["python"]["code"], "1 + 1"); + assert_eq!(got["python"]["output"], "value"); + s.execute("cell.set", json!({"cell": "A1", "input": "hello"})).unwrap(); + assert_eq!(code(&s, 0, "A1"), None); + s.execute("edit.clearFormats", json!({"range": "A2"})).unwrap(); + assert_eq!(code(&s, 0, "A2").as_deref(), Some("2 + 2"), "clearing formats keeps the code"); + s.execute("edit.clearContents", json!({"range": "A2"})).unwrap(); + assert_eq!(code(&s, 0, "A2"), None); + s.execute("edit.clearAll", json!({"range": "A3"})).unwrap(); + assert_eq!(code(&s, 0, "A3"), None); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(code(&s, 0, "A3").as_deref(), Some("3 + 3"), "undo brings the code back"); +} + +#[test] +fn copy_fill_and_sort_carry_the_code_and_paste_values_drops_it() { + let mut s = s(); + plant(&mut s, 0, "A1", "xl('B1') * 2"); + s.execute("edit.copy", json!({"range": "A1"})).unwrap(); + s.execute("edit.paste", json!({"at": "C1"})).unwrap(); + assert_eq!(code(&s, 0, "C1").as_deref(), Some("xl('B1') * 2"), "the code is copied as it is"); + s.execute("edit.pasteSpecial", json!({"at": "D1", "what": "values"})).unwrap(); + assert_eq!(code(&s, 0, "D1"), None); + assert_eq!(super::v(&s, "D1"), Value::Number(1.0), "the cached value is pasted"); + s.execute("edit.fillDown", json!({"range": "A1:A3"})).unwrap(); + assert_eq!(code(&s, 0, "A3").as_deref(), Some("xl('B1') * 2")); + // Sorting moves Python cells with their rows. + s.execute("range.setValues", json!({"range": "E1", "values": [[3], [1], [2]]})).unwrap(); + plant(&mut s, 0, "F1", "'three'"); + plant(&mut s, 0, "F2", "'one'"); + s.execute("data.sort", json!({"range": "E1:F3", "keys": [{"column": "E"}]})).unwrap(); + assert_eq!(code(&s, 0, "F1").as_deref(), Some("'one'")); + assert_eq!(code(&s, 0, "F3").as_deref(), Some("'three'")); +} + +#[test] +fn xl_references_follow_inserts_moves_and_renames() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + plant(&mut s, 0, "C5", &format!("a = xl(\"A1:A3\")\nb = xl('{other}!B2', headers=True)\nc = xl(dynamic)\n# xl(\"A1\") stays in comments")); + s.execute("home.insertRows", json!({"rows": "2:2"})).unwrap(); + let c = code(&s, 0, "C6").unwrap(); + assert!(c.starts_with("a = xl(\"A1:A4\")\n"), "{c}"); + assert!(c.contains(&format!("xl('{other}!B2', headers=True)")), "{c}"); + assert!(c.contains("# xl(\"A1\") stays"), "{c}"); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Data"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().contains("xl('Data!B2', headers=True)")); + // Cutting the cells a reference names moves the reference with them. + s.execute("edit.cut", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "H1"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().starts_with("a = xl(\"H1:H4\")"), "{:?}", code(&s, 0, "C6")); + // Deleting the referenced cells leaves #REF!, which fails when the code runs. + // The selection is elsewhere, so only the named column goes. + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("home.deleteColumns", json!({"cols": "H:H"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().starts_with("a = xl(\"#REF!\")"), "{:?}", code(&s, 0, "C6")); +} + +#[test] +fn a_rename_to_a_name_that_needs_quotes_rewrites_single_quoted_references() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + plant(&mut s, 0, "A1", &format!("a = xl('{other}!B2')\nb = xl(\"{other}!C3\")")); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Q4 2026"})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), "a = xl(\"'Q4 2026'!B2\")\nb = xl(\"'Q4 2026'!C3\")"); + // A name with both quotes in it: the literal's own quote is escaped. + s.execute("sheet.rename", json!({"sheet": 1, "name": "Bob's \"Q4\""})).unwrap(); + let c = code(&s, 0, "A1").unwrap(); + assert_eq!(c, "a = xl(\"'Bob''s \\\"Q4\\\"'!B2\")\nb = xl(\"'Bob''s \\\"Q4\\\"'!C3\")"); + let refs: Vec> = gridcraft_model::python::xl_calls(&c).into_iter().map(|x| x.reference).collect(); + assert_eq!(refs, [Some("'Bob''s \"Q4\"'!B2".to_string()), Some("'Bob''s \"Q4\"'!C3".to_string())]); + // And back to a plain name. + s.execute("sheet.rename", json!({"sheet": 1, "name": "Data"})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), "a = xl(\"Data!B2\")\nb = xl(\"Data!C3\")"); +} + +#[test] +fn a_cut_to_another_sheet_keeps_references_on_the_source_sheet() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let (src, dest) = { + let wb = &s.doc().unwrap().wb; + (wb.sheet(0).unwrap().name.clone(), wb.sheet(1).unwrap().name.clone()) + }; + plant(&mut s, 0, "A1", "a = xl(\"B5\")\nb = xl('A2')"); + plant(&mut s, 0, "A2", "1"); + s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + s.execute("edit.paste", json!({"at": "C1"})).unwrap(); + // B5 stays on the source sheet; A2 moved with the cut, so it follows to the destination. + assert_eq!(code(&s, 1, "C1").unwrap(), format!("a = xl(\"{src}!B5\")\nb = xl('{dest}!C2')")); + assert_eq!(code(&s, 0, "A1"), None); + // Within one sheet nothing is qualified. + s.execute("edit.cut", json!({"range": "C1"})).unwrap(); + s.execute("edit.paste", json!({"at": "E1"})).unwrap(); + assert_eq!(code(&s, 1, "E1").unwrap(), format!("a = xl(\"{src}!B5\")\nb = xl('{dest}!C2')")); + // A copy to another sheet still carries the code as it is. + plant(&mut s, 0, "A9", "xl(\"B5\")"); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("edit.copy", json!({"range": "A9"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + s.execute("edit.paste", json!({"at": "A9"})).unwrap(); + assert_eq!(code(&s, 1, "A9").as_deref(), Some("xl(\"B5\")")); +} + +#[test] +fn goal_seek_and_solver_refuse_to_change_a_python_cell() { + let mut s = s(); + plant(&mut s, 0, "A1", "2"); + s.execute("cell.set", json!({"cell": "B1", "input": "=A1*2"})).unwrap(); + let e = s.execute("data.goalSeek", json!({"set": "B1", "to": 10, "changing": "A1"})).unwrap_err(); + assert!(e.to_string().contains("must contain a value"), "{e}"); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("2"), "the code is kept"); + // The set cell must be a formula: a Python cell isn't one this build can recalculate. + s.execute("cell.set", json!({"cell": "C1", "input": "3"})).unwrap(); + assert!(s.execute("data.goalSeek", json!({"set": "A1", "to": 10, "changing": "C1"})).is_err()); + let e = s.execute("data.solver", json!({"objective": "B1", "goal": "max", "variables": "A1"})).unwrap_err(); + assert!(e.to_string().contains("constants"), "{e}"); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("2")); +} + +#[test] +fn text_to_columns_keeps_a_py_piece_as_text() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "'=PY(\"x\");7"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::text("=PY(\"x\");7")); + s.execute("data.textToColumns", json!({"range": "A1", "delimiters": [";"]})).unwrap(); + // The default text qualifier takes the quotes away, as in Excel. + assert_eq!(super::v(&s, "A1"), Value::text("=PY(x)"), "the piece is kept, not cleared"); + assert_eq!(code(&s, 0, "A1"), None, "and it is not a Python cell"); + assert_eq!(super::v(&s, "B1"), Value::Number(7.0)); +} + +#[test] +fn python_cells_survive_native_json() { + let mut s = s(); + plant(&mut s, 0, "B2", "x = 1\nx"); + let wb = s.doc().unwrap().wb.clone(); + let json = serde_json::to_string(&*wb).unwrap(); + let back: gridcraft_model::Workbook = serde_json::from_str(&json).unwrap(); + let cell = back.sheet(0).unwrap().cell(CellRef::parse("B2").unwrap()).unwrap(); + assert_eq!(cell.py.as_ref().unwrap().code, "x = 1\nx"); + // Cells written before Python existed have no `py` field. + let plain: Cell = serde_json::from_value(json!({"value": {"t": "Number", "v": 2.0}, "formula": null, "style": 0})).unwrap(); + assert!(plain.py.is_none()); + assert!(!serde_json::to_string(&plain).unwrap().contains("py"), "no field is written for ordinary cells"); +} + +#[test] +fn new_errors_parse_and_have_error_type_numbers() { + use gridcraft_core::CellError; + for (text, e) in + [("#PYTHON!", CellError::Python), ("#BUSY!", CellError::Busy), ("#TIMEOUT!", CellError::Timeout), ("#BLOCKED!", CellError::Blocked)] + { + assert_eq!(CellError::parse(text), Some(e)); + assert_eq!(e.as_str(), text); + } + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "=ERROR.TYPE(#BLOCKED!)"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Number(11.0)); + s.execute("cell.set", json!({"cell": "A2", "input": "=ISERROR(#PYTHON!)"})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Bool(true)); +} + +#[test] +fn go_to_special_counts_a_python_cell_as_a_formula_not_a_constant() { + let mut s = s(); + plant(&mut s, 0, "A1", "1 + 1"); + s.execute("cell.set", json!({"cell": "A2", "input": "=1+1"})).unwrap(); + s.execute("cell.set", json!({"cell": "A3", "input": "7"})).unwrap(); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + let r = s.execute("edit.goToSpecial", json!({"kind": "formulas"})).unwrap(); + assert_eq!(r["count"], 2, "{r}"); + assert_eq!(r["selection"], "A1:A2", "{r}"); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + let r = s.execute("edit.goToSpecial", json!({"kind": "constants"})).unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["selection"], "A3", "{r}"); +} + +#[test] +fn a_macro_counts_python_code_as_data_and_a_blocked_spill_as_no_write() { + let mut s = s(); + // F2 shows 1, its cached value: a step that enters 1 there still replaces the code. + plant(&mut s, 0, "F2", "1"); + // H2's code shows #BLOCKED!, as any other new code there would. + s.execute("python.set", json!({"cell": "H2", "code": "'a'"})).unwrap(); + // J2's result spills over J2:J3. A step that writes J3 blocks it, which doesn't write J2. + s.execute("python.set", json!({"cell": "J2", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("J2").unwrap()).unwrap(); + let data = vec![Value::Number(5.0), Value::Number(6.0)]; + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, data).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(super::v(&s, "J3"), Value::Number(6.0)); + super::macros::put( + &mut s, + json!({"name": "Py", "steps": [ + {"command": "cell.set", "params": {"cell": "F2", "input": "1"}}, + {"command": "python.set", "params": {"cell": "H2", "code": "'b'"}}, + {"command": "cell.set", "params": {"cell": "J3", "input": "x"}} + ]}), + ); + let c = s.execute("macro.check", json!({"name": "Py"})).unwrap(); + assert_eq!(c["footprint"]["sheets"][0]["cells"], json!(["F2", "H2", "J3"]), "{c}"); + assert_eq!(c["footprint"]["sheets"][0]["conflicts"], json!(["F2", "H2"]), "{c}"); + let e = s.execute("macro.run", json!({"name": "Py", "onConflict": "fail"})).unwrap_err().to_string(); + assert!(e.contains("F2") && e.contains("H2") && !e.contains("J2"), "{e}"); + assert_eq!(code(&s, 0, "F2").as_deref(), Some("1"), "nothing was changed"); +} + +#[test] +fn replace_edits_a_python_cells_code_and_keeps_it_a_python_cell() { + let mut s = s(); + plant(&mut s, 0, "A1", "x = 1\nx"); + { + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + Arc::make_mut(cell.py.as_mut().unwrap()).object = true; + d.wb = Arc::new(wb); + } + let r = s.execute("edit.replace", json!({"what": "x", "with": "y"})).unwrap(); + assert_eq!(r["replaced"], 1); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("y = 1\ny")); + let d = s.doc().unwrap(); + let cell = d.wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap(); + assert!(cell.py.as_ref().unwrap().object, "the return type is kept"); + assert_eq!(cell.value, Value::Error(gridcraft_core::CellError::Blocked)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("x = 1\nx")); +} + +#[test] +fn replace_leaves_python_code_that_would_no_longer_fit() { + let mut s = s(); + let long = "a".repeat(gridcraft_model::python::MAX_FORMULA_CHARS / 2); + plant(&mut s, 0, "A1", &long); + let r = s.execute("edit.replace", json!({"what": "a", "with": "bb"})).unwrap(); + assert_eq!(r["replaced"], 0); + assert_eq!(r["skipped"], 1); + assert_eq!(code(&s, 0, "A1").as_deref(), Some(long.as_str())); +} + +#[test] +fn a_hidden_python_cell_on_a_protected_sheet_hides_its_code() { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "secret = 1\nsecret"})).unwrap(); + s.execute("python.set", json!({"cell": "B1", "code": "'shown'"})).unwrap(); + s.execute("home.formatCells", json!({"range": "A1", "style": {"protection": {"locked": true, "hidden": true}}})).unwrap(); + let hidden = |s: &Session, a: &str| { + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + crate::display::formula_hidden(&d.wb, sh, CellRef::parse(a).unwrap()) + }; + assert!(!hidden(&s, "A1"), "an unprotected sheet hides nothing"); + s.execute("review.protectSheet", json!({})).unwrap(); + assert!(hidden(&s, "A1"), "Hidden on a protected sheet hides the code, as it hides a formula"); + assert!(!hidden(&s, "B1")); + // Editing it is refused where a formula's would be: the cell is locked. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "2"})).is_err()); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("secret = 1\nsecret")); +} + +#[test] +fn every_merge_keeps_only_the_upper_left_cells_python_code() { + let mut s = s(); + for (cmd, row) in [("home.mergeAcross", 1), ("home.mergeCells", 2), ("home.mergeCenter", 3)] { + plant(&mut s, 0, &format!("A{row}"), "'kept'"); + plant(&mut s, 0, &format!("B{row}"), "'merged away'"); + s.execute(cmd, json!({"range": format!("A{row}:B{row}")})).unwrap(); + assert_eq!(code(&s, 0, &format!("A{row}")).as_deref(), Some("'kept'"), "{cmd}"); + assert_eq!(code(&s, 0, &format!("B{row}")), None, "{cmd}: the hidden cell is no Python cell"); + assert_eq!(super::v(&s, &format!("B{row}")), Value::Empty, "{cmd}"); + } +} + +#[test] +fn unmerging_lets_a_blocked_python_result_spill_again() { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, vec![Value::Number(5.0), Value::Number(6.0)]).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Number(6.0)); + s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Error(gridcraft_core::CellError::Spill), "a merged cell blocks the spill"); + s.execute("home.unmergeCells", json!({"range": "A2:B2"})).unwrap(); + assert_eq!((super::v(&s, "A1"), super::v(&s, "A2")), (Value::Number(5.0), Value::Number(6.0)), "it spills again"); +} + +#[test] +fn save_model_asks_before_it_writes_over_a_python_cell_that_shows_nothing() { + let mut s = s(); + for (cell, input) in [("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + // H2 is a Python cell whose cached value is empty: its code is still content. + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_cell( + CellRef::parse("H2").unwrap(), + Cell { value: Value::Empty, formula: None, style: Default::default(), py: Some(Arc::new(PyCode::new("None"))) }, + ); + } + let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24"]}); + let e = s.execute("data.solverSaveModel", json!({"to": "H1", "model": model})).unwrap_err().to_string(); + assert!(e.contains(crate::cmd::analysis::OVERWRITE_ERROR) && e.contains("H2"), "{e}"); + assert_eq!(code(&s, 0, "H2").as_deref(), Some("None"), "nothing was written"); +} + +/// A1 is a Python cell whose kept result `[5, 6]` spills over A1:A2, and B1 reads A2. +pub(super) fn spill_with_a_reader() -> crate::Session { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, vec![Value::Number(5.0), Value::Number(6.0)]).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "=SUM(A2)"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(6.0)); + s +} + +#[test] +fn new_python_code_recalculates_the_readers_of_its_old_spill() { + let mut s = spill_with_a_reader(); + s.execute("python.set", json!({"cell": "A1", "code": "[7, 8]"})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Empty, "new code has no result yet"); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "B1 read the old spill"); + // The same code again keeps its result, and its spill. + let mut s = spill_with_a_reader(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + assert_eq!((super::v(&s, "A2"), super::v(&s, "B1")), (Value::Number(6.0), Value::Number(6.0))); +} + +#[test] +fn replace_in_python_code_recalculates_the_readers_of_its_old_spill() { + let mut s = spill_with_a_reader(); + let r = s.execute("edit.replace", json!({"what": "[5,", "with": "[7,"})).unwrap(); + assert_eq!(r["replaced"], 1); + assert_eq!(super::v(&s, "A2"), Value::Empty); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "B1 read the old spill"); +} + +#[test] +fn clearing_pasting_over_or_blocking_a_python_spill_recalculates_its_readers() { + let mut s = spill_with_a_reader(); + s.execute("edit.clearContents", json!({"range": "A1"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "clear"); + let mut s = spill_with_a_reader(); + s.execute("cell.set", json!({"cell": "D1", "input": "9"})).unwrap(); + s.execute("edit.copy", json!({"range": "D1"})).unwrap(); + s.execute("edit.paste", json!({"at": "A1"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "paste"); + let mut s = spill_with_a_reader(); + s.execute("home.mergeCells", json!({"range": "A2:A3"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Error(gridcraft_core::CellError::Spill)); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "merge"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(6.0), "undo"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "redo"); +} + +/// `prefix` and a comment padded to the longest code that still fits in one cell. +fn at_the_limit(prefix: &str) -> String { + let with = |n: usize| format!("{prefix}\n#{}", "x".repeat(n)); + let (mut lo, mut hi) = (0, gridcraft_model::python::MAX_FORMULA_CHARS); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if PyCode::new(&with(mid)).fits() { lo = mid } else { hi = mid - 1 } + } + with(lo) +} + +#[test] +fn an_edit_that_would_make_python_code_too_long_is_refused() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + let refused = |e: crate::EngineError, cell: &str| { + let e = e.to_string(); + assert!(e.contains(&format!("!{cell} longer than Excel's 8192-character")) && e.contains("nothing was changed"), "{e}"); + }; + // A sheet rename that lengthens a reference. + let a1 = at_the_limit(&format!("a = xl(\"{other}!B2\")")); + plant(&mut s, 0, "A1", &a1); + refused(s.execute("sheet.rename", json!({"sheet": 1, "name": "A much longer sheet name"})).unwrap_err(), "A1"); + assert_eq!(code(&s, 0, "A1").unwrap(), a1); + assert_eq!(s.doc().unwrap().wb.sheet(1).unwrap().name, other); + // One of the same length is made. + let same = "Z".repeat(other.chars().count()); + s.execute("sheet.rename", json!({"sheet": 1, "name": same})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), a1.replace(&other, &same)); + // Code short of the limit still follows each edit. + plant(&mut s, 0, "A7", "d = xl(\"Z1\")"); + s.execute("selection.set", json!({"range": "B10"})).unwrap(); + s.execute("home.insertColumns", json!({"cols": "Y:Y"})).unwrap(); + assert_eq!(code(&s, 0, "A7").unwrap(), "d = xl(\"AA1\")"); + // An inserted column that turns Z1 into AA1. + let a3 = at_the_limit("b = xl(\"Z1\")"); + plant(&mut s, 0, "A3", &a3); + s.execute("cell.set", json!({"cell": "D1", "input": "kept"})).unwrap(); + s.execute("selection.set", json!({"range": "C1"})).unwrap(); + refused(s.execute("home.insertColumns", json!({"cols": "C:C"})).unwrap_err(), "A3"); + assert_eq!(code(&s, 0, "A3").unwrap(), a3); + assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().value(CellRef::parse("D1").unwrap()), Value::text("kept")); + // A cut to another sheet, which qualifies B9 with the source sheet. + let a5 = at_the_limit("c = xl(\"B9\")"); + plant(&mut s, 0, "A5", &a5); + s.execute("edit.cut", json!({"range": "A5"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + refused(s.execute("edit.paste", json!({"at": "C1"})).unwrap_err(), "C1"); + assert_eq!(code(&s, 0, "A5").unwrap(), a5); + assert_eq!(code(&s, 1, "C1"), None); +} + +/// Makes `cell` a Python cell whose cached value is empty, as a file's `PY` formula with no cached +/// value reads. +fn plant_empty(s: &mut Session, cell: &str) { + plant(s, 0, cell, "x = 1"); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + if let Some(c) = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse(cell).unwrap()) { + c.value = Value::Empty; + } + d.wb = Arc::new(wb); +} + +#[test] +fn python_code_with_an_empty_value_counts_as_content() { + // A report or a PivotTable asks before replacing it. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Sales"], ["East", 1], ["West", 2], ["East", 3]]})).unwrap(); + plant_empty(&mut s, "D2"); + let report = json!({"tool": "Descriptive Statistics", "range": "B1:B4", "labels": true, "output": "D1"}); + assert!(s.execute("data.analysisToolPak", report).is_err(), "the report asks for overwrite"); + plant_empty(&mut s, "H4"); + let pivot = s.execute("insert.pivotTable", json!({"destination": "Sheet1!H3", "rows": ["Region"], "values": ["Sales"]})); + assert!(pivot.is_err_and(|e| e.to_string().contains("already data"))); + assert_eq!((code(&s, 0, "D2"), code(&s, 0, "H4")), (Some("x = 1".into()), Some("x = 1".into())), "the code is kept"); + // Cells aren't pushed off the sheet over it. + plant_empty(&mut s, "K1048576"); + assert!(s.execute("home.insertCells", json!({"range": "K1", "shift": "down"})).is_err()); + assert_eq!(code(&s, 0, "K1048576"), Some("x = 1".into())); + // A table without a header row doesn't push it off the sheet either. + s.execute("range.setValues", json!({"range": "X1", "values": [[1], [2]]})).unwrap(); + plant_empty(&mut s, "X1048576"); + assert!(s.execute("insert.table", json!({"range": "X1:X2", "header": false})).is_err()); + assert_eq!(code(&s, 0, "X1048576"), Some("x = 1".into())); + // It is part of the data region. + s.execute("range.setValues", json!({"range": "P1", "values": [[1], [""], [3]]})).unwrap(); + plant_empty(&mut s, "P2"); + let sh = s.doc().unwrap().wb.sheet(0).unwrap().clone(); + assert_eq!(crate::selection::current_region(&sh, CellRef::parse("P1").unwrap()).a1(), "P1:P3"); + // Pasted into part of a legacy array, it is refused like any content. + s.execute("selection.set", json!({"range": "R1:R3"})).unwrap(); + s.execute("cell.set", json!({"input": "=5", "array": true})).unwrap(); + plant_empty(&mut s, "T1"); + s.execute("edit.copy", json!({"range": "T1"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array"))); +} diff --git a/crates/engine/src/tests/python_commands.rs b/crates/engine/src/tests/python_commands.rs new file mode 100644 index 0000000000..eb794c609c --- /dev/null +++ b/crates/engine/src/tests/python_commands.rs @@ -0,0 +1,245 @@ +//! The python.* commands. + +use gridcraft_core::{CellError, Value}; +use serde_json::json; + +use super::{s, v}; + +fn set(s: &mut crate::Session, cell: &str, code: &str) -> serde_json::Value { + s.execute("python.set", json!({"cell": cell, "code": code})).unwrap() +} + +#[test] +fn set_stores_the_code_and_blocks_the_cell_until_it_can_run() { + let mut s = s(); + let r = set(&mut s, "B1", "xl('A1') + 1"); + assert_eq!(r["cell"], "B1"); + assert_eq!(v(&s, "B1"), Value::Error(CellError::Blocked)); + let got = s.execute("cell.get", json!({"cell": "B1"})).unwrap(); + assert_eq!(got["python"]["code"], "xl('A1') + 1"); + assert_eq!(got["python"]["output"], "value"); + assert_eq!(got["input"], "xl('A1') + 1"); + // The active cell by default. + s.execute("selection.set", json!({"cell": "D4"})).unwrap(); + s.execute("python.set", json!({"code": "2"})).unwrap(); + assert_eq!(s.execute("cell.get", json!({"cell": "D4"})).unwrap()["python"]["code"], "2"); + // One undo step takes the cell back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.execute("cell.get", json!({"cell": "D4"})).unwrap()["python"].is_null()); +} + +#[test] +fn unchanged_code_keeps_its_cached_result() { + let mut s = s(); + set(&mut s, "A1", "21 * 2"); + // As a file would have cached it. + { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let cell = sh.cells.get_mut(gridcraft_core::CellRef::new(0, 0)).unwrap(); + let py = std::sync::Arc::make_mut(cell.py.as_mut().unwrap()); + py.output = Some(gridcraft_model::PyOutput { value: Value::Number(42.0), type_name: "int".into(), preview: "42".into(), convertible: true }); + cell.value = Value::Number(42.0); + } + set(&mut s, "A1", "21 * 2"); + assert_eq!(v(&s, "A1"), Value::Number(42.0), "same code, same result"); + s.execute("python.set", json!({"cell": "A1", "code": "21 * 2", "output": "object"})).unwrap(); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "object"); + set(&mut s, "A1", "21 * 3"); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked), "new code has no result yet"); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "object", "the return type stays"); +} + +#[test] +fn set_refuses_bad_params_long_code_headers_and_protected_cells() { + let mut s = s(); + for p in [ + json!({"cell": "A1"}), + json!({"cell": "A1", "code": 5}), + json!({"cell": "not a cell", "code": "1"}), + json!({"cell": "A1", "code": "1", "output": "sideways"}), + ] { + assert!(s.execute("python.set", p.clone()).is_err(), "{p}"); + } + // The limit is the stored PY(…) formula's 8,192 characters. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "y".repeat(8_080)})).is_err()); + s.execute("python.set", json!({"cell": "A1", "code": "y".repeat(8_079)})).unwrap(); + let quoted = format!("{}{}", "\"".repeat(1_200), "y".repeat(5_800)); + let e = s.execute("python.set", json!({"cell": "A2", "code": quoted})).unwrap_err(); + assert!(e.to_string().contains("8192") || e.to_string().contains("8,192"), "{e}"); + // A table header is the column's name. + s.execute("range.setValues", json!({"range": "C1", "values": [["Name", "Score"], ["a", 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "C1:D2", "headers": true})).unwrap(); + assert!(s.execute("python.set", json!({"cell": "D1", "code": "1"})).is_err()); + assert_eq!(v(&s, "D1"), Value::text("Score")); + set(&mut s, "D2", "1"); + // A locked cell on a protected sheet refuses it. + s.execute("review.protectSheet", json!({})).unwrap(); + let e = s.execute("python.set", json!({"cell": "F1", "code": "1"})).unwrap_err(); + assert!(e.to_string().contains("protected"), "{e}"); +} + +#[test] +fn set_over_a_spilling_formula_takes_the_spill_away() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(3)"})).unwrap(); + assert_eq!(v(&s, "A3"), Value::Number(3.0)); + set(&mut s, "A1", "[1, 2, 3]"); + assert_eq!(v(&s, "A3"), Value::Empty); + assert!(s.doc().unwrap().wb.sheet(0).unwrap().spill_ranges.is_empty()); +} + +/// A cached result as a file would have kept it on the cell: `[[1], [2], [3]]`, a list. +fn cache_list(s: &mut crate::Session, cell: &str) { + let at = gridcraft_core::CellRef::parse(cell).unwrap(); + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let py = std::sync::Arc::make_mut(sh.cells.get_mut(at).unwrap().py.as_mut().unwrap()); + let arr = gridcraft_core::Array::new(3, 1, vec![1.0.into(), 2.0.into(), 3.0.into()]).map(Value::from).unwrap(); + py.output = Some(gridcraft_model::PyOutput { value: arr, type_name: "list".into(), preview: "[1, 2, 3]".into(), convertible: true }); +} + +/// A1 holds `[1, 2, 3]` with its cached list spilled over A1:A3 as Excel values; B1 reads A3. +fn cached_spill_with_a_reader() -> crate::Session { + let mut s = s(); + set(&mut s, "A1", "[1, 2, 3]"); + cache_list(&mut s, "A1"); + s.execute("formulas.calculateNow", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "=SUM(A3)"})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(1.0)); + assert_eq!(v(&s, "B1"), Value::Number(3.0)); + s +} + +fn output_of(s: &mut crate::Session, cell: &str) -> serde_json::Value { + s.execute("cell.get", json!({"cell": cell})).unwrap()["python"]["output"].clone() +} + +fn undo_depth(s: &mut crate::Session) -> Option { + s.execute("history.list", json!({})).unwrap()["undo"].as_array().map(Vec::len) +} + +#[test] +fn output_switches_the_return_type_and_drops_a_result_of_the_other_type() { + let mut s = cached_spill_with_a_reader(); + // The mode it already has changes nothing and adds no undo step. + let undo = undo_depth(&mut s); + let r = s.execute("python.output", json!({"cell": "A1", "mode": "value"})).unwrap(); + assert_eq!(r["output"], "value"); + assert_eq!(undo_depth(&mut s), undo); + assert_eq!(v(&s, "A3"), Value::Number(3.0), "the kept result still spills"); + // Without `mode` it switches. The cached list is an Excel value's result: as with python.set + // and a new return type, the cell has no result until it runs, and its old spill goes with + // its readers recalculated. + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + let r = s.execute("python.output", json!({})).unwrap(); + assert_eq!(r["output"], "object"); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked)); + assert_eq!(v(&s, "A3"), Value::Empty, "the old spill goes"); + assert_eq!(v(&s, "B1"), Value::Number(0.0), "and what read it is recalculated"); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["code"], "[1, 2, 3]", "the code stays"); + // The same as python.set with the same code and the other return type. + let mut by_set = cached_spill_with_a_reader(); + by_set.execute("python.set", json!({"cell": "A1", "code": "[1, 2, 3]", "output": "object"})).unwrap(); + for c in ["A1", "A3", "B1"] { + assert_eq!(v(&s, c), v(&by_set, c), "{c}"); + } + assert_eq!(output_of(&mut s, "A1"), output_of(&mut by_set, "A1")); + // Switching back brings no result back: the dropped one belonged to the old type. + s.execute("python.output", json!({"cell": "A1", "mode": "value"})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked)); + assert_eq!(v(&s, "A3"), Value::Empty); + // Each switch is one undo step, and undoing the first brings the result and its spill back. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + assert_eq!(v(&s, "A1"), Value::Number(1.0)); + assert_eq!(v(&s, "A3"), Value::Number(3.0)); + assert_eq!(v(&s, "B1"), Value::Number(3.0)); + // A cell with no result keeps showing #BLOCKED!. + set(&mut s, "C1", "x = 1"); + s.execute("python.output", json!({"cell": "C1"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Error(CellError::Blocked)); + assert_eq!(output_of(&mut s, "C1"), "object"); +} + +#[test] +fn output_refuses_table_headers_and_locked_cells_as_set_does() { + let mut s = s(); + // A Python cell in a table's header row (as a file could hold one): python.set refuses to + // put code there, and python.output refuses to change it. + s.execute("range.setValues", json!({"range": "C1", "values": [["Name", "Score"], ["a", 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "C1:D2", "headers": true})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(gridcraft_core::CellRef::parse("D1").unwrap()).unwrap(); + cell.py = Some(std::sync::Arc::new(gridcraft_model::PyCode::new("'Score'"))); + } + let e = s.execute("python.output", json!({"cell": "D1"})).unwrap_err(); + assert!(e.to_string().contains("table header"), "{e}"); + assert_eq!(output_of(&mut s, "D1"), "value"); + // A locked cell on a protected sheet refuses it; an unlocked one formatted Hidden takes it, + // as it takes python.set. + set(&mut s, "F1", "1"); + set(&mut s, "G1", "2"); + s.execute("home.formatCells", json!({"range": "G1", "style": {"protection": {"locked": false, "hidden": true}}})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + let e = s.execute("python.output", json!({"cell": "F1"})).unwrap_err(); + assert!(e.to_string().contains("protected"), "{e}"); + assert_eq!(output_of(&mut s, "F1"), "value"); + s.execute("python.set", json!({"cell": "G1", "code": "2"})).unwrap(); + s.execute("python.output", json!({"cell": "G1"})).unwrap(); + assert_eq!(output_of(&mut s, "G1"), "object"); +} + +#[test] +fn output_refuses_cells_without_python_and_bad_modes() { + let mut s = s(); + // Empty params: the active cell, which holds no Python code. + let e = s.execute("python.output", json!({})).unwrap_err(); + assert!(e.to_string().contains("isn't a Python cell"), "{e}"); + s.execute("cell.set", json!({"cell": "B1", "input": "=1+1"})).unwrap(); + assert!(s.execute("python.output", json!({"cell": "B1"})).is_err()); + set(&mut s, "A1", "1"); + for p in [json!({"cell": "A1", "mode": "sideways"}), json!({"cell": "A1", "mode": 1}), json!({"cell": "nowhere"})] { + assert!(s.execute("python.output", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "value"); + // python.set refuses a return type that isn't text too, rather than ignoring it. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "1", "output": true})).is_err()); +} + +#[test] +fn a_recorded_switch_keeps_the_return_type_it_set() { + // python.output without `mode` switches, so a recording keeps the return type the switch set + // (as Bold records `on`): played back on a cell that already has it, nothing switches back. + let mut s = s(); + set(&mut s, "A1", "1"); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("python.output", json!({"cell": "A1"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + let m = s.execute("macro.get", json!({"name": "Rec"})).unwrap(); + let m = crate::macros::parse_macro(&m).unwrap(); + let steps = crate::macros::command_steps(&m.steps); + let step = steps.iter().find(|(_, id, _)| *id == "python.output").map(|(_, _, p)| (*p).clone()); + assert_eq!(step.and_then(|p| p.get("mode").cloned()), Some(json!("object"))); + for _ in 0..2 { + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + } + // A run inside a script is recorded the same way. + s.execute("automate.newScript", json!({"name": "Switch", "commands": [{"command": "python.output", "params": {"cell": "A1"}}]})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Switch"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec2"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + for _ in 0..2 { + s.execute("macro.run", json!({"name": "Rec2", "onConflict": "overwrite"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + } +} diff --git a/crates/engine/src/tests/python_files.rs b/crates/engine/src/tests/python_files.rs new file mode 100644 index 0000000000..cad3f87456 --- /dev/null +++ b/crates/engine/src/tests/python_files.rs @@ -0,0 +1,744 @@ +//! Python cells in files: native JSON, and xlsx as `_xlfn._xlws.PY(index,0|1)` with the code in +//! the Python part ([MS-XLSX] 2.1.23, 2.3.10) and cached values. Nothing here runs Python: results +//! are cached ones, as a file would hold them. + +use std::io::{Read, Write}; +use std::sync::Arc; + +use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; +use gridcraft_model::{Cell, PyCode, PyOutput, Workbook}; +use serde_json::json; + +use super::{s, v}; +use crate::{Session, Trust}; + +fn py(s: &mut Session, cell: &str, code: &str) { + s.execute("python.set", json!({"cell": cell, "code": code})).unwrap(); +} + +/// Gives a Python cell a result, as running it (or a file's cache) would. +fn cache(s: &mut Session, cell: &str, value: Value, type_name: &str) { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let c = sh.cells.get_mut(CellRef::parse(cell).unwrap()).unwrap(); + let p = Arc::make_mut(c.py.as_mut().unwrap()); + p.output = Some(PyOutput { value, type_name: type_name.into(), preview: String::new(), convertible: true }); +} + +fn array(rows: usize, cols: usize, data: Vec) -> Value { + Value::Array(Arc::new(Array::new(rows, cols, data).unwrap())) +} + +fn save(s: &mut Session, format: &str) -> Vec { + let r = s.execute("file.saveBytes", json!({"format": format})).unwrap(); + crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap() +} + +fn open(s: &mut Session, name: &str, bytes: &[u8]) { + s.execute("file.open", json!({"name": name, "base64": crate::io::base64_encode(bytes)})).unwrap(); +} + +fn part(bytes: &[u8], name: &str) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + z.by_name(name).unwrap().read_to_string(&mut xml).unwrap(); + xml +} + +fn sheet_xml(bytes: &[u8]) -> String { + part(bytes, "xl/worksheets/sheet1.xml") +} + +/// The package with `edit` applied to each XML part (by name), and `add` added. +fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &str)]) -> Vec { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let name = f.name().to_string(); + let mut data = Vec::new(); + f.read_to_end(&mut data).unwrap(); + if let Ok(text) = std::str::from_utf8(&data) { + data = edit(&name, text).into_bytes(); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(&data).unwrap(); + } + for (name, text) in add { + out.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(text.as_bytes()).unwrap(); + } + out.finish().unwrap().into_inner() +} + +/// The package with `edit` applied to the first sheet's XML. +fn with_sheet_xml(bytes: &[u8], edit: impl Fn(&str) -> String) -> Vec { + with_parts(bytes, |name, text| if name == "xl/worksheets/sheet1.xml" { edit(text) } else { text.to_string() }, &[]) +} + +/// `xml` with its `` replaced by `data`. +fn replace_sheet_data(xml: &str, data: &str) -> String { + match (xml.find(""), xml.find("")) { + (Some(a), Some(b), _) => format!("{}{data}{}", &xml[..a], &xml[b + "".len()..]), + (_, _, Some(a)) => format!("{}{data}{}", &xml[..a], &xml[a + "".len()..]), + _ => panic!("no sheetData in {xml}"), + } +} + +/// An empty workbook's package with `data` as its first sheet's cells and, when `scripts` is +/// given, a Python part holding them (the relationship and the content type included), as +/// [MS-XLSX] 2.1.23 describes it. +fn excel_shaped(data: &str, scripts: Option<&[&str]>) -> Vec { + let mut s = s(); + let plain = save(&mut s, "xlsx"); + let Some(scripts) = scripts else { return with_sheet_xml(&plain, |xml| replace_sheet_data(xml, data)) }; + let codes: String = scripts.iter().map(|c| format!("{c}")).collect(); + let python = format!( + "\n{codes}" + ); + const REL: &str = + ""; + const TYPE: &str = ""; + let edit = |name: &str, text: &str| match name { + "xl/worksheets/sheet1.xml" => replace_sheet_data(text, data), + "xl/_rels/workbook.xml.rels" => text.replace("", &format!("{REL}")), + "[Content_Types].xml" => text.replace("", &format!("{TYPE}")), + _ => text.to_string(), + }; + with_parts(&plain, edit, &[("xl/python/python1.xml", &python)]) +} + +fn code(s: &Session, cell: &str) -> Option { + s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_deref()).cloned() +} + +/// A workbook with a value, a formula over a Python cell, a spilling table, an object, long code +/// with quotes and line breaks, and an error. +fn build() -> (Session, String) { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "21"})).unwrap(); + py(&mut s, "B1", "xl('A1') * 2"); + cache(&mut s, "B1", Value::Number(42.0), "int"); + s.execute("cell.set", json!({"cell": "A5", "input": "=B1+1"})).unwrap(); + py(&mut s, "C1", "[[1, 'two'], [3, \"four\"]]"); + cache(&mut s, "C1", array(2, 2, vec![1.0.into(), Value::text("two"), 3.0.into(), Value::text("four")]), "list"); + s.execute("python.set", json!({"cell": "E1", "code": "[1, 2]", "output": "object"})).unwrap(); + cache(&mut s, "E1", array(2, 1, vec![1.0.into(), 2.0.into()]), "list"); + let long = format!("# {}\ntext = \"say \\\"hi\\\"\"\nlen(text)", "x".repeat(7_900)); + assert!(PyCode::new(&long).fits()); + py(&mut s, "F1", &long); + cache(&mut s, "F1", Value::Number(8.0), "int"); + py(&mut s, "G1", "1/0"); + { + let d = s.doc_mut().unwrap(); + let sh = Arc::make_mut(&mut d.wb).sheet_mut(0).unwrap(); + sh.cells.get_mut(CellRef::parse("G1").unwrap()).unwrap().value = Value::Error(CellError::Python); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(v(&s, "B1"), Value::Number(42.0)); + assert_eq!(v(&s, "A5"), Value::Number(43.0)); + assert_eq!(v(&s, "D2"), Value::text("four")); + assert_eq!(v(&s, "E1"), Value::text("list"), "a Python object shows its type"); + assert_eq!(v(&s, "E2"), Value::Empty, "and doesn't spill"); + (s, long) +} + +#[test] +fn xlsx_stores_the_code_in_the_python_part_with_cached_values() { + let (mut s, long) = build(); + let bytes = save(&mut s, "xlsx"); + let xml = sheet_xml(&bytes); + // The formula names the cell's script by index, in the order the cells are written: B1, C1, + // E1, F1, G1. + assert!(xml.contains("_xlfn._xlws.PY(0,0)42"), "{xml}"); + assert!(xml.contains(">_xlfn._xlws.PY(2,1)"), "the Python object cell has return type 1: {xml}"); + assert!(!xml.contains("xl('A1')"), "the code is not in the sheet"); + let python = part(&bytes, "xl/python.xml"); + assert!( + python.contains("xl('A1') * 2"), + "{python}" + ); + assert_eq!(python.matches("").count(), 5); + assert!( + part(&bytes, "[Content_Types].xml").contains("") + ); + assert!( + part(&bytes, "xl/_rels/workbook.xml.rels") + .contains("Type=\"http://schemas.microsoft.com/office/2023/09/relationships/Python\" Target=\"python.xml\"") + ); + assert!(xml.contains("t=\"array\" ref=\"C1:D2\""), "the spill is saved like a dynamic array's: {xml}"); + assert!(xml.contains("#VALUE!") && !xml.contains("#PYTHON!"), "Python errors are cached as #VALUE!"); + + open(&mut s, "book.xlsx", &bytes); + assert_eq!(s.doc().unwrap().trust, Trust::FromFile); + // Cached values show, spills included, and the code is back. + assert_eq!(v(&s, "B1"), Value::Number(42.0)); + assert_eq!(v(&s, "A5"), Value::Number(43.0)); + assert_eq!( + (v(&s, "C1"), v(&s, "D1"), v(&s, "C2"), v(&s, "D2")), + (Value::Number(1.0), Value::text("two"), Value::Number(3.0), Value::text("four")) + ); + assert_eq!(code(&s, "B1").unwrap().code, "xl('A1') * 2"); + assert!(code(&s, "E1").unwrap().object); + assert_eq!(code(&s, "F1").unwrap().code, long, "long code with quotes and line breaks survives"); + assert_eq!(v(&s, "G1"), Value::Error(CellError::Value)); + // A blocker typed into the spill area gives #SPILL!; clearing it spills again, without + // running anything. + s.execute("cell.set", json!({"cell": "D2", "input": "x"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Error(CellError::Spill)); + s.execute("edit.clearContents", json!({"range": "D2"})).unwrap(); + assert_eq!(v(&s, "D2"), Value::text("four")); + // Saved again, the file holds the same formulas and scripts. + let again = save(&mut s, "xlsx"); + assert!(sheet_xml(&again).contains("_xlfn._xlws.PY(0,0)")); + assert_eq!(part(&again, "xl/python.xml"), python); + // A workbook without Python cells has no Python part. + let mut plain = super::s(); + assert!(!save(&mut plain, "xlsx").windows(10).any(|w| w == b"python.xml")); +} + +#[test] +fn excel_authored_python_cells_are_read_as_python() { + // A workbook as [MS-XLSX] 2.3.10 describes it: `_xlfn._xlws.PY(index,0|1,params…)` naming a + // script of the Python part, whose code names the parameters as `%Px%`, with a spilled result + // cached. + let data = "_xlfn._xlws.PY(0,0)1\ + _xlfn._xlws.PY(1,1,C1:C3)DataFrame\ + 2"; + let bytes = excel_shaped(data, Some(&["[1, 2]", "df = xl(\"%P2%\", headers=True)\ndf.describe()"])); + let mut s = s(); + open(&mut s, "excel.xlsx", &bytes); + let a1 = code(&s, "A1").expect("an Excel Python cell is a Python cell"); + assert_eq!(a1.code, "[1, 2]"); + assert!(!a1.object); + assert_eq!((v(&s, "A1"), v(&s, "A2")), (Value::Number(1.0), Value::Number(2.0)), "its spilled values are kept"); + let cell = s.doc().unwrap().wb.active().unwrap().cell(CellRef::new(0, 0)).unwrap().clone(); + assert!(cell.formula.is_none()); + let b1 = code(&s, "B1").unwrap(); + assert_eq!(b1.code, "df = xl(\"C1:C3\", headers=True)\ndf.describe()", "a parameter is put back as its reference"); + assert!(b1.object); + assert_eq!(v(&s, "B1"), Value::text("DataFrame")); + // Saved by GridCraft, the code goes back into a Python part, the reference as text. + let again = save(&mut s, "xlsx"); + assert!(part(&again, "xl/python.xml").contains("df = xl(\"C1:C3\", headers=True)\ndf.describe()")); + // The string-literal form (other applications, files GridCraft wrote before) still reads. + let literal = "_xlfn._xlws.PY(\"1 + 1\",1)2"; + open(&mut s, "literal.xlsx", &excel_shaped(literal, None)); + assert_eq!(code(&s, "A1").map(|p| (p.code, p.object)), Some(("1 + 1".to_string(), true))); +} + +#[test] +fn a_py_formula_naming_a_missing_script_keeps_only_its_value() { + let data = "_xlfn._xlws.PY(0,0)5_xlfn._xlws.PY(3,0)6"; + for (name, bytes) in [("one.xlsx", excel_shaped(data, Some(&["5"]))), ("none.xlsx", excel_shaped(data, None))] { + let (wb, warnings) = crate::io::open_bytes(name, &bytes).unwrap(); + let sh = wb.sheet(0).unwrap(); + let b1 = sh.cell(CellRef::parse("B1").unwrap()).unwrap(); + assert!(b1.py.is_none() && b1.formula.is_none(), "{name}: no code to keep, and no formula #NAME? would replace"); + assert_eq!(b1.value, Value::Number(6.0), "{name}"); + assert!(warnings.iter().any(|w| w.contains("Python")), "{name}: {warnings:?}"); + } + let (wb, _) = crate::io::open_bytes("one.xlsx", &excel_shaped(data, Some(&["5"]))).unwrap(); + assert_eq!(wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().py.as_ref().map(|p| p.code.as_str()), Some("5")); +} + +/// `bytes` with the part `name` stored uncompressed and one byte of its data changed, so the +/// archive is intact but reading the part fails its checksum. +fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let entry = f.name().to_string(); + let mut data = Vec::new(); + f.read_to_end(&mut data).unwrap(); + let options = zip::write::SimpleFileOptions::default(); + let options = if entry == name { options.compression_method(zip::CompressionMethod::Stored) } else { options }; + out.start_file(entry, options).unwrap(); + out.write_all(&data).unwrap(); + } + let mut zipped = out.finish().unwrap().into_inner(); + let at = zipped.windows(marker.len()).position(|w| w == marker.as_bytes()).expect("the marker is stored as it is"); + zipped[at + 1] ^= 0x20; + zipped +} + +#[test] +fn a_damaged_python_part_is_a_warning_and_the_workbook_opens_with_its_values() { + let data = "_xlfn._xlws.PY(0,0)59"; + let good = excel_shaped(data, Some(&["5"])); + // The part's data fails its checksum (a damaged archive entry). + let damaged = with_damaged_part(&good, "xl/python/python1.xml", ""); + // The part is not well-formed XML, before its first script. + let broken = |at: &'static str, with: &'static str| { + with_parts(&good, move |name, text| if name == "xl/python/python1.xml" { text.replace(at, with) } else { text.to_string() }, &[]) + }; + let malformed = broken("", "", Color::Auto)]); + let mut sh = (*wb.sheets[0]).clone(); + sh.shapes.push(Shape { + id: 3, + kind: ShapeKind::TextBox, + anchor: Anchor { cell: CellRef::parse("D2").unwrap(), width: 80.0, height: 30.0, ..Default::default() }, + fill: Color::Auto, + line: Color::Auto, + text: "plain".into(), + format: Default::default(), + math: Default::default(), + }); + wb.sheets[0] = Arc::new(sh); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 3); + assert_eq!(s[0].text, "{".repeat(40)); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[1].text, "\u{1F600} & ]]> ", "XML-illegal characters are dropped, the rest kept"); + assert_eq!(s[2].kind, ShapeKind::TextBox); + assert_eq!(s[2].text, "plain"); +} + +#[test] +fn office_math_edited_elsewhere_reads_back_as_edited() { + // GridCraft writes the source in the description and Office Math in the body. Another + // application that edits the Office Math (Excel) leaves the description alone; the marker in + // the description no longer matches the body, so the Office Math is converted and the stale + // source dropped, and the next save writes the edited equation. + let wb = book(vec![equation(1, "B2", "x^2", Color::Rgb(0x1F4E79))]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + assert!(described(&d, "x^2")); + // Excel's edit: the base `x` becomes `y`, in the Office Math only. + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + let edited = d[m0..m1].replacen("x", "y", 1); + assert_ne!(edited, d[m0..m1]); + d.replace_range(m0..m1, &edited); + parts.insert(name, d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[0].text, "{y}^{2}", "the edited Office Math, converted"); + assert_eq!(s[0].line, Color::Rgb(0x1F4E79)); + // Saving writes the edited equation; the old source is gone. + let again = drawing(&unzip(&write_xlsx(&back).unwrap())); + assert!(described(&again, "{y}^{2}") && !again.contains("x^2"), "{again}"); +} + +#[test] +fn a_marker_over_garbage_office_math_falls_back_without_panicking() { + // Office Math that is not the marker's and not in the subset either: the Choice is left + // alone and the fallback text box, which carries the description, is read as the equation. + let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + d.replace_range(m0..m1 + "".len(), "junk"); + parts.insert(name.clone(), d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[0].text, "x^2"); + // A description whose marker is malformed is not GridCraft's source: with Office Math the + // maths is converted; without it the box is text. + let d2 = drawing(&unzip(&write_xlsx(&wb).unwrap())).replace("descr=\"gridcraft:latex:", "descr=\"gridcraft:latex:zz:"); + parts.insert(name, d2.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!((s[0].kind, s[0].text.as_str()), (ShapeKind::Equation, "{x}^{2}")); +} + +#[test] +fn office_math_outside_the_subset_reads_the_fallback() { + let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + // Another writer: no GridCraft source, Office Math the reader does not convert (a + // pre-subscript), and a fallback text box with its own text. + while let Some(a) = d.find(" descr=\"gridcraft:latex:") { + let b = d[a + 8..].find('"').unwrap() + a + 9; + d.replace_range(a..b, ""); + } + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + d.replace_range( + m0..m1 + "".len(), + "12y", + ); + let fb = d.find("").unwrap(); + let t = d[fb..].find("x^2").unwrap() + fb; + d.replace_range(t..t + "x^2".len(), "the writer's fallback"); + parts.insert(name, d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::TextBox, "not an equation"); + assert_eq!(s[0].text, "the writer's fallback", "the fallback is read, not the empty Office Math box"); +} + +#[test] +fn hostile_sources_round_trip_exactly() { + // Sources built from the characters XML and LaTeX treat specially: each is saved (as Office + // Math with a fallback, or as text) and read back as the same equation source. + const PARTS: &[&str] = &[ + "x", + "\\frac{a}{b}", + "\"", + "'", + "<", + ">", + "&", + "&", + "]]>", + " + CFBundleLocalizations + + en + cs + de + el + es + fr + it + ja + ko + nl + pl + pt-BR + ro + ru + sr + tr + uk + vi + zh-Hans + CFBundleDisplayName GridCraft CFBundleName diff --git a/packaging/windows/INSTALLATION.md b/packaging/windows/INSTALLATION.md new file mode 100644 index 0000000000..982a5b4202 --- /dev/null +++ b/packaging/windows/INSTALLATION.md @@ -0,0 +1,35 @@ +# Windows installation policy checks + +New installations default to the current account under `Programs\ArtCraft\`. +The first setup page offers installation for everyone. Scope is selected before duplicate +checks and directory costing. An update uses the existing context's remembered exact folder; +`INSTALLFOLDER` supplied explicitly is never replaced. It is a secure MSI property so the +chosen folder reaches the elevated installer. Silent machine updates pass `ALLUSERS=1`. +A cross-context copy is refused; changing context means uninstalling the old copy first. + +App registration follows the selected context. Existing optional shortcuts and file-handler +choices stay app-owned. No new cleanup operation or model/settings migration is introduced. +Packaged resources remain package-owned; separately downloaded shared models are not caches +and are outside this installer's ownership. + +## Repeatable metadata tests + +On Windows with WiX 5.0.2 and its matching UI/Util extensions: + +```powershell +./packaging/windows/test-install-policy.ps1 -OutputDirectory ./target/install-policy-tests +``` + +The script builds x64, x86 and arm64 packages with deliberately non-executable payloads. It +uses the actual package source and compiled database. A safe Windows Installer session checks +24 scope/registration/maintenance cases, remembered and explicit custom folders, sequencing, +upgrade identity and the original registration inventory recorded in `install-policy.json`. +The release packaging script runs the compiled checker before signing. Packaging CI runs the +small fixture builds without compiling the Rust application. + +Never install or distribute the `NOT-INSTALLABLE.msi` fixtures as an app. Passing these checks +does not prove real installation, elevation, legacy-version upgrades, registry writes, optional +shortcut/menu behaviour, cancellation, rollback or uninstall. Those still require the real +payload in an authorised clean Windows test environment. Cross-architecture metadata is not +execution evidence on those architectures. Existing open installer/association PRs must be +reconciled before publication. Nothing here changes macOS/Linux native packaging conventions. diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 new file mode 100644 index 0000000000..cc9416e9c9 --- /dev/null +++ b/packaging/windows/check-install-policy.ps1 @@ -0,0 +1,296 @@ +<# +.SYNOPSIS + Check the compiled installation policy without installing any product. +.DESCRIPTION + Uses Windows Installer's safe session (OpenPackage option 1). Only property-setting custom + actions are exercised. No AppSearch, install, repair, removal or file-writing action runs. +#> +param([Parameter(Mandatory = $true)] [string] $MsiPath) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +function Read-Rows($Database, [string] $Sql, [int] $Columns) { + $view = $Database.OpenView($Sql) + try { + [void]$view.Execute() + while ($null -ne ($record = $view.Fetch())) { + try { + $values = @(for ($i = 1; $i -le $Columns; $i++) { + $record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, @($i)) + }) + ,$values + } finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($record) } + } + } finally { + [void]$view.Close() + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($view) + } +} +function Set-SessionProperty($Session, [string] $Name, [string] $Value) { + [void]$Session.GetType().InvokeMember('Property', 'SetProperty', $null, $Session, @($Name, $Value)) +} +function Get-SessionProperty($Session, [string] $Name) { + $Session.GetType().InvokeMember('Property', 'GetProperty', $null, $Session, @($Name)) +} +function Get-PackageTemplate($Database) { + # Summary information property 7 is the platform: "Intel;1033", "x64;1033" or "Arm64;1033". + $summary = $Database.GetType().InvokeMember('SummaryInformation', 'GetProperty', $null, $Database, @(0)) + try { [string]$summary.GetType().InvokeMember('Property', 'GetProperty', $null, $summary, @(7)) } + finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($summary) } +} +$installer = $null; $database = $null; $session = $null +try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $file = (Resolve-Path -LiteralPath $MsiPath).Path + $database = $installer.OpenDatabase($file, 0) + $session = $installer.OpenPackage($file, 1) + $properties = @{} + foreach ($row in (Read-Rows $database 'SELECT `Property`, `Value` FROM `Property`' 2)) { $properties[$row[0]] = $row[1] } + $secureProperties = @($properties['SecureCustomProperties'] -split ';') + if ('INSTALLFOLDER' -notin $secureProperties) { + throw 'The selected installation folder must survive elevation (secure INSTALLFOLDER).' + } + if ($policy.mode -eq 'perUser') { + if ($properties.ContainsKey('ALLUSERS')) { throw 'Launcher must remain per-user; machine self-update is not part of this change.' } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'Launcher upgrade identity changed.' } + $dirs = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { $dirs[$row[0]] = @($row[1],$row[2]) } + if ($dirs['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or $dirs['CraftSuiteFolder'][1] -ne 'ArtCraft' -or + $dirs['CraftSuiteFolder'][0] -ne 'LocalProgramsFolder' -or $dirs['LocalProgramsFolder'][0] -ne 'LocalAppDataFolder') { + throw 'Launcher new-install folder must be under the per-user ArtCraft suite root.' + } + foreach ($explicit in @('', 'F:\Chosen exact launcher')) { + Set-SessionProperty $session 'PREVIOUSINSTALLFOLDER' 'E:\Existing exact launcher' + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + $row = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftRestoreLauncherFolder''' 1)[0] + if ($session.EvaluateCondition($row[0]) -eq 1) { + if ($session.DoAction('CraftRestoreLauncherFolder') -ne 1) { throw 'Launcher restore action failed.' } + } + $expected = if ($explicit) { $explicit } else { 'E:\Existing exact launcher' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Launcher custom or existing path was lost.' } + } + $rows = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($rows | Where-Object { $_[0] -ne '1' }).Count) { throw 'Launcher registration must stay under the current account.' } + foreach ($entry in $policy.registry) { + if (@($rows | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }).Count -ne 1) { + throw 'Launcher registration or shortcut preference changed unexpectedly.' + } + } + Write-Output 'PASS ArtCraft Launcher: per-user scope, suite folder, remembered/custom paths and existing registration. No installation performed.' + return + } + if ($properties['ALLUSERS'] -ne '2' -or $properties['MSIINSTALLPERUSER'] -ne '1') { + throw 'Policy regression: new packages must default to the per-user dual-scope context.' + } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'The existing upgrade identity must not change.' } + $directories = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { + $directories[$row[0]] = @($row[1], $row[2]) + } + if ($directories['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or + $directories['CraftSuiteFolder'][1] -ne 'ArtCraft') { throw 'Expected the app under the ArtCraft suite folder.' } + $programs = $directories['CraftSuiteFolder'][0] + if ($programs -eq 'ProgramFiles6432Folder') { $programs = $directories[$programs][0] } + if ($programs -notin 'ProgramFilesFolder', 'ProgramFiles64Folder') { + throw 'Use Windows Installer native folder redirection, not a hard-coded profile path.' + } + $guards = @(Read-Rows $database 'SELECT `Condition`, `Description` FROM `LaunchCondition`' 2 | + Where-Object { $_[0] -match 'CRAFT_(USER|MACHINE)_DIR' }) + if ($guards.Count -ne 2) { throw 'Expected both duplicate-installation guards.' } + $cases = 0 + foreach ($scope in @('', '2', '1')) { + foreach ($user in @('', 'D:\Existing user app')) { + foreach ($machine in @('', 'E:\Existing machine app')) { + foreach ($installed in @('', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'Installed' $installed + Set-SessionProperty $session 'CRAFT_USER_DIR' $user + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' $machine + $allowed = $true + foreach ($guard in $guards) { + $value = $session.EvaluateCondition($guard[0]) + if ($value -notin 0, 1) { throw 'Invalid duplicate guard.' } + if ($value -eq 0) { $allowed = $false } + } + $opposite = if ($scope -eq '1') { $user } else { $machine } + $expected = [bool]$installed -or -not [bool]$opposite + if ($allowed -ne $expected) { throw "Scope regression: ALLUSERS='$scope', user=$([bool]$user), machine=$([bool]$machine), maintenance=$([bool]$installed)." } + $cases++ + } + } + } + } + # Execute the actual authored type-51 actions in a safe session, not copied resolver logic. + foreach ($scope in @('', '2', '1')) { + foreach ($explicit in @('', 'F:\Chosen exact app')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + Set-SessionProperty $session 'CRAFT_USER_DIR' 'D:\Existing user app' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $action = if ($scope -eq '1') { 'CraftRestoreMachineFolder' } else { 'CraftRestoreUserFolder' } + # Evaluate the compiled condition, so the test exercises it instead of calling the action directly. + $restore = @(Read-Rows $database ('SELECT `Condition` FROM `InstallExecuteSequence` WHERE `Action` = ''{0}''' -f $action) 1)[0] + $selected = $session.EvaluateCondition($restore[0]) -eq 1 + if ($selected -eq [bool]$explicit) { throw "$action must run only when no folder was supplied (condition: $($restore[0]))." } + if ($selected -and $session.DoAction($action) -ne 1) { throw 'Remembered-folder property action failed.' } + $expected = if ($explicit) { $explicit } elseif ($scope -eq '1') { 'E:\Existing machine app' } else { 'D:\Existing user app' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Custom or remembered folder was not preserved.' } + } + } + $ui = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallUISequence`' 2)) { $ui[$row[0]] = [int]$row[1] } + if (-not ($ui['AppSearch'] -lt $ui['CraftPreferMachineScope'] -and + $ui['CraftPreferMachineScope'] -lt $ui['CraftScopeDlg'] -and + $ui['CraftScopeDlg'] -lt $ui['FindRelatedProducts'] -and + $ui['FindRelatedProducts'] -lt $ui['LaunchConditions'] -and + $ui['CraftScopeDlg'] -lt $ui['CraftRestoreUserFolder'] -and $ui['CraftRestoreUserFolder'] -lt $ui['CostInitialize'])) { + throw 'Scope must be chosen after AppSearch and before FindRelatedProducts, launch checks and costing.' + } + # Windows Installer resolves Program Files for the context it started in, before the wizard's scope choice. + # The wizard therefore sets the new-install folder itself, and only in the wizard. + $defaults = @(Read-Rows $database 'SELECT `Action`, `Sequence`, `Condition` FROM `InstallUISequence`' 3 | Where-Object { $_[0] -like 'CraftDefault*' }) + if ($defaults.Count -lt 2) { throw 'The wizard must set the new-install folder after the scope page; Program Files is resolved before the choice.' } + foreach ($row in $defaults) { + if (-not ($ui['CraftScopeDlg'] -lt [int]$row[1] -and [int]$row[1] -lt $ui['CostInitialize'])) { throw "$($row[0]) must run after the scope page and before costing." } + } + if (@(Read-Rows $database 'SELECT `Action` FROM `InstallExecuteSequence`' 1 | Where-Object { $_[0] -like 'CraftDefault*' }).Count) { + throw 'Silent installs must not use the wizard-only default folder actions.' + } + # The machine default comes from the environment of the package architecture, not from a folder name. + # x86 packages use Program Files (x86) on 64-bit Windows; x64 and Arm64 packages use the 64-bit root. + $machineRoot = if ((Get-PackageTemplate $database) -match '^Intel') { + if (Get-SessionProperty $session 'VersionNT64') { ${env:ProgramFiles(x86)} } else { $env:ProgramFiles } + } elseif ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } + $machineFolder = (Join-Path $machineRoot "ArtCraft\$($policy.name)") + '\' + foreach ($scope in @('1', '')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' '' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + foreach ($row in @($defaults | Sort-Object { [int]$_[1] })) { + if ($session.EvaluateCondition($row[2]) -eq 1 -and $session.DoAction($row[0]) -ne 1) { throw "$($row[0]) failed." } + } + $folder = Get-SessionProperty $session 'INSTALLFOLDER' + $wanted = if ($scope -eq '1') { $machineFolder } else { (Join-Path $env:LOCALAPPDATA "Programs\ArtCraft\$($policy.name)") + '\' } + if ($folder -ine $wanted) { throw "Wizard default folder for ALLUSERS='$scope' is '$folder', expected '$wanted'." } + } + $execute = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } + foreach ($action in @('CraftRestoreUserFolder','CraftRestoreMachineFolder')) { + if (-not ($execute['AppSearch'] -lt $execute[$action] -and $execute[$action] -lt $execute['CostInitialize'])) { + throw 'Silent updates must restore the folder before directory costing.' + } + } + foreach ($resolver in @('CraftUFromLegacyExe','CraftMFromLegacyExe')) { + if (-not ($execute['AppSearch'] -lt $execute[$resolver] -and $execute[$resolver] -lt $execute['LaunchConditions'])) { + throw 'Both legacy folder resolvers must run after AppSearch and before the launch checks.' + } + } + # Switching the first-page choice must reset BOTH properties, including a back-and-forth change. + $events = @(Read-Rows $database 'SELECT `Event`, `Argument`, `Condition`, `Ordering` FROM `ControlEvent` WHERE `Dialog_` = ''CraftScopeDlg'' AND `Control_` = ''Next'' ORDER BY `Ordering`' 4) + # Model the full-UI upgrade entry with an existing machine-wide copy. Run + # the actual preference action, then the compiled Next events before discovery. + Set-SessionProperty $session 'ALLUSERS' '2' + Set-SessionProperty $session 'CRAFT_SCOPE' 'user' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $preference = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftPreferMachineScope''' 1)[0] + if ($session.EvaluateCondition($preference[0]) -ne 1 -or $session.DoAction('CraftPreferMachineScope') -ne 1 -or + (Get-SessionProperty $session 'CRAFT_SCOPE') -ne 'machine') { + throw 'Full-UI machine upgrades must initially select the existing machine context.' + } + foreach ($choice in @('machine','user','machine','user')) { + Set-SessionProperty $session 'CRAFT_SCOPE' $choice + foreach ($event in $events) { + if ($event[0] -notmatch '^\[([^\]]+)\]$') { continue } + $property = $Matches[1] + if ($session.EvaluateCondition($event[2]) -eq 1) { + Set-SessionProperty $session $property $(if ($event[1] -eq '{}') { '' } else { $event[1] }) + } + } + $allUsers = Get-SessionProperty $session 'ALLUSERS' + $perUser = Get-SessionProperty $session 'MSIINSTALLPERUSER' + if (($choice -eq 'machine' -and ($allUsers -ne '1' -or $perUser)) -or + ($choice -eq 'user' -and ($allUsers -or $perUser -ne '1'))) { + throw 'Scope selector does not reset the requested installation context.' + } + } + $actions = @(Read-Rows $database 'SELECT `Action`, `Source`, `Target`, `Type` FROM `CustomAction`' 4) + $savedOptions = @($actions | Where-Object { $_[0] -match '^CraftLoadOption[0-9]+M$' }) + foreach ($option in $savedOptions) { + if ([int]$option[3] -ne 51) { throw 'Saved-option test may run only property-setting actions.' } + $number = [regex]::Match($option[0], '[0-9]+').Value + foreach ($scope in @('2','1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session "CRAFT_OPTION_${number}_M" 'saved-machine-choice' + Set-SessionProperty $session "CRAFT_OPTION_${number}_U" 'saved-user-choice' + Set-SessionProperty $session $option[1] '' + $action = "CraftLoadOption$number" + $(if ($scope -eq '1') { 'M' } else { 'U' }) + if ($session.DoAction($action) -ne 1) { throw 'Saved-option property action failed.' } + $expected = if ($scope -eq '1') { 'saved-machine-choice' } else { 'saved-user-choice' } + if ((Get-SessionProperty $session $option[1]) -ne $expected) { throw 'Saved installer choices leaked across contexts.' } + } + } + # Follow the compiled control conditions, not the source's intended appearance. + $controls = @(Read-Rows $database 'SELECT `Dialog_`, `Control`, `Type`, `Attributes`, `Text` FROM `Control`' 5) + $conditions = @() + if (@(Read-Rows $database 'SELECT `Name` FROM `_Tables` WHERE `Name` = ''ControlCondition''' 1).Count) { + $conditions = @(Read-Rows $database 'SELECT `Dialog_`, `Control_`, `Action`, `Condition` FROM `ControlCondition`' 4) + } + function Test-ControlVisible($Control) { + $visible = ([int]$Control[3] -band 1) -ne 0 + foreach ($condition in $conditions) { + if ($condition[0] -eq $Control[0] -and $condition[1] -eq $Control[1] -and $session.EvaluateCondition($condition[3]) -eq 1) { + if ($condition[2] -eq 'Show') { $visible = $true } + if ($condition[2] -eq 'Hide') { $visible = $false } + } + } + return $visible + } + foreach ($button in @($controls | Where-Object { $_[0] -in 'InstallWelcome','InstallMaintenance','DesktopShortcutDlg' -and ([int]$_[3] -band 8388608) -ne 0 })) { + $plain = @($controls | Where-Object { $_[0] -eq $button[0] -and $_[1] -eq ($button[1] + 'User') }) + if ($plain.Count -ne 1 -or ([int]$plain[0][3] -band 8388608)) { throw 'Scope-aware buttons need an unshielded per-user counterpart.' } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + if ((Test-ControlVisible $button) -ne ($scope -eq '1') -or (Test-ControlVisible $plain[0]) -ne ($scope -ne '1')) { + throw 'The elevation shield must follow the selected scope.' + } + } + $dialog = $button[0]; $shieldId = $button[1]; $plainId = $plain[0][1] + $shieldEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$shieldId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + $plainEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$plainId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + if (($shieldEvents -join "`n") -ne ($plainEvents -join "`n")) { throw 'Per-user and machine buttons must perform the same operation.' } + } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + foreach ($text in @($controls | Where-Object { $_[4] -like '*for all users*' })) { + if ((Test-ControlVisible $text) -ne ($scope -eq '1')) { throw 'The welcome-page scope text must follow the selected scope.' } + } + } + if ($policy.id -in 'deckcraft','filmcraft','soundcraft') { + foreach ($route in @(@('WelcomeDlg','Next','InstallDirDlg'),@('InstallDirDlg','Back','WelcomeDlg'))) { + $dialog = $route[0]; $control = $route[1] + $routes = @(Read-Rows $database "SELECT ``Argument``, ``Condition`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$control' AND ``Event`` = 'NewDialog' ORDER BY ``Ordering``" 2) + Set-SessionProperty $session 'Installed' '' + $destination = '' + foreach ($event in $routes) { if ($session.EvaluateCondition($event[1]) -eq 1) { $destination = $event[0] } } + if ($destination -ne $route[2]) { throw 'Skipping the licence page must work in both navigation directions.' } + } + } + $registry = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($registry | Where-Object { $_[0] -in '1', '2' }).Count) { throw 'Registration must follow the selected context, not force HKCU or HKLM.' } + if (@($registry | Where-Object { $_[0] -eq '0' -and $_[1] -match '^Software\\Classes(\\|$)' }).Count) { + throw 'HKCR keys must be relative to Classes.' + } + foreach ($entry in $policy.registry) { + $found = @($registry | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }) + if ($found.Count -ne 1) { throw "Lost or changed registration: $($entry[1]) / $($entry[2])" } + } + $installDir = @($registry | Where-Object { $_[0] -eq '-1' -and $_[1] -eq "Software\$($policy.name)" -and $_[2] -eq 'InstallDir' -and $_[3] -eq '[INSTALLFOLDER]' }) + if ($installDir.Count -ne 1) { throw 'A context-sensitive installation-folder record is required.' } + Write-Output "PASS $($policy.name): $cases scope cases, folder preservation, action sequencing and registry contract. No installation performed." +} finally { + foreach ($com in @($session, $database, $installer)) { + if ($null -ne $com) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($com) } + } +} diff --git a/packaging/windows/gridcraft.wxs b/packaging/windows/gridcraft.wxs index dcc441be9b..44340746ad 100644 --- a/packaging/windows/gridcraft.wxs +++ b/packaging/windows/gridcraft.wxs @@ -1,34 +1,14 @@ - - - + + + - + @@ -42,16 +22,10 @@ execute sequence cannot reload the old choice after the user unchecks the box. --> - - - - - + + + + @@ -60,12 +34,16 @@ - - - + + + + + + + + + @@ -104,8 +82,7 @@ - + @@ -151,7 +128,9 @@ - + + + @@ -159,54 +138,55 @@ - + - + + + - + - + - + - - - - - - + + + + + + - - + + - - - - + + + + - - - - - - - + + + + + + + + @@ -216,16 +196,13 @@ - + - + - + diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json new file mode 100644 index 0000000000..ebe9888998 --- /dev/null +++ b/packaging/windows/install-policy.json @@ -0,0 +1,150 @@ +{ + "id": "gridcraft", + "name": "GridCraft", + "upgradeCode": "5511327B-F305-41BE-92D0-EB84944E7C4D", + "sources": [ + "gridcraft.wxs" + ], + "icon": "assets/app-icon/gridcraft.ico", + "localization": [], + "extensions": [], + "payloads": [ + "gridcraft-cli.exe", + "gridcraft.exe" + ], + "registry": [ + [ + "-1", + "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\gridcraft.exe", + "", + "[#GridcraftExe]" + ], + [ + "-1", + "Software\\Classes\\GridCraft.Workbook", + "", + "GridCraft Workbook" + ], + [ + "-1", + "Software\\Classes\\GridCraft.Workbook\\DefaultIcon", + "", + "\"[#GridcraftExe]\",0" + ], + [ + "-1", + "Software\\Classes\\GridCraft.Workbook\\shell\\open\\command", + "", + "\"[#GridcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\GridCraft.TextData", + "", + "GridCraft Text Data" + ], + [ + "-1", + "Software\\Classes\\GridCraft.TextData\\DefaultIcon", + "", + "\"[#GridcraftExe]\",0" + ], + [ + "-1", + "Software\\Classes\\GridCraft.TextData\\shell\\open\\command", + "", + "\"[#GridcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\.xlsx\\OpenWithProgids", + "GridCraft.Workbook", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\Classes\\.xlsm\\OpenWithProgids", + "GridCraft.Workbook", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\Classes\\.xlsb\\OpenWithProgids", + "GridCraft.Workbook", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\Classes\\.ods\\OpenWithProgids", + "GridCraft.Workbook", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\Classes\\.csv\\OpenWithProgids", + "GridCraft.TextData", + "GridCraft.TextData" + ], + [ + "-1", + "Software\\Classes\\.tsv\\OpenWithProgids", + "GridCraft.TextData", + "GridCraft.TextData" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities", + "ApplicationName", + "GridCraft" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities", + "ApplicationDescription", + "Open-source spreadsheet for .xlsx, CSV and TSV files" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities\\FileAssociations", + ".xlsx", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities\\FileAssociations", + ".xlsm", + "GridCraft.Workbook" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities\\FileAssociations", + ".csv", + "GridCraft.TextData" + ], + [ + "-1", + "Software\\GridCraft\\Capabilities\\FileAssociations", + ".tsv", + "GridCraft.TextData" + ], + [ + "-1", + "Software\\RegisteredApplications", + "GridCraft", + "Software\\GridCraft\\Capabilities" + ], + [ + "-1", + "Software\\GridCraft\\Installer", + "DesktopShortcut", + "[DESKTOPSHORTCUT]" + ], + [ + "-1", + "Software\\GridCraft\\Installer", + "DesktopShortcutComponent", + "#1" + ] + ], + "mode": "dualScope" +} diff --git a/packaging/windows/install-policy.wxi b/packaging/windows/install-policy.wxi new file mode 100644 index 0000000000..04c1597e59 --- /dev/null +++ b/packaging/windows/install-policy.wxi @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index a1c2805b1f..9a1303064a 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -113,6 +113,8 @@ Invoke-Native 'wix build' { -d "DocsDir=$Docs" -d "HasCraftFontLicences=$HasCraftFontLicences" ` -o $Msi } +# Check the compiled scope, path and registration contract before signing. +& (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $Msi # wix writes its debug symbols (.wixpdb) next to the MSI; keep them out of the release assets. Remove-Item -Force -ErrorAction SilentlyContinue ([IO.Path]::ChangeExtension($Msi, '.wixpdb')) & (Join-Path $PSScriptRoot 'sign.ps1') $Msi diff --git a/packaging/windows/test-desktop-shortcut.ps1 b/packaging/windows/test-desktop-shortcut.ps1 index f3c25b2c8a..1eae4a7fdc 100644 --- a/packaging/windows/test-desktop-shortcut.ps1 +++ b/packaging/windows/test-desktop-shortcut.ps1 @@ -16,7 +16,7 @@ if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_OS -ne 'Windows' -or $env:RUN } if (-not $WorkDir) { $WorkDir = Join-Path $env:RUNNER_TEMP 'gridcraft-shortcut-smoke' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path -$InstallDir = Join-Path $env:ProgramFiles 'GridCraft' +$InstallDir = Join-Path $env:ProgramFiles 'ArtCraft\GridCraft' $DesktopLink = Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) 'GridCraft.lnk' $StartLink = Join-Path ([Environment]::GetFolderPath('CommonPrograms')) 'GridCraft.lnk' $ChoiceKey = 'HKLM:\Software\GridCraft\Installer' @@ -65,7 +65,8 @@ function Get-ProductCode([string] $Msi) { function Invoke-Msi([string] $Name, [string[]] $Arguments) { $log = Join-Path $WorkDir "$Name.log" # /norestart is unconditional. Each operation and the workflow have time limits. - $process = Start-Process msiexec.exe -ArgumentList ($Arguments + @('/qn', '/norestart', '/l*v', "`"$log`"")) -PassThru + # Keep this existing regression on the explicit all-users route, including cross-account removal. + $process = Start-Process msiexec.exe -ArgumentList ($Arguments + @('ALLUSERS=1', '/qn', '/norestart', '/l*v', "`"$log`"")) -PassThru try { if (-not $process.WaitForExit(120000)) { $process.Kill() diff --git a/packaging/windows/test-install-policy.ps1 b/packaging/windows/test-install-policy.ps1 new file mode 100644 index 0000000000..d455d19d16 --- /dev/null +++ b/packaging/windows/test-install-policy.ps1 @@ -0,0 +1,54 @@ +<# +.SYNOPSIS + Build non-executable installer metadata fixtures; never install them. +#> +param( + [Parameter(Mandatory = $true)] [string] $OutputDirectory, + [ValidateSet('x64','x86','arm64')] [string[]] $Architectures = @('x64','x86','arm64') +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +[void](New-Item -ItemType Directory -Force -Path $OutputDirectory) +$output = (Resolve-Path -LiteralPath $OutputDirectory).Path +Add-Type -AssemblyName System.Drawing +foreach ($arch in $Architectures) { + $stage = Join-Path $output $arch + [void](New-Item -ItemType Directory -Force -Path $stage) + foreach ($name in $policy.payloads) { + $destination = Join-Path $stage $name + [void](New-Item -ItemType Directory -Force -Path ([IO.Path]::GetDirectoryName($destination))) + Set-Content -LiteralPath $destination -Encoding Ascii -Value 'NON-EXECUTABLE MSI METADATA TEST FIXTURE' + } + foreach ($folder in @('docs','models','notices')) { + $path = Join-Path $stage $folder + [void](New-Item -ItemType Directory -Force -Path $path) + Set-Content -LiteralPath (Join-Path $path "$folder-fixture.txt") -Value 'Metadata test fixture, not a user file or model.' + } + foreach ($model in @('metadata-one.rten','metadata-two.rten')) { + Set-Content -LiteralPath (Join-Path (Join-Path $stage 'models') $model) -Encoding Ascii -Value 'NON-EXECUTABLE MODEL METADATA FIXTURE' + } + foreach ($spec in @(@('banner.bmp',493,58),@('dialog.bmp',493,312))) { + $bitmap = [Drawing.Bitmap]::new($spec[1],$spec[2],[Drawing.Imaging.PixelFormat]::Format24bppRgb) + try { $bitmap.Save((Join-Path $stage $spec[0]),[Drawing.Imaging.ImageFormat]::Bmp) } + finally { $bitmap.Dispose() } + } + Set-Content -LiteralPath (Join-Path $stage 'licence.rtf') -Encoding Ascii -Value '{\rtf1 Metadata test fixture.}' + $sources = @($policy.sources | ForEach-Object { Join-Path $PSScriptRoot $_ }) + $msi = Join-Path $stage "$($policy.id)-NOT-INSTALLABLE.msi" + $extensions = @($policy.extensions | ForEach-Object { '-ext'; "WixToolset.$_.wixext" }) + & wix build @sources -arch $arch @extensions ` + -culture en-US -d 'Version=0.0.1' -d 'DisplayVersion=0.0.1-metadata-test' ` + -d "BinDir=$stage" -d "IconPath=$(Join-Path $root $policy.icon)" ` + -d "DocsDir=$(Join-Path $stage 'docs')" -d "ModelsDir=$(Join-Path $stage 'models')" ` + -d "AppNoticesDir=$(Join-Path $stage 'notices')" -d 'HasCraftFontLicences=1' -d 'HasCli=1' ` + -d "BannerBmp=$(Join-Path $stage 'banner.bmp')" -d "DialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "UiBannerBmp=$(Join-Path $stage 'banner.bmp')" -d "UiDialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "LicenseRtf=$(Join-Path $stage 'licence.rtf')" -o $msi @($policy.localization | ForEach-Object { '-loc'; Join-Path $PSScriptRoot $_ }) + if ($LASTEXITCODE -ne 0) { throw "WiX validation failed for $arch (exit $LASTEXITCODE)." } + $shell = (Get-Process -Id $PID).Path + & $shell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $msi + if ($LASTEXITCODE -ne 0) { throw "Compiled installer policy failed for $arch (exit $LASTEXITCODE)." } + Write-Output "PASS $arch metadata-only package. This is not an executable installer." +} diff --git a/xtask/src/keytips.rs b/xtask/src/keytips.rs index 5b7137455a..b662dd1011 100644 --- a/xtask/src/keytips.rs +++ b/xtask/src/keytips.rs @@ -323,6 +323,11 @@ fn render_tests(entries: &[Entry], probe: &Probe) -> String { id = e.target, ), }, + // Options is a Backstage page rather than a dialog box. + "dialog" if e.target == "options" => format!( + "sequence(&mut h, {seq:?}, false);\n assert!(h.state().backstage.is_some(), \"{seq} must open the Options page\");", + seq = e.seq, + ), "dialog" => format!( "sequence(&mut h, {seq:?}, false);\n assert!(h.state().dialog.is_some(), \"{seq} must open the {dialog} dialog\");", seq = e.seq, diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index cd3229e8be..148c80aaff 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -31,6 +31,8 @@ pub const TABLE: &[(&str, Class)] = &[ ("pdf", Class::Layer(0)), ("formula", Class::Layer(1)), ("functions", Class::Layer(1)), + // Equation layout (LaTeX to glyphs, rules and paths) and OMML, on top of RaTeX. + ("math", Class::Layer(1)), ("model", Class::Layer(2)), ("calc", Class::Layer(2)), ("xlsx", Class::Layer(2)), @@ -58,8 +60,9 @@ fn intra_layer_allowed(from: &str, to: &str) -> bool { } /// Format crates may only depend on these workspace crates (on top of the layer rule), so a -/// file format never pulls in calculation or engine code. -pub const FORMAT_ALLOWED: &[(&str, &[&str])] = &[("xlsx", &["core", "formula", "model"])]; +/// file format never pulls in calculation or engine code. `math` converts equations to and from +/// OMML. +pub const FORMAT_ALLOWED: &[(&str, &[&str])] = &[("xlsx", &["core", "formula", "math", "model"])]; /// External crates that constitute a UI toolkit / windowing dependency. /// Entries ending in `*` are prefixes.