Compare commits

..
401 changed files with 3070 additions and 29257 deletions
-16
View File
@@ -1,16 +0,0 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
-107
View File
@@ -1,107 +0,0 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/gridcraft",
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "gridcraft-nightly-20261124",
"repository": "storytold/gridcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135773,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_gridcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
-2
View File
@@ -9,8 +9,6 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
-59
View File
@@ -1,59 +0,0 @@
name: GridCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: gridcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/gridcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191
with:
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
app-name: gridcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# Forward exactly the secrets the signer's sign steps read, named explicitly (never `inherit`),
# as the stable Release caller does. The callee must declare them; it does since the shared
# change that added them, and `uses:` is pinned to that revision.
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
-33
View File
@@ -1,33 +0,0 @@
name: GridCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/gridcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191
with:
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
app-name: gridcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+2 -21
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
@@ -22,25 +22,6 @@ jobs:
# 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
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]
with:
egress-policy: audit
- uses: actions/[email protected]
with:
persist-credentials: false
- name: Run the synthetic nightly packaging suites
run: python3 packaging/nightly-tests.py
- name: Check the committed nightly icons still match their provenance
run: python3 packaging/nightly-icons.py --check
windows-install-policy:
timeout-minutes: 10
name: Windows installation policy (no app build)
-6
View File
@@ -8,9 +8,3 @@ plan/
/.claude/
/target-*/
/craft-fonts/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
+69
View File
@@ -0,0 +1,69 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**GridCraft** (`storytold/gridcraft`) is an open-source spreadsheet application written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `gridcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
-6
View File
@@ -38,12 +38,6 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg |
| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master |
| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) |
| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master |
| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon |
| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon |
| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives |
| `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation |
| `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files |
| `docs/images/hero-sales.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 |
Generated
+183 -1558
View File
File diff suppressed because it is too large Load Diff
+31 -45
View File
@@ -30,36 +30,32 @@ gridcraft-math = { path = "crates/math" }
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
# craft-libs revision.
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
# foundation
thiserror = "2"
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
clap = { version = "4", features = ["derive"] }
clap_complete = "4"
clap_mangen = "0.2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
@@ -69,10 +65,8 @@ web-time = "1.1.0"
rayon = "1"
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
quick-xml = "0.41"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
zip = { version = "3", default-features = false, features = ["deflate"] }
sha2 = { version = "0.11", default-features = false }
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
sha1 = { version = "0.11", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
@@ -98,15 +92,7 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["ui"] }
# The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is
# to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the
# printer controls. Same craft-libs revision as above.
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -134,18 +120,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
-4
View File
@@ -165,10 +165,6 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t
matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings)
log to standard error only.
The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names
(`--launch-profile nightly-v1 --profile-root <dir>`); a nightly build refuses to start without one,
so a Nightly run never touches the stable app's settings, prefs or logs.
## For agents: MCP, CLI and the control channel
```sh
+1 -29
View File
@@ -2,10 +2,9 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
This page is the summary. The detail is in:
@@ -152,15 +151,10 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked |
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
@@ -171,9 +165,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
@@ -193,20 +184,14 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) |
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
@@ -224,7 +209,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
@@ -297,7 +281,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | Change | Summary |
|---|---|---|
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences |
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
@@ -313,17 +296,13 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
| 2026-10-31 | minor | Progress log: Function Library |
| 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles |
| 2026-10-26 | minor | Progress log: Excel open check |
| 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets |
| 2026-10-26 | minor | Progress log: Arabic PDF text |
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
| 2026-10-26 | minor | Progress log: Arabic font fallback |
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
| 2026-10-24 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
| 2026-10-24 | minor | Progress log: password to modify (#921) |
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
@@ -336,21 +315,14 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save |
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
-11
View File
@@ -9,10 +9,6 @@ publish = false
[lints]
workspace = true
[lib]
name = "gridcraft_cli"
path = "src/lib.rs"
[[bin]]
name = "gridcraft-cli"
path = "src/main.rs"
@@ -26,10 +22,3 @@ log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
zip = { workspace = true }
quick-xml = { workspace = true }
thiserror = { workspace = true }
clap = { workspace = true }
[dev-dependencies]
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
@@ -1,42 +0,0 @@
//! Writes gridcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `gridcraft-cli.1` and one per subcommand, such as
//! `gridcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
//! (see `packaging/`):
//!
//! ```sh
//! cargo run -p gridcraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = gridcraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "gridcraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`gridcraft-cli-help-convert.1`).
clap_mangen::generate_to(gridcraft_cli::command(), dir)
}
-316
View File
@@ -1,316 +0,0 @@
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string;
//! what clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
//!
//! `run` is ordered: its `--cmd` and `--script` steps run in the order they were given, so the repeatable options are
//! kept with their positions and read back in order ([`RunArgs::steps`]).
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::Value;
use crate::script::{ScriptError, Step, parse_command};
/// The end of every subcommand's `--help`.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// The top-level `--help` ends with the environment and the exit status.
const TOP_NOTES: &str = "Environment:\n none: the CLI reads no environment variables of its own\n\nExit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// What a script line looks like (the `run` help ends with it).
const SCRIPT_LINES: &str = "A script line is `id={json}`, `id {json}`, `id`, or {\"command\": \"id\", \"params\": {…}}; blank lines and lines starting with # or // are skipped.";
/// Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window
#[derive(Parser, Debug)]
#[command(name = "gridcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Sheets, used ranges, tables, charts and names of a workbook
#[command(after_help = EXIT_STATUS)]
Info(InfoArgs),
/// Convert a workbook: xlsx, csv, tsv, json, html or pdf, by the extension of OUT
#[command(after_help = EXIT_STATUS)]
Convert(ConvertArgs),
/// Evaluate one formula, optionally against a workbook
#[command(after_help = EXIT_STATUS)]
Eval(EvalArgs),
/// Print a range as an aligned table or CSV
#[command(after_help = EXIT_STATUS)]
Cat(CatArgs),
/// Cached-value calc oracle and XLSX round-trip fidelity of files or folders (exit 1 on any difference)
#[command(after_help = EXIT_STATUS)]
Check(CheckArgs),
/// Run commands and scripts on a workbook, then save or print it
#[command(after_help = format!("{SCRIPT_LINES}\n\n{EXIT_STATUS}"))]
Run(RunArgs),
/// List the commands
#[command(after_help = EXIT_STATUS)]
Commands(ListArgs),
/// List the formula functions
#[command(after_help = EXIT_STATUS)]
Functions(FunctionsArgs),
/// Serve MCP on stdio, headless or driving the running app
#[command(after_help = EXIT_STATUS)]
Mcp(McpArgs),
/// Send one control-channel request to the running app
#[command(after_help = EXIT_STATUS)]
Send(SendArgs),
/// Whether this system confines programs (no program: a confined self-test)
///
/// With a program it runs that program confined, with the given read and executable paths and the system's shared
/// libraries, passing its output and exit status through; its own lines then go to standard error. Every path is
/// absolute. Exit status: 0 when every attempt is as required (or the program succeeded), 1 otherwise (a refused
/// launch included), 2 when GridCraft has no sandbox for this kind of system.
#[command(name = "sandbox-check", after_help = EXIT_STATUS)]
SandboxCheck(SandboxCheckArgs),
}
#[derive(Args, Debug)]
pub(crate) struct InfoArgs {
/// The workbook
pub(crate) file: PathBuf,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ConvertArgs {
/// The workbook to read
pub(crate) input: PathBuf,
/// The file to write (.xlsx, .csv, .tsv, .json, .html or .pdf)
pub(crate) output: PathBuf,
/// The sheet to write, by name or index
#[arg(long, value_name = "NAME")]
pub(crate) sheet: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct EvalArgs {
/// The formula; a leading `=` is optional
#[arg(allow_hyphen_values = true, value_parser = formula)]
pub(crate) formula: String,
/// Evaluate against this workbook
#[arg(long = "in", value_name = "FILE")]
pub(crate) input: Option<PathBuf>,
/// The sheet to evaluate on, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// The cell the formula sits in
#[arg(long, value_name = "A1")]
pub(crate) cell: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CatArgs {
/// The workbook
pub(crate) file: PathBuf,
/// The range to print (default: the used range)
#[arg(long, value_name = "A1:D20")]
pub(crate) range: Option<String>,
/// The sheet to print, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// Show formulas instead of values
#[arg(long)]
pub(crate) formulas: bool,
/// Print CSV instead of an aligned table
#[arg(long)]
pub(crate) csv: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CheckArgs {
/// Files to check, or folders to scan for .xlsx and .xlsm files
#[arg(required = true, value_name = "FILE_OR_DIR")]
pub(crate) inputs: Vec<PathBuf>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
/// How far a cached number may differ from the recalculated one
#[arg(long, value_name = "T", allow_negative_numbers = true, value_parser = tolerance)]
pub(crate) tolerance: Option<f64>,
/// How many mismatches to list per file
#[arg(long = "max-report", value_name = "N")]
pub(crate) max_report: Option<usize>,
}
/// A formula may start with one dash (`-1+3`), but `--word` is a mistyped option, not a formula (`=--1` is one).
fn formula(text: &str) -> Result<String, UsageError> {
if text.starts_with("--") { Err(UsageError::Formula(text.to_owned())) } else { Ok(text.to_owned()) }
}
fn tolerance(text: &str) -> Result<f64, UsageError> {
text.parse().ok().filter(|t: &f64| t.is_finite() && *t >= 0.0).ok_or_else(|| UsageError::Tolerance(text.to_owned()))
}
/// The command or the script file of a `run` step.
#[derive(Clone, Debug)]
pub(crate) enum RunStep {
/// `--cmd`; a blank or comment line is `None`.
Cmd(Option<Step>),
/// `--script`
Script(PathBuf),
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// Start from this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Start from a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
/// Run one command, `ID={json}`; repeatable, in order with `--script`
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = command_step)]
cmds: Vec<Option<Step>>,
/// Run a script file of command lines (.jsonl); repeatable, in order with `--cmd`
#[arg(long = "script", value_name = "FILE")]
scripts: Vec<PathBuf>,
/// Save the workbook here when the steps are done (by extension)
#[arg(long, value_name = "FILE")]
pub(crate) out: Option<PathBuf>,
/// Print a range when the steps are done (`used` or empty: the used range); repeatable
#[arg(long, value_name = "RANGE")]
pub(crate) print: Vec<String>,
/// The sheet `--print` shows, by name or index
#[arg(long, value_name = "S", requires = "print")]
pub(crate) sheet: Option<String>,
/// `--print` shows formulas instead of values
#[arg(long, requires = "print")]
pub(crate) formulas: bool,
/// `--print` writes CSV instead of an aligned table
#[arg(long, requires = "print")]
pub(crate) csv: bool,
/// Don't print each command's result
#[arg(long)]
pub(crate) quiet: bool,
/// The steps in the order they were given.
#[arg(skip)]
pub(crate) steps: Vec<RunStep>,
}
/// The values of a repeatable option with the position each was given at.
fn at<T: Clone>(sub: &ArgMatches, id: &str, values: &[T]) -> Vec<(usize, T)> {
sub.indices_of(id).into_iter().flatten().zip(values.iter().cloned()).collect()
}
impl RunArgs {
fn check(&mut self, sub: &ArgMatches) {
let mut steps: Vec<(usize, RunStep)> = at(sub, "cmds", &self.cmds).into_iter().map(|(i, c)| (i, RunStep::Cmd(c))).collect();
steps.extend(at(sub, "scripts", &self.scripts).into_iter().map(|(i, p)| (i, RunStep::Script(p))));
steps.sort_by_key(|(i, _)| *i);
self.steps = steps.into_iter().map(|(_, s)| s).collect();
}
}
fn command_step(text: &str) -> Result<Option<Step>, UsageError> {
parse_command(text).map_err(UsageError::Cmd)
}
#[derive(Args, Debug)]
pub(crate) struct ListArgs {
/// Only those whose id, label or menu contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct FunctionsArgs {
/// Only those whose name or description contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// Only this category
#[arg(long, value_name = "C")]
pub(crate) category: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
/// Drive the running app (started with `gridcraft --control PORT`) instead of a headless workbook
#[arg(long, value_name = "PORT", conflicts_with_all = ["input", "sample"])]
pub(crate) connect: Option<String>,
/// Serve this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Serve a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct SendArgs {
/// The control port of the running app
pub(crate) port: String,
/// The control-channel method
pub(crate) method: String,
/// Its parameters, as JSON
#[arg(value_name = "JSON", value_parser = json_value)]
pub(crate) params: Option<Value>,
}
fn json_value(text: &str) -> Result<Value, UsageError> {
serde_json::from_str(text).map_err(|e| UsageError::Json(e.to_string()))
}
#[derive(Args, Debug)]
pub(crate) struct SandboxCheckArgs {
/// Let the program read this path; repeatable
#[arg(long, value_name = "PATH")]
pub(crate) read: Vec<PathBuf>,
/// Let the program execute this path; repeatable
#[arg(long = "exec", value_name = "PATH")]
pub(crate) exec: Vec<PathBuf>,
/// After `--`: the program to run confined, and its arguments
#[arg(last = true, value_name = "PROGRAM")]
pub(crate) program: Vec<OsString>,
}
/// A mistake in the command line that clap can't see by itself.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum UsageError {
#[error("--tolerance: expected a number ≥ 0, not `{0}`")]
Tolerance(String),
#[error("unexpected argument '{0}' found (start a formula that begins with `--` with `=`, as in `=--1`)")]
Formula(String),
#[error("--cmd: {0}")]
Cmd(ScriptError),
#[error("bad JSON params: {0}")]
Json(String),
}
/// The clap definition of the whole command line (completions and man pages are generated from it).
pub fn command() -> clap::Command {
Cli::command()
}
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("gridcraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
if let (Command::Run(run), Some(("run", sub))) = (&mut cli.command, matches.subcommand()) {
run.check(sub);
}
Ok(cli)
}
+29 -15
View File
@@ -15,6 +15,7 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::{Cursor, Read as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use gridcraft_engine::calc::{Calc, Key};
use gridcraft_engine::cmd::inspect::value_json;
@@ -23,10 +24,7 @@ use gridcraft_engine::formula::{Expr, quote_sheet};
use gridcraft_engine::model::{Cell, Sheet, Workbook};
use serde_json::{Value as Json, json};
use crate::args::CheckArgs;
use crate::commands::{number_text, pretty};
use crate::error::CliError;
use crate::{Io, outln};
use super::{Args, USAGE, number_text, pretty};
mod calc;
mod fidelity;
@@ -191,16 +189,32 @@ impl Diffs {
/// `check <file-or-dir>... [--json] [--tolerance X] [--max-report N]`. Exit 0 when every file opens,
/// every checked formula matches and every round trip is clean; 1 otherwise; 2 on a usage error.
pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
let usage = |e: String| {
eprintln!("gridcraft-cli: {e}\n{USAGE}");
ExitCode::from(2)
};
let a = match Args::parse(args, &["tolerance", "max-report"], &["json"]) {
Ok(a) => a,
Err(e) => return usage(e),
};
if a.positional.is_empty() {
return usage("missing <file-or-dir>".into());
}
let mut opts = Options::default();
if let Some(t) = a.tolerance {
opts.tolerance = t;
if let Some(t) = a.opt("tolerance") {
match t.parse::<f64>() {
Ok(t) if t.is_finite() && t >= 0.0 => opts.tolerance = t,
_ => return usage(format!("--tolerance needs a number ≥ 0, not `{t}`")),
}
}
if let Some(n) = a.max_report {
opts.max_report = n;
if let Some(n) = a.opt("max-report") {
match n.parse::<usize>() {
Ok(n) => opts.max_report = n,
Err(_) => return usage(format!("--max-report needs a whole number, not `{n}`")),
}
}
let inputs: Vec<String> = a.inputs.iter().map(|p| p.to_string_lossy().into_owned()).collect();
let Discovery { files, failures: mut reports, .. } = collect_inputs(&inputs);
let Discovery { files, failures: mut reports, .. } = collect_inputs(&a.positional);
reports.extend(files.iter().map(|p| {
let path = p.to_string_lossy().into_owned();
match gridcraft_engine::io::read_file(&path) {
@@ -208,12 +222,12 @@ pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
Err(e) => FileReport { path, error: Some(e.to_string()), ..Default::default() },
}
}));
if a.json {
outln!(io, "{}", pretty(&report_json(&reports, &opts)));
if a.has("json") {
outln!("{}", pretty(&report_json(&reports, &opts)));
} else {
print_human(io, &reports, &opts)?;
print_human(&reports, &opts);
}
Ok(if !files.is_empty() && reports.iter().all(FileReport::is_clean) { 0 } else { 1 })
if !files.is_empty() && reports.iter().all(FileReport::is_clean) { ExitCode::SUCCESS } else { ExitCode::FAILURE }
}
#[derive(Default)]
+1 -8
View File
@@ -65,13 +65,6 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect()
}
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
/// in another workbook, a data connection or the Data Model).
fn pivot_count(s: &Sheet) -> usize {
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
s.pivots.len() + kept
}
fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) {
if a != b {
d.push(|| format!("{sheet}: {a} → {b}"));
@@ -161,7 +154,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec<Categor
}
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+33 -92
View File
@@ -110,20 +110,12 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
/// same name, and looking up a CP437 name scans the whole archive.
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
}
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
}
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
let mut buf = Vec::new();
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
Ok(buf)
@@ -136,8 +128,8 @@ enum PartError {
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
// One byte past what is left shows that the part doesn't fit.
let limit = MAX_XML_PART.min(budget.saturating_add(1));
let mut buf = Vec::new();
@@ -158,10 +150,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Re
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
let names = zip_names(&mut zip);
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
let mut workbook = "xl/workbook.xml".to_string();
if let Some((i, rels)) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
if let Some(rels) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
&& let Ok(els) = xml_elements(&xml)
&& let Some(target) = els
.iter()
@@ -170,8 +162,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
{
workbook = resolve_target("", target);
}
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
let Some(name) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
xml_elements(&xml)
.ok()
.into_iter()
@@ -185,15 +177,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
let mut issues = Vec::new();
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
match ct_name {
None => issues.push("no [Content_Types].xml".to_string()),
Some((i, n)) => {
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
Some(n) => {
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
match el.as_str() {
"Default" => {
if let Some(x) = attr(&attrs, "Extension") {
@@ -210,9 +202,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
}
}
}
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
for (_, n) in &sorted {
let mut sorted: Vec<&String> = names.iter().collect();
sorted.sort();
for n in &sorted {
let key = part_key(n);
if key == "[content_types].xml" {
continue;
@@ -227,7 +219,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
for p in missing_overrides {
issues.push(format!("content type override for missing part /{p}"));
}
for (i, n) in sorted {
for n in sorted {
let key = part_key(n);
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
@@ -241,7 +233,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
issues.push(format!("{n} describes missing part {source}"));
}
let mut ids = HashSet::new();
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
if el != "Relationship" {
continue;
}
@@ -276,17 +268,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
// Several relationships name the same part; each fresh check decompressed it again, so
// repeated references to one highly compressible part multiplied the work. The verdict is
// remembered per (part, named content) and the decompression the package can cause is
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
// would otherwise each spend a full per-part allowance.
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut kinds = BTreeMap::new();
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
@@ -300,8 +292,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
}
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
if !external
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
{
continue;
}
@@ -322,7 +314,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
/// package's remaining checks may cause, and once it is spent the part counts as having content.
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
"comments" => Some(b"comment"),
"vmldrawing" => Some(b"shape"),
@@ -333,17 +325,17 @@ fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut H
Some(_) => "shape",
None => "any",
};
if let Some(v) = verdicts.get(&(index, marker)) {
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
return *v;
}
let v = holds_something_uncached(zip, index, marker, budget);
verdicts.insert((index, marker), v);
let v = holds_something_uncached(zip, name, marker, budget);
verdicts.insert((name.to_ascii_lowercase(), marker), v);
v
}
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
use quick_xml::events::Event;
let Ok(f) = zip.by_index(index) else { return true };
let Ok(f) = zip.by_name(name) else { return true };
if *budget == 0 {
return true;
}
@@ -400,57 +392,6 @@ mod tests {
z.finish().unwrap().into_inner()
}
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
z.write_all(first.as_bytes()).unwrap();
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
z.write_all(second.as_bytes()).unwrap();
let mut bytes = z.finish().unwrap().into_inner();
// The name sits in the local header and in the central directory; both get the CP437 byte.
let mut at = 0;
let mut patched = 0;
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
bytes[at + i + 9] = 0x82;
at += i + PLACEHOLDER.len();
patched += 1;
}
assert_eq!(patched, 2);
bytes
}
fn rels_xml(rels: &[(&str, &str)]) -> String {
let body: String = rels
.iter()
.map(|(id, kind)| {
format!(
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
)
})
.collect();
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
}
#[test]
fn parts_with_the_same_decoded_name_are_each_validated() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
let issues = validate_package(&bytes).unwrap();
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
assert_eq!(duplicates, 1, "{issues:?}");
}
#[test]
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
let kinds = relationship_kinds(&bytes).unwrap();
assert!(kinds.contains_key("custom"), "{kinds:?}");
assert!(kinds.contains_key("audio"), "{kinds:?}");
}
#[test]
fn relationship_parts_count_against_the_decompression_budget() {
// Each part fits the per-part allowance, but together they need more than the budget.
+31 -41
View File
@@ -131,16 +131,15 @@ fn fit(s: &str, w: usize) -> String {
if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::<String>()) }
}
fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_reports(reports: &[FileReport]) {
for r in reports {
outln!(io, "== {}", r.path);
outln!("== {}", r.path);
if let Some(e) = &r.error {
outln!(io, " can't open: {e}");
outln!(" can't open: {e}");
continue;
}
let c = &r.calc;
outln!(
io,
" formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile",
c.formula_cells,
c.checked,
@@ -150,15 +149,14 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
c.volatile
);
if c.stale_cache {
outln!(io, " (the producer asked for a full recalculation on load: its cached values aren't results)");
outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)");
}
if c.bool_as_number > 0 {
outln!(io, " ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
}
for m in &c.mismatches {
let tag = if m.primary { "mismatch" } else { " (downstream)" };
outln!(
io,
" {tag} {} {} expected {} got {} [{}]",
m.cell,
one_line(&m.formula),
@@ -168,33 +166,31 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
);
}
if c.mismatched > c.mismatches.len() {
outln!(io, " … {} more mismatches", c.mismatched - c.mismatches.len());
outln!(" … {} more mismatches", c.mismatched - c.mismatches.len());
}
let rt = &r.round_trip;
if let Some(e) = &rt.error {
outln!(io, " round trip: {e}");
outln!(" round trip: {e}");
}
let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect();
if differing.is_empty() && rt.error.is_none() {
outln!(io, " round trip: all equal");
outln!(" round trip: all equal");
}
for cat in differing {
outln!(io, " round trip {}: {} difference(s)", cat.name, cat.diffs);
outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs);
for e in &cat.examples {
outln!(io, " {}", one_line(e));
outln!(" {}", one_line(e));
}
if cat.diffs > cat.examples.len() {
outln!(io, " … {} more", cat.diffs - cat.examples.len());
outln!(" … {} more", cat.diffs - cat.examples.len());
}
}
}
Ok(())
}
fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_table(reports: &[FileReport]) {
let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50);
outln!(
io,
"{:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip",
"file",
"formulas",
@@ -207,7 +203,7 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
for r in reports {
let label = fit(&r.path, w);
if let Some(e) = &r.error {
outln!(io, "{label:<w$} can't open: {}", one_line(&fit(e, 100)));
outln!("{label:<w$} can't open: {}", one_line(&fit(e, 100)));
continue;
}
let c = &r.calc;
@@ -217,7 +213,6 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
(None, d) => d.join(","),
};
outln!(
io,
"{label:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}",
c.formula_cells,
c.checked,
@@ -227,36 +222,33 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
c.volatile
);
}
Ok(())
}
fn print_rankings(io: &mut Io, t: &Totals, opts: &Options) -> Result<(), CliError> {
fn print_rankings(t: &Totals, opts: &Options) {
let top = ranked(&t.functions);
if !top.is_empty() {
outln!(io, "");
outln!(io, "top mismatching functions (primary = no mismatching precedent):");
outln!(io, " {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
outln!("");
outln!("top mismatching functions (primary = no mismatching precedent):");
outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
for (n, s) in top.iter().take(opts.max_report.max(1)) {
outln!(io, " {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
}
}
let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect();
sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
if !sigs.is_empty() {
outln!(io, "");
outln!(io, "mismatch signatures (expected → GridCraft):");
outln!("");
outln!("mismatch signatures (expected → GridCraft):");
for (sig, n) in sigs.iter().take(opts.max_report.max(1)) {
outln!(io, " {n:>8} {sig}");
outln!(" {n:>8} {sig}");
}
}
Ok(())
}
fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
outln!(io, "");
outln!(io, "files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
fn print_totals(t: &Totals) {
outln!("");
outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
outln!(
io,
"formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)",
t.formula_cells,
t.checked,
@@ -266,25 +258,23 @@ fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
t.volatile
);
if t.bool_as_number > 0 {
outln!(io, "booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
}
let cats: Vec<String> = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect();
outln!(
io,
"round trip: {} of {} files differ{}{}",
t.round_trip_differing,
t.opened,
if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() },
if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) }
);
Ok(())
}
pub(super) fn print_human(io: &mut Io, reports: &[FileReport], opts: &Options) -> Result<(), CliError> {
print_file_reports(io, reports)?;
outln!(io, "");
print_file_table(io, reports)?;
pub(super) fn print_human(reports: &[FileReport], opts: &Options) {
print_file_reports(reports);
outln!("");
print_file_table(reports);
let t = totals(reports);
print_rankings(io, &t, opts)?;
print_totals(io, &t)
print_rankings(&t, opts);
print_totals(&t);
}
+1 -1
View File
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
let mut pending: Vec<(&str, &str)> = rels.to_vec();
for i in 0..src.len() {
let mut f = src.by_index(i).unwrap();
let name = f.name().unwrap().to_string();
let name = f.name().to_string();
let mut body = String::new();
f.read_to_string(&mut body).unwrap();
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
-438
View File
@@ -1,438 +0,0 @@
//! The subcommands: each takes its typed arguments and the streams, and returns what to exit with.
use gridcraft_engine::Session;
use serde_json::{Value, json};
use crate::args::{CatArgs, Command, ConvertArgs, EvalArgs, FunctionsArgs, InfoArgs, ListArgs, McpArgs, RunArgs, RunStep, SendArgs};
use crate::error::{CliError, unicode};
use crate::script::parse_command;
use crate::{Io, check, errln, outln, sandbox_check};
/// Run a parsed command line; gives the exit code (0, or 1 when `check` found a difference and said so itself).
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<i32, CliError> {
match command {
Command::Info(a) => info(&a, io),
Command::Convert(a) => convert(&a, io),
Command::Eval(a) => eval(&a, io),
Command::Cat(a) => cat(&a, io),
Command::Run(a) => run(&a, io),
Command::Commands(a) => commands(&a, io),
Command::Functions(a) => functions(&a, io),
Command::Mcp(a) => mcp(&a, io),
Command::Send(a) => send(&a, io),
Command::Check(a) => return check::run(&a, io),
Command::SandboxCheck(a) => return sandbox_check::run(&a, io),
}
.map(|()| 0)
}
// ---------------------------------------------------------------- helpers
fn exec(io: &mut Io, s: &mut Session, id: &str, params: Value) -> Result<Value, CliError> {
let r = s.execute_headless(id, params).map_err(CliError::engine);
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
errln!(io, "Warning: {warning}");
}
}
r
}
fn open(io: &mut Io, path: &std::path::Path) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.open", json!({"path": unicode(path)?}))?;
Ok(s)
}
fn sample(io: &mut Io, name: &str) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.new", json!({"sample": name}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(io: &mut Io, s: &mut Session, sheet: Option<&str>) -> Result<(), CliError> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(io, s, "sheet.activate", p)?;
}
Ok(())
}
pub(crate) fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
pub(crate) fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(a: &InfoArgs, io: &mut Io) -> Result<(), CliError> {
let path = unicode(&a.file)?;
let mut s = open(io, &a.file)?;
let v = exec(io, &mut s, "document.inspect", json!({}))?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
outln!(io, "{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
io,
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(
io,
" table {} {} ({})",
t["name"].as_str().unwrap_or("?"),
t["range"].as_str().unwrap_or("?"),
t["style"].as_str().unwrap_or("")
);
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(io, " chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(io, " filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!(io, "names:");
for n in names {
outln!(io, " {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(a: &ConvertArgs, io: &mut Io) -> Result<(), CliError> {
let out = unicode(&a.output)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(CliError::OutputFormat { out: out.to_owned() });
}
let mut s = open(io, &a.input)?;
activate_sheet(io, &mut s, a.sheet.as_deref())?;
if pdf {
let result = exec(io, &mut s, "file.exportPdf", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
let d = s.doc().map_err(CliError::engine)?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(CliError::engine)?;
gridcraft_engine::io::write_file(out, &bytes).map_err(CliError::engine)?;
errln!(io, "wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(a: &EvalArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match &a.input {
Some(p) => open(io, p)?,
None => blank(),
};
activate_sheet(io, &mut s, a.sheet.as_deref())?;
let formula = if a.formula.starts_with('=') { a.formula.clone() } else { format!("={}", a.formula) };
let mut p = json!({"formula": formula});
if let Some(c) = &a.cell {
p["cell"] = json!(c);
}
let v = exec(io, &mut s, "formulas.evaluate", p)?;
if a.json {
outln!(io, "{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!(io, "{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(io: &mut Io, s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), CliError> {
activate_sheet(io, s, sheet)?;
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(io, s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(io, s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!(io, "{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!(io, "{}", line.trim_end());
}
Ok(())
}
fn cat(a: &CatArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = open(io, &a.file)?;
print_range(io, &mut s, a.range.as_deref(), a.sheet.as_deref(), a.formulas, a.csv)
}
fn run(a: &RunArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
let mut step = 0usize;
for item in &a.steps {
let cmds: Vec<(String, Value, String)> = match item {
RunStep::Cmd(c) => c.iter().map(|(id, p)| (id.clone(), p.clone(), "--cmd".to_string())).collect(),
RunStep::Script(path) => {
let value = path.display().to_string();
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
let origin = format!("{value}:{}", i + 1);
if let Some((id, p)) = parse_command(line).map_err(|source| CliError::Script { origin: origin.clone(), source })? {
v.push((id, p, origin));
}
}
v
}
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(io, &mut s, &id, p).map_err(|e| CliError::Step { step, origin, id: id.clone(), message: e.to_string() })?;
if !a.quiet && !r.is_null() {
outln!(io, "{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = &a.out {
let out = unicode(out)?;
let r = exec(io, &mut s, "file.save", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes)", r["bytes"]);
}
for range in &a.print {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(io, &mut s, range, a.sheet.as_deref(), a.formulas, a.csv)?;
}
Ok(())
}
fn commands(a: &ListArgs, io: &mut Io) -> Result<(), CliError> {
let q = a.search.as_ref().or(a.word.as_ref()).map(|q| q.to_ascii_lowercase());
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.json {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!(io, "{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!(io, "{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!(io, "{:<w$} {}", "", c.params);
}
errln!(io, "{} commands", list.len());
Ok(())
}
fn functions(a: &FunctionsArgs, io: &mut Io) -> Result<(), CliError> {
let mut p = json!({});
if let Some(q) = a.search.as_ref().or(a.word.as_ref()) {
p["search"] = json!(q);
}
if let Some(c) = &a.category {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(io, &mut s, "formulas.functions", p)?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!(io, "{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(io, " {cat}: {desc}");
}
errln!(io, "{} functions", list.len());
Ok(())
}
fn connect(port: &str) -> Result<gridcraft_mcp::Remote, CliError> {
use gridcraft_mcp::control_addr;
let addr = control_addr(port);
gridcraft_mcp::Remote::connect(&addr).map_err(|e| CliError::Connect { addr, port: port.to_owned(), message: e.to_string() })
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app started with
/// `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(a: &McpArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::{Backend, Headless, Server};
let backend: Box<dyn Backend> = match &a.connect {
Some(c) => Box::new(connect(c)?),
None => {
let session = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
errln!(io, "gridcraft-cli: MCP server on stdio ({})", backend.describe());
// The server speaks on the process's own stdin and stdout: that is the protocol, not this program's output.
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(CliError::engine)
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(a: &SendArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::Backend;
let params = a.params.clone().unwrap_or_else(|| json!({}));
let mut r = connect(&a.port)?;
let v = r.call(&a.method, params).map_err(CliError::engine)?;
outln!(io, "{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = crate::run(["convert", input.to_str().unwrap(), output.to_str().unwrap()], &mut out, &mut err);
assert_eq!(code, 0, "{}", String::from_utf8_lossy(&err));
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
-39
View File
@@ -1,39 +0,0 @@
use std::path::{Path, PathBuf};
/// Why a command failed: printed as `error: {e}`, exit 1. The engine, the MCP backends and the sandbox report their
/// failures as text; [`CliError::Engine`] carries it.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError {
/// What the engine, a backend or a library reported.
#[error("{0}")]
Engine(String),
/// The engine's commands take paths as JSON, which holds only text.
#[error("{}: the path is not valid Unicode", .0.display())]
NotUnicode(PathBuf),
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: std::io::Error },
#[error("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)")]
OutputFormat { out: String },
#[error("cannot connect to the GridCraft app at {addr}: {message} (start it with `gridcraft --control {port}`)")]
Connect { addr: String, port: String, message: String },
#[error("step {step} ({origin}, {id}): {message}")]
Step { step: usize, origin: String, id: String, message: String },
#[error("{origin}: {source}")]
Script { origin: String, source: crate::script::ScriptError },
#[error("sandbox-check: {0}")]
Sandbox(String),
/// Standard output went away.
#[error("can't write to stdout: {0}")]
Stdout(std::io::Error),
}
impl CliError {
pub(crate) fn engine(e: impl ToString) -> Self {
Self::Engine(e.to_string())
}
}
/// A path as the text the engine's commands take.
pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> {
path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned()))
}
-120
View File
@@ -1,120 +0,0 @@
//! Headless GridCraft (`gridcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
//! through the binary; `gridcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod args;
mod check;
mod commands;
mod error;
mod sandbox_check;
mod script;
use std::ffi::OsString;
use std::io::Write;
use error::CliError;
pub use args::command;
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
pub(crate) struct Io<'a> {
pub(crate) out: &'a mut dyn Write,
pub(crate) err: &'a mut dyn Write,
}
/// Writes a line of results; fails with [`CliError::Stdout`], which `run` turns into a quiet end for a closed pipe
/// (`gridcraft-cli commands | head`) and a message for any other error.
macro_rules! outln {
($io:expr, $($arg:tt)*) => {
writeln!($io.out, $($arg)*).map_err($crate::error::CliError::Stdout)?
};
}
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
macro_rules! errln {
($io:expr, $($arg:tt)*) => {
drop(writeln!($io.err, $($arg)*))
};
}
pub(crate) use {errln, outln};
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the tokens a shell would see
/// before `--` count: after it they are file names.
fn launch_profile_argument(args: &[OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
/// to `out`, exit 0.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// A confined launcher run (and its probes) comes first, before anything else starts.
if let Some(code) = gridcraft_sandbox::handle_args(&args) {
return code;
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a CLI option, and a CLI
// that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&args) {
let _ = writeln!(err, "error: {flag} belongs to the GridCraft desktop app, not this CLI");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match args::parse(&args) {
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
let _ = write!(to, "{}", e.render());
return e.exit_code();
}
};
let mut io = Io { out, err };
match commands::dispatch(cli.command, &mut io) {
Ok(code) => code,
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
Err(CliError::Stdout(e)) if e.kind() == std::io::ErrorKind::BrokenPipe => 0,
Err(e) => {
errln!(io, "error: {e}");
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 rather than acting on
/// whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
}
+663 -4
View File
@@ -1,9 +1,668 @@
//! `gridcraft-cli`: headless GridCraft. Thin wiring over [`gridcraft_cli::run`].
//! Headless GridCraft.
//!
//! ```text
//! gridcraft-cli info <file> [--json]
//! gridcraft-cli convert <in> <out> [--sheet NAME]
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
//! gridcraft-cli version | --version
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use std::process::ExitCode;
/// `println!` that ends the program quietly when stdout is closed (`gridcraft-cli commands |
/// head`) instead of panicking on a broken pipe.
macro_rules! outln {
($($arg:tt)*) => {{
use std::io::Write as _;
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
$crate::stdout_failed(e);
}
}};
}
mod check;
mod sandbox_check;
use gridcraft_engine::Session;
use serde_json::{Value, json};
const USAGE: &str = "usage:
gridcraft-cli info <file> [--json] sheets, used ranges, tables, charts, names
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html/pdf by extension
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
[--out FILE] [--print RANGE] [--quiet]
a script line is id={json} or {\"command\": \"id\", \"params\": {…}};
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli send <port> <method> [json]
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
whether this system confines programs (no program: a confined self-test)
gridcraft-cli version";
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly; any
/// other write error is reported.
fn stdout_failed(e: std::io::Error) -> ! {
if e.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("gridcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
}
fn main() -> ExitCode {
let (mut out, mut err) = (std::io::stdout().lock(), std::io::stderr().lock());
// An exit code is 0 to 2 here; 128 + signal is the shell's, for a process a signal ended.
ExitCode::from(u8::try_from(gridcraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err)).unwrap_or(1))
// A confined launcher run (and its probes) comes first, before anything else starts.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
return ExitCode::from(u8::try_from(code).unwrap_or(1));
}
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let r = match args.first().map(String::as_str) {
Some("--version" | "-V" | "version") => {
outln!("gridcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--help" | "-h" | "help") => {
outln!("{USAGE}");
Ok(())
}
Some("info") => info(rest),
Some("convert") => convert(rest),
Some("eval") => eval(rest),
Some("cat") => cat(rest),
Some("run") => run(rest),
Some("check") => return check::main(rest),
Some("sandbox-check") => return sandbox_check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("mcp") => mcp(rest),
Some("send") => send(rest),
Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")),
None => Err(USAGE.to_string()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("gridcraft-cli: {e}");
ExitCode::FAILURE
}
}
}
// ---------------------------------------------------------------- argument parsing
/// Parsed arguments: positionals, `--flag value` options and boolean `--switch`es.
struct Args {
positional: Vec<String>,
opts: Vec<(String, String)>,
switches: Vec<String>,
}
impl Args {
/// `with_value` lists the options that take a value; `switches` the boolean ones. Anything
/// else starting with `--` is an error.
fn parse(args: &[String], with_value: &[&str], switches: &[&str]) -> Result<Args, String> {
let mut out = Args { positional: vec![], opts: vec![], switches: vec![] };
let mut it = args.iter();
while let Some(a) = it.next() {
if let Some(name) = a.strip_prefix("--").filter(|n| !n.is_empty()) {
let (name, inline) = match name.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (name, None),
};
if with_value.contains(&name) {
let v = match inline {
Some(v) => v,
None => it.next().cloned().ok_or_else(|| format!("--{name} needs a value"))?,
};
out.opts.push((name.to_string(), v));
} else if switches.contains(&name) && inline.is_none() {
out.switches.push(name.to_string());
} else {
return Err(format!("unknown option --{name}"));
}
} else {
out.positional.push(a.clone());
}
}
Ok(out)
}
fn opt(&self, name: &str) -> Option<&str> {
self.opts.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
}
fn has(&self, name: &str) -> bool {
self.switches.iter().any(|s| s == name)
}
fn pos(&self, i: usize, what: &str) -> Result<&str, String> {
self.positional.get(i).map(String::as_str).ok_or_else(|| format!("missing {what}\n{USAGE}"))
}
fn no_extra(&self, n: usize) -> Result<(), String> {
match self.positional.get(n) {
Some(x) => Err(format!("unexpected argument `{x}`")),
None => Ok(()),
}
}
}
// ---------------------------------------------------------------- helpers
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
eprintln!("Warning: {warning}");
}
}
r
}
fn open(path: &str) -> Result<Session, String> {
let mut s = Session::new();
exec(&mut s, "file.open", json!({"path": path}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(s: &mut Session, sheet: Option<&str>) -> Result<(), String> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(s, "sheet.activate", p)?;
}
Ok(())
}
fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &[], &["json"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
let v = exec(&mut s, "document.inspect", json!({}))?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
outln!("{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(" table {} {} ({})", t["name"].as_str().unwrap_or("?"), t["range"].as_str().unwrap_or("?"), t["style"].as_str().unwrap_or(""));
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(" chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(" filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!("names:");
for n in names {
outln!(" {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["sheet"], &[])?;
let input = a.pos(0, "<in>")?;
let out = a.pos(1, "<out>")?;
a.no_extra(2)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(format!("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)"));
}
let mut s = open(input)?;
activate_sheet(&mut s, a.opt("sheet"))?;
if pdf {
let result = exec(&mut s, "file.exportPdf", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
let d = s.doc().map_err(|e| e.to_string())?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sheet", "cell"], &["json"])?;
let formula = a.pos(0, "<formula>")?;
a.no_extra(1)?;
let mut s = match a.opt("in") {
Some(p) => open(p)?,
None => blank(),
};
activate_sheet(&mut s, a.opt("sheet"))?;
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
let mut p = json!({"formula": formula});
if let Some(c) = a.opt("cell") {
p["cell"] = json!(c);
}
let v = exec(&mut s, "formulas.evaluate", p)?;
if a.has("json") {
outln!("{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!("{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), String> {
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!("{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!("{}", line.trim_end());
}
Ok(())
}
fn cat(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["range", "sheet"], &["formulas", "csv"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
print_range(&mut s, a.opt("range"), a.opt("sheet"), a.has("formulas"), a.has("csv"))
}
/// One command from `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
fn parse_command(text: &str) -> Result<Option<(String, Value)>, String> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| format!("bad JSON: {e}"))?;
// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the
// script still exited 0, so a typo made a valid, wrong workbook (#2256).
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let (plural, list) = (if unknown.len() == 1 { "key" } else { "keys" }, unknown.join("`, `"));
return Err(format!("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}"));
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or("JSON command needs a `command` field")?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| format!("{id}: bad JSON params: {e}"))? };
Ok(Some((id.to_string(), params)))
}
fn run(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sample", "cmd", "script", "out", "print", "sheet"], &["quiet", "csv", "formulas"])?;
a.no_extra(0)?;
let mut s = match (a.opt("in"), a.opt("sample")) {
(Some(_), Some(_)) => return Err("give --in or --sample, not both".into()),
(Some(p), None) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
let quiet = a.has("quiet");
let mut step = 0usize;
for (name, value) in &a.opts {
let cmds: Vec<(String, Value, String)> = match name.as_str() {
"cmd" => parse_command(value)?.map(|(id, p)| vec![(id, p, "--cmd".to_string())]).unwrap_or_default(),
"script" => {
let text = std::fs::read_to_string(value).map_err(|e| format!("{value}: {e}"))?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
if let Some((id, p)) = parse_command(line).map_err(|e| format!("{value}:{}: {e}", i + 1))? {
v.push((id, p, format!("{value}:{}", i + 1)));
}
}
v
}
_ => continue,
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(&mut s, &id, p).map_err(|e| format!("step {step} ({origin}, {id}): {e}"))?;
if !quiet && !r.is_null() {
outln!("{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = a.opt("out") {
let r = exec(&mut s, "file.save", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes)", r["bytes"]);
}
for (name, range) in &a.opts {
if name == "print" {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(&mut s, range, a.opt("sheet"), a.has("formulas"), a.has("csv"))?;
}
}
Ok(())
}
fn commands(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search"], &["json"])?;
let q = a.opt("search").or(a.positional.first().map(String::as_str)).map(str::to_ascii_lowercase);
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.has("json") {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!("{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!("{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!("{:<w$} {}", "", c.params);
}
eprintln!("{} commands", list.len());
Ok(())
}
fn functions(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search", "category"], &["json"])?;
let mut p = json!({});
if let Some(q) = a.opt("search").or(a.positional.first().map(String::as_str)) {
p["search"] = json!(q);
}
if let Some(c) = a.opt("category") {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(&mut s, "formulas.functions", p)?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!("{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(" {cat}: {desc}");
}
eprintln!("{} functions", list.len());
Ok(())
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
a.no_extra(0)?;
let backend: Box<dyn Backend> = match a.opt("connect") {
Some(c) => {
let addr = control_addr(c);
Box::new(
Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
)
}
None => {
let session = match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Remote, control_addr};
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
let params: Value = match args.get(2) {
Some(t) => serde_json::from_str(t).map_err(|e| format!("bad JSON params: {e}"))?,
None => json!({}),
};
if let Some(x) = args.get(3) {
return Err(format!("unexpected argument `{x}`"));
}
let addr = control_addr(port);
let mut r = Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
let v = r.call(method, params)?;
outln!("{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused");
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused");
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn args_parsing() {
let v: Vec<String> = ["a", "--range", "A1", "--csv", "--sheet=S"].iter().map(|s| s.to_string()).collect();
let a = Args::parse(&v, &["range", "sheet"], &["csv"]).unwrap();
assert_eq!(a.positional, ["a"]);
assert_eq!(a.opt("range"), Some("A1"));
assert_eq!(a.opt("sheet"), Some("S"));
assert!(a.has("csv"));
assert!(Args::parse(&["--nope".to_string()], &[], &[]).is_err());
assert!(Args::parse(&["--range".to_string()], &["range"], &[]).is_err());
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
convert(&[input.to_string_lossy().into_owned(), output.to_string_lossy().into_owned()]).unwrap();
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
+46 -42
View File
@@ -12,41 +12,54 @@
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
use crate::args::SandboxCheckArgs;
use crate::error::CliError;
use crate::{Io, errln, outln};
use gridcraft_sandbox::{Canary, Policy, REFUSED_EXIT_CODE, REPORT_FLAG, Support};
pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("gridcraft-cli: sandbox-check: {e}");
ExitCode::FAILURE
}
}
}
fn run(args: &[String]) -> Result<ExitCode, String> {
let mut policy = Policy::new().with_system_libraries();
for path in &a.read {
policy = policy.read(path);
let mut it = args.iter();
let mut program: Option<(PathBuf, Vec<OsString>)> = None;
while let Some(a) = it.next() {
match a.as_str() {
"--read" => policy = policy.read(it.next().ok_or("--read needs a path")?),
"--exec" => policy = policy.exec(it.next().ok_or("--exec needs a path")?),
"--" => {
let p = it.next().ok_or("a program follows `--`")?;
program = Some((PathBuf::from(p), it.by_ref().map(OsString::from).collect()));
}
other => return Err(format!("unknown option `{other}`")),
}
}
for path in &a.exec {
policy = policy.exec(path);
}
let program: Option<(PathBuf, Vec<OsString>)> = a.program.split_first().map(|(p, rest)| (PathBuf::from(p), rest.to_vec()));
// With a program, its standard output is passed through untouched, so this command's own
// lines go to standard error; the self-test's report is the output, on standard output.
let report = program.is_none();
let say = |io: &mut Io, line: String| -> Result<(), CliError> {
let say = |line: String| {
if report {
outln!(io, "{line}");
outln!("{line}");
} else {
errln!(io, "{line}");
eprintln!("{line}");
}
Ok(())
};
match gridcraft_sandbox::support() {
Support::Available(how) => say(io, format!("sandbox: available ({how})"))?,
Support::Available(how) => say(format!("sandbox: available ({how})")),
Support::Unsupported(why) => {
say(io, format!("sandbox: unsupported ({why})"))?;
return Ok(2);
say(format!("sandbox: unsupported ({why})"));
return Ok(ExitCode::from(2));
}
}
let canary = Canary::create().map_err(|e| CliError::Sandbox(e.to_string()))?;
let exe = std::env::current_exe().map_err(|e| CliError::Sandbox(e.to_string()))?;
let canary = Canary::create().map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let (program, program_args) = match program {
Some((p, a)) => (p, a),
// A confined copy of this program, reporting each attempt; it reads its own executable as
@@ -57,38 +70,29 @@ pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
}
};
let policy = policy.exec(program.clone());
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| CliError::Sandbox(e.to_string()))?;
let status = cmd.status().map_err(|e| CliError::Sandbox(format!("couldn't start the launcher: {e}")))?;
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| e.to_string())?;
let status = cmd.status().map_err(|e| format!("couldn't start the launcher: {e}"))?;
drop(canary);
match status.code() {
Some(0) => {
say(
io,
if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into(),
)?;
Ok(0)
say(if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into());
Ok(ExitCode::SUCCESS)
}
Some(REFUSED_EXIT_CODE) => {
// The launcher's refusal and a program's own exit share the code; the launcher's reason,
// when it refused, is the `gridcraft-sandbox: refused:` line above.
say(
io,
format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
),
)?;
Ok(1)
say(format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
));
Ok(ExitCode::FAILURE)
}
other => {
say(
io,
format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
),
)?;
Ok(1)
say(format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
));
Ok(ExitCode::FAILURE)
}
}
}
-92
View File
@@ -1,92 +0,0 @@
//! One command of a script: `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
use serde_json::{Value, json};
/// A command line that cannot be read.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum ScriptError {
#[error("bad JSON: {0}")]
BadJson(String),
/// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
/// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the script still exited 0, so a
/// typo made a valid, wrong workbook (#2256).
#[error("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}")]
UnknownKeys { plural: &'static str, list: String },
#[error("JSON command needs a `command` field")]
NoCommand,
#[error("{id}: bad JSON params: {why}")]
BadParams { id: String, why: String },
}
/// A command and its parameters.
pub(crate) type Step = (String, Value);
/// The command in `text`, or `None` for a blank line, a `#` comment or a `//` comment.
pub(crate) fn parse_command(text: &str) -> Result<Option<Step>, ScriptError> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| ScriptError::BadJson(e.to_string()))?;
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let plural = if unknown.len() == 1 { "key" } else { "keys" };
return Err(ScriptError::UnknownKeys { plural, list: unknown.join("`, `") });
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or(ScriptError::NoCommand)?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() {
json!({})
} else {
serde_json::from_str(rest).map_err(|e| ScriptError::BadParams { id: id.to_string(), why: e.to_string() })?
};
Ok(Some((id.to_string(), params)))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused").to_string();
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused").to_string();
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
}
-142
View File
@@ -1,142 +0,0 @@
//! What the command line does with its arguments: RFC-0018's contract, through the binary. A usage error exits 2 on
//! stderr; help and the version go to stdout with exit 0; an unknown or repeated flag after a subcommand is refused.
use std::process::Command;
struct Ran {
code: Option<i32>,
out: String,
err: String,
}
fn run(args: &[&str]) -> Ran {
let o = Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).output().unwrap();
Ran { code: o.status.code(), out: String::from_utf8_lossy(&o.stdout).into_owned(), err: String::from_utf8_lossy(&o.stderr).into_owned() }
}
const SUBCOMMANDS: [&str; 11] = ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"];
/// A usage error: exit 2, nothing on stdout, `error:` and the offending argument on stderr.
fn usage_error(args: &[&str], names: &str) {
let r = run(args);
assert_eq!(r.code, Some(2), "{args:?}: {:?} / {:?}", r.out, r.err);
assert_eq!(r.out, "", "{args:?}");
assert!(r.err.starts_with("error:") && r.err.contains(names), "{args:?}: {:?}", r.err);
}
#[test]
fn every_subcommand_answers_help_and_version_on_stdout() {
for sub in SUBCOMMANDS {
for flag in ["--help", "-h"] {
let r = run(&[sub, flag]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} {flag}");
assert!(r.out.contains(&format!("Usage: gridcraft-cli {sub}")), "{sub} {flag}: {:?}", r.out);
assert!(r.out.contains("Exit status:"), "{sub} {flag}: {:?}", r.out);
}
let r = run(&[sub, "--version"]);
assert!(r.out.starts_with(&format!("gridcraft-cli-{sub} ")), "{sub}: {:?}", r.out);
}
let r = run(&["help", "run"]);
assert_eq!(r.code, Some(0));
}
#[test]
fn an_unknown_option_is_refused_by_name_in_every_subcommand() {
for sub in ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"] {
usage_error(&[sub, "--no-such-option"], "--no-such-option");
}
// An option of another subcommand is not this one's.
usage_error(&["commands", "--sample", "x"], "--sample");
usage_error(&["info", "a.xlsx", "--csv"], "--csv");
usage_error(&["cat", "a.xlsx", "--json"], "--json");
}
#[test]
fn a_missing_or_extra_argument_is_a_usage_error() {
usage_error(&["info"], "FILE");
usage_error(&["info", "a", "b"], "b");
usage_error(&["convert", "a.xlsx"], "OUTPUT");
usage_error(&["eval"], "FORMULA");
usage_error(&["check"], "FILE_OR_DIR");
usage_error(&["send", "7979"], "METHOD");
usage_error(&["run", "--in"], "--in");
usage_error(&["run", "--cmd"], "--cmd");
usage_error(&["commands", "a", "b"], "b");
}
#[test]
fn a_repeated_single_value_flag_is_refused() {
usage_error(&["convert", "a.xlsx", "b.csv", "--sheet", "1", "--sheet", "2"], "--sheet");
usage_error(&["run", "--in", "a.xlsx", "--in", "b.xlsx"], "--in");
usage_error(&["run", "--out", "a.xlsx", "--out", "b.xlsx"], "--out");
usage_error(&["check", "x.xlsx", "--tolerance", "1", "--tolerance", "2"], "--tolerance");
}
#[test]
fn conflicting_flags_are_refused_before_anything_starts() {
usage_error(&["run", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["mcp", "--connect", "7979", "--in", "a.xlsx"], "--connect");
usage_error(&["mcp", "--connect", "7979", "--sample", "sales"], "--connect");
usage_error(&["mcp", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["commands", "x", "--search", "y"], "--search");
// `--print` carries the options that shape it.
usage_error(&["run", "--csv"], "--print");
usage_error(&["run", "--sheet", "1"], "--print");
}
#[test]
fn a_value_that_cannot_mean_anything_is_a_usage_error() {
usage_error(&["check", "x.xlsx", "--tolerance", "-1"], "--tolerance");
usage_error(&["check", "x.xlsx", "--tolerance", "nan"], "--tolerance");
usage_error(&["check", "x.xlsx", "--max-report", "many"], "--max-report");
usage_error(&["run", "--cmd", "x={bad"], "--cmd");
usage_error(&["send", "7979", "m", "{bad"], "JSON");
}
/// `eval` takes its formula as the first thing, even one that starts with a dash; `--` ends the options.
#[test]
fn a_formula_may_start_with_a_dash() {
let r = run(&["eval", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2"), "{:?}", r.err);
let r = run(&["eval", "--json", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2.0"), "{:?}", r.err);
// A mistyped option is not a formula; `=` makes it one.
usage_error(&["eval", "--no-such-option"], "--no-such-option");
assert_eq!(run(&["eval", "=--1"]).code, Some(0));
}
/// A word after the options (or after `--`) is a filter; `--search` is the same filter as an option.
#[test]
fn commands_and_functions_filter_by_a_word_or_search() {
let a = run(&["commands", "--json", "home.bold"]);
let b = run(&["commands", "--json", "--search", "home.bold"]);
assert_eq!((a.code, b.code), (Some(0), Some(0)));
assert_eq!(a.out, b.out);
assert!(a.out.contains("home.bold"));
let r = run(&["functions", "--json", "--category", "Math and trigonometry", "SUM"]);
assert_eq!(r.code, Some(0), "{}", r.err);
}
/// A failed command is exit 1 with `error:`; connection failures are command failures, not usage errors.
#[test]
fn a_failed_command_exits_1_with_an_error_line() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port().to_string();
drop(listener);
for args in [&["send", &port, "x"][..], &["mcp", "--connect", &port], &["info", "/no/such/file.xlsx"], &["convert", "/no/such.xlsx", "o.csv"]] {
let r = run(args);
assert_eq!(r.code, Some(1), "{args:?}: {:?}", r.err);
assert_eq!(r.out, "");
assert!(r.err.starts_with("error:"), "{args:?}: {:?}", r.err);
}
}
/// The nightly profile protocol belongs to the desktop app: exit 2 before any subcommand parses it.
#[test]
fn the_launcher_profile_arguments_are_refused() {
for args in [&["--launch-profile", "nightly-v1", "info", "a.xlsx"][..], &["info", "--profile-root=/tmp/x", "a.xlsx"]] {
let r = run(args);
assert_eq!((r.code, r.out.as_str()), (Some(2), ""), "{args:?}");
assert!(r.err.contains("desktop app"), "{:?}", r.err);
}
}
+6 -12
View File
@@ -25,18 +25,12 @@ fn tmpdir(name: &str) -> PathBuf {
#[test]
fn version_and_usage() {
assert_eq!(ok(&["--version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
assert_eq!(ok(&["-V"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
// `--version` reaches the subcommands, and there is no `version` subcommand.
assert!(ok(&["run", "--version"]).starts_with("gridcraft-cli-run "));
for unknown in ["frobnicate", "version"] {
let o = run(&[unknown]);
assert_eq!(o.status.code(), Some(2), "{unknown}");
assert!(String::from_utf8_lossy(&o.stderr).contains("unrecognized subcommand"));
}
// No arguments: the usage on stderr, a usage error.
assert_eq!(ok(&["version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
let o = run(&["frobnicate"]);
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown subcommand"));
let o = run(&[]);
assert_eq!(o.status.code(), Some(2));
assert!(o.stdout.is_empty() && String::from_utf8_lossy(&o.stderr).contains("Usage: gridcraft-cli"));
assert!(!o.status.success());
}
#[test]
@@ -281,7 +275,7 @@ fn a_script_line_with_an_unknown_key_stops_the_run() {
assert!(!info.contains("Sheet2"), "and no sheet was added with a default name: {info}");
// The usage text says what a line looks like, which is how this was found.
let usage = ok(&["run", "--help"]);
let usage = String::from_utf8_lossy(&run(&[]).stderr).into_owned() + &String::from_utf8_lossy(&run(&["--help"]).stdout);
assert!(usage.contains(r#"{"command": "id", "params": {…}}"#), "{usage}");
let _ = std::fs::remove_dir_all(&dir);
-143
View File
@@ -1,143 +0,0 @@
//! `gridcraft_cli::run` called in-process: the same program the binary is, with its streams captured, so the whole of
//! RFC-0018's surface is covered without a subprocess per case.
fn run(args: &[&str]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = gridcraft_cli::run(args.iter().copied(), &mut out, &mut err);
(code, String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap())
}
struct Dir(std::path::PathBuf);
impl Dir {
fn new(name: &str) -> Dir {
let dir = std::env::temp_dir().join(format!("gc-inproc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Dir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_owned()
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn help_and_version_exit_0_on_stdout_and_usage_errors_exit_2_on_stderr() {
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"], &["run", "-V"], &["check", "--help"]] {
let (code, out, err) = run(args);
assert_eq!((code, err.as_str()), (0, ""), "{args:?}");
assert!(!out.is_empty(), "{args:?}");
}
for args in [&[][..], &["bogus"], &["info"], &["run", "--nope"], &["info", "--bogus"]] {
let (code, out, err) = run(args);
assert_eq!((code, out.as_str()), (2, ""), "{args:?}");
assert!(err.contains("Usage: gridcraft-cli"), "{args:?}: {err}");
}
}
#[test]
fn eval_info_cat_and_commands_write_results_to_stdout_and_progress_to_stderr() {
let dir = Dir::new("flow");
let book = dir.file("b.xlsx");
let (code, out, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("cell.set") && err.contains("wrote"), "{out} / {err}");
let (code, out, _) = run(&["eval", "=SUM(1,2,3)"]);
assert_eq!((code, out.trim()), (0, "6"));
let (code, out, err) = run(&["info", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("Sheet1"), "{out}");
let (code, out, _) = run(&["info", "--json", &book]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, out, _) = run(&["cat", &book, "--csv"]);
assert_eq!((code, out.trim()), (0, "2"));
let (code, out, _) = run(&["cat", &book, "--formulas"]);
assert_eq!((code, out.trim()), (0, "=1+1"));
let csv = dir.file("b.csv");
let (code, _, err) = run(&["convert", &book, &csv]);
assert_eq!(code, 0, "{err}");
assert_eq!(std::fs::read_to_string(&csv).unwrap().trim(), "2");
let (code, _, err) = run(&["convert", &book, &dir.file("b.nope")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:") && err.contains("unknown output format"), "{err}");
}
#[test]
fn run_keeps_cmd_and_script_in_the_order_given() {
let dir = Dir::new("order");
let script = dir.file("s.jsonl");
std::fs::write(&script, "cell.set={\"cell\":\"A1\",\"input\":\"2\"}\n").unwrap();
// The script writes A1 = 2 after the first --cmd wrote 1 and before the last wrote 3: the last one wins.
let (code, out, err) = run(&[
"run",
"--quiet",
"--cmd",
r#"cell.set={"cell":"A1","input":"1"}"#,
"--script",
&script,
"--cmd",
r#"cell.set={"cell":"B1","input":"=A1*10"}"#,
"--print",
"A1:B1",
"--csv",
]);
assert_eq!(code, 0, "{err}");
assert_eq!(out.trim(), "2,20", "{out}");
let (code, _, err) = run(&["run", "--script", &dir.file("missing.jsonl")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:"), "{err}");
let (code, _, err) = run(&["run", "--cmd", "no.such.command"]);
assert_eq!(code, 1);
assert!(err.contains("step 1 (--cmd, no.such.command)"), "{err}");
}
#[test]
fn check_reports_and_exits_with_the_verdict() {
let dir = Dir::new("check");
let book = dir.file("b.xlsx");
assert_eq!(run(&["run", "--quiet", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]).0, 0);
let (code, out, _) = run(&["check", &book]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("files: 1"), "{out}");
let (code, out, _) = run(&["check", "--json", &book, "--tolerance", "1e-6", "--max-report", "3"]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, _, _) = run(&["check", &dir.file("missing.xlsx")]);
assert_eq!(code, 1);
}
#[test]
fn sandbox_check_without_a_program_reports_on_stdout() {
let (code, out, _) = run(&["sandbox-check"]);
assert!(out.starts_with("sandbox:"), "{out}");
assert!(code == 0 || code == 1 || code == 2, "{code}");
}
/// A closed stdout (`gridcraft-cli commands | head`) ends the program quietly; any other write error is reported.
#[test]
fn a_closed_pipe_ends_quietly_and_another_write_error_is_an_error() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err).unwrap().starts_with("error:"));
}
-3
View File
@@ -1,7 +1,4 @@
//! The crate's integration tests, one module per file, built as one test binary.
mod args;
mod cli;
mod in_process;
mod man_and_completions;
mod sandbox;
mod text_to_columns_quotes;
@@ -1,55 +0,0 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
gridcraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut gridcraft_cli::command(), "gridcraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
#[test]
fn man_pages_render_for_the_command_and_every_subcommand() {
let cmd = gridcraft_cli::command();
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
let mut out = Vec::new();
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
assert!(!out.is_empty(), "{}", page.get_name());
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
/// `packaging/freebsd/package.sh` install, `gridcraft-cli.1` and a page per subcommand, and no
/// pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("gc-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["gridcraft-cli.bash", "_gridcraft-cli", "gridcraft-cli.fish", "gridcraft-cli.elv", "_gridcraft-cli.ps1"];
let subcommands = ["cat", "check", "commands", "convert", "eval", "functions", "info", "mcp", "run", "sandbox-check", "send"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("gridcraft-cli.1".into());
expected.extend(subcommands.iter().map(|s| format!("gridcraft-cli-{s}.1")));
expected.sort();
assert_eq!(written, expected);
std::fs::remove_dir_all(&dir).unwrap();
}
+2 -2
View File
@@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true }
gridcraft-ui-egui = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
-3
View File
@@ -49,7 +49,6 @@ pub fn start() {
canvas,
options,
Box::new(move |cc| {
gridcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let inbox: Inbox = Inbox::default();
let mut session = Session::new();
// In host mode the host sends the workbook to edit; no sample meanwhile.
@@ -159,7 +158,6 @@ impl eframe::App for WebShell {
});
}
self.app.logic(ctx);
self.app.close_path(ctx);
// Store changed preferences straight away: a reload or closed tab runs no exit code (#1562).
let changed = self.prefs.changed(&self.app);
if !changed.is_empty() {
@@ -179,7 +177,6 @@ impl eframe::App for WebShell {
/// Forwards a browser frame's raw input to the shared app before eframe handles it.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+1 -3
View File
@@ -32,7 +32,7 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
[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 = { workspace = true }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
@@ -46,8 +46,6 @@ 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.
pollster = "1"
# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`).
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+6 -48
View File
@@ -1,67 +1,25 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing but the channel work. A missing resource compiler is a
//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1`
//! turns it into an error (for release builds).
//!
//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets
//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which
//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the
//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1`
//! is a build error, so a typo cannot silently ship the wrong channel.
#[path = "src/build_channel.rs"]
mod build_channel;
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)");
let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=gridcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("GRIDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=GRIDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" })
.set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" })
res.set_icon("../../assets/app-icon/gridcraft.ico")
.set("ProductName", "GridCraft")
.set("FileDescription", "GridCraft spreadsheet")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "gridcraft.exe")
.set("InternalName", "gridcraft");
if nightly {
// The Launcher compares the PE ProductVersion with the exact feed identity.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
-92
View File
@@ -1,92 +0,0 @@
//! The one place a GridCraft data root is resolved, so the nightly profile and the platform
//! default can never disagree.
//!
//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`,
//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by
//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state.
//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has
//! no environment override of its own: the platform's published folder is the whole story.
use std::ffi::OsString;
use std::path::PathBuf;
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
match platform {
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
_ => env("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft")),
}
}
/// The folder the settings and the log files live in.
pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option<OsString>, nightly_root: Option<&std::path::Path>) -> Option<PathBuf> {
match nightly_root {
// The profile was already validated (absolute, fenced, writable) before this runs.
Some(root) => Some(root.to_path_buf()),
None => default_config_dir(platform, env),
}
}
pub fn config_dir() -> Option<PathBuf> {
config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root())
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json`.
pub fn log_dir() -> Option<PathBuf> {
Some(config_dir()?.join("logs"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
let map: BTreeMap<String, OsString> = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect();
move |key| map.get(key).cloned()
}
#[test]
fn each_platform_keeps_its_published_folder() {
// The base is joined with the host's own separator, so these hold on any machine the gate
// runs on: what each platform publishes is the folder name, not how the host spells a slash.
let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming");
assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft")));
let home = PathBuf::from("/home/u");
assert_eq!(
config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None),
Some(home.join("Library/Application Support/GridCraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft")));
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None);
}
#[test]
fn an_empty_xdg_config_home_falls_back_to_the_home_folder() {
let home = PathBuf::from("/home/u");
let home_str = home.to_string_lossy().into_owned();
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None),
Some(home.join(".config").join("gridcraft"))
);
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
}
#[test]
fn the_nightly_profile_is_the_whole_answer() {
let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile");
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf()));
assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs"));
}
}
-55
View File
@@ -1,55 +0,0 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/gridcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345"));
for invalid in [
"",
"0.19.1",
"0.19.1-nightly",
"0.19.1-nightly.20261124",
"0.19.1-nightly.20261124.7.1.gABCDEF012345",
"0.19.1-nightly.20261124.7.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.19.1-nightly.20261124.1.1.gabcdef012345",
"0.19.1-nightly.20261124.1.1.gabcdef012345/other",
"0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
-73
View File
@@ -1,73 +0,0 @@
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
//! stable build, and a nightly build cannot be talked out of its profile.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
-223
View File
@@ -1,223 +0,0 @@
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their original arguments and directory policy. No environment mutation.
//!
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
//! of this can create a directory, open a log or start a window.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
/// runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+71 -339
View File
@@ -9,25 +9,16 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod app_dirs;
#[cfg(target_os = "macos")]
mod apple_events;
// The build channel's own parser and icon-path tests (build.rs compiles the same file by path).
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(any(target_os = "windows", target_os = "macos", test))]
mod graphics;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod opener;
mod print;
mod process_identity;
mod profile_root;
use std::cell::RefCell;
use std::rc::Rc;
@@ -38,63 +29,45 @@ use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
/// The app, its native window per workbook window, and (macOS) the menu bar and Finder events.
/// The session record and its notice flag are only meaningful in the nightly channel.
struct App {
app: SheetApp,
windows: DocWindows,
#[cfg(target_os = "macos")]
menu: Option<native_menu::NativeMenu>,
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
/// The Nightly session record, shared with the exit hook and the return path.
nightly: nightly_session::Shared,
/// Whether this window already told the user the previous session did not finish.
nightly_notice_shown: bool,
}
struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
{
if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.menu = Some(native_menu::NativeMenu::install(ctx));
if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.2 = Some(native_menu::NativeMenu::install(ctx));
}
if let Some(m) = &mut self.menu {
m.poll(&mut self.app, ctx, self.windows.focused_viewport());
if let Some(m) = &mut self.2 {
m.poll(&mut self.0, ctx, self.1.focused_viewport());
}
apple_events::poll(&self.apple_events, &mut self.app, ctx);
apple_events::poll(&self.3, &mut self.0, ctx);
}
self.0.logic(ctx);
self.1.logic(&mut self.0, ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
self.app.close_path(ctx);
}
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
self.0.raw_input_hook(ctx, raw);
// Files dropped on the window open as workbooks.
for f in std::mem::take(&mut raw.dropped_files) {
if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) {
self.app.open_path(&p);
self.0.open_path(&p);
}
}
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.windows.show(&mut self.app, ui);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.1.show(&mut self.0, ui);
}
fn on_exit(&mut self) {
print::finish_pending_jobs();
save_prefs(&self.app);
save_prefs(&self.0);
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here. A nightly has no updater at all.
if gridcraft_ui_egui::channel::stable_services_allowed() {
self.app.start_pending_update();
}
// The Nightly session record is finished here: every way of quitting reaches `on_exit`,
// and on macOS AppKit's terminate ends the process right after it, so nothing after
// `eframe::run_native` can run there. `finish_once` makes the later call a no-op.
nightly_session::finish_once(&self.nightly, self.nightly_notice_shown);
// dropping the app, so the helper is started here.
self.0.start_pending_update();
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
// macOS adapter subclasses the window's content view and restores its class on teardown;
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
@@ -108,10 +81,17 @@ impl eframe::App for App {
}
}
/// The settings folder: the validated nightly profile, else the platform's own folder
/// (`app_dirs`). Every writer of user state goes through it.
fn config_dir() -> Option<std::path::PathBuf> {
app_dirs::config_dir()
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft"))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft"))
}
}
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
@@ -122,7 +102,7 @@ fn prefs_enabled() -> bool {
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
fn log_dir() -> Option<std::path::PathBuf> {
app_dirs::log_dir()
Some(config_dir()?.join("logs"))
}
fn load_prefs(app: &mut SheetApp) {
@@ -261,155 +241,13 @@ fn icon() -> Option<egui::IconData> {
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version`
/// on a runner) never gets here: the version query is answered before this and before any profile work.
fn report_launch_profile_error(error: &str) {
eprintln!("GridCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("GridCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("GridCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch channel and profile before any startup service or side effect.
/// `None` means the answer was printed (`--version`) and the process is done.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window (a dialog
// here would hang a headless runner and fail a Linux build).
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let channel =
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) =
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
{
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
/// opened as a file.
#[derive(Debug, Default, PartialEq)]
struct DesktopArgs {
control_port: Option<u16>,
control_token: Option<String>,
sample: Option<String>,
files: Vec<String>,
}
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--" => {
parsed.files.extend(args[i + 1..].iter().cloned());
break;
}
"--control" => {
i += 1;
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
parsed.control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => parsed.files.push(a.to_string()),
}
i += 1;
}
parsed
}
/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a
/// document named `--control` is opened rather than read as a flag.
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
}
fn main() -> eframe::Result<()> {
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
// this same executable) comes before everything else: it opens no window, writes no log, and
// becomes the program it confines. It must stay ahead of the launch profile, or a nightly build
// would refuse its own sandbox helper.
// A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else:
// it opens no window, writes no log, and becomes the program it confines.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
std::process::exit(code);
}
// Then the Launcher protocol and the version query (see `prepare_launch`).
let Some(arguments) = prepare_launch() else { return Ok(()) };
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
// for a control server can never write the stable app's token file.
if let Some(root) = launch_profile::current().root() {
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
Ok(()) => {}
Err(error) => {
report_launch_profile_error(&error);
std::process::exit(2);
}
}
}
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
// Commands catch their panics (`Session::execute`), but the default hook only prints to
@@ -430,34 +268,43 @@ fn main() -> eframe::Result<()> {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n"));
}
}));
let args: Vec<String> = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect();
let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1;
let args: Vec<String> = std::env::args().skip(1).collect();
// The restart helper a self-update spawns: it finishes the swap and relaunches, then exits.
// A nightly has no updater, so it never runs this and never inherits a stable swap.
if !nightly
&& let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if let Err(e) = done {
eprintln!("GridCraft update helper failed: {e}");
std::process::exit(1);
}
return Ok(());
}
// Before `--` only: everything after it is a file, even one named `--version`.
if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", gridcraft_ui_egui::channel::version());
if args.iter().any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
// The control channel is a stable-only service: a nightly window owns no port, writes no
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
if nightly_control_refused(nightly, &args) {
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
std::process::exit(2);
let mut control_port: Option<u16> = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut control_token: Option<String> = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok();
let mut sample: Option<String> = None;
let mut files: Vec<String> = Vec::new();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--control" => {
i += 1;
control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => files.push(a.to_string()),
}
i += 1;
}
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
let parsed = desktop_args(&args, control_port, control_token);
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
// The log file lives in the settings folder, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
@@ -465,9 +312,7 @@ fn main() -> eframe::Result<()> {
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => {
log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display())
}
Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
@@ -482,41 +327,14 @@ fn main() -> eframe::Result<()> {
}
let mut app = SheetApp::new(session, services());
app.watch_desktop_theme();
// The updater is a stable-only service: a nightly is installed, replaced and updated by the
// Launcher, so it never checks for one, never prompts and never writes craft-update's state.
if !nightly {
app.start_update_check();
}
app.start_update_check();
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.
// Nightly session health: the record is written before the window exists and finished by
// `on_exit`. A record left by an interrupted run is reported once, then cleared on the next
// clean quit.
let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None));
let mut nightly_notice_shown = false;
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) {
Ok((watch, unavailable)) => {
if let Some(watch) = &watch
&& watch.previous_unclean()
{
app.notice = Some(gridcraft_ui_egui::Notice {
text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(),
kind: gridcraft_ui_egui::NoticeKind::Warning,
action: None,
});
nightly_notice_shown = true;
}
if unavailable {
log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded");
}
*session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch;
}
Err(error) => log::warn!("Nightly session state was not written: {error}"),
}
// 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.
@@ -526,16 +344,11 @@ fn main() -> eframe::Result<()> {
// Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the
// window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame.
app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none();
// The window carries its channel's name and OS app id: a nightly window is never mistaken for
// the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A
// Flatpak package carries its own id instead, which is what its .desktop file and portal name.
let window_app_id =
std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string());
let mut viewport = egui::ViewportBuilder::default()
.with_title(gridcraft_ui_egui::channel::default_title())
.with_title("GridCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([640.0, 420.0])
.with_app_id(window_app_id)
.with_app_id("ai.storyteller.gridcraft")
.with_drag_and_drop(true)
.with_decorations(!app.window_controls);
if cfg!(target_os = "macos") {
@@ -574,13 +387,12 @@ fn main() -> eframe::Result<()> {
let pending = std::cell::Cell::new(Some(app));
let run = |options: eframe::NativeOptions| {
eframe::run_native(
gridcraft_ui_egui::channel::name(),
"GridCraft",
options,
Box::new(|cc| {
let Some(mut app) = pending.take() else {
return Err("the app was already created".into());
};
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
if let Some(port) = control_port {
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
@@ -589,16 +401,14 @@ fn main() -> eframe::Result<()> {
}
}
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
Ok(Box::new(App {
Ok(Box::new(App(
app,
windows,
#[cfg(target_os = "macos")]
menu: None,
None,
#[cfg(target_os = "macos")]
apple_events: apple_events.connect(&cc.egui_ctx),
nightly: session_watch.clone(),
nightly_notice_shown,
}))
apple_events.connect(&cc.egui_ctx),
)))
}),
)
};
@@ -606,7 +416,7 @@ fn main() -> eframe::Result<()> {
// A graphics error before the app existed: start once more with the other backend (eframe
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
#[cfg(target_os = "windows")]
let result = if let Err(eframe::Error::Wgpu(e)) = &result
if let Err(eframe::Error::Wgpu(e)) = &result
&& let Some(app) = pending.take()
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
{
@@ -614,14 +424,8 @@ fn main() -> eframe::Result<()> {
pending.set(Some(app));
let mut options = retry_options;
graphics::configure_backends(&mut options, backends);
run(options)
} else {
result
};
// A start that failed before the app existed never reached `on_exit`, and on the platforms
// where the event loop returns this is also the end of a clean exit. `finish_once` makes the
// second of the two calls a no-op, so a successor's record is never touched.
nightly_session::finish_once(&session_watch, nightly_notice_shown);
return run(options);
}
result
}
@@ -653,75 +457,3 @@ mod packaging_tests {
}
}
}
#[cfg(test)]
mod launch_separator_tests {
use super::*;
use crate::build_flavor::BuildFlavor;
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_other_platforms_root_spelling_is_refused_as_relative() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
let argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
}
#[test]
fn the_launchers_separator_is_never_a_file() {
let parsed = desktop_args(&launcher_argv(&[]), None, None);
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
}
#[test]
fn files_after_the_separator_are_opened_in_order() {
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
assert_eq!((parsed.sample, parsed.control_port), (None, None));
}
#[test]
fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() {
let argv = launcher_argv(&["--control"]);
assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse");
let parsed = desktop_args(&argv, None, None);
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
}
#[test]
fn a_control_flag_before_the_separator_still_names_the_port() {
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
assert!(nightly_control_refused(true, &with_file));
let parsed = desktop_args(&with_file, None, None);
assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()]));
let plain = vec!["--control".to_string(), "7979".to_string()];
assert!(nightly_control_refused(true, &plain));
let parsed = desktop_args(&plain, None, None);
assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::<String>::new()));
assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel");
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
-310
View File
@@ -1,310 +0,0 @@
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
//!
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker: only the app's controlled return path does, and
//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after
//! `on_exit`, so nothing after `eframe::run_native` runs there).
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Replace `path` with `bytes` without following a link at the destination: the temporary file is
/// created exclusively beside it and renamed over it, so a planted link is replaced, not written
/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is
/// the app's own file and must not depend on the engine's script sandbox policy.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?;
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(".new");
let tmp = path.with_file_name(tmp_name);
match std::fs::remove_file(&tmp) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let write = (|| -> io::Result<()> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let mut file = options.open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, path)
})();
if write.is_err() {
let _ = std::fs::remove_file(&tmp);
}
write
}
/// The owner's session, shared by the app's exit hook and the return path.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage, while
/// Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable, or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
// The commit is read back from the version (`…g<sha12>`), never invented here.
let commit = gridcraft_ui_egui::channel::commit_for(version);
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit,
}))?;
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed it
/// yet (a failed start before the app existed), the record is left for the next owner.
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed
/// process never calls this.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("gridcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
fn version() -> &'static str {
"0.19.1-nightly.20261124.7.1.gabcdef012345"
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable").unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), version()).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), version()).unwrap().unwrap());
// The renderer failed before the app existed: no notice was shown.
let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), version()).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
let successor = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1)).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect());
assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment");
watch.complete().unwrap();
}
#[test]
fn a_version_without_a_commit_does_not_invent_one() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
assert!(data["commit"].is_null());
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), version()).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
#[test]
#[cfg(unix)]
fn replacing_a_planted_record_link_writes_our_own_file_only() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap();
// regular_or_missing refuses an alias outright; the temporary writer is what a first write
// uses, and it never follows one either.
assert!(Session::begin(Some(&fixture.0), version()).is_err());
// The link is at RECORD itself: writing there must replace the alias, not follow it.
atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap();
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours");
assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through");
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
assert!(!fixture.0.join(".nightly-session.json.new").exists());
}
}
+10 -12
View File
@@ -1,12 +1,15 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
pub fn discover() -> Discover {
Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
let printers = craft_print::printers()
.into_iter()
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
let _ = sender.send(printers);
});
receiver
@@ -31,17 +34,12 @@ pub fn submit() -> Submit {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
printer: match settings.destination {
Destination::Printer(name) => Some(name),
_ => None,
},
printer: Some(settings.printer),
copies: settings.copies.clamp(1, 999),
collate: settings.collate,
duplex: settings.duplex.and_then(|value| match value {
Duplex::LongEdge => Some(craft_print::Duplex::LongEdge),
Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge),
Duplex::Off => Some(craft_print::Duplex::Off),
_ => None,
duplex: settings.duplex.map(|value| match value {
Duplex::LongEdge => craft_print::Duplex::LongEdge,
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
Duplex::Off => craft_print::Duplex::Off,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
-81
View File
@@ -1,81 +0,0 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's
//! advertised shortcuts keep matching it.
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityError(String);
impl std::fmt::Display for IdentityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for IdentityError {}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
#[test]
fn a_non_nightly_build_never_reaches_the_windows_api() {
assert!(initialize(false, "nightly-id").is_ok());
}
}
-528
View File
@@ -1,528 +0,0 @@
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
//! nightly root, in both directions, so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
pub const CONTROL_DIR: &str = "Control";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// FreeBSD, the BSDs and anything else have no nightly channel.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
/// ancestor is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
// token folder, plus both MSI install folders (`install-policy.wxi`).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/GridCraft"),
library.join("Caches/GridCraft"),
library.join("Caches/ai.storyteller.gridcraft"),
library.join("Preferences/GridCraft"),
library.join("Preferences/ai.storyteller.gridcraft.plist"),
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
home.join("Applications/GridCraft.app"),
PathBuf::from("/Applications/GridCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at the stable app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything.
pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, CONTROL_DIR, "control folder")
}
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// A crashed launch can leave a probe with this name behind: take the next one instead of
// failing, and remove only the file this call created, never someone else's.
loop {
let probe =
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(_) => return std::fs::remove_file(&probe),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
{
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
// instance may carry a profile. Any other, the stable app's included, could point it at
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
return Err(format!(
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
id.to_string_lossy()
));
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect a subfolder elsewhere.
control_directory(&chosen)?;
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
control_directory(&confirmed)?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/gridcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn every_stable_data_root_is_refused_on_its_own_platform() {
let mut fixture = Fixture::new();
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
// and per-machine install folders and the control-token folder.
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert!(!stable.exists());
}
assert!(
fixture
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
.is_err()
);
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
assert!(!base.join("ArtCraft/GridCraft").exists());
}
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
// macOS: the four Library rows and the bundle itself.
for suffix in [
"Application Support/GridCraft",
"Caches/GridCraft",
"Preferences/GridCraft",
"Saved Application State/ai.storyteller.gridcraft.savedState",
] {
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
}
}
#[test]
fn the_launcher_profile_row_is_accepted_on_every_platform() {
let fixture = Fixture::new();
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &data).unwrap(), data);
}
assert!(
fixture
.check(
Platform::Linux,
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
)
.is_ok(),
"the Launcher's own folder is not GridCraft's install"
);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Control"), platform));
assert!(overlaps(&root.join("Control"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
}
}
#[test]
fn the_install_folder_of_the_running_build_is_refused() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
}
}
#[test]
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let mut fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in [
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
("ai.storyteller.gridcraft", false),
("ai.storyteller.gridcraft.nightly-v1", false),
("io.github.other.Gridcraft", false),
] {
fixture.env.insert("FLATPAK_ID".into(), id.into());
let result = fixture.check(Platform::Linux, &root);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
assert!(result.unwrap_err().contains("not writable"));
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
assert!(!fixture.home().join(".config/gridcraft").exists());
}
#[test]
fn a_file_in_place_of_the_profile_is_refused() {
let fixture = Fixture::new();
let candidate = fixture.root.join("not-a-directory");
std::fs::write(&candidate, b"a file, not a profile").unwrap();
assert!(fixture.check(Platform::Linux, &candidate).is_err());
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
}
#[cfg(unix)]
#[test]
fn profile_entry_aliases_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
for name in ["ui.json", "logs", "Control", "profile"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = fixture.check_with(Platform::Linux, &private, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-logs")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let fixture = Fixture::new();
let outside = fixture.home().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(fixture.check(Platform::Linux, &private).is_err());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
#[test]
fn the_control_folder_is_a_private_lazy_subfolder() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
let control = control_directory(&private).unwrap();
assert!(control.starts_with(&private) && control != private);
assert!(!control.exists(), "resolving it must not create it");
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
}
#[test]
fn the_writable_probe_leaves_nothing_behind() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
ensure_writable(&private).unwrap();
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
}
}
-13
View File
@@ -50,16 +50,3 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`.
Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the
`.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`.
## Nightly channel
The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and
change only the field colour: `#1f9d55` in the stable icon, `#14532d` in
`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the
channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id).
`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from
it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it
uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the
method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and
`python3 packaging/nightly-icons.py --check` verifies the committed files still match it.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-30
View File
@@ -1,30 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- GridCraft Nightly (nightly-v1) icon: the stable artwork with only its background contribution
deepened. Foreground, geometry and alpha are unchanged; no badge, letter or crescent, so the
channel reads from the app and the Launcher in text.
Palette: ink #0b0b0c, paper #efe9dc, stable field #1f9d55
(proposed), nightly field #14532d. -->
<defs>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
</defs>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="#14532d"/>
<g transform="rotate(-6 256 268)" stroke="#0b0b0c" stroke-linejoin="round" stroke-linecap="round">
<!-- page with a folded top-right corner -->
<path d="M112 76 H336 L404 144 V440 H112 Z" fill="#efe9dc" stroke-width="14"/>
<path d="M336 76 V144 H404" fill="none" stroke-width="12"/>
<!-- title lines -->
<path d="M146 106 H272 M146 130 H232" stroke-width="12"/>
<!-- header row and row-number column, in the app colour -->
<path d="M112 164 H404 V204 H164 V440 H112 Z" fill="#14532d" stroke="none"/>
<!-- grid -->
<path d="M112 164 H404 M112 204 H404 M112 250 H404 M112 296 H404 M112 342 H404 M112 388 H404
M164 164 V440 M244 164 V440 M324 164 V440" fill="none" stroke-width="8"/>
<!-- the selected cell and its fill handle -->
<rect x="244" y="250" width="80" height="46" fill="none" stroke-width="16"/>
<rect x="312" y="284" width="24" height="24" fill="#0b0b0c" stroke="#efe9dc" stroke-width="5"/>
<!-- double rule under the total -->
<path d="M252 410 H316 M252 424 H316" stroke-width="7"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

-56
View File
@@ -1,56 +0,0 @@
{
"title": "GridCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"inputs": [
{
"path": "assets/app-icon/gridcraft-nightly.svg",
"sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b",
"purpose": "vector master for every frame"
},
{
"path": "assets/app-icon/gridcraft.svg",
"sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850",
"purpose": "stable artwork this is derived from"
}
],
"method": {
"kind": "vector render of the project-owned artwork with only its field colour deepened",
"stable_field": "#1f9d55",
"nightly_field": "#14532d",
"unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding",
"sizes": "each frame rendered at its own size, never upscaled",
"renderer": "chrome",
"generator": "packaging/nightly-icons.py"
},
"outputs": {
"gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0",
"gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400",
"gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751",
"gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
}
}
+3
View File
@@ -11,4 +11,7 @@ disallowed-methods = [
{ 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
-6
View File
@@ -118,9 +118,3 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.alosslessdev]
real_name = "Francisco Herrera"
-27
View File
@@ -62,28 +62,6 @@ pub struct Lambda {
pub env: Vec<(String, Ev)>,
}
/// What the tail of a LAMBDA body came to.
enum Tail {
Done(Ev),
/// A call to make in place of the current one, its arguments evaluated.
Call(Arc<Lambda>, Vec<(String, Ev)>),
}
/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the
/// chain is a loop, not a recursion, so it cannot overflow the native stack.
impl Drop for Lambda {
fn drop(&mut self) {
let mut pending = std::mem::take(&mut self.env);
while let Some((_, ev)) = pending.pop() {
if let Ev::L(l) = ev
&& let Ok(mut inner) = Arc::try_unwrap(l)
{
pending.append(&mut inner.env);
}
}
}
}
#[derive(Clone, Debug)]
pub enum Ev {
V(Value),
@@ -106,11 +84,6 @@ fn err(e: CellError) -> Ev {
/// calls in progress, so it still runs.
const MAX_LAMBDA_CALLS: usize = 140;
/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps
/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!`
/// for 5,460, which is 5,460 invocations in the chain.
const MAX_TAIL_CALLS: usize = 5460;
/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it,
/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames
/// above the formula. A cell that another cell's formula computes on demand shares the budget of the
+7 -1
View File
@@ -216,7 +216,13 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
}
}),
BinOp::Concat => match (a.to_text(), b.to_text()) {
(Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)),
(Ok(x), Ok(y)) => {
if x.len() + y.len() > 32767 * 4 {
Value::Error(CellError::Value)
} else {
Value::text(x + &y)
}
}
(Err(e), _) | (_, Err(e)) => Value::Error(e),
},
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
-11
View File
@@ -5,17 +5,6 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip
use std::sync::Arc;
impl<'h> Evaluator<'h> {
/// `IF` with an array condition: element-wise.
pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev {
let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true));
let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) };
Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() {
Ok(true) => t.clone(),
Ok(false) => f.clone(),
Err(e) => Value::Error(e),
}))
}
pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev {
match name {
"IF" => self.if_call(args),
+4 -84
View File
@@ -1,26 +1,17 @@
use super::MAX_LAMBDA_CALLS;
use super::array::{broadcast_len, single};
use super::special::is_special;
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err};
use std::sync::Arc;
impl<'h> Evaluator<'h> {
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
match self.bind_args(l, args) {
Ok(bound) => self.call_lambda_values(l, bound),
Err(e) => e,
}
}
/// The arguments of a call to `l`, evaluated in the current scope.
fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result<Vec<(String, Ev)>, Ev> {
// Too many or too few argument positions is #VALUE!. An explicitly empty position, as in
// `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()`
// parses to no arguments, which for a one-parameter lambda can also be read as one empty
// position, so that call still binds the parameter as omitted.
let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1);
if !positions_ok {
return Err(err(CellError::Value));
return err(CellError::Value);
}
let mut bound = Vec::with_capacity(l.params.len());
for (i, p) in l.params.iter().enumerate() {
@@ -30,56 +21,7 @@ impl<'h> Evaluator<'h> {
};
bound.push((p.clone(), v));
}
Ok(bound)
}
/// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches,
/// parentheses), and returns the call with its arguments evaluated instead of making it, so
/// that `call_lambda_values` can loop. Anything else is evaluated here.
fn tail_step(&mut self, e: &Expr) -> Tail {
match e {
Expr::Paren(x) => self.tail_step(x),
Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => {
let c = self.arg_val(args, 0).unwrap_or_default();
if let Value::Array(arr) = &c {
return Tail::Done(self.if_elementwise(arr, args));
}
match c.to_bool() {
Ok(true) => self.tail_step_branch(args.get(1)),
Ok(false) => match args.get(2) {
Some(_) => self.tail_step_branch(args.get(2)),
None => Tail::Done(Ev::V(Value::Bool(false))),
},
Err(x) => Tail::Done(err(x)),
}
}
Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Name)),
},
Expr::Invoke(callee, args) => match self.eval(callee) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Value)),
},
_ => Tail::Done(self.eval(e)),
}
}
/// An `IF` branch; an omitted one (`IF(c,,1)`) is 0.
fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail {
match branch {
Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))),
Some(b) => self.tail_step(b),
}
}
fn tail_call(&mut self, l: Arc<Lambda>, args: &[Expr]) -> Tail {
match self.bind_args(&l, args) {
Ok(bound) => Tail::Call(l, bound),
Err(e) => Tail::Done(e),
}
self.call_lambda_values(l, bound)
}
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
@@ -96,29 +38,7 @@ impl<'h> Evaluator<'h> {
self.calls += 1;
let saved = std::mem::replace(&mut self.env, l.env.clone());
self.env.extend(bound);
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
let mut tails = 0;
let mut step = self.tail_step(&l.body);
let r = loop {
match step {
Tail::Done(v) => break v,
Tail::Call(next, bound) => {
tails += 1;
if tails >= MAX_TAIL_CALLS {
break err(CellError::Num);
}
self.fuel = match self.fuel.checked_sub(1) {
Some(f) => f,
None => break err(CellError::Calc),
};
self.env.clear();
self.env.extend(next.env.iter().cloned());
self.env.extend(bound);
step = self.tail_step(&next.body);
}
}
};
let r = self.eval(&l.body);
self.env = saved;
self.calls -= 1;
r
+1 -1
View File
@@ -195,7 +195,7 @@ impl Precedents<'_> {
}
}
pub(super) fn is_special(n: &str) -> bool {
fn is_special(n: &str) -> bool {
matches!(
n,
"IF" | "IFS"
+1 -1
View File
@@ -12,7 +12,7 @@ mod trimrange;
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
pub use precision::DisplayedPrecision;
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
#[cfg(test)]
mod tests;
+2 -3
View File
@@ -718,7 +718,7 @@ impl Calc {
} else {
Vec::new()
};
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
if !blocked {
for (o, r) in outranked {
for c in r.iter() {
@@ -785,7 +785,6 @@ fn spill_is_blocked(
range: RangeRef,
end: CellRef,
standing: &Standing,
array_len: usize,
) -> bool {
let outranked = |cell: CellRef| {
sheet
@@ -797,7 +796,7 @@ fn spill_is_blocked(
|| end.col >= gridcraft_core::MAX_COLS
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|| sheet.merges.iter().any(|merge| merge.intersects(&range))
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.1)))
|| sheet.tables.iter().any(|table| table.range.contains(anchor.1))
}
fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) {
+3 -4
View File
@@ -162,8 +162,7 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
})
}
/// Whether an array result at `k` can't spill: it is in a table (a one-value result is shown
/// there, as in Excel), or its area runs off the sheet,
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
@@ -189,7 +188,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
end.row >= gridcraft_core::MAX_ROWS
|| end.col >= gridcraft_core::MAX_COLS
|| sh.merges.iter().any(|m| m.intersects(&range))
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|| sh.tables.iter().any(|t| t.range.contains(anchor))
|| sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (!cell.value.is_empty() || cell.formula.is_some()))
|| sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c) && spilled_over(*c))
}
@@ -201,7 +200,7 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef,
CellRef::new(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)));
RangeRef::new(anchor, end) == range
&& !sheet.merges.iter().any(|m| m.intersects(&range))
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
&& range
.iter()
.enumerate()
+3 -161
View File
@@ -820,42 +820,6 @@ fn arrays_do_not_spill_in_tables() {
assert_eq!(t.num("E4"), 4.0);
}
#[test]
fn one_value_array_in_a_table_is_not_a_spill() {
// Excel shows a one-value dynamic-array result in a table column; two or more is #SPILL! (#2335).
let table = |range: &str| gridcraft_model::Table {
id: 1,
name: "Table1".into(),
range: gridcraft_core::RangeRef::parse(range).unwrap(),
header_row: true,
totals_row: false,
columns: vec![],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: false,
filter: vec![],
table_type: None,
connection_id: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
t.set("A1", "7");
t.set("A2", "8");
t.set("C4", "=FILTER(A1:A2,A1:A2>7)");
t.set("C5", "=FILTER(A1:A2,A1:A2>0)");
t.set("H4", "=FILTER(A1:A2,A1:A2>7)");
t.set("D4", "=ROWS(C4#)");
assert_eq!((t.num("C4"), t.num("H4"), t.num("D4")), (8.0, 8.0, 1.0));
assert_eq!(t.get("C5"), Value::Error(CellError::Spill));
// Recalculating again keeps the one-value result.
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("C4"), 8.0);
assert_eq!(t.num("D4"), 1.0);
}
#[test]
fn ifs_and_lazy() {
let mut t = T::new();
@@ -1217,67 +1181,17 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
comment: String::new(),
hidden: false,
});
// W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel
// (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds
// one more call per step.
// F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step.
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))");
[tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
[tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("recursion must not overflow the stack")
};
let small = run(1 << 20);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
#[test]
fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() {
// Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000.
let run = |stack: usize| {
std::thread::Builder::new()
.stack_size(stack)
.spawn(|| {
let mut wb = Workbook::new();
wb.names.push(gridcraft_model::DefinedName {
name: "TAILN".into(),
scope: None,
formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(),
comment: String::new(),
hidden: false,
});
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
// The same chain through parentheses and an applied lambda, and one that returns the base case's value.
let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string();
let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string();
let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string();
// Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse.
let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string();
[tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures]
.map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("tail recursion must not overflow the stack")
};
let num = Value::Error(CellError::Num);
let small = run(1 << 20);
assert_eq!(
small,
[
Value::Number(0.0),
Value::Number(0.0),
num.clone(),
num.clone(),
Value::Number(7.0),
Value::Number(7.0),
num,
Value::Number(0.0),
Value::Number(0.0)
]
);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
@@ -2121,65 +2035,6 @@ fn offset_extreme_arguments_return_ref() {
}
}
/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15
/// significant digits. Every expectation was observed in Excel 365 with these fixtures
/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order.
#[test]
fn sorts_and_ranks_compare_numbers_exactly() {
let mut t = T::new();
for (at, input) in [
// The noisy value first, then the exact one first.
("A1", "=0.1+0.2"),
("B1", "e"),
("A2", "0.3"),
("B2", "t"),
("D1", "0.3"),
("E1", "t"),
("D2", "=0.1+0.2"),
("E2", "e"),
("G1", "=100+1E-14"),
("H1", "e"),
("G2", "100"),
("H2", "t"),
] {
t.set(at, input);
}
let e = 0.1 + 0.2;
let n = Value::Number;
let s = |x: &str| Value::from(x);
let cases: Vec<(&str, Value)> = vec![
("=A1=A2", Value::Bool(true)),
("=COUNTIF(A1:A2,0.3)", n(2.0)),
("=INDEX(SORT(A1:B2),1,2)", s("t")),
("=INDEX(SORT(D1:E2),1,2)", s("t")),
("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")),
("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")),
("=INDEX(SORT(G1:H2),1,2)", s("t")),
("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")),
("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")),
("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")),
("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")),
("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")),
// Already exact: UNIQUE, RANK, LARGE/SMALL, MODE.
("=ROWS(UNIQUE(A1:A2))", n(2.0)),
("=RANK.EQ(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1:A2,1)", n(1.0)),
("=RANK.AVG(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)),
("=LARGE(A1:A2,1)", n(e)),
("=SMALL(A1:A2,1)", n(0.3)),
("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)),
];
let mut wrong = Vec::new();
for (formula, expected) in cases {
let got = crate::evaluate(&t.wb, 0, c("Z1"), formula);
if got != expected {
wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}"));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// `@` intersects a reference with the formula's row (a column range) or column (a row range);
/// a 2D range both (circular when it includes the formula's cell); a range the formula does not
/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly.
@@ -2762,19 +2617,6 @@ fn loan_schedule_residue_keeps_excels_sign() {
assert_eq!(t.get("P7"), Value::Text("".into()));
}
#[test]
fn concat_operator_cuts_at_the_cell_limit() {
// Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767.
let mut t = T::new();
t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))");
t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")");
t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))");
t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")");
t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))");
assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0));
assert_eq!(t.get("A5"), Value::Error(CellError::Value));
}
#[test]
fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() {
let mut t = T::new();
+6 -13
View File
@@ -16,7 +16,6 @@ enum Fam {
Col100,
Line,
LineStack,
Line100,
Area,
AreaStack,
Area100,
@@ -32,7 +31,6 @@ fn family(k: ChartKind) -> Fam {
ColumnStacked100 | BarStacked100 => Fam::Col100,
Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line,
LineStacked => Fam::LineStack,
LineStacked100 | LineStacked100Markers => Fam::Line100,
Area => Fam::Area,
AreaStacked => Fam::AreaStack,
AreaStacked100 => Fam::Area100,
@@ -42,7 +40,7 @@ fn family(k: ChartKind) -> Fam {
/// Families stacked to 100%: each category's values are shares of its total.
fn is_100(f: Fam) -> bool {
matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100)
matches!(f, Fam::Col100 | Fam::Area100)
}
fn is_col(f: Fam) -> bool {
@@ -50,12 +48,7 @@ fn is_col(f: Fam) -> bool {
}
fn is_line(f: Fam) -> bool {
matches!(f, Fam::Line | Fam::LineStack | Fam::Line100)
}
/// Line kinds that draw a marker at each point.
fn has_markers(k: ChartKind) -> bool {
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
matches!(f, Fam::Line | Fam::LineStack)
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
@@ -163,7 +156,7 @@ impl BarSink {
}
fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec<Vec<Option<(f64, f64)>>> {
// Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart).
// Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart).
let mut totals: Vec<((bool, Fam), Vec<f64>)> = Vec::new();
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
@@ -194,7 +187,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
let a = sec.get(i).copied().unwrap_or(false);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
let key = (a, fam);
let si = if stacked {
match stacks.iter().position(|(k, _, _)| *k == key) {
@@ -223,7 +216,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
}),
(Some((_, pos, _)), _) => {
let v = v.unwrap_or(0.0);
let v = if is_100(fam) { share(key, j, v) } else { v };
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
pos.get_mut(j).map(|acc| {
let base = *acc;
*acc = clean(*acc + v);
@@ -431,7 +424,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if has_markers(k) && cw >= 3.0 {
if k == ChartKind::LineMarkers && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
}
if labels_on {
+2 -4
View File
@@ -57,10 +57,8 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
.clone()
.map(|s| {
let sw = match s.kind {
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
Swatch::Line
}
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
_ => Swatch::Box,
};
+2 -2
View File
@@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay
let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 };
if settings.show_keys {
let swatch = match series.kind {
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line,
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
_ => Swatch::Box,
};
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
+8 -20
View File
@@ -360,7 +360,7 @@ fn category_label(wb: &Workbook, src: Option<(&gridcraft_model::Sheet, RangeRef)
/// the outer levels of a multi-level axis: a category range wider than a column of values (or
/// taller than a row of values) groups its innermost labels, year beside month. Each outer level
/// has one entry per category, non-empty where a group starts, as the cells are.
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (Vec<String>, Vec<Vec<String>>) {
let cells: Option<(usize, RangeRef)> = parse_ref(wb, sheet, formula);
let value_range = parse_ref(wb, sheet, values).map(|(_, r)| r);
// Bound the category dimension by `limit` and read only the cells the levels use (the
@@ -419,21 +419,12 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limi
let at = |row: usize, col: usize| texts.get(row * w + col).cloned().unwrap_or_default();
let column = |c: usize| (0..h).map(|row| at(row, c)).collect::<Vec<String>>();
let row = |rr: usize| (0..w).map(|c| at(rr, c)).collect::<Vec<String>>();
let value_count = eval_list_in(wb, sheet, values, limit, 0).len();
let by_columns = if value_count == h && w > 1 && h != w {
true
} else if value_count == w && h > 1 && h != w {
false
} else {
levels.by_columns
};
let outer = if by_columns { w.saturating_sub(1).min(3) } else { h.saturating_sub(1).min(3) };
let result = if by_columns {
let outer = levels.outer as usize;
if levels.by_columns {
(column(w - 1), (1..=outer).filter_map(|k| (w - 1).checked_sub(k)).map(column).collect())
} else {
(row(h - 1), (1..=outer).filter_map(|k| (h - 1).checked_sub(k)).map(row).collect())
};
if innermost { (result.0, vec![]) } else { result }
}
}
/// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on
@@ -483,7 +474,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
if categories.is_none()
&& let Some(f) = &s.categories
{
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit, s.innermost_categories);
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
c.truncate(limit);
if !c.is_empty() {
categories = Some(c);
@@ -511,10 +502,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
secondary: s.secondary,
smooth: s.smooth,
trendlines,
number_format: match &s.number_format {
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
_ => ref_format(wb, sheet, &s.values),
},
number_format: ref_format(wb, sheet, &s.values),
});
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
@@ -533,7 +521,7 @@ mod label_budget_tests {
#[test]
fn category_labels_share_one_byte_budget() {
let wb = Workbook::new();
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS, false);
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
assert_eq!(texts.len(), 100_000);
assert_eq!(texts.first().map(String::len), Some(super::MAX_LABEL_CHARS));
assert!(texts.iter().map(String::len).sum::<usize>() <= super::MAX_CATEGORY_BYTES);
@@ -556,7 +544,7 @@ mod label_budget_tests {
}
}
// Five columns: column A is a fourth outer level and is discarded.
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS, false);
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
assert_eq!(outer.len(), 3);
assert_eq!(inner.last().map(String::len), Some(super::MAX_LABEL_CHARS));
assert_eq!(outer.first().and_then(|l| l.last()).map(String::len), Some(super::MAX_LABEL_CHARS));
+1 -140
View File
@@ -8,7 +8,7 @@ use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 28] = [
const ALL_KINDS: [ChartKind; 26] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -18,8 +18,6 @@ const ALL_KINDS: [ChartKind; 28] = [
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -551,9 +549,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
// References use their cells' format, whatever the series says.
number_format: Some("0%".into()),
innermost_categories: false,
},
Series {
name: None,
@@ -566,8 +561,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: Some("Literal".into()),
@@ -580,8 +573,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: Some("0.0%".into()),
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -601,7 +592,6 @@ fn resolve_from_workbook() {
assert!(s1.secondary);
assert_eq!(d.series[2].name, "Literal");
assert_eq!(d.series[2].values.len(), 4);
assert_eq!(d.series[2].number_format, "0.0%");
// Default categories.
c.series.remove(0);
@@ -622,8 +612,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: None,
@@ -636,8 +624,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -655,8 +641,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
@@ -675,8 +659,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 7, &c);
assert_eq!(d.series.len(), 1);
@@ -1382,8 +1364,6 @@ fn pie_points_follow_workbook_theme() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
@@ -1439,47 +1419,6 @@ fn area_charts_draw_source_value_labels_only_when_enabled() {
}
}
#[test]
fn a_multi_level_category_block_draws_its_innermost_level() {
// A PivotChart's two levels of row labels in A1:B4, the outer one (country) on the left:
// one label per point, from the innermost column.
let mut wb = Workbook::new();
{
let s = wb.sheet_mut(0).unwrap();
s.name = "Graph".into();
for (r, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
if !outer.is_empty() {
s.set_value(CellRef::new(r as u32, 0), Value::from(*outer));
}
s.set_value(CellRef::new(r as u32, 1), Value::from(*inner));
s.set_value(CellRef::new(r as u32, 2), Value::Number(r as f64 + 1.0));
s.set_value(CellRef::new(5, r as u32), Value::from(*inner));
s.set_value(CellRef::new(6, r as u32), Value::from(*outer));
}
}
let mut c = chart(ChartKind::ColumnClustered);
c.series = vec![Series {
categories: Some("Graph!$A$1:$B$4".into()),
values: "Graph!$C$1:$C$4".into(),
innermost_categories: true,
..Series::default()
}];
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// A block with a column per point: its last row is the innermost level.
c.series[0].categories = Some("Graph!$A$6:$D$7".into());
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Canada", "", "USA", ""]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// Without the flag, every cell is a label, as for any other chart.
c.series[0].categories = Some("Graph!$A$1:$B$4".into());
c.series[0].innermost_categories = false;
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert_eq!(data.category_levels, vec![vec!["Canada", "", "USA", ""]]);
}
#[test]
fn drawing_and_resolving_agree_on_the_combo_plot_kind() {
// Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind,
@@ -1552,62 +1491,6 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() {
assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2)));
}
#[test]
fn hundred_percent_stacked_lines_end_each_category_at_its_total() {
let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]);
for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] {
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(),
series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)],
};
let mut c = chart(kind);
c.data_labels = false;
let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
let t = texts(&p);
assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}");
assert!(!t.contains(&"40"), "{kind:?}: {t:?}");
// The value axis labels sit on their gridlines.
let label_y = |s: &str| {
p.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == s => Some(*y),
_ => None,
})
.unwrap_or(f32::NAN)
};
let (y0, y100) = (label_y("0%"), label_y("100%"));
assert!(y0 > y100, "{kind:?}: {y0} {y100}");
let frac = |y: f32| (y0 - y) / (y0 - y100);
let line = |color: Rgba| {
p.iter()
.find_map(|p| match p {
// The series line is 2.25 wide; its legend swatch is 2.0.
Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => {
Some(pts.iter().map(|q| frac(q[1])).collect::<Vec<f32>>())
}
_ => None,
})
.unwrap_or_default()
};
let (north, south) = (line(north_color), line(south_color));
assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}");
// A category whose total is zero stays on the baseline.
for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() {
assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]);
}
// Point markers have a white outline; the legend's marker swatches have none.
let circles = |outlined: bool| {
p.iter()
.filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined))
.count()
};
let with_markers = kind == ChartKind::LineStacked100Markers;
assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}");
}
}
#[test]
fn two_level_categories_resolve_and_draw() {
let years = ["2023", "", "", "2024", "", ""];
@@ -1682,22 +1565,6 @@ fn two_level_categories_resolve_and_draw() {
assert!(d.category_levels.is_empty());
}
#[test]
fn square_category_blocks_keep_their_declared_orientation_on_ties() {
let mut wb = Workbook::new();
let s = wb.sheet_mut(0).unwrap();
s.name = "Data".into();
for (i, value) in ["A1", "B1", "A2", "B2", "A3", "B3"].iter().enumerate() {
s.set_value(CellRef::parse(value).unwrap(), Value::from(*value));
s.set_value(CellRef::new(3, i as u32), Value::Number(i as f64 + 1.0));
}
let mut c = chart(ChartKind::Line);
c.series = vec![Series { categories: Some("Data!$A$1:$B$2".into()), values: "Data!$A$3:$B$3".into(), ..Series::default() }];
let d = resolve(&wb, 0, &c);
assert_eq!(d.categories, vec!["A2", "B2"]);
assert_eq!(d.category_levels, vec![vec!["A1", "B1"]]);
}
#[test]
fn a_huge_trendline_forecast_does_not_collapse_the_columns() {
let m = ApproxMeasure;
@@ -1774,7 +1641,6 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
@@ -1811,7 +1677,6 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
@@ -1833,8 +1698,6 @@ fn volatile_series_formulas_are_detected() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1864,8 +1727,6 @@ fn volatile_defined_names_are_followed() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
-29
View File
@@ -148,32 +148,3 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() {
assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h);
}
}
#[test]
fn table_keys_for_100_percent_stacked_lines_use_line_swatches() {
for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] {
let mut c = chart(kind);
c.title = Some(String::new());
c.legend = LegendPos::None;
c.data_labels = false;
c.data_table = Some(ChartDataTable::default());
let color = [1, 2, 3, 255];
let d = ChartData {
categories: ["Jan", "Feb"].map(String::from).to_vec(),
series: vec![series("Rate", &[1.0, 3.0], color, kind)],
..Default::default()
};
let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure);
let header_y = p
.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == "Jan" => Some(*y),
_ => None,
})
.unwrap();
let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count();
assert_eq!(key_circles, usize::from(marker), "{kind:?}");
let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y));
assert!(!key_box, "{kind:?} key is a line swatch");
}
}
-65
View File
@@ -162,43 +162,6 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
Some(serial as f64)
}
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
let serial = if month <= 1 { day } else { 31 + day };
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
}
(year, month, day)
}
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
/// or one before the epoch or after 9999-12-31.
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
match (sys, y, m, d) {
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
_ => {}
}
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
return None;
}
let base = match sys {
DateSystem::D1900 => UNIX_1899_12_30,
DateSystem::D1904 => UNIX_1904_01_01,
};
let serial = days_from_civil(y, m, d) - base;
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
}
/// Date/time from a serial. `None` for negative or too-large serials.
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
@@ -421,32 +384,4 @@ mod tests {
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
Ok(())
}
#[test]
fn iso_dates_count_real_days() {
let s = DateSystem::D1900;
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
for (serial, ymd) in
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
{
let d = datetime_from_serial(s, serial as f64).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
}
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
let s = DateSystem::D1904;
let d = datetime_from_serial(s, 0.5).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
}
}
+1 -1
View File
@@ -16,4 +16,4 @@ pub use addr::{
};
pub use date::DateSystem;
pub use region::Region;
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
-26
View File
@@ -49,19 +49,6 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
parse_numeric(s.trim(), sys).map(|(n, _)| n)
}
/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users
/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5,
/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse
/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+`
/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does.
pub fn starts_formula(input: &str) -> bool {
input.starts_with('=')
|| (input.len() > 1
&& input.starts_with(['+', '-'])
&& parse_number_text(input).is_none()
&& !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some()))
}
/// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs,
/// thousands separators, currency, percent, exponent, a parenthesised negative). Dates, times and
/// fractions kept as text are not flagged, as in Excel.
@@ -590,19 +577,6 @@ mod tests {
assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4"));
}
#[test]
fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() {
// #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did.
for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] {
assert!(starts_formula(s), "{s}");
}
// Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or
// apostrophe, `+` before a time and other text stay text.
for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] {
assert!(!starts_formula(s), "{s}");
}
}
#[test]
fn dates_and_times() {
assert_eq!(p("10/7/2026").value, Value::Number(46302.0));
-52
View File
@@ -434,16 +434,12 @@ fn secondary_weights(s: &str) -> impl Iterator<Item = u16> + '_ {
}
/// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last.
/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT,
/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2`
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
match (a, b) {
(Value::Empty, Value::Empty) => Ordering::Equal,
(Value::Empty, _) => Ordering::Greater,
(_, Value::Empty) => Ordering::Less,
(Value::Error(_), Value::Error(_)) => Ordering::Equal,
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
_ => compare(a, b),
}
}
@@ -501,31 +497,6 @@ pub fn sci_text(n: f64, sig: usize) -> String {
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
}
/// Longest text a cell can hold, in UTF-16 code units.
pub const MAX_TEXT_CHARS: usize = 32_767;
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
pub fn cap_text(mut s: String) -> String {
if s.len() > MAX_TEXT_CHARS {
let mut units = 0;
if let Some((i, _)) = s.char_indices().find(|(_, c)| {
units += c.len_utf16();
units > MAX_TEXT_CHARS
}) {
s.truncate(i);
}
}
s
}
/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through.
pub fn cap_value(v: Value) -> Value {
match v {
Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())),
v => v,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -609,16 +580,6 @@ mod tests {
assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater);
}
#[test]
fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() {
let face = "😀";
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS));
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS));
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face));
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1));
assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383));
}
#[test]
fn arabic_diacritics_sort_with_their_base_letter() {
assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less);
@@ -814,19 +775,6 @@ mod tests {
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
}
#[test]
fn sort_orders_numbers_exactly() {
let num = Value::Number;
let e = 0.1 + 0.2;
assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less);
assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater);
assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less);
assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal);
assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less);
// `=` keeps its 15-digit comparison.
assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal);
}
#[test]
fn arrays() -> Result<(), std::io::Error> {
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).ok_or_else(|| std::io::Error::other("valid array"))?;
-377
View File
@@ -1,377 +0,0 @@
//! Calculation benchmarks on fixed workbooks built in code (release build). Run through
//! `cargo xtask bench`, which builds this in release and compares against a saved baseline, or
//! directly: `cargo run --release -p gridcraft-engine --example bench -- [--quick] [--rows N]
//! [--reps N] [--filter NAME] [--json PATH]`.
//!
//! Every scenario builds its workbook untimed, runs one warm-up, then times `reps` runs of one
//! operation through `Session::execute` (so a timing includes what an edit costs the user: undo
//! history, graph update and recalculation). Results are checked so a scenario that silently
//! stopped recalculating fails instead of getting fast.
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
use std::time::{Duration, Instant};
use gridcraft_core::{CellRef, Value};
use gridcraft_engine::Session;
use serde_json::{Value as Json, json};
struct Cfg {
rows: usize,
reps: usize,
filter: Option<String>,
}
struct Outcome {
name: &'static str,
what: String,
times: Vec<Duration>,
cells: usize,
}
type R<T> = Result<T, String>;
/// A scenario: its name and the function that runs it.
type Scenario = (&'static str, fn(&Cfg) -> R<Outcome>);
fn main() -> std::process::ExitCode {
match run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("bench: {e}");
std::process::ExitCode::FAILURE
}
}
}
fn run() -> R<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let quick = args.iter().any(|a| a == "--quick");
let cfg = Cfg {
rows: count(flag("--rows"), "--rows")?.unwrap_or(if quick { 10_000 } else { 100_000 }).max(200),
reps: count(flag("--reps"), "--reps")?.unwrap_or(if quick { 3 } else { 7 }).max(1),
filter: flag("--filter"),
};
let scenarios: [Scenario; 10] = [
("edit.chain", edit_chain),
("edit.fanout", edit_fanout),
("edit.sliding", edit_sliding),
("edit.sumifs", edit_sumifs),
("edit.lookup", edit_lookup),
("enter.formulas", enter_formulas),
("recalc.full", recalc_full),
("data.sort", data_sort),
("xlsx.save", xlsx_save),
("xlsx.open", xlsx_open),
];
println!("GridCraft calc bench: {} rows, {} reps (median / min)\n", cfg.rows, cfg.reps);
println!("{:<16} {:>10} {:>10} {:>9} workload", "scenario", "median", "min", "cells");
let mut results = Vec::new();
// A failed scenario is reported and the others still run, so one regression doesn't hide
// the numbers for everything else.
let mut failed = Vec::new();
let selected: Vec<_> = scenarios.into_iter().filter(|(name, _)| cfg.filter.as_deref().is_none_or(|p| name.contains(p))).collect();
if selected.is_empty() {
// An empty run would otherwise save as a baseline with nothing in it.
return Err(format!("--filter {} matches no scenario", cfg.filter.as_deref().unwrap_or("")));
}
for (name, f) in selected {
let o = match f(&cfg) {
Ok(o) => o,
Err(e) => {
println!("{name:<16} {:>10} {e}", "FAILED");
failed.push(name);
continue;
}
};
let (med, min) = stats(&o.times);
let cells = if o.cells == 0 { "-".to_string() } else { o.cells.to_string() };
println!("{:<16} {:>10} {:>10} {:>9} {}", o.name, ms(med), ms(min), cells, o.what);
results.push(json!({"name": o.name, "what": o.what, "median_ms": med, "min_ms": min, "cells": o.cells}));
}
if let Some(path) = flag("--json") {
let out = json!({"rows": cfg.rows, "reps": cfg.reps, "results": results, "failed": failed});
let text = serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?;
std::fs::write(&path, text).map_err(|e| format!("{path}: {e}"))?;
}
if failed.is_empty() { Ok(()) } else { Err(format!("{} scenario(s) failed: {}", failed.len(), failed.join(", "))) }
}
fn stats(times: &[Duration]) -> (f64, f64) {
let mut v: Vec<f64> = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect();
v.sort_by(f64::total_cmp);
// An even count averages the two middle samples.
let mid = v.len() / 2;
let med = match (v.len() % 2, v.get(mid.wrapping_sub(1)), v.get(mid)) {
(0, Some(a), Some(b)) => (a + b) / 2.0,
(_, _, Some(m)) => *m,
_ => 0.0,
};
(med, v.first().copied().unwrap_or(0.0))
}
fn ms(v: f64) -> String {
if v >= 100.0 { format!("{v:.0} ms") } else { format!("{v:.2} ms") }
}
fn exec(s: &mut Session, cmd: &str, p: Json) -> R<Json> {
s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}"))
}
/// A count flag's value; one that isn't a number is an error, not the default.
fn count(v: Option<String>, name: &str) -> R<Option<usize>> {
v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose()
}
fn session() -> R<Session> {
let mut s = Session::new();
s.new_workbook();
Ok(s)
}
/// Writes `rows` rows starting at `col` row 1, `make(i)` giving row i (0-based), in chunks.
fn fill(s: &mut Session, col: &str, rows: usize, make: impl Fn(usize) -> Json) -> R<()> {
let chunk = 10_000;
let mut r = 0;
while r < rows {
let n = chunk.min(rows - r);
let vals: Vec<Json> = (r..r + n).map(&make).collect();
exec(s, "range.setValues", json!({"range": format!("{col}{}", r + 1), "values": vals}))?;
r += n;
}
Ok(())
}
fn num(s: &Session, at: &str) -> R<f64> {
let c = CellRef::parse(at).ok_or_else(|| format!("bad ref {at}"))?;
let d = s.doc().map_err(|e| e.to_string())?;
match d.wb.sheet(0).map(|sh| sh.value(c)) {
Some(Value::Number(n)) => Ok(n),
other => Err(format!("{at} = {other:?}, expected a number")),
}
}
fn expect(s: &Session, at: &str, want: f64) -> R<()> {
let got = num(s, at)?;
if (got - want).abs() <= 1e-6 * want.abs().max(1.0) { Ok(()) } else { Err(format!("{at} = {got}, expected {want}")) }
}
fn recalc_cells(s: &Session) -> usize {
s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0)
}
/// Runs a warm-up then `reps` timed calls of `op(rep)`, then `check(rep)` (untimed) after each.
fn time(
cfg: &Cfg,
s: &mut Session,
op: impl FnMut(&mut Session, usize) -> R<()>,
check: impl Fn(&Session, usize) -> R<()>,
) -> R<(Vec<Duration>, usize)> {
time_prepared(cfg, s, |_| Ok(()), op, check)
}
/// [`time`] with `prep` run (untimed) before each call, to put back the state `op` starts from.
fn time_prepared(
cfg: &Cfg,
s: &mut Session,
mut prep: impl FnMut(&mut Session) -> R<()>,
mut op: impl FnMut(&mut Session, usize) -> R<()>,
check: impl Fn(&Session, usize) -> R<()>,
) -> R<(Vec<Duration>, usize)> {
let mut times = Vec::with_capacity(cfg.reps);
let mut cells = 0;
for rep in 0..=cfg.reps {
prep(s)?;
let t = Instant::now();
op(s, rep)?;
let dt = t.elapsed();
check(s, rep)?;
cells = recalc_cells(s);
if rep > 0 {
times.push(dt);
}
}
Ok((times, cells))
}
/// Value typed into A1 on rep `r`: alternates so every rep changes something.
fn a1(r: usize) -> f64 {
(r % 2 + 2) as f64
}
/// A running sum `B[n] = B[n-1] + A[n]`: one edit at the top recalculates a dependency chain
/// `rows` deep.
fn edit_chain(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |_| json!([1]))?;
fill(&mut s, "B", n, |i| json!([if i == 0 { "=A1".to_string() } else { format!("=B{i}+A{}", i + 1) }]))?;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{n}"), (n - 1) as f64 + a1(r)),
)?;
Ok(Outcome { name: "edit.chain", what: format!("edit A1 under a {n}-deep running sum"), times, cells })
}
/// `rows` formulas that each read `$A$1`: one edit, a wide and shallow dirty set.
fn edit_fanout(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
exec(&mut s, "cell.set", json!({"cell": "A1", "input": "1"}))?;
fill(&mut s, "B", n, |i| json!([format!("=$A$1*{}", i + 1)]))?;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{n}"), a1(r) * n as f64),
)?;
Ok(Outcome { name: "edit.fanout", what: format!("edit $A$1 read by {n} formulas"), times, cells })
}
/// `rows` overlapping 100-row window sums; an edit in the middle dirties ~100 of them, so this
/// measures the range index lookup, not evaluation.
fn edit_sliding(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n + 99, |_| json!([1]))?;
fill(&mut s, "B", n, |i| json!([format!("=SUM(A{}:A{})", i + 1, i + 100)]))?;
let mid = n / 2;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": format!("A{mid}"), "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{mid}"), 99.0 + a1(r)),
)?;
Ok(Outcome { name: "edit.sliding", what: format!("edit one cell under {n} 100-row SUM windows"), times, cells })
}
/// 100 whole-column SUMIFS over `rows` rows of data, all dirtied by one data edit.
fn edit_sumifs(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?;
fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?;
// Rows whose category is 0 (i % 100 == 0), A1 among them.
let per = n.div_ceil(100) as f64;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, "D1", per - 1.0 + a1(r)),
)?;
Ok(Outcome { name: "edit.sumifs", what: format!("edit data under 100 SUMIFS(A:A,B:B,k) over {n} rows"), times, cells })
}
/// 100 exact-match XLOOKUPs over whole columns of `rows` keys, all dirtied by one key edit.
fn edit_lookup(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?;
let step = n / 100;
fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B,0)", (k + 1) * step)]))?;
let last = (2 * 100 * step) as f64;
let (times, cells) = time(
cfg,
&mut s,
// D1 looks up the key in A{step}: removing it (-step) makes D1 fall back to 0, putting it
// back finds it again. Every lookup reads A:A, so all 100 recalculate either way.
|s, r| {
let key = if r % 2 == 0 { format!("-{step}") } else { step.to_string() };
exec(s, "cell.set", json!({"cell": format!("A{step}"), "input": key})).map(drop)
},
|s, r| {
expect(s, "D1", if r % 2 == 0 { 0.0 } else { (2 * step) as f64 })?;
expect(s, "D100", last)
},
)?;
Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells })
}
/// Entering `rows` formulas in one command: parse, graph insertion and first evaluation.
fn enter_formulas(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?;
let vals: Vec<Json> = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect();
let (times, cells) = time_prepared(
cfg,
&mut s,
// Each run enters the formulas into empty cells, not over the previous run's.
|s| exec(s, "edit.clearAll", json!({"range": format!("B1:B{n}")})).map(drop),
|s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop),
|s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0),
)?;
Ok(Outcome { name: "enter.formulas", what: format!("enter {n} formulas =An*2+1 in one paste"), times, cells })
}
/// A model with 3 formulas per row (arithmetic and a row SUM), recalculated in full.
fn model(n: usize) -> R<Session> {
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i % 97) as f64, format!("=A{}*2", i + 1), format!("=B{0}+A{0}", i + 1), format!("=SUM(A{0}:C{0})", i + 1)]))?;
Ok(s)
}
fn recalc_full(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
// Manual calculation, and A[n] changed (untimed) before each run, so D[n] is stale until
// Calculate Now recalculates: a Calculate Now that did nothing fails the check.
exec(&mut s, "formulas.calculationOptions", json!({"mode": "manual"}))?;
let mut rep = 0;
let (times, cells) = time_prepared(
cfg,
&mut s,
|s| {
rep += 1;
exec(s, "cell.set", json!({"cell": format!("A{n}"), "input": (100 + rep).to_string()})).map(drop)
},
|s, _| exec(s, "formulas.calculateNow", json!({})).map(drop),
|s, r| expect(s, &format!("D{n}"), (101 + r) as f64 * 6.0),
)?;
Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells })
}
fn data_sort(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([format!("Item {i}"), (i % 97) as f64, ((i * 7919) % 1000) as f64]))?;
let (times, _) = time(
cfg,
&mut s,
|s, r| {
let cmd = if r % 2 == 0 { "data.sortDescending" } else { "data.sortAscending" };
exec(s, cmd, json!({"range": format!("A1:C{n}"), "column": "B"})).map(drop)
},
|s, r| expect(s, "B1", if r % 2 == 0 { 96.0 } else { 0.0 }),
)?;
// A sort with no formulas recalculates nothing; 0 shows as "-".
Ok(Outcome { name: "data.sort", what: format!("sort {n} rows x 3 columns by a numeric key"), times, cells: 0 })
}
fn save_bytes(s: &mut Session) -> R<String> {
let r = exec(s, "file.saveBytes", json!({"format": "xlsx"}))?;
r.get("base64").and_then(Json::as_str).map(str::to_string).ok_or_else(|| "file.saveBytes: no base64".to_string())
}
fn xlsx_save(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
let (times, _) = time(cfg, &mut s, |s, _| save_bytes(s).map(drop), |_, _| Ok(()))?;
Ok(Outcome { name: "xlsx.save", what: format!("save the {n}-row model as XLSX"), times, cells: 0 })
}
fn xlsx_open(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
let b64 = save_bytes(&mut s)?;
let last = ((n - 1) % 97) as f64 * 6.0;
let (times, cells) = time(
cfg,
&mut s,
|s, _| exec(s, "file.open", json!({"name": "bench.xlsx", "base64": b64})).map(drop),
|s, _| expect(s, &format!("D{n}"), last),
)?;
Ok(Outcome { name: "xlsx.open", what: format!("open the {n}-row model from XLSX (with full recalc)"), times, cells })
}
+60
View File
@@ -0,0 +1,60 @@
//! Performance scenarios on large workbooks (release build):
//! `cargo run --release -p gridcraft-engine --example perf -- [rows]`
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
use std::time::Instant;
use gridcraft_engine::Session;
use serde_json::json;
fn main() {
let rows: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
let mut s = Session::new();
s.new_workbook();
// Data: rows × 6 numeric columns, built through range.setValues in chunks.
let t = Instant::now();
let chunk = 10_000;
let mut r = 0;
while r < rows {
let n = chunk.min(rows - r);
let vals: Vec<serde_json::Value> = (0..n)
.map(|i| json!([format!("Item {}", r + i), (r + i) as f64, ((r + i) % 97) as f64, ((r + i) % 13) as f64 * 1.5, 1.0, 2.0]))
.collect();
s.execute("range.setValues", json!({"range": format!("A{}", r + 1), "values": vals})).expect("set");
r += n;
}
println!("fill {rows}x6 values: {:?}", t.elapsed());
// Formulas: G = B*C+D, H = running sum of G (chain).
let t = Instant::now();
s.execute("cell.set", json!({"cell": "G1", "input": "=B1*C1+D1"})).expect("g1");
s.execute("edit.autoFill", json!({"source": "G1", "target": format!("G1:G{rows}")})).expect("fill g");
println!("fill {rows} formulas G=B*C+D: {:?}", t.elapsed());
let t = Instant::now();
s.execute("cell.set", json!({"cell": "H1", "input": "=G1"})).expect("h1");
s.execute("cell.set", json!({"cell": "H2", "input": "=H1+G2"})).expect("h2");
s.execute("edit.autoFill", json!({"source": "H2", "target": format!("H2:H{rows}")})).expect("fill h");
println!("fill {rows} chained running-sum formulas: {:?}", t.elapsed());
let t = Instant::now();
s.execute("cell.set", json!({"cell": "J1", "input": format!("=SUM(G1:G{rows})")})).expect("sum");
s.execute("cell.set", json!({"cell": "J2", "input": "=SUMIFS(B:B,C:C,\">50\")"})).expect("sumifs");
s.execute("cell.set", json!({"cell": "J3", "input": "=XLOOKUP(\"Item 77777\",A:A,B:B)"})).expect("xlookup");
println!("aggregate formulas: {:?}", t.elapsed());
// Edit at the top: everything below recalculates.
let t = Instant::now();
s.execute("cell.set", json!({"cell": "B1", "input": "5"})).expect("edit");
println!("edit B1 → recalc {} cells: {:?}", s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0), t.elapsed());
let t = Instant::now();
s.execute("data.sortDescending", json!({"range": format!("A1:F{rows}"), "column": "C"})).expect("sort");
println!("sort {rows} rows: {:?}", t.elapsed());
let t = Instant::now();
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).expect("save");
let b64 = r["base64"].as_str().unwrap_or("").to_string();
println!("save xlsx ({} bytes): {:?}", r["bytes"], t.elapsed());
let t = Instant::now();
s.execute("file.open", json!({"name": "big.xlsx", "base64": b64})).expect("open");
println!("open xlsx + full recalc: {:?}", t.elapsed());
let t = Instant::now();
s.execute("edit.undo", json!({})).ok();
println!("undo: {:?}", t.elapsed());
}
-2
View File
@@ -18,7 +18,6 @@ pub mod macros;
pub mod pivot;
pub mod print;
pub mod python;
pub mod quick_analysis;
pub mod review;
pub mod sheet;
pub mod slicer;
@@ -188,7 +187,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(forecast::specs());
v.extend(analysis::specs());
v.extend(print::specs());
v.extend(quick_analysis::specs());
v
})
}
+1 -1
View File
@@ -23,9 +23,9 @@ mod sort;
mod tools;
mod validation;
pub use filter::filter_values;
pub(crate) use filter::{apply_filter, grow_autofilter};
use filter::{clear_filter, filter_by, reapply, toggle_filter};
pub use filter::{filter_selection, filter_values};
use grouping::{detail, group, outline_settings, show_levels, subtotal};
pub use sort::sort_context;
use sort::{quick_sort, sort};
+80 -228
View File
@@ -1,9 +1,8 @@
use super::sort::sort_key;
use super::{
AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param,
data_target, edit, json,
current_region, data_target, edit, json,
};
use std::collections::{HashMap, HashSet};
// ---------------------------------------------------------------- filter
@@ -15,63 +14,14 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some());
let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone()));
if let Some(name) = in_table {
// An explicit range over part of the table is refused, as when installing a filter on it.
if p.get("range").is_some()
&& let Some(sh) = s.doc()?.wb.sheet(sheet)
&& let Some(t) = sh.tables.iter().find(|t| t.name == name)
&& t.range.intersects(&r)
&& !(t.header_row
&& t.range.start.row == r.start.row
&& t.range.contains(r.start)
&& t.range.contains(r.end)
&& r.start.col == t.range.start.col
&& r.end.col == t.range.end.col
&& t.data_range().is_none_or(|data| r.end.row >= data.end.row))
{
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
}
return edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let filtered: Vec<u32> = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect();
let mut cleared = false;
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
t.filter_button = !t.filter_button;
if !t.filter_button {
t.filter.clear();
// The sheet AutoFilter hosted on this table's header row is the table's filter too.
cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range));
}
}
if cleared {
sh.autofilter = None;
for r in filtered {
if let Some(info) = sh.rows.get_mut(&r) {
info.hidden = false;
}
}
// Rows another table's criteria hide stay hidden: evaluate each such table's saved
// criteria through the live filter, then hide the union once (a later table would
// unhide what an earlier one excluded) and take the filter off again.
let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> =
sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect();
let mut excluded: std::collections::HashSet<u32> = std::collections::HashSet::new();
for (range, criteria) in others {
if let Some(sh) = cx.wb.sheet_mut(sheet) {
sh.autofilter = Some(AutoFilter { range, criteria });
}
apply_filter(&mut cx.wb, sheet);
if let Some(sh) = cx.wb.sheet(sheet) {
excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r)));
}
}
if let Some(sh) = cx.wb.sheet_mut(sheet) {
sh.autofilter = None;
for r in excluded {
sh.rows.entry(r).or_default().hidden = true;
}
}
cx.structural = true;
}
Ok(Json::Null)
});
}
@@ -94,58 +44,19 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
}
/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection.
///
/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses
/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the
/// table's cells out of the region). Inside a table the filter covers the table from its header
/// row, which is saved as the table's own filter, and takes over the criteria the table already
/// had so there is one filter to save.
fn install_filter(s: &mut Session, p: &Json) -> Result<Json> {
let (sheet, mut r) = data_target(s, p, "data.filter")?;
{
// A selected header row filters the data below it (#201).
if p.get("range").is_none() && r.height() == 1 {
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() {
r = crate::selection::current_region_outside_tables(sh, d.selection.active);
}
// A selected header row filters the data below it (#201).
if p.get("range").is_none() && r.height() == 1 {
let region = match sh.table_at(r.start) {
Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range),
None => crate::selection::current_region_outside_tables(sh, r.start),
};
if region.end.row > r.end.row {
r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col));
}
}
}
let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
// The table whose header row the filter starts on, when it lies inside that table.
let host =
sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end));
if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) {
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
}
// A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them.
if let Some(t) = host.and_then(|i| sh.tables.get(i)) {
if t.data_range().is_some_and(|data| r.end.row < data.end.row) {
return Err(bad("data.filter", "filter the table's full data range"));
}
let shift = r.start.col.saturating_sub(t.range.start.col);
if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) {
return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width"));
let below = current_region(sh, r.start).end.row;
if below > r.end.row {
r = RangeRef::new(r.start, CellRef::new(below, r.end.col));
}
}
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let mut criteria = vec![];
if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) {
// The criteria are saved with the table only while its filter buttons are on.
t.filter_button = true;
let shift = r.start.col.saturating_sub(t.range.start.col);
criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect();
}
sh.autofilter = Some(AutoFilter { range: r, criteria });
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
Ok(json!({"filter": true, "range": r.a1()}))
})
}
@@ -270,18 +181,19 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) {
}
}
/// Statistics use the original range within the grid, regardless of the other active criteria.
fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap<usize, (Option<f64>, f64)> {
let r = af.range;
/// Hides rows of the autofilter range that fail any criterion.
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
let Some(sh) = wb.sheet(sheet) else { return };
let Some(af) = sh.autofilter.clone() else { return };
// An imported range can name rows past the grid; none of those exist to hide.
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
let mut hide = Vec::new();
// Precompute per-criterion top10 threshold and average once, not per row.
let mut col_stats = HashMap::new();
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
for (i, (off, c)) in af.criteria.iter().enumerate() {
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
let Some(col) = r.start.col.checked_add(*off) else { continue };
// Keep main's imported-range bound after extracting statistics from apply_filter.
let mut nums: Vec<f64> = (r.start.row.saturating_add(1)..=r.end.row.min(gridcraft_core::MAX_ROWS - 1))
.filter_map(|row| sh.value(CellRef::new(row, col)).as_f64())
.collect();
let col = r.start.col + off;
let mut nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::<f64>() / nums.len() as f64 };
let thr = match c {
FilterCriterion::Top10 { bottom, percent, count } => {
@@ -295,97 +207,59 @@ fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap<usize, (Option<f64>, f64
col_stats.insert(i, (thr, avg));
}
}
col_stats
}
/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query.
struct FilterMatcher<'a> {
wb: &'a Workbook,
sh: &'a Sheet,
af: &'a AutoFilter,
stats: HashMap<usize, (Option<f64>, f64)>,
values: HashMap<usize, HashSet<String>>,
}
impl<'a> FilterMatcher<'a> {
fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self {
let values = af
.criteria
.iter()
.enumerate()
.filter_map(|(i, (_, crit))| match crit {
FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())),
_ => None,
})
.collect();
Self { wb, sh, af, stats: filter_stats(sh, af), values }
}
fn row_matches(&self, row: u32, excluded_offset: Option<u32>) -> bool {
self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit))
}
fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool {
let Some(col) = self.af.range.start.col.checked_add(off) else { return true };
let c = CellRef::new(row, col);
let v = self.sh.value(c);
let text = crate::display::cell_text(self.wb, self.sh, c);
match crit {
FilterCriterion::Values { blanks, .. } => {
if filter_blank(&v) {
*blanks
} else {
self.values
.get(&i)
.is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase()))
}
}
FilterCriterion::Custom { a, b, and } => {
let x = custom_ok(&v, &text, &a.0, &a.1);
match b {
Some(b) => {
let y = custom_ok(&v, &text, &b.0, &b.1);
if *and { x && y } else { x || y }
}
None => x,
}
}
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) {
(Some(n), Some((thr, _))) => {
let thr = thr.unwrap_or(n);
if *bottom { n <= thr } else { n >= thr }
}
_ => false,
},
FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) {
(Some(n), Some((_, avg))) => {
if *above {
n > *avg
for row in r.start.row + 1..=r.end.row {
let mut visible = true;
for (i, (off, crit)) in af.criteria.iter().enumerate() {
let c = CellRef::new(row, r.start.col + off);
let v = sh.value(c);
let text = crate::display::cell_text(wb, sh, c);
let ok = match crit {
FilterCriterion::Values { values, blanks } => {
if filter_blank(&v) {
*blanks
} else {
n < *avg
values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display()))
}
}
_ => false,
},
FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col,
// Icon criteria are retained from files but cannot be evaluated yet.
FilterCriterion::Icon { .. } => true,
FilterCriterion::Custom { a, b, and } => {
let x = custom_ok(&v, &text, &a.0, &a.1);
match b {
Some(b) => {
let y = custom_ok(&v, &text, &b.0, &b.1);
if *and { x && y } else { x || y }
}
None => x,
}
}
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) {
(Some(n), Some((thr, _))) => {
let thr = thr.unwrap_or(n);
if *bottom { n <= thr } else { n >= thr }
}
_ => false,
},
FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) {
(Some(n), Some((_, avg))) => {
if *above {
n > *avg
} else {
n < *avg
}
}
_ => false,
},
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
// Icons are not evaluated here: the row keeps its current visibility.
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
};
if !ok {
visible = false;
break;
}
}
hide.push((row, !visible));
}
}
/// Hides rows of the autofilter range that fail any criterion.
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
let Some(sh) = wb.sheet(sheet) else { return };
let Some(af) = sh.autofilter.clone() else { return };
// An imported range can name rows past the grid; none of those exist to hide.
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
let matcher = FilterMatcher::new(wb, sh, &af);
// Reapplying a retained icon filter preserves visibility until icons can be evaluated.
let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. }));
let hide: Vec<_> =
(r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect();
let Some(shm) = wb.sheet_mut(sheet) else { return };
for (row, h) in hide {
if h {
@@ -420,52 +294,30 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
})
}
/// Distinct display values from rows matching the other columns' criteria.
/// The current criterion only determines checkboxes, so its unchecked alternatives stay available.
/// Distinct display values of a filter column (for the dropdown list).
pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> {
column_filter_values(wb, sheet, col, true)
}
/// Applies edited eligible choices to the whole column's checkbox state, retaining choices hidden by other filters.
pub fn filter_selection(wb: &Workbook, sheet: usize, col: u32, choices: &[(String, bool)]) -> Vec<(String, bool)> {
let mut edited = std::collections::BTreeMap::new();
for (value, on) in choices {
*edited.entry(value.to_ascii_lowercase()).or_insert(false) |= *on;
}
let mut selection = column_filter_values(wb, sheet, col, false);
for (value, on) in &mut selection {
if let Some(checked) = edited.get(&value.to_ascii_lowercase()) {
*on = *checked;
}
}
selection
}
fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bool) -> Vec<(String, bool)> {
let Some(sh) = wb.sheet(sheet) else { return vec![] };
let Some(af) = &sh.autofilter else { return vec![] };
if col < af.range.start.col || col > af.range.end.col {
return vec![];
}
let off = col - af.range.start.col;
let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off);
let matcher = FilterMatcher::new(wb, sh, af);
let off = col.saturating_sub(af.range.start.col);
let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c);
let mut seen = std::collections::BTreeMap::new();
// Imported end rows cannot add choices beyond the grid either.
for row in
af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)).min(gridcraft_core::MAX_ROWS - 1)
{
if eligible_only && !matcher.row_matches(row, Some(off)) {
continue;
}
for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) {
let c = CellRef::new(row, col);
let v = sh.value(c);
let blank = filter_blank(&v);
let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) };
let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit));
let on = match selected {
Some(FilterCriterion::Values { values, blanks }) => {
if blank {
*blanks
} else {
values.iter().any(|x| x.eq_ignore_ascii_case(&t))
}
}
_ => true,
};
let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) };
// One choice can represent rows with different colors; keep any matching row checked.
*seen.entry((key, t)).or_insert(false) |= on;
seen.entry((key, t)).or_insert(on);
}
let mut values: Vec<_> = seen.into_iter().collect();
values.sort_by(|((a, ta), _), ((b, tb), _)| {
+1 -3
View File
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
"AutoFill",
[],
None,
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)",
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)",
has_doc,
auto_fill
),
@@ -206,7 +206,6 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
d.selection = e.selection;
// Step by step: a rename and a new sheet undone together match up only one step apart.
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
@@ -228,7 +227,6 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
d.wb = e.wb;
d.selection = e.selection;
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
+17 -67
View File
@@ -8,12 +8,14 @@ use super::{
/// Typing `=PY(` doesn't make a Python cell; this says what does.
pub(crate) const PY_FORMULA: &str = "Python cells are made with the python.set command (the code as `code`), not by typing =PY(…).";
/// Whether typing `input` into a cell is meant as a formula: `=…`, or `+…`/`-…` when the entry
/// isn't a number on its own, as Excel takes `+5+4` and `+SUM(1)` (see
/// [`gridcraft_core::parse::starts_formula`]). A `+…`/`-…` entry that doesn't parse as a formula
/// still enters as text (`--`), see [`input_to_cell`].
/// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or
/// a parenthesis (not a number), as Excel takes `+SUM(1)`.
pub(crate) fn is_formula_input(input: &str) -> bool {
gridcraft_core::parse::starts_formula(input)
input.starts_with('=')
|| (input.len() > 1
&& (input.starts_with('+') || input.starts_with('-'))
&& gridcraft_core::parse::parse_number_text(input).is_none()
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('))
}
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
@@ -27,21 +29,13 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
}
let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@";
if fmt_is_text {
return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style, py: None }));
return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None }));
}
let is_formula = is_formula_input(input);
if is_formula && gridcraft_model::python::is_py_formula(input) {
return Err(EngineError::Other(PY_FORMULA.into()));
}
// As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`)
// and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused.
if is_formula
&& !input.starts_with('=')
&& let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb)
{
return Ok(cell);
}
if input.starts_with('=') {
if is_formula {
let body = input.strip_prefix('=').unwrap_or(input);
let expr = wb.name_call_case(parse_typed_formula(body)?);
check_arg_counts(&expr)?;
@@ -71,8 +65,6 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
return Ok(Some(cell));
}
let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system);
// Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped).
parsed.value = gridcraft_core::cap_value(parsed.value);
// Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already
// formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions.
if parsed.format.is_none()
@@ -151,66 +143,24 @@ pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
// the cell; a cell elsewhere (or on another sheet) gets a one-cell array.
let selected = cx.sel.current();
let range = if sheet == active_sheet && selected.contains(at) { selected } else { RangeRef::cell(at) };
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
// Excel forms no array from a constant: every cell of the selection takes the value.
if cell.formula.is_none() && !range.is_single() {
if range.count() > crate::fill::MAX_FILL_CELLS {
return Err(EngineError::Other("That selection is too large to fill.".into()));
}
let mut by_style: std::collections::HashMap<StyleId, Option<Cell>> = std::collections::HashMap::new();
for c in range.iter() {
let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default();
let filled = match by_style.get(&style) {
Some(filled) => filled.clone(),
None => {
let filled = input_to_cell(&input, sheet, c, &mut cx.wb)?;
by_style.insert(style, filled.clone());
filled
}
};
let sh = cx.sheet_mut(sheet)?;
match filled {
Some(f) => {
sh.set_cell(c, f);
crate::cmd::data::grow_autofilter(sh, c);
}
None => {
sh.remove_cell(c);
}
}
cx.touch(sheet, c);
}
return Ok(Json::Null);
}
// A table header can't hold an array's value, and a table resizes under it.
if !range.is_single() && cx.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&range))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
if let Some(f) = cell.formula.as_mut() {
std::sync::Arc::make_mut(f).array = Some(range);
}
let sh = cx.sheet_mut(sheet)?;
// The array takes the whole range: other cells in it lose their contents. Walk the
// cells the sheet holds rather than every address, so a whole-column array clears
// all of its area, and mark each cleared cell so formulas reading it recalculate.
let cleared: Vec<(CellRef, StyleId)> =
sh.cells.iter_range(range).filter(|(c, x)| *c != range.start && x.has_content()).map(|(c, x)| (c, x.style)).collect();
for &(c, style) in &cleared {
sh.set_cell(c, Cell { style, ..Cell::default() });
// The array takes the whole range: other cells in it lose their contents.
for c in range.iter().skip(1).take(1_000_000) {
if let Some(old) = sh.cells.get(c).filter(|x| x.has_content()) {
let style = old.style;
sh.set_cell(c, Cell { style, ..Cell::default() });
}
}
sh.set_cell(range.start, cell);
cx.touch(sheet, range.start);
// The array's results land in every cell of the range, stored or not, so readers of
// an empty result cell need the touch too. A huge range marks only the cells it held.
if range.count() <= 1_000_000 {
for c in range.iter() {
cx.touch(sheet, c);
}
} else {
for (c, _) in cleared {
cx.touch(sheet, c);
}
}
return Ok(Json::Null);
}
let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?;
@@ -319,7 +269,7 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
}
Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style, py: None })
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None })
}
}
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
-2
View File
@@ -52,8 +52,6 @@ pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
"weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday),
"months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month),
"years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year),
"linearTrend" => crate::fill::FillMode::LinearTrend,
"growthTrend" => crate::fill::FillMode::GrowthTrend,
_ => crate::fill::FillMode::Series,
};
if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS {
+2 -39
View File
@@ -76,34 +76,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
return Err(EngineError::Other("Too many cells to paste as links at once.".into()));
}
let same_doc = s.doc()?.uid == clip.doc_uid;
// A cut in this workbook moves its cells: the source is emptied before the destination is
// written. As in Excel, it moves only as a plain Paste onto one cell or an area of its own size
// and shape. Every other way (a Paste Special option, tiling over a larger or differently shaped
// area, a row the filter hides) would write the cut cells somewhere other than one place, or not
// at all, after their source was gone, so it is refused here, before anything changes, and the
// cut stays pending.
let cut_move = clip.cut && same_doc;
if cut_move {
let plain = what == What::All && !link && !skip_blanks && !transpose && op == "none";
if !plain {
return Err(EngineError::Other("Cut cells can only be pasted with Paste. To use Paste Special, copy them instead.".into()));
}
let anchored = cell_param_on(s, p, "at", dest_sheet)?.is_some() || sel.is_single();
if !anchored && (sel.height() != h || sel.width() != w) {
return Err(EngineError::Other(
"The cut cells and the paste area aren't the same size and shape: select one cell, or an area the size of the cut cells.".into(),
));
}
// The rows the cut itself would land on, whatever the paste would skip: an anchored or
// taller block is pasted straight down, so `skip_rows` (which only a tiled single row uses)
// can't tell whether it would write into a hidden row.
if let Some(end) = at.offset(i64::from(h) - 1, i64::from(w) - 1) {
let dest = RangeRef::new(at, end);
if s.doc()?.wb.sheet(dest_sheet).is_some_and(|sh| !super::filtered_rows(sh, dest).is_empty()) {
return Err(EngineError::Other("The cut area can't be pasted into rows the filter hides.".into()));
}
}
}
let cut_move = clip.cut && same_doc && what == What::All;
let src_wb = clip.wb.clone();
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
@@ -235,12 +208,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
moved.dynamic = f.dynamic;
return Some(std::sync::Arc::new(moved));
}
let moved = if transpose {
// A transposed paste turns the references instead of shifting them (#2450).
gridcraft_formula::adjust::transpose_relative(e, sc, dest)
} else {
gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64)
};
let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) }))
};
let moved_py = |cell: &Cell| -> Result<Option<std::sync::Arc<gridcraft_model::PyCode>>> {
@@ -421,11 +389,6 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
let nm = RangeRef::new(a, b);
let sh = cx.sheet_mut(dest_sheet)?;
// A table can't hold merged cells (Excel removes the table on open): the
// cells are pasted there unmerged.
if sh.tables.iter().any(|t| t.range.intersects(&nm)) {
continue;
}
sh.merges.retain(|x| !x.intersects(&nm));
sh.merges.push(nm);
}
-7
View File
@@ -52,13 +52,6 @@ impl crate::DocState {
// View state: set in place, so the workbook is neither copied nor made dirty.
self.wb.set_active_sheet(i);
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
// A sheet's first visit starts at A1, which may be part of a merged cell: take it whole,
// as a click would (#1348). A selection the sheet remembers comes back as it was.
if self.selection == crate::Selection::default()
&& let Some(sh) = self.wb.sheet(i)
{
self.selection.expand_merges(sh);
}
}
}
-194
View File
@@ -148,27 +148,6 @@ fn go_to_keeps_the_references_entered_newest_first() {
assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}");
}
#[test]
fn cell_set_cuts_text_to_32767_characters() {
// Excel cuts a 40,000-character entry to 32,767; a formula is left alone.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap();
// An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text.
s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap();
s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
for at in ["B1", "C1"] {
assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}");
}
assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767));
assert_eq!(get(&mut s, "A2"), json!(32767.0));
s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap();
assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766));
}
#[test]
fn cell_set_takes_numbers_for_input_and_value() {
// #697: a JSON number for `input` used to clear the cell instead of entering it.
@@ -229,15 +208,6 @@ fn set_values_can_store_strings_as_the_text_they_are() {
assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err());
// A line break still turns on Wrap Text.
s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap();
// Text stored as given still stops at Excel's 32,767-character cell limit.
let long = "x".repeat(40_000);
s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap();
let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count()));
assert_eq!(len.flatten(), Some(32_767));
s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap();
let emoji_len =
s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count()));
assert_eq!(emoji_len.flatten(), Some(32_766));
assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo"));
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
@@ -344,137 +314,6 @@ fn an_array_entered_outside_the_selection_covers_only_its_cell() {
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
}
/// The value a full recalculation from scratch gives `a1` on the active sheet.
fn fully_recalculated(s: &Session, a1: &str) -> Value {
let mut fresh = (*s.doc().unwrap().wb).clone();
gridcraft_calc::Calc::new().recalc_all(&mut fresh);
fresh.active().unwrap().value(CellRef::parse(a1).unwrap())
}
#[test]
fn array_entering_a_constant_recalculates_readers_of_the_cells_it_fills() {
// Found by the command-sequence fuzzer (seeds 4, 1213): only the array's first cell was
// marked changed, so formulas reading the cells it cleared kept their old values.
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[5, 6, "=B1+1"]]})).unwrap();
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "7", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
// Excel fills both cells with the constant and forms no array.
for a in ["A1", "B1"] {
let c = sh.cell(CellRef::parse(a).unwrap()).unwrap();
assert_eq!(c.value, Value::number(7.0));
assert!(c.formula.is_none());
}
assert_eq!(sh.value(CellRef::parse("C1").unwrap()), Value::number(8.0));
// The fuzzer's minimal repro on the budget sample.
let mut s = Session::new();
s.execute("file.new", json!({"sample": "budget"})).unwrap();
s.execute("selection.set", json!({"active": "C5", "range": "C5:D5"})).unwrap();
s.execute("cell.set", json!({"array": true, "cell": "C5", "input": "7"})).unwrap();
let in_memory = s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D15").unwrap());
assert_eq!(in_memory, fully_recalculated(&s, "D15"));
}
#[test]
fn array_entering_a_constant_grows_an_autofilter_below_it() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap();
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
s.execute("selection.set", json!({"range": "A4:A5"})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "new", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.autofilter.as_ref().map(|f| f.range.a1()), Some("A1:B5".to_string()));
}
#[test]
fn array_entering_a_formula_fills_every_cell_as_an_array() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A2", "input": "5"})).unwrap();
for (input, want) in [("=1", 1.0), ("=A2", 5.0)] {
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": input, "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
for a in ["A1", "B1"] {
assert_eq!(sh.value(CellRef::parse(a).unwrap()), Value::number(want), "{input} {a}");
}
let f = sh.cell(CellRef::parse("A1").unwrap()).and_then(|c| c.formula.clone()).unwrap();
assert_eq!(f.array, Some(RangeRef::parse("A1:B1").unwrap()));
}
}
#[test]
fn readers_of_an_empty_array_result_cell_see_its_result() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1", "input": "=B1+1"})).unwrap();
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "=5", "array": true})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D1").unwrap()), Value::number(6.0));
assert_eq!(fully_recalculated(&s, "D1"), Value::number(6.0));
}
#[test]
fn a_whole_column_constant_fills_its_whole_area() {
// The loop stopped after a million addresses, so cells further down the column kept
// their old content (and their readers weren't recalculated).
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
s.execute("selection.set", json!({"active": "D1", "range": "D:D"})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "1", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::number(1.0));
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(2.0));
assert_eq!(fully_recalculated(&s, "F1"), Value::number(2.0));
}
#[test]
fn clearing_more_than_a_million_cells_recalculates_readers_of_all_of_them() {
// Clear marked only the first million addresses of the range as changed, so formulas
// reading a cleared cell further down kept its old value.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
s.execute("edit.clearContents", json!({"range": "D:D"})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::Empty);
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(1.0));
}
#[test]
fn clearing_a_spill_recalculates_readers_of_its_spilled_cells() {
// Clear marks only the cells the sheet holds; a spill's other cells go with its anchor.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(5)"})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": "=A3+1"})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(4.0));
s.execute("edit.clearContents", json!({"range": "A1:A5"})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(1.0));
assert_eq!(fully_recalculated(&s, "C1"), Value::number(1.0));
}
#[test]
fn readers_of_an_array_formulas_cells_see_its_results() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B2", "values": [[1], [2]]})).unwrap();
s.execute("cell.set", json!({"cell": "C3", "input": "100"})).unwrap();
s.execute("cell.set", json!({"cell": "E1", "input": "=C3+C4+1"})).unwrap();
s.execute("selection.set", json!({"range": "C2:C4"})).unwrap();
s.execute("cell.set", json!({"cell": "C2", "input": "=B2:B3*2", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("E1").unwrap()), fully_recalculated(&s, "E1"));
}
#[test]
fn wildcards() {
assert!(wildcard("hello", "h*o"));
@@ -636,39 +475,6 @@ fn cut_paste_that_overflows_the_grid_moves_nothing() {
assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0));
}
#[test]
fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() {
// #2450: the values moved but the formula kept the offset it had in the source column,
// so it read the cell above instead of the cell to its left.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap();
s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap();
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial");
assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap());
assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does");
assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it");
}
#[test]
fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() {
// Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $
// is left standing, and a whole column comes back as a range open to the sheet's edge.
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap();
s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap();
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap();
let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone();
assert_eq!(formula(&mut s, "C10"), "=C11+1");
assert_eq!(formula(&mut s, "D10"), "=$B$1");
assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)");
assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)");
}
#[test]
fn drag_and_drop_asks_before_replacing_data() {
// #3136: dragging column B's border onto column A replaced A without asking.
+18 -124
View File
@@ -1,5 +1,4 @@
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
use gridcraft_model::Cell;
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
@@ -12,85 +11,30 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
}
.ok_or_else(|| bad("table.resize", "select a cell in a table"))?;
edit(s, |cx| {
let wb = &cx.wb;
let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?;
let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?;
let sheet = cx.sheet_mut(si)?;
let headers: Vec<String> = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect();
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
if r.start.row != t.range.start.row || !r.intersects(&t.range) {
return Err(EngineError::Other(
"The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(),
));
}
// Like Excel, the new range can't take in another table, a merged area, a PivotTable or a
// multi-cell array formula (a spill is fine: it shows #SPILL! inside the table).
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
let mut cols = Vec::new();
for (i, h) in headers.iter().enumerate() {
let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() };
let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned();
cols.push(existing.unwrap_or(TableColumn {
name,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
xml: None,
}));
}
if sheet.merges.iter().any(|m| m.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap merged cells.".into()));
}
if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) {
return Err(EngineError::Other("A table can't overlap a PivotTable report.".into()));
}
if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
// Header text per new column (`None`: empty). Without a header row, a column that stays
// keeps its name.
let texts: Vec<Option<String>> = (r.start.col..=r.end.col)
.map(|c| {
if !t.header_row {
return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone());
}
let at = CellRef::new(r.start.row, c);
let v = sheet.value(at);
let text = match v.as_text() {
Some(x) => x.to_string(),
None => crate::display::value_text(wb, sheet, at),
};
(!text.trim().is_empty()).then_some(text)
})
.collect();
let names = resized_column_names(&texts);
let old = t.range;
let old_cols = t.columns.clone();
let header_row = t.header_row;
let mut cols = Vec::with_capacity(names.len());
for (c, name) in (r.start.col..=r.end.col).zip(&names) {
// A column that stays keeps its settings (totals, calculated formula): with a header
// row it's found by name, without one by position.
let existing = if header_row {
// A header that was normalized into a generated name keeps the settings of the
// column at its address, not of whichever column already has that name.
let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref());
if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) {
old_cols.get((c - old.start.col) as usize)
} else {
old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name))
}
} else if c >= old.start.col && c <= old.end.col {
old_cols.get((c - old.start.col) as usize)
} else {
None
};
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
});
}
let sheet = cx.sheet_mut(si)?;
if header_row {
// Headers hold constant text: a generated or de-duplicated name is written into its
// cell, so the header row and the column names never disagree.
for (c, col) in (r.start.col..=r.end.col).zip(&cols) {
let at = CellRef::new(r.start.row, c);
let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none());
if !constant_text {
let style = sheet.style_id(at);
sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() });
}
}
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
t.columns = cols;
t.range = r;
cx.structural = true;
@@ -98,56 +42,6 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Unique column names for a resized table, from each column's header text (`None` = empty), the
/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`,
/// compared without case), and an empty header continues a `ColumnN` neighbour on its left
/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free
/// `ColumnN`.
fn resized_column_names(texts: &[Option<String>]) -> Vec<String> {
use std::collections::{HashMap, HashSet};
let mut taken: HashSet<String> = HashSet::new();
let mut next_suffix: HashMap<String, u64> = HashMap::new();
// The lowest `ColumnN` not yet tried, so many empty headers stay linear.
let mut lowest = 1u64;
let mut names: Vec<String> = Vec::with_capacity(texts.len());
let dedupe = |base: &str, taken: &HashSet<String>, next_suffix: &mut HashMap<String, u64>| {
let k = next_suffix.entry(base.to_lowercase()).or_insert(2);
let mut n = base.to_string();
while taken.contains(&n.to_lowercase()) {
n = format!("{base}{k}");
*k = k.saturating_add(1);
}
n
};
for text in texts {
let name = match text {
Some(t) => dedupe(t, &taken, &mut next_suffix),
None => {
let left = names.last().and_then(|l| {
l.strip_prefix("Column")
.filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
.and_then(|d| d.parse::<u64>().ok())
});
match left {
Some(n) => {
let cand = format!("Column{}", n.saturating_add(1));
if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand }
}
None => {
while taken.contains(&format!("column{lowest}")) {
lowest = lowest.saturating_add(1);
}
format!("Column{lowest}")
}
}
}
};
taken.insert(name.to_lowercase());
names.push(name);
}
names
}
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
/// into a rectangle of billions of slots.
+3 -30
View File
@@ -3,12 +3,12 @@
use serde_json::{Value as Json, json};
use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param};
use crate::{DocState, EngineError};
use crate::DocState;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
@@ -59,19 +59,6 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
};
let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted;
let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?;
// A password to modify: the right one or a read-only open, or the workbook doesn't open.
let mut read_only = false;
if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) {
read_only = bool_param(p, "readOnly").unwrap_or(false);
match str_param(p, "modifyPassword") {
_ if read_only => {}
None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))),
Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => {
return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into()));
}
Some(_) => {}
}
}
wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir);
// What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but
// never a folder, so it reports `[name]Sheet` with none; an import reports the file it came
@@ -91,7 +78,7 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
// An import has no save target: ordinary Save must ask for a new destination. Neither does a
// workbook decrypted with its password, so Save never replaces the encrypted original with
// an unprotected copy.
let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).map(str::to_string);
let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string);
// Replace an untouched blank Book1 like Excel does.
if s.documents().len() == 1
&& s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty()))
@@ -100,9 +87,6 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
}
// Someone else may have made the file: its active content asks before it runs.
let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile);
if read_only {
doc.read_only_source = str_param(p, "path").map(str::to_string);
}
if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx {
doc.content_kind = Some(crate::io::FileKind::Xlsx);
}
@@ -122,14 +106,6 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
)
}
/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink).
fn same_file(a: &str, b: &str) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(x), Ok(y)) => x == y,
_ => a == b,
}
}
fn save(s: &mut Session, p: &Json) -> Result<Json> {
let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) {
Some(p) => p,
@@ -138,9 +114,6 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
return ok();
}
};
if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) {
return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file."));
}
// A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the
// document keeps its file and its unsaved changes.
if std::path::Path::new(&path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
-2
View File
@@ -439,8 +439,6 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
})
.collect();
sheet.charts.push(Chart {
+3 -246
View File
@@ -553,12 +553,7 @@ fn format_cells(s: &mut Session, p: &Json) -> Result<Json> {
{
*st = new;
}
})?;
// A number format set here widens columns as the ribbon's do (observed: Excel 16.0).
if patch.get("num_fmt").is_some() {
widen_for_numbers(s, p)?;
}
ok()
})
}
/// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the
@@ -642,11 +637,6 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let how =
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
// Excel has no merged cells in a table (a file with one loses the table when Excel opens it):
// merging there is refused, unmerging is still allowed.
if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) {
return Err(EngineError::Other("You can't merge cells in a table.".into()));
}
edit(s, |cx| {
let mut touched = Vec::new();
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
@@ -742,95 +732,9 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
set_fmt(s, p, &code)
}
/// How many stored cells [`widen_for_numbers`] looks at in one command.
const MAX_WIDEN_CELLS: usize = 1_000_000;
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
let nf = NumFmt::new(code);
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
widen_for_numbers(s, p)
}
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or
/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit,
/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
/// and columns never narrow.
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
if sh.show_formulas {
return Ok(Json::Null);
}
let targets: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&used)).collect();
// Merged areas over the targets as sorted row intervals per column, so each cell is checked
// with a binary search rather than a scan of every merge.
let mut merged: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
for m in sh.merges.iter().filter(|m| !m.is_single()) {
for x in targets.iter().filter_map(|r| m.intersection(r)) {
for col in x.start.col..=x.end.col {
merged.entry(col).or_default().push((m.start.row, m.end.row));
}
}
}
for v in merged.values_mut() {
v.sort_unstable();
v.dedup();
}
let in_merge = |c: CellRef| {
merged.get(&c.col).is_some_and(|v| {
let i = v.partition_point(|&(r0, _)| r0 <= c.row);
i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1)
})
};
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
// The stored cells looked at are capped, not the area: a sparse target as tall as the sheet
// still widens for the numbers it holds. Spilled values count as the grid shows them.
let mut budget = MAX_WIDEN_CELLS;
for r in &targets {
let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c));
for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) {
if budget == 0 {
break;
}
budget -= 1;
if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_)))
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|| in_merge(c)
{
continue;
}
let id = sh.style_id(c);
let st = cx.wb.styles.get(id);
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
continue;
}
let text = crate::display::cell_text(&cx.wb, sh, c);
let exact = measured.len() < EXACT_TEXT_WIDTHS;
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
Some(m) => m(t, &st.font, exact),
None => approx_text_width(t, st.font.size, st.font.bold),
});
let w = w + 6.0 + st.align.indent as f32 * 9.0;
let e = need.entry(c.col).or_insert(0.0);
*e = e.max(w);
}
}
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
let sh = cx.sheet_mut(sheet)?;
for (c, w) in widen {
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
}
Ok(Json::Null)
})
apply_style(s, p, |st| st.num_fmt = nf.clone())
}
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
@@ -915,8 +819,8 @@ mod sizes;
use cell_styles::cell_style;
pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style};
use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
pub use sizes::{approx_text_width, chars_to_points};
use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
#[cfg(test)]
mod tests {
@@ -952,112 +856,6 @@ mod tests {
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
}
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
let sh = s.active().unwrap().wb.active().unwrap();
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
}
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
#[test]
fn increase_decimal_widens_a_column_nobody_sized() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
let (w, custom) = col(&s, 0);
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
assert_eq!(text, "3.141592650");
assert!(w > default, "the column widens for {text}: {w} vs {default}");
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
assert!(!custom, "it isn't a width set by hand, so it can widen again");
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
let wide = col(&s, 0).0;
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
}
#[test]
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
for a in ["A1", "B1", "D1"] {
s.execute("home.comma", json!({"range": a})).unwrap();
}
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
let (default, _) = col(&s, 4);
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
assert!(!col(&s, 0).1);
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
let fitted = col(&s, 0).0;
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
}
fn book() -> (crate::Session, f32) {
let mut s = crate::Session::new();
s.new_workbook();
let (default, _) = col(&s, 0);
(s, default)
}
/// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area.
#[test]
fn a_sparse_target_widens_for_the_numbers_it_holds() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap();
s.execute("home.comma", json!({"range": "A:E"})).unwrap();
assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down");
}
/// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1.
#[test]
fn a_spilled_number_widens_its_column() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap();
s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap();
assert!(col(&s, 7).0 > default, "H widens for the value it shows");
}
/// A merged area keeps its columns; the cell beside it widens.
#[test]
fn a_merged_area_keeps_its_columns() {
let (mut s, default) = book();
s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap();
s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap();
s.execute("home.comma", json!({"range": "J1:L1"})).unwrap();
assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K");
assert!(col(&s, 11).0 > default, "L does");
}
#[test]
fn format_cells_widens_for_a_number_format_only() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap();
assert_eq!(col(&s, 1).0, default, "no number format, no widening");
s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap();
assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does");
assert!(!col(&s, 0).1);
}
#[test]
fn format_cells_takes_the_documented_keys() {
let mut s = crate::Session::new();
@@ -1072,47 +870,6 @@ mod tests {
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
}
/// A table draws its header row bold; AutoFit measures that, not the cell's own plain font.
#[test]
fn autofit_measures_a_table_header_in_the_table_style_font() {
let mut s = crate::Session::new();
s.new_workbook();
let heading = "Quarterly Revenue by Region";
s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap();
s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap();
let sh = s.active().unwrap().wb.active().unwrap();
let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1));
assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}");
}
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
#[test]
fn format_cells_sets_outlined_letters() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": true}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], true);
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": false}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], false);
}
/// The Format Cells dialog sends the active cell's whole style to every selected cell, so a
/// non-outlined active cell must clear outline on the others, as it does bold.
#[test]
fn format_cells_whole_style_clears_outline_on_the_selection() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "plain"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "hollow"})).unwrap();
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"outline": true, "bold": true}}})).unwrap();
let style = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"].clone();
s.execute("home.formatCells", json!({"range": "A1:B1", "style": style})).unwrap();
let font = s.execute("cell.get", json!({"cell": "B1"})).unwrap()["style"]["font"].clone();
assert_eq!((font["bold"].clone(), font["outline"].clone()), (json!(false), json!(false)));
}
#[test]
fn arabic_vowel_and_direction_marks_add_no_width() {
let plain = approx_text_width("محمد يدرس في المدرسة", 11.0, false);
+5 -12
View File
@@ -107,7 +107,6 @@ pub(super) fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w as f32);
e.hidden = w == 0.0;
e.custom = true;
}
}
Ok(Json::Null)
@@ -188,15 +187,14 @@ fn arabic_em(c: char) -> Option<f32> {
/// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a
/// quick measure so a huge column doesn't lay out every value.
pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000;
const EXACT_TEXT_WIDTHS: usize = 2_000;
pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let (si, lines) = line_targets(s, p, false)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
// Keyed by style and boldness: a table's style can make a cell bold (its header row).
let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap<String, f32>> = Default::default();
let mut measured: std::collections::HashMap<StyleId, std::collections::HashMap<String, f32>> = Default::default();
let mut distinct = 0usize;
// Selected columns, then one pass over the populated cells (the store is row-oriented, so a
// scan per column would revisit every row for each selected column, empty or not).
@@ -230,26 +228,22 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
}
let id = sh.style_id(cell);
let st = cx.wb.styles.get(id);
// The font as the grid draws the cell: in a table, the table style's (a bold
// header row), not only the cell's own.
let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font);
let font = table_font.as_ref().unwrap_or(&st.font);
let text = crate::display::cell_text(&cx.wb, sh, cell);
for line in text.lines() {
let w = match &measure {
Some(m) => {
let known = measured.entry((id, font.bold)).or_default();
let known = measured.entry(id).or_default();
match known.get(line) {
Some(w) => *w,
None => {
let w = m(line, font, distinct < EXACT_TEXT_WIDTHS);
let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS);
known.insert(line.to_owned(), w);
distinct += 1;
w
}
}
}
None => approx_text_width(line, font.size, font.bold),
None => approx_text_width(line, st.font.size, st.font.bold),
};
let w = w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell);
let max = maxes.entry(cell.col).or_insert(0.0);
@@ -264,7 +258,6 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w.ceil());
e.hidden = false;
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
}
Ok(Json::Null)
})
+3 -301
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Chart",
["Insert", "Charts"],
None,
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
@@ -217,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Conditional Formatting",
["Home", "Styles"],
None,
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
has_doc,
add_cf
),
@@ -227,7 +227,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Manage Rules…",
["Home", "Styles", "Conditional Formatting"],
None,
"{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}",
"{delete?: index, moveUp?: index, moveDown?: index}",
has_doc,
manage_cf
),
@@ -496,302 +496,4 @@ mod tests {
s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap();
s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap();
}
#[test]
fn colour_scale_thresholds_are_clamped_to_the_percent_range() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "percent", "value": -5, "color": "#112233"},
{"type": "percentile", "value": 150, "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Percent(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percentile(100.0), Color::Rgb(0x445566)),
(CfValueKind::Max, Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_reject_empty_formulas_and_unknown_types() {
let mut s = Session::new();
s.new_workbook();
let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}});
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "formula", "value": " ", "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("formula"), "{err}");
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "median", "value": 50, "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown stop type `median`"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn colour_scale_rejects_a_stops_value_that_is_not_an_array() {
let mut s = Session::new();
s.new_workbook();
// `stops` present but misshapen used to fall back to the default scale instead of erroring.
for stops in [json!({}), json!(null), json!("min")] {
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("`stops` must be an array"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule");
}
#[test]
fn colour_scale_formulas_are_stored_verbatim() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "formula", "value": "=$Z$1", "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into()));
}
#[test]
fn manage_rules_rejects_a_non_index_edit() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] {
let err = s
.execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("`edit` must be a rule index"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1));
}
#[test]
fn manage_rules_rejects_an_edit_past_the_last_rule() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
let err = s
.execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 1"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
// On a 32-bit target this used to cast to zero and replace the rule at index 0.
let err =
s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 4294967296"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_names_itself_in_a_style_error() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
// A style shared by both commands must name the one that was called.
let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}});
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(!err.contains("home.conditionalFormat"), "{err}");
let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
}
#[test]
fn manage_rules_names_itself_in_a_stop_count_error() {
let mut s = Session::new();
s.new_workbook();
let err = s
.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
}
#[test]
fn a_formula_rule_needs_a_formula_that_parses() {
let mut s = Session::new();
s.new_workbook();
// An empty box used to create a rule that never applies.
let err =
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string();
assert!(err.contains("formula is empty"), "{err}");
// `=C1>` used to be written as `<formula>C1&gt;</formula>`, which Excel refuses to open.
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}}))
.unwrap_err()
.to_string();
assert!(err.contains("invalid"), "{err}");
assert!(err.contains("does not parse"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored");
}
#[test]
fn an_invalid_formula_on_edit_leaves_the_rule_alone() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2");
}
#[test]
fn a_given_stop_value_must_be_a_number() {
let mut s = Session::new();
s.new_workbook();
for ty in ["num", "percent", "percentile"] {
let err = s
.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": ty, "value": "5", "color": "#112233"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{ty}: {err}");
assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}");
}
// A refused scale stores nothing.
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn an_omitted_stop_value_is_zero() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "num", "color": "#112233"},
{"type": "percent", "color": "#445566"},
{"type": "percentile", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Number(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percent(0.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(0.0), Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "num", "value": 5, "color": "#445566"},
{"type": "percentile", "value": 90, "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(
stops,
vec![
(CfValueKind::Min, Color::Rgb(0x112233)),
(CfValueKind::Number(5.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(90.0), Color::Rgb(0x778899)),
]
);
s.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
{"type": "max", "color": "#DEFDEF"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
}
}
-6
View File
@@ -46,8 +46,6 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
("bar", _) => ChartKind::BarClustered,
("line", "markers") => ChartKind::LineMarkers,
("line", "stacked") => ChartKind::LineStacked,
("line", "stacked100") => ChartKind::LineStacked100,
("line", "stacked100Markers") => ChartKind::LineStacked100Markers,
("line", _) => ChartKind::Line,
("pie", _) => ChartKind::Pie,
("doughnut", _) => ChartKind::Doughnut,
@@ -108,8 +106,6 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
});
}
} else {
@@ -126,8 +122,6 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
});
}
}
+82 -144
View File
@@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool {
/// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a
/// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than
/// dropped: dropped, it left a rule with an empty format that matches and shows nothing.
fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
fn cf_style_json(st: &Json) -> Result<Json> {
const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"];
let err = |m: String| bad(cmd, m);
let err = |m: String| bad("home.conditionalFormat", m);
let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) };
let mut st = obj.clone();
if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) {
@@ -103,40 +103,36 @@ fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> {
// Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1'
// only parses after several strips and would still be saved unparseable. (#1999 review)
let parsed = formula.strip_prefix('=').unwrap_or(formula);
// A rule with no formula never applies; the dialog also keeps OK disabled for it.
if parsed.trim().is_empty() {
return Err(bad(cmd, format!("the {what} formula is empty")));
}
if gridcraft_formula::parse(parsed).is_err() {
if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() {
return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file")));
}
Ok(())
}
fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
if let gridcraft_model::features::CfValueKind::Formula(f) = v {
check_cf_formula(cmd, what, f)?;
check_cf_formula("home.conditionalFormat", what, f)?;
}
Ok(())
}
fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
fn check_cf_rule(rule: &CfRule) -> Result<()> {
const CMD: &str = "home.conditionalFormat";
match rule {
CfRule::CellIs { a, b, .. } => {
check_cf_formula(cmd, "comparison value", a)?;
check_cf_formula(CMD, "comparison value", a)?;
if let Some(b) = b {
check_cf_formula(cmd, "second comparison value", b)?;
check_cf_formula(CMD, "second comparison value", b)?;
}
}
CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?,
CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?,
CfRule::DataBar { min, max, .. } => {
check_cf_value(cmd, "data bar minimum", min)?;
check_cf_value(cmd, "data bar maximum", max)?;
check_cf_value("data bar minimum", min)?;
check_cf_value("data bar maximum", max)?;
}
CfRule::ColorScale { stops } => {
for (kind, _) in stops {
check_cf_value(cmd, "color scale threshold", kind)?;
check_cf_value("color scale threshold", kind)?;
}
}
_ => {}
@@ -144,53 +140,41 @@ fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
Ok(())
}
fn cf_style(rule: &Json, cmd: &str) -> Result<Style> {
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
};
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
match rule.get("style") {
let style = Box::new(match rule.get("style") {
Some(st) if !st.is_null() => {
let st = cf_style_json(st, cmd)?;
let st = cf_style_json(st)?;
let base = serde_json::to_value(Style::default()).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad(cmd, e.to_string()))?)
serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad("home.conditionalFormat", e.to_string()))?
}
_ => Ok(preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText"))),
}
}
fn cf_value_kind(v: Option<&Json>, default: CfValueKind, cmd: &str) -> Result<CfValueKind> {
let Some(Json::Object(o)) = v else { return Ok(default) };
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
// A value that is given must be a number: a string used to be read as 0 without a word.
// Only an omitted `value` defaults to zero.
let number = || -> Result<f64> {
match o.get("value") {
None => Ok(0.0),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("the `{t}` stop's `value` must be a number, not {v}"))),
_ => preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText")),
});
let kind = g("type").unwrap_or_else(|| "cellIs".into());
let value_kind = |v: Option<&Json>, default: CfValueKind| -> CfValueKind {
match v {
Some(Json::Object(o)) => {
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
let val = o.get("value").and_then(Json::as_f64).unwrap_or(0.0);
match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
"percent" => CfValueKind::Percent(val),
"percentile" => CfValueKind::Percentile(val),
"formula" => CfValueKind::Formula(o.get("value").and_then(Json::as_str).unwrap_or("").into()),
_ => CfValueKind::Number(val),
}
}
_ => default,
}
};
Ok(match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
// The dialog clamps these to 0-100; engine callers get the same range.
"percent" => CfValueKind::Percent(number()?.clamp(0.0, 100.0)),
"percentile" => CfValueKind::Percentile(number()?.clamp(0.0, 100.0)),
"formula" => {
let f = o.get("value").and_then(Json::as_str).unwrap_or("");
if f.trim().is_empty() {
return Err(bad(cmd, "a formula stop needs a formula"));
}
// Stored exactly: the evaluator takes the formula as written.
CfValueKind::Formula(f.into())
}
"num" => CfValueKind::Number(number()?),
other => return Err(bad(cmd, format!("unknown stop type `{other}`"))),
})
}
fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
let style = Box::new(cf_style(rule, cmd)?);
let kind = g("type").unwrap_or_else(|| "cellIs".into());
match kind.as_str() {
let rule = match kind.as_str() {
"cellIs" => {
// Excel's file and VBA names (`lessThan`, …) are accepted too.
let op = match g("operator").as_deref().unwrap_or("greater") {
@@ -202,7 +186,7 @@ fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
"greater" | "greaterThan" => CfOperator::Greater,
other => return Err(bad(cmd, format!("unknown operator `{other}`"))),
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
};
let a = rule.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default();
let b = rule.get("value2").map(crate::cmd::edit::json_to_input);
@@ -217,85 +201,59 @@ fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
format!("\"{}\"", v.replace('"', "\"\""))
}
};
Ok(CfRule::CellIs { op, a: quote(a), b: b.map(quote), style })
CfRule::CellIs { op, a: quote(a), b: b.map(quote), style }
}
"expression" => Ok(CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style }),
"containsText" => Ok(CfRule::ContainsText { text: g("text").unwrap_or_default(), style }),
"notContainsText" => Ok(CfRule::NotContainsText { text: g("text").unwrap_or_default(), style }),
"beginsWith" => Ok(CfRule::BeginsWith { text: g("text").unwrap_or_default(), style }),
"endsWith" => Ok(CfRule::EndsWith { text: g("text").unwrap_or_default(), style }),
"blanks" => Ok(CfRule::Blanks { style }),
"noBlanks" => Ok(CfRule::NoBlanks { style }),
"errors" => Ok(CfRule::Errors { style }),
"noErrors" => Ok(CfRule::NoErrors { style }),
"duplicate" => Ok(CfRule::Duplicate { style }),
"unique" => Ok(CfRule::Unique { style }),
"top10" => Ok(CfRule::Top10 {
"expression" => CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style },
"containsText" => CfRule::ContainsText { text: g("text").unwrap_or_default(), style },
"notContainsText" => CfRule::NotContainsText { text: g("text").unwrap_or_default(), style },
"beginsWith" => CfRule::BeginsWith { text: g("text").unwrap_or_default(), style },
"endsWith" => CfRule::EndsWith { text: g("text").unwrap_or_default(), style },
"blanks" => CfRule::Blanks { style },
"noBlanks" => CfRule::NoBlanks { style },
"errors" => CfRule::Errors { style },
"noErrors" => CfRule::NoErrors { style },
"duplicate" => CfRule::Duplicate { style },
"unique" => CfRule::Unique { style },
"top10" => CfRule::Top10 {
bottom: rule.get("bottom").and_then(Json::as_bool).unwrap_or(false),
percent: rule.get("percent").and_then(Json::as_bool).unwrap_or(false),
rank: rule.get("rank").and_then(Json::as_u64).unwrap_or(10) as u32,
style,
}),
"aboveAverage" => {
Ok(CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style })
}
"timePeriod" => Ok(CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style }),
},
"aboveAverage" => CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style },
"timePeriod" => CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style },
"colorScale" => {
let stops = if let Some(stops) = rule.get("stops") {
// A present but misshapen `stops` is a mistake, not a request for `colors`.
let list = stops.as_array().ok_or_else(|| bad(cmd, "`stops` must be an array"))?;
let mut out = Vec::with_capacity(list.len().min(3));
for stop in list {
let color = crate::cmd::format::color_param(stop.get("color")).ok_or_else(|| bad(cmd, "a colour-scale stop needs a colour"))?;
out.push((cf_value_kind(Some(stop), CfValueKind::Min, cmd)?, color));
}
if !(2..=3).contains(&out.len()) {
return Err(bad(cmd, "a colour scale needs two or three stops"));
}
out
} else {
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
}
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
let stops = match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
};
Ok(CfRule::ColorScale { stops })
CfRule::ColorScale { stops }
}
"dataBar" => Ok(CfRule::DataBar {
min: cf_value_kind(rule.get("min"), CfValueKind::Min, cmd)?,
max: cf_value_kind(rule.get("max"), CfValueKind::Max, cmd)?,
"dataBar" => CfRule::DataBar {
min: value_kind(rule.get("min"), CfValueKind::Min),
max: value_kind(rule.get("max"), CfValueKind::Max),
color: crate::cmd::format::color_param(rule.get("color")).unwrap_or(Color::rgb(0x63, 0x8E, 0xC6)),
gradient: rule.get("gradient").and_then(Json::as_bool).unwrap_or(true),
show_value: true,
}),
"iconSet" => Ok(CfRule::IconSet {
},
"iconSet" => CfRule::IconSet {
set: g("set").unwrap_or_else(|| "3TrafficLights1".into()),
thresholds: vec![],
reverse: rule.get("reverse").and_then(Json::as_bool).unwrap_or(false),
show_value: true,
}),
other => Err(bad(cmd, format!("unknown rule type `{other}`"))),
}
}
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
},
other => return Err(bad("home.conditionalFormat", format!("unknown rule type `{other}`"))),
};
let rule = cf_rule(rule, "home.conditionalFormat")?;
check_cf_rule("home.conditionalFormat", &rule)?;
check_cf_rule(&rule)?;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let priority = sh.cond_formats.iter().map(|c| c.priority).max().unwrap_or(0) + 1;
@@ -337,33 +295,17 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() && p.get("edit").is_none() {
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
let list: Vec<Json> = s
.doc()?
.wb
.sheet(sheet)
.map(|sh| {
sh.cond_formats
.iter()
.map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule, "priority": c.priority}))
.collect()
sh.cond_formats.iter().map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule})).collect()
})
.unwrap_or_default();
return Ok(json!({"rules": list}));
}
let edited = match (p.get("edit"), p.get("rule")) {
(None, _) => None,
(Some(_), None) => return Err(bad("home.manageRules", "missing `rule` for an edit")),
(Some(e), Some(rule)) => {
let i = e.as_u64().ok_or_else(|| bad("home.manageRules", "`edit` must be a rule index"))?;
// A number too large for `usize` on this target names no rule: casting it would
// wrap to a real index and replace that rule instead of reporting out of range.
let i = usize::try_from(i).map_err(|_| bad("home.manageRules", format!("no conditional format at index {i}")))?;
let rule = cf_rule(rule, "home.manageRules")?;
check_cf_rule("home.manageRules", &rule)?;
Some((i, rule))
}
};
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
// The count is taken again after each step: a delete shortens the list.
@@ -372,10 +314,6 @@ pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
{
sh.cond_formats.remove(i);
}
if let Some((i, rule)) = edited {
let cf = sh.cond_formats.get_mut(i).ok_or_else(|| bad("home.manageRules", format!("no conditional format at index {i}")))?;
cf.rule = rule;
}
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
&& i > 0
&& i < sh.cond_formats.len()
+2 -2
View File
@@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
None => {
let sheet = target_sheet(s, p)?;
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
let Some(h) = crate::links::cell_link(&s.doc()?.wb, sheet, at) else {
let Some(h) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.hyperlinks.get(&at)) else {
return Err(EngineError::Other("There's no hyperlink in this cell.".into()));
};
h.target
h.target.clone()
}
};
match crate::links::classify(&target) {
-7
View File
@@ -74,13 +74,6 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
};
let sh = cx.sheet_mut(sheet)?;
// As in Excel, the table unmerges the merged cells it covers: a table can't hold them.
let merged = sh.merges.len();
sh.merges.retain(|m| !m.intersects(&r));
if sh.merges.len() != merged {
cx.structural = true;
}
let sh = cx.sheet_mut(sheet)?;
let mut names: Vec<String> = Vec::new();
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
// headers don't take cubic time.
+1 -1
View File
@@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
"style": style,
"merge": sh.merge_at(c).map(|m| m.a1()),
"comment": sh.comments.get(&c),
"hyperlink": crate::links::cell_link(&d.wb, sheet, c),
"hyperlink": sh.hyperlinks.get(&c),
"python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({
"code": py.code,
"output": if py.object { "object" } else { "value" },
+1 -9
View File
@@ -118,15 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
value_settings
),
cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter),
cmd!(
"pivot.sort",
"Sort Field",
[],
None,
"{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}",
has_doc,
sort
),
cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort),
cmd!(
"pivot.group",
"Group Field",
+4 -16
View File
@@ -1,8 +1,8 @@
use super::fields::{AreaPlacement, add_to_area, in_axes};
use super::params::{func_name, func_param, group_name, group_param, layout_name, show_as_name, sort_name};
use super::{
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotField, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook,
bad, bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, bad,
bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
};
// ---------------------------------------------------------------- insert
@@ -327,18 +327,6 @@ pub(super) fn summarize_table(s: &mut Session, p: &Json) -> Result<Json> {
// ---------------------------------------------------------------- queries
fn field_json(f: &PivotField) -> Json {
json!({
"field": f.source_col,
"caption": f.caption,
"sort": sort_name(f.sort),
"sortBy": f.sort_by,
"group": group_name(f.date_group),
"numberFormat": f.number_format,
"collapsed": f.collapsed_items,
})
}
pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
json!({
"id": pt.id,
@@ -347,8 +335,8 @@ pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
"anchor": pt.anchor.a1(),
"range": pt.last_range.map(|r| r.a1()),
"source": pt.source,
"rows": pt.rows.iter().map(field_json).collect::<Vec<_>>(),
"columns": pt.columns.iter().map(field_json).collect::<Vec<_>>(),
"rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
"columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
"values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::<Vec<_>>(),
"filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::<Vec<_>>(),
"layout": layout_name(pt.layout),
-6
View File
@@ -551,12 +551,6 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
None => {}
}
let name = v.name.clone();
// Fields sorted by this value field follow its new caption.
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) {
f.sort_by = Some(name.clone());
}
}
if let Some(slot) = pt.values.get_mut(i) {
*slot = v;
}
+1 -21
View File
@@ -71,24 +71,8 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
"none" | "manual" | "source" => PivotSort::None,
o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))),
};
// Sort by a value field (its caption or source field) instead of by the item labels.
let by = str_param(p, "by").map(str::to_string);
update(s, p, |pt, _, _| {
let by = match by {
Some(b) => Some(
pt.values
.iter()
.find(|v| v.name.eq_ignore_ascii_case(&b))
.or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b)))
.map(|v| v.name.clone())
.ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?,
),
None => None,
};
let f = axis_field(C, pt, &field)?;
f.sort = order;
f.sort_by = by;
f.sort_scope.clear();
axis_field(C, pt, &field)?.sort = order;
Ok(json!({}))
})
}
@@ -180,11 +164,7 @@ pub(super) fn layout(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some((on, top)) = subtotals {
// Design › Subtotals applies to every field, replacing per-field settings.
pt.subtotals = on;
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
f.subtotal = None;
}
if let Some(t) = top {
pt.subtotals_top = t;
}
+4 -508
View File
@@ -1,5 +1,4 @@
use gridcraft_core::{CellError, CellRef, Value};
use gridcraft_model::{PivotLayout, PivotSort};
use serde_json::{Value as Json, json};
use crate::Session;
@@ -318,10 +317,6 @@ fn assert_values_on_rows_tabular(s: &mut Session) {
assert_eq!(text(s, "A3"), "Region");
assert_eq!(text(s, "B3"), "Values");
assert_eq!(text(s, "C3"), "Total");
// The Values field's caption heads its column, as in Excel's saved reports.
edit_pt(s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(s, "B3"), "Data");
edit_pt(s, |p| p.data_caption = None);
}
fn assert_values_on_rows_position(s: &mut Session) {
@@ -506,231 +501,6 @@ fn refresh_after_source_edits() {
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
}
/// Edits the active sheet's last PivotTable in the model (settings only a file sets) and
/// refreshes it.
fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) {
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
let si = wb.active_sheet();
f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap());
s.execute("pivot.refresh", json!({})).unwrap();
}
#[test]
fn sort_by_value_within_each_parent() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
// East 415, West 285, North 135.
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales"));
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]);
s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]);
assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err());
// The sort follows a renamed value field; sorting without `by` sorts by label again.
s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue"));
assert_eq!(text(&s, "A4"), "North");
s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by, None);
assert_eq!(text(&s, "A4"), "West");
// Inner items sort within their parent; subtotals stay with their group.
s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap();
s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap();
// East: Pears 195, Apples 160, Plums 60.
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], ["East", "Pears", "Apples", "Plums", "East Total"]);
assert_eq!(val(&s, "C4"), Value::Number(195.0));
// West: Apples 170, Plums 70, Pears 45.
assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]);
// Columns sort by their row totals.
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]);
}
#[test]
fn captions_renamed_items_and_manual_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.row_header_caption = Some("Area".into());
p.col_header_caption = Some("Fruit".into());
p.grand_total_caption = Some("Everything".into());
p.rows[0].item_captions = vec![("East".into(), "Eastern".into())];
p.columns[0].sort = PivotSort::None;
p.columns[0].item_order = vec!["Plums".into(), "Pears".into()];
});
assert_eq!(text(&s, "A4"), "Area");
assert_eq!(text(&s, "B3"), "Fruit");
// Listed items first, the rest after.
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]);
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(text(&s, "A8"), "Everything");
// A renamed item sorts by its label still, and a filter still names it by its label.
s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap();
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(val(&s, "E5"), Value::Number(415.0));
// Outline layout: the field's custom name heads its column.
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Outline;
p.rows[0].caption = Some("Sales area".into());
p.columns[0].caption = Some("Kind".into());
});
assert_eq!(text(&s, "A4"), "Sales area");
assert_eq!(text(&s, "B3"), "Kind");
}
#[test]
fn field_subtotals_repeat_labels_and_values_row() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
assert_eq!(text(&s, "A7"), "East Total");
// Region without subtotals although the table has them; labels repeated on every row.
edit_pt(&mut s, |p| {
p.rows[0].subtotal = Some(false);
p.rows[0].repeat_labels = true;
});
assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1);
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]);
assert_eq!(text(&s, "B7"), "Apples");
// Outline repeats the labels too.
s.execute("pivot.layout", json!({"layout": "outline"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]);
// Two values without a column field: the Values row (Outline/Tabular) holds the caption.
s.execute("pivot.removeField", json!({"field": "Product"})).unwrap();
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
assert_eq!(text(&s, "B3"), "Values");
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]);
edit_pt(&mut s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(&s, "B3"), "Data");
edit_pt(&mut s, |p| p.show_values_row = false);
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]);
// Compact layout never shows it.
edit_pt(&mut s, |p| {
p.show_values_row = true;
p.layout = PivotLayout::Compact;
});
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]);
}
#[test]
fn empty_cell_caption_classic_layout_and_date_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap();
// East has no record with 1 unit: blank, or the "For empty cells show" caption.
assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]);
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
assert_eq!(text(&s, "B5"), "0");
// Classic layout, one value and no column field: the value caption above the row
// headers and a "Total" column.
s.execute("pivot.removeField", json!({"field": "Units"})).unwrap();
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Tabular;
p.classic_layout = true;
});
assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]);
assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1);
// A field number format applies to the item labels; date items sort after text, as in
// Excel.
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
s.execute("pivot.removeField", json!({"field": "Region"})).unwrap();
s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap();
edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into()));
assert_eq!(text(&s, "A5"), "NA");
}
#[test]
fn only_date_formatted_cells_sort_as_dates() {
// The two mixed columns of ClosedXML's VariousDataTypesInTableColumns, in source order.
// Excel caches each date-formatted cell as `<d>` and each General one as `<n>`, and its
// saved items list numbers first and dates after errors, whatever the first cell is.
let mixed = ["", "TRUE", "14.5", "10", "ABC", "=1/0", "8/10/2020", "16:30"];
// 1 and 1.52… are 12/31/1899 and 12/31/1899 12:30, which typed input reads as text.
let with_num = ["1", "1.5208333333333333", "12/24/2020", "16:30", "0.1", "45000", ""];
let order = |inputs: &[&str], dates: Option<&str>| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "K"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "V"})).unwrap();
for (i, input) in inputs.iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("A{}", i + 2), "input": input})).unwrap();
s.execute("cell.set", json!({"cell": format!("B{}", i + 2), "input": "1"})).unwrap();
}
if let Some(range) = dates {
s.execute("home.formatCells", json!({"range": range, "style": {"num_fmt": "m/d/yyyy h:mm"}})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"]})).unwrap();
edit_pt(&mut s, |p| p.rows[0].sort = PivotSort::Asc);
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().skip(1).filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l != "Grand Total").collect()
};
// Excel's saved <items> order for each field.
let excel_mixed = ["10", "14.5", "ABC", "TRUE", "#DIV/0!", "0.6875", "44053", "(blank)"];
let excel_with_num = ["0.1", "45000", "0.6875", "1", "1.52083333333333", "44189", "(blank)"];
assert_eq!(order(&mixed, None), excel_mixed);
assert_eq!(order(&with_num, Some("A2:A3")), excel_with_num);
// One number in a date cell and in a General cell is one item, which sorts as a number
// whichever cell comes first.
let number = ["5", "44053", "ABC"];
assert_eq!(order(&["5", "8/10/2020", "44053", "ABC"], None), number);
assert_eq!(order(&["5", "44053", "8/10/2020", "ABC"], None), number);
}
#[test]
fn a_general_cell_filtered_out_still_makes_its_number_sort_as_a_number() {
// 3/15/2023 is 45000: the General 45000 in row 3 makes that item a number, as in Excel's
// cache, even when the report filter leaves only the date cell.
let order = |filter: bool| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "K"), ("B1", "V"), ("C1", "R"), ("A2", "3/15/2023"), ("A3", "45000"), ("A4", "ABC")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
for (row, r) in [(2, "a"), (3, "b"), (4, "a")] {
s.execute("cell.set", json!({"cell": format!("B{row}"), "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{row}"), "input": r})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"], "filters": ["R"]})).unwrap();
s.execute("pivot.sort", json!({"field": "K", "order": "asc"})).unwrap();
if filter {
s.execute("pivot.filter", json!({"field": "R", "selected": ["a"]})).unwrap();
}
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l == "45000" || l == "ABC").collect()
};
assert_eq!(order(false), ["45000", "ABC"]);
assert_eq!(order(true), ["45000", "ABC"]);
}
#[test]
fn dates_sort_after_logicals_and_errors() {
// Excel's ascending item order: numbers, text, logicals, errors, dates, blanks.
let mut s = sales();
s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap();
s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.rows[0].number_format = None;
p.rows[0].sort = PivotSort::Asc;
});
let p = pt(&s);
let r = p.last_range.unwrap();
let labels: Vec<String> = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect();
// 46037 is 1/15/2026, the first date.
assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]);
}
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
}
@@ -1383,289 +1153,12 @@ fn collapsed_column_items_count_as_one_column_group() {
s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap();
}
#[test]
fn design_subtotals_replace_field_settings() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// A file's field can override the table default (`defaultSubtotal`).
edit_pt(&mut s, |p| {
p.subtotals = false;
p.rows[0].subtotal = Some(true);
});
assert!(find_row(&s, "East Total").is_some());
// Design › Subtotals › Do Not Show Subtotals applies to every field.
s.execute("pivot.subtotals", json!({"mode": "none"})).unwrap();
assert!(pt(&s).rows.iter().all(|f| f.subtotal.is_none()));
assert_eq!(find_row(&s, "East Total"), None);
edit_pt(&mut s, |p| p.rows[0].subtotal = Some(false));
s.execute("pivot.subtotals", json!({"mode": "bottom"})).unwrap();
assert!(find_row(&s, "East Total").is_some());
}
#[test]
fn numeric_empty_cell_caption_is_a_number() {
let mut s = sales();
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
// South has no Apples: the cell shows the caption, a number as Excel stores it.
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
let south = find_row(&s, "South").unwrap();
let apples = CellRef::new(south, 1);
assert_eq!(text(&s, &CellRef::new(south - 3, 1).a1()), "Apples");
assert_eq!(val(&s, &apples.a1()), Value::Number(0.0));
edit_pt(&mut s, |p| p.empty_caption = Some("n/a".into()));
assert_eq!(val(&s, &apples.a1()), Value::text("n/a"));
}
/// Saves the active workbook, applies `patch` to the first PivotTable part and reopens it.
fn reopen_patched(s: &Session, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch)
}
/// Saves the active workbook, applies `patch` to `part` and reopens it.
fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
use std::io::{Read, Write};
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let name = f.name().unwrap().to_string();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
if name == part {
b = patch(&String::from_utf8(b).unwrap()).into_bytes();
}
out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
out.write_all(&b).unwrap();
}
let bytes = out.finish().unwrap().into_inner();
crate::io::open_bytes("t.xlsx", &bytes).unwrap()
}
#[test]
fn sort_by_value_in_a_column_keeps_its_scope() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Excel's "sort by the values in the Apples column": the scope also names Product's
// item 0 (Apples). Apples: East 160, West 170, North 90; totals East 415, West 285.
let one = "<references count=\"1\"><reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let values_ref = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let two = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>");
let (wb, _) = reopen_patched(&s, |x| {
assert!(x.contains(one), "{x}");
x.replace(one, &two)
});
let si = wb.active_sheet();
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
let apples = gridcraft_model::PivotScopeItem { source_col: "Product".into(), item: "Apples".into(), ..Default::default() };
assert_eq!(p.rows[0].sort_scope, vec![apples]);
let out = crate::pivot::compute(&wb, p, si).unwrap();
let labels: Vec<String> = out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).collect();
let order: Vec<&str> = labels.iter().map(String::as_str).filter(|l| ["East", "West", "North"].contains(l)).collect();
assert_eq!(order, ["West", "East", "North"]);
// Saving writes the scope back.
let again = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
let (back, _) = crate::io::open_bytes("t.xlsx", &again).unwrap();
assert_eq!(back.sheet(si).unwrap().pivots.last().unwrap().rows[0].sort_scope, p.rows[0].sort_scope);
// A scope GridCraft can't represent (two Product items) loads as a sort by label, with
// a warning, instead of as a sort by the grand total.
let bad = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"2\" selected=\"0\"><x v=\"0\"/><x v=\"1\"/></reference>");
let (wb2, warnings) = reopen_patched(&s, |x| x.replace(one, &bad));
let p2 = wb2.sheet(wb2.active_sheet()).unwrap().pivots.last().unwrap();
assert_eq!(p2.rows[0].sort_by, None);
assert!(p2.rows[0].sort_scope.is_empty());
assert!(warnings.iter().any(|w| w.contains("scope")), "{warnings:?}");
}
/// Saves and reopens a workbook.
fn reopen_wb(wb: &gridcraft_model::Workbook) -> gridcraft_model::Workbook {
let bytes = crate::io::save_bytes(wb, "t.xlsx").unwrap();
crate::io::open_bytes("t.xlsx", &bytes).unwrap().0
}
/// The labels in the report's first column, as computed from `wb`, keeping only `keep`.
fn first_col(wb: &gridcraft_model::Workbook, keep: &[&str]) -> Vec<String> {
let si = wb.active_sheet();
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
let out = crate::pivot::compute(wb, p, si).unwrap();
out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).filter(|l| keep.contains(&l.as_str())).collect()
}
const VALUES_REF: &str = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
/// The Values-only sort scope the writer emits, as a `<references>` opening.
fn values_only() -> String {
format!("<references count=\"1\">{VALUES_REF}")
}
#[test]
fn sort_scope_tells_date_levels_of_one_column_apart() {
use gridcraft_model::{PivotDateGroup, PivotField};
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
let date = p.columns[0].clone();
p.columns =
vec![PivotField { date_group: PivotDateGroup::Years, ..date.clone() }, PivotField { date_group: PivotDateGroup::Quarters, ..date }];
});
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sort by the values in the 2026 › Qtr2 column: Years is cache field 5 (item 1 = 2026,
// after "<1/15/2026"), Quarters the Date field 2 (item 2 = Qtr2). Qtr2 holds West 70,
// East 60, North 30; the totals are East 415, West 285, North 135.
let refs = format!(
"<references count=\"3\">{VALUES_REF}<reference field=\"5\" count=\"1\" selected=\"0\"><x v=\"1\"/></reference><reference field=\"2\" count=\"1\" selected=\"0\"><x v=\"2\"/></reference>"
);
let (wb, _) = reopen_patched(&s, |x| {
assert!(x.contains(&values_only()), "{x}");
x.replace(&values_only(), &refs)
});
let regions = ["East", "West", "North"];
assert_eq!(first_col(&wb, &regions), ["West", "East", "North"]);
// Saving writes both references back.
let back = reopen_wb(&wb);
let scope = |wb: &gridcraft_model::Workbook| wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.clone();
assert_eq!(scope(&back).len(), 2);
assert_eq!(scope(&back), scope(&wb));
assert_eq!(first_col(&back, &regions), ["West", "East", "North"]);
}
#[test]
fn custom_subtotal_functions_keep_the_subtotal_rows() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Field Settings › Subtotals › Custom (Sum and Count) on Product, as Excel stores it.
let (wb, warnings) = reopen_patched(&s, |x| {
let start = x.match_indices("<pivotField ").nth(1).unwrap().0;
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" countSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/><item t=\"count\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert_ne!(p.rows[1].subtotal, Some(false));
// Shown with the automatic subtotal, with a warning.
let plain = reopen_wb(&s.doc().unwrap().wb);
let all = |wb: &gridcraft_model::Workbook| {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().map(|r| r.iter().map(|c| c.value.display()).collect::<Vec<_>>()).collect::<Vec<_>>()
};
assert_eq!(all(&wb), all(&plain));
assert!(warnings.iter().any(|w| w.contains("subtotal")), "{warnings:?}");
}
#[test]
fn custom_subtotals_on_the_first_field_keep_the_table_default() {
use std::io::Read;
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Custom Sum subtotal on Region (cache field 0, the first axis field), no xpdl extension.
let (wb, _) = reopen_patched(&s, |x| {
assert!(!x.contains("pivotTableDefinition16"), "{x}");
let start = x.find("<pivotField ").unwrap();
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert!(p.subtotals);
assert_eq!([p.rows[0].subtotal, p.rows[1].subtotal], [None, None]);
// Saving doesn't add a table default of "off" the file never had.
let bytes = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
z.by_name("xl/pivotTables/pivotTable1.xml").unwrap().read_to_string(&mut xml).unwrap();
assert!(!xml.contains("EnabledSubtotalsDefault=\"0\""), "{xml}");
}
#[test]
fn sort_scope_on_a_vanished_item_sorts_as_after_saving() {
let mut s = sales();
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sorted by the values in the Kiwis column (Product item 3)…
let refs = format!("<references count=\"2\">{VALUES_REF}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"3\"/></reference>");
let (mut wb, _) = reopen_patched(&s, |x| x.replace(&values_only(), &refs));
assert_eq!(wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.len(), 1);
// …then Kiwis leaves the source: the rows sort by the grand total, before and after saving.
let src = wb.sheets.iter().position(|sh| sh.name == "Sheet1").unwrap();
wb.sheet_mut(src).unwrap().set_value(CellRef::parse("B14").unwrap(), Value::text("Apples"));
let regions = ["East", "West", "North", "South"];
let total_order = ["East", "West", "North", "South"];
assert_eq!(first_col(&wb, &regions), total_order);
assert_eq!(first_col(&reopen_wb(&wb), &regions), total_order);
}
#[test]
fn date_groups_not_sorted_are_in_date_order() {
let mut s = sales();
// The first record is in Qtr4.
s.execute("cell.set", json!({"cell": "C2", "input": "12/1/2026"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
s.execute("pivot.group", json!({"field": "Date", "by": "quarters"})).unwrap();
s.execute("pivot.sort", json!({"field": "Date", "order": "none"})).unwrap();
let quarters = ["Qtr1", "Qtr2", "Qtr3", "Qtr4"];
assert_eq!(first_col(&s.doc().unwrap().wb, &quarters), quarters);
let back = reopen_wb(&s.doc().unwrap().wb);
assert_eq!(first_col(&back, &quarters), quarters);
// A reordered list still wins; items it doesn't name follow in date order.
let mut wb = back;
let si = wb.active_sheet();
wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap().rows[0].item_order = vec!["Qtr3".into()];
assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
assert_eq!(first_col(&reopen_wb(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
}
#[test]
fn manual_order_of_time_items_from_an_excel_cache() {
// Excel caches times as `<d v="1899-12-30T08:00:00"/>`: those items must name the
// report's 8:00 and 9:30, or a refresh puts the blank ahead of them.
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap();
// The report's first column: times as minutes, and the blank item.
let shifts = |wb: &gridcraft_model::Workbook| -> Vec<String> {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid
.iter()
.filter_map(|r| match &r.first()?.value {
Value::Number(n) => Some(format!("{}", (n * 1440.0).round())),
v if v.display() == "(blank)" => Some(v.display()),
_ => None,
})
.collect()
};
let order = ["480", "570", "(blank)"];
assert_eq!(shifts(&s.doc().unwrap().wb), order);
let excel_items = "<d v=\"1899-12-30T08:00:00\"/><d v=\"1899-12-30T09:30:00\"/><m/>";
let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| {
let ours = "<n v=\"0.3333333333333333\"/><n v=\"0.3958333333333333\"/><m/>";
assert!(x.contains(ours), "{x}");
x.replace(ours, excel_items)
});
assert_eq!(shifts(&back), order);
// Saving writes that order back.
assert_eq!(shifts(&reopen_wb(&back)), order);
}
#[test]
fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"source": "Sheet1!A1:E13", "destination": "Sheet1!H10", "rows": ["Region"], "values": ["Sales"]})).unwrap();
assert_eq!(pt(&s).last_range.unwrap().a1(), "H10:I14");
// Rows above the report (and below the source) move the report only.
s.execute("home.insertRows", json!({"rows": "16:17"})).unwrap();
s.execute("home.insertRows", json!({"rows": "6:7"})).unwrap();
assert_eq!(text(&s, "H12"), "Row Labels");
@@ -1673,6 +1166,7 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(l[0]["anchor"], "H12");
assert_eq!(l[0]["range"], "H12:I16");
assert_eq!(l[0]["source"], "Sheet1!A1:E15");
// A row above the source moves both.
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
let p = pt(&s);
assert_eq!(p.source, "Sheet1!A2:E16");
@@ -1681,10 +1175,12 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(pt(&s).last_range.unwrap().a1(), "H13:I17");
assert_eq!(text(&s, "H13"), "Row Labels");
assert_eq!(val(&s, "I17"), Value::Number(TOTAL));
// Deleting a column left of the report moves it left.
s.execute("home.deleteColumns", json!({"cols": "F:F"})).unwrap();
let p = pt(&s);
assert_eq!(p.anchor.a1(), "G13");
assert_eq!(p.last_range.unwrap().a1(), "G13:H17");
// Deleting rows above moves it up.
s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap();
assert_eq!(pt(&s).source, "Sheet1!A1:E15");
assert_eq!(pt(&s).anchor.a1(), "G12");

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