Merge upstream main into fix/pivot-refresh-fidelity

This commit is contained in:
Neil Cawse committed 2026-11-02 00:47:39 +00:00
commit 80f29610ee
167 files changed
+7916 -690

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ on:
permissions:
contents: write
packages: write
concurrency:
group: release-${{ github.ref }}
+5 -10
View File
@@ -2,8 +2,6 @@
GridCraft is a clean-room, open-source, Rust-native spreadsheet targeting Microsoft Excel parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../designcraft` (InDesign-class, the closest reference), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../effectcraft` (After Effects).
Standards and learnings shared across the crafting apps live in `../../craftrules` (checked out next to the craft apps, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/excel/*.md` (`observed-ui.md` holds measured observations of the running app).
2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -20,7 +18,7 @@ Standards and learnings shared across the crafting apps live in `../../craftrule
- The ArtCraft brand files in `docs/brand/` are ArtCraft trademarks under `docs/brand/LICENSE-brand.txt`, the one exception.
## Never crash
People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md).
People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.**
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
- **Errors are `Result<T, E>`** through the crate's error type and `?`.
- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): validate indexes and ranges before access, use checked access when validity is not established, use checked/saturating arithmetic, and cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references).
@@ -31,8 +29,8 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
## Non-negotiables
- **Clean-room.** Microsoft Excel is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic workbooks, take screenshots (by window id) stored only under `plan/excel/screenshots/`. Never read, disassemble or copy anything inside the Office bundle, never commit files produced by Excel, never copy GPL/AGPL/LGPL code (LibreOffice, Gnumeric…). Function behaviour comes from public documentation and observation.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. Standard: craftrules `standards/fonts.md`.
- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified (craftrules `standards/test-corpora.md`). Never commit large binary fixtures; build test workbooks in code.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults.
- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified. Never commit large binary fixtures; build test workbooks in code.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, ribbon path, shortcut, params doc, `enabled`, `run`) + tests. Ids follow Excel's ribbon (`home.bold`, `insert.chart`, `data.sortAscending`) plus primitives (`cell.set`, `selection.set`, `range.setValues`). UI-only commands live in `crates/ui-egui`. The control channel, CLI and MCP reach all of them.
- **Programmatic calls never open dialogs**: a command with empty params runs with defaults or returns an error; only menu-style invocation opens a dialog (`UiRequest::Dialog`).
- **Layering** is enforced by `cargo xtask layers`: `core`/`numfmt` (L0) → `formula`/`functions` (L1) → `model`/`calc`/`xlsx` (L2) → `chart` (L3) → `engine` (L5) → `ui-egui`/`mcp` (L6) → `apps/*` (L7). Nothing below L6 depends on egui/eframe/winit/rfd. **The UI crate is swappable.**
@@ -51,7 +49,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done.
## Roadmap
`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules `standards/progress-docs.md` and points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`.
`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`.
## Contributor credits (About window)
@@ -62,14 +60,11 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
(copy the template at the top of the file)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
+9 -9
View File
@@ -12,15 +12,15 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
| `epaint_default_fonts::HACK_REGULAR` (dependency font input) | Source Foundry Authors (Hack; DejaVu and Bitstream Vera foundations) | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Hack](https://github.com/source-foundry/Hack) | MIT + Bitstream Vera License (full upstream texts in `NOTICE`) | Hack-Regular.ttf is egui's bundled monospace face and GridCraft's last-resort symbol fallback. Dependency asset unmodified here, no font file copied into this repository. |
| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | The Noto Project Authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Noto Emoji](https://fonts.google.com/noto/specimen/Noto+Emoji) | SIL Open Font License 1.1 (full upstream text in `NOTICE`) | NotoEmoji-Regular.ttf is enabled by egui's `monochrome_emoji_fonts` feature and used as the monochrome emoji fallback. Dependency asset unmodified here, no font file copied into this repository. |
| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Canonical Ltd. and the Ubuntu Font Family authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Ubuntu font](https://design.ubuntu.com/font) | Ubuntu Font Licence 1.0 (full upstream text in `NOTICE`) | Ubuntu-Light.ttf is egui's default proportional face. Dependency asset unmodified here, no font file copied into this repository. |
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | craftrules `assets/brand/` | ArtCraft brand terms | Trademark |
| `docs/brand/LICENSE-brand.txt` | (licence text) | craftrules | — | |
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/LICENSE-brand.txt` | (licence text) | project | — | |
| `assets/app-icon/gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | PLACEHOLDER app icon (ledger page); replaced by the owner's creature art later |
| `packaging/macos/dmg/background.svg` | @XusBadia | original (hand-written SVG, derived from the GridCraft app icon `assets/app-icon/gridcraft.svg`, referenced via `<image>`, not copied; text is outlined glyph paths; `packaging/macos/dmg/generate.py` renders it to `background.tiff`) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | GridCraft macOS DMG window background for the Finder window; added 2026-10-08 |
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
+4 -6
View File
@@ -2,8 +2,6 @@
GridCraft is a clean-room, open-source, Rust-native spreadsheet targeting Microsoft Excel parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and BSD, and on the web via WASM. Siblings with the same conventions: `../designcraft` (InDesign-class, the closest reference), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../effectcraft` (After Effects).
Standards and learnings shared across the crafting apps live in `../../craftrules` (checked out next to the craft apps, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/excel/*.md` (`observed-ui.md` holds measured observations of the running app).
2. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's.
@@ -20,7 +18,7 @@ Standards and learnings shared across the crafting apps live in `../../craftrule
- The ArtCraft brand files in `docs/brand/` are ArtCraft trademarks under `docs/brand/LICENSE-brand.txt`, the one exception.
## Never crash
People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md).
People trust GridCraft with their numbers; a crash loses their work. **This outranks feature work.**
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
- **Errors are `Result<T, E>`** through the crate's error type and `?`.
- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references).
@@ -31,8 +29,8 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
## Non-negotiables
- **Clean-room.** Microsoft Excel is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic workbooks, take screenshots (by window id) stored only under `plan/excel/screenshots/`. Never read, disassemble or copy anything inside the Office bundle, never commit files produced by Excel, never copy GPL/AGPL/LGPL code (LibreOffice, Gnumeric…). Function behaviour comes from public documentation and observation.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. Standard: craftrules `standards/fonts.md`.
- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified (craftrules `standards/test-corpora.md`). Never commit large binary fixtures; build test workbooks in code.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults.
- **Test corpora** (real Excel-authored files) live in a separate corpus repo, fetched pinned and sha256-verified. Never commit large binary fixtures; build test workbooks in code.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, ribbon path, shortcut, params doc, `enabled`, `run`) + tests. Ids follow Excel's ribbon (`home.bold`, `insert.chart`, `data.sortAscending`) plus primitives (`cell.set`, `selection.set`, `range.setValues`). UI-only commands live in `crates/ui-egui`. The control channel, CLI and MCP reach all of them.
- **Programmatic calls never open dialogs**: a command with empty params runs with defaults or returns an error; only menu-style invocation opens a dialog (`UiRequest::Dialog`).
- **Layering** is enforced by `cargo xtask layers`: `core`/`numfmt` (L0) → `formula`/`functions` (L1) → `model`/`calc`/`xlsx` (L2) → `chart` (L3) → `engine` (L5) → `ui-egui`/`mcp` (L6) → `apps/*` (L7). Nothing below L6 depends on egui/eframe/winit/rfd. **The UI crate is swappable.**
@@ -50,7 +48,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done.
## Roadmap
`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It follows craftrules `standards/progress-docs.md` and points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`.
`ROADMAP.md` (committed) is the one-page summary: stage, headline numbers, dimensions, languages, progress log. It points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
Generated
+31 -30
View File
@@ -220,7 +220,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -889,12 +889,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -917,9 +917,10 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"craft-winprint-gdi",
"log",
"miniz_oxide 0.9.1",
"roxmltree",
"tempfile",
@@ -930,7 +931,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -950,7 +951,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"chrono",
"dunce",
@@ -976,7 +977,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1456,7 +1457,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1936,7 +1937,7 @@ dependencies = [
[[package]]
name = "gridcraft"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"arboard",
"chrono",
@@ -1963,7 +1964,7 @@ dependencies = [
[[package]]
name = "gridcraft-calc"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
@@ -1975,7 +1976,7 @@ dependencies = [
[[package]]
name = "gridcraft-chart"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-calc",
"gridcraft-core",
@@ -1986,7 +1987,7 @@ dependencies = [
[[package]]
name = "gridcraft-cli"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-engine",
"gridcraft-mcp",
@@ -1998,7 +1999,7 @@ dependencies = [
[[package]]
name = "gridcraft-core"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"chrono",
"js-sys",
@@ -2009,7 +2010,7 @@ dependencies = [
[[package]]
name = "gridcraft-engine"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-calc",
"gridcraft-chart",
@@ -2031,7 +2032,7 @@ dependencies = [
[[package]]
name = "gridcraft-formula"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-core",
"serde",
@@ -2040,7 +2041,7 @@ dependencies = [
[[package]]
name = "gridcraft-functions"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-core",
"regex",
@@ -2048,7 +2049,7 @@ dependencies = [
[[package]]
name = "gridcraft-mcp"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-engine",
"log",
@@ -2057,7 +2058,7 @@ dependencies = [
[[package]]
name = "gridcraft-model"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
@@ -2069,18 +2070,18 @@ dependencies = [
[[package]]
name = "gridcraft-numfmt"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-core",
]
[[package]]
name = "gridcraft-pdf"
version = "0.13.0"
version = "0.15.0"
[[package]]
name = "gridcraft-ui-egui"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"craft-ui",
"craft-update",
@@ -2105,7 +2106,7 @@ dependencies = [
[[package]]
name = "gridcraft-web"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"eframe",
"egui",
@@ -2122,7 +2123,7 @@ dependencies = [
[[package]]
name = "gridcraft-xlsx"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"aes",
"gridcraft-core",
@@ -3461,7 +3462,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -3875,7 +3876,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4185,7 +4186,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4244,7 +4245,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -4978,7 +4979,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5937,7 +5938,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -6403,7 +6404,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.13.0"
version = "0.15.0"
dependencies = [
"gridcraft-engine",
"serde_json",
+3 -3
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
[workspace.package]
version = "0.13.0"
version = "0.15.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -27,7 +27,7 @@ gridcraft-pdf = { path = "crates/pdf" }
# Every craft-libs crate (craft-update and craft-window here, craft-ui in ui-egui, craft-print in
# the app) comes from one storytold/craft-libs revision.
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", version = "=0.1.0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.1.0", features = ["egui"] }
# foundation
thiserror = "2"
@@ -63,7 +63,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 = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["egui"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", default-features = false, features = ["egui"] }
[workspace.lints.rust]
unsafe_code = "forbid"
+9 -1
View File
@@ -298,7 +298,15 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | **Spreadsheets and data · you are here** | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
+14 -3
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column; earlier: macro engine and `macro.*` commands; macro interface on the Automate tab) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-01 · **Change:** minor (Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
@@ -135,6 +135,11 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | What landed |
|---|---|
| 2026-11-01 | XLSX keeps the first visible workbook window's active sheet and display settings together, falling back to the first view when all are hidden. Tab ratios are normalized to 0–1000 on import and export; invalid numeric text uses 600. Synthetic round trips cover isolated attributes, missing views, and active tabs after sheet deletion/reordering; firstSheet remains separate #2264 work (#3057). |
| 2026-10-31 | Esc in File › Info, Print or Options first leaves the text field; the next Esc returns to the sheet (#3035) |
| 2026-10-31 | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) |
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
@@ -167,6 +172,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
| 2026-10-14 | Recalculation: when two arrays of one recalculation want the same empty cells, the formulas that read the one laid out second (at its anchor or over the cells it would have spilled into) read `#SPILL!` and empty cells instead of its values |
@@ -233,7 +239,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-11 | PivotCharts (`insert.pivotChart`): charts bound to a PivotTable's report, following refreshes and layout changes (#311) |
| 2026-10-11 | FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.ETS.STAT: AAA exponential smoothing forecasts (#314) |
| 2026-10-11 | File tab Backstage view (Home, New, Open, Info, Save As, Print preview, Export, Options) and `file.options` (#174) |
| 2026-10-10 | Ribbon translated into Japanese, Chinese, Korean, Brazilian Portuguese and Russian with system-language default (#31, #104, #82); CJK/Thai/Hebrew font fallback (#38); clear messages for encrypted and `.xls` files (#17); smooth line charts (#62). Progress docs restructured to the craftrules standard; full re-measure (this page). Initial ribbon key tips (#43), in-place text box editing (#84), copy as HTML table (#36). ODS and XLSB data import (#100, #101); recalc linear in the number of range formulas (#66); RISC-V Linux build; Flatpak repository on Pages; web cell-commit trap fixed |
| 2026-10-10 | Ribbon translated into Japanese, Chinese, Korean, Brazilian Portuguese and Russian with system-language default (#31, #104, #82); CJK/Thai/Hebrew font fallback (#38); clear messages for encrypted and `.xls` files (#17); smooth line charts (#62). Progress docs restructured; full re-measure (this page). Initial ribbon key tips (#43), in-place text box editing (#84), copy as HTML table (#36). ODS and XLSB data import (#100, #101); recalc linear in the number of range formulas (#66); RISC-V Linux build; Flatpak repository on Pages; web cell-commit trap fixed |
| 2026-10-09 | Community fixes: spill range operator `A1#`, sheet-scoped names, protection refuses locked-cell edits, Insert/Delete Cells adjust references, `DATE(1900,2,29)`, SUMIF sizing, `ROUND` at 15 digits, `_xlpm.` LAMBDA parameters in XLSX, vertical scrollbar, system appearance, border previews; v0.4.0 |
| 2026-10-08 | v0.2.0 and v0.3.0 releases; Flatpak, AppImage zsync, branded DMG; desktop log file; DirectX 12 default on Windows |
| 2026-10-07 | About window with contributor and model credits; macOS release runner |
@@ -244,6 +250,10 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | Change | Summary |
|---|---|---|
| 2026-11-01 | trivial | Workbook views: selected window settings stay together, tab ratios are bounded, and regressions cover isolated settings and sheet edits; readiness estimates unchanged (#3057) |
| 2026-10-31 | minor | File-page text fields keep the view open when Esc cancels an edit (#3035) |
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
| 2026-10-31 | minor | Progress log: Function Library |
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
@@ -262,6 +272,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
@@ -296,5 +307,5 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% per audience; full number unchanged (additive weighted sum) |
| 2026-10-10 | minor | Added Mainstream practitioner (~50%) and Essentials user (~63%); languages updated for the 10-10 merges (ribbon in ja, zh, ko, pt-BR, ru); localization 5%→10%; full number re-checked (51.6, unchanged) |
| 2026-10-10 | minor | Checked against the alpha gate (six core workflows pass): stays alpha |
| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; restructured to the progress-docs standard; detail moved to `docs/` |
| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; progress docs restructured; detail moved to `docs/` |
| 2026-10-07 | major | First estimates: catalog 89%, functions ~93%, depth ~65%, ~35 h to alpha, ~215 h to full parity |
+3 -2
View File
@@ -230,8 +230,9 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
{
// With `noopener` the new browsing context can't hold a reference back to the
// editor window and navigate it while the user reads the linked page.
let _ = w.open_with_url_and_target(&url, "_blank,noopener");
// editor window and navigate it while the user reads the linked page. It must be a
// window *feature*: inside the target string it would only name the new window.
let _ = w.open_with_url_and_target_and_features(&url, "_blank", "noopener,noreferrer");
}
})),
inbox: Some(inbox),
+5 -1
View File
@@ -30,7 +30,7 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
# Cargo.toml).
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true }
@@ -52,6 +52,10 @@ muda = { version = "0.21", default-features = false }
# by PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which our
# workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping.
fmv-macos-events = "=0.1.0"
# apple_events.rs brings the app forward for a Dock quit's question. Already in Cargo.lock (muda,
# winit); pinned exactly to the same versions.
objc2 = "=0.6.5"
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder", "NSWindow"] }
# tests/mac_menu_appkit.rs: reads AppKit's menu bar back. Already in Cargo.lock (muda, winit);
# pinned exactly to the same versions.
+28 -1
View File
@@ -11,6 +11,8 @@
use fmv_macos_events::{Event, Inbox, Registration};
use gridcraft_ui_egui::SheetApp;
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSRequestUserAttentionType};
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
pub struct AppleEvents {
@@ -44,7 +46,32 @@ pub fn poll(inbox: &Inbox, app: &mut SheetApp, ctx: &egui::Context) {
}
}
// Quit from the Dock or the system: each unsaved workbook is asked about in its window.
Event::Quit => app.request_quit(ctx),
Event::Quit => {
app.request_quit(ctx);
if app.dialog.is_some() {
bring_app_forward();
}
}
}
}
}
/// A Dock quit reaches GridCraft behind other apps, hidden or minimized, and its question has to
/// be seen. egui's Focus goes through winit, which skips a minimized window or a hidden app, and
/// macOS may refuse an activation it didn't expect, so ask AppKit directly and bounce the Dock
/// icon until the user switches over.
fn bring_app_forward() {
let Some(mtm) = MainThreadMarker::new() else { return };
let ns_app = NSApplication::sharedApplication(mtm);
ns_app.unhide(None);
for window in ns_app.windows().to_vec() {
if window.isMiniaturized() {
window.deminiaturize(None);
}
}
#[allow(deprecated)] // `activate` needs macOS 14; this works on every supported version.
ns_app.activateIgnoringOtherApps(true);
if !ns_app.isActive() {
ns_app.requestUserAttention(NSRequestUserAttentionType::CriticalRequest);
}
}
+164 -15
View File
@@ -12,16 +12,47 @@
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use std::time::{Duration, Instant};
use gridcraft_mcp::control_auth;
use gridcraft_ui_egui::ControlRequest;
use serde_json::{Value as Json, json};
const MAX_LINE: usize = 64 * 1024 * 1024;
/// How long a new connection may take to send its token.
/// How long a new connection may take to send its token, in total.
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
/// How many connections may be waiting to authenticate at once. Anyone on the machine can
/// connect without the token, so past this a new connection is closed before anything is read:
/// each waiting one holds a thread and a socket.
const MAX_PENDING_AUTH: usize = 16;
/// How the server treats connections that haven't authenticated yet.
#[derive(Clone, Copy)]
struct AuthLimits {
timeout: Duration,
max_pending: usize,
}
const AUTH_LIMITS: AuthLimits = AuthLimits { timeout: AUTH_TIMEOUT, max_pending: MAX_PENDING_AUTH };
/// A connection that is still waiting to authenticate; dropping it frees its place.
struct Pending(Arc<AtomicUsize>);
impl Pending {
/// A place among the `max` waiting connections, or `None` when they are all taken.
fn claim(waiting: &Arc<AtomicUsize>, max: usize) -> Option<Pending> {
waiting.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok()?;
Some(Pending(Arc::clone(waiting)))
}
}
impl Drop for Pending {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
/// The secret of this run: the one the user chose (`--control-token`, `GRIDCRAFT_CONTROL_TOKEN`),
/// else 256 random bits from the operating system, written to a file only the user can read.
@@ -51,35 +82,75 @@ pub fn start(port: u16, chosen_token: Option<String>, ctx: egui::Context) -> std
/// Accept connections on `listener`; requests arrive on the returned receiver.
fn serve_listener(listener: TcpListener, token: Arc<str>, ctx: egui::Context) -> std::io::Result<Receiver<ControlRequest>> {
serve_listener_with(listener, token, ctx, AUTH_LIMITS)
}
fn serve_listener_with(listener: TcpListener, token: Arc<str>, ctx: egui::Context, limits: AuthLimits) -> std::io::Result<Receiver<ControlRequest>> {
let (tx, rx) = channel();
let waiting = Arc::new(AtomicUsize::new(0));
std::thread::Builder::new().name("control".into()).spawn(move || {
for stream in listener.incoming().flatten() {
for stream in listener.incoming() {
let Ok(stream) = stream else {
// Out of sockets or handles: wait for some to free instead of spinning on the error.
std::thread::sleep(Duration::from_millis(50));
continue;
};
// Dropping the stream closes it before anything is read.
let Some(place) = Pending::claim(&waiting, limits.max_pending) else { continue };
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
let _ = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx));
let _ =
std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx, limits.timeout, Some(place)));
}
})?;
Ok(rx)
}
/// Read the connection's first line (at most [`control_auth::MAX_AUTH_LINE`] bytes, within
/// [`AUTH_TIMEOUT`]) and check the token. `true` when the peer may go on.
fn authenticate(reader: &mut BufReader<TcpStream>, out: &mut TcpStream, token: &str) -> bool {
let _ = out.set_read_timeout(Some(AUTH_TIMEOUT));
let mut first = String::new();
let read = reader.by_ref().take(control_auth::MAX_AUTH_LINE as u64).read_line(&mut first);
let verdict = match read {
Ok(n) if n > 0 && first.ends_with('\n') => control_auth::check_first_line(&first, token),
/// `timeout` in total) and check the token. `true` when the peer may go on.
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
fn authenticate(reader: &mut BufReader<TcpStream>, out: &mut TcpStream, token: &str, timeout: Duration) -> bool {
let deadline = Instant::now().checked_add(timeout).unwrap_or_else(Instant::now);
let mut first = Vec::new();
let read = read_auth_line(reader, &mut first, deadline);
let verdict = match (read, std::str::from_utf8(&first)) {
(Ok(()), Ok(line)) if line.ends_with('\n') => control_auth::check_first_line(line, token),
_ => Err(json!({"ok": false, "error": "authentication required"})),
};
let allowed = verdict.is_ok();
let reply = verdict.unwrap_or_else(|e| e);
let _ = writeln!(out, "{reply}");
let _ = out.set_read_timeout(None);
let _ = reader.get_ref().set_read_timeout(None);
allowed
}
/// Read the first line, at most [`control_auth::MAX_AUTH_LINE`] bytes, by `deadline`.
///
/// The timeout goes on the handle the reader reads: on Windows a `try_clone` of the stream keeps
/// its own, so one set on the writing half never fired (a silent peer held its thread forever).
/// It is shortened before every read, so a peer sending one byte at a time can't stretch it.
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
fn read_auth_line(reader: &mut BufReader<TcpStream>, line: &mut Vec<u8>, deadline: Instant) -> std::io::Result<()> {
let max = control_auth::MAX_AUTH_LINE;
while line.len() < max && line.last() != Some(&b'\n') {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(std::io::ErrorKind::TimedOut.into());
}
reader.get_ref().set_read_timeout(Some(left))?;
let buf = reader.fill_buf()?;
if buf.is_empty() {
break;
}
let room = max.saturating_sub(line.len());
let take = buf.iter().take(room).position(|b| *b == b'\n').map_or(buf.len().min(room), |i| i + 1);
line.extend(buf.iter().take(take));
reader.consume(take);
}
Ok(())
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
@@ -148,11 +219,14 @@ fn is_http_request_line(text: &str) -> bool {
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context, auth_timeout: Duration, place: Option<Pending>) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
let mut reader = BufReader::new(read);
if !authenticate(&mut reader, &mut out, token) {
let allowed = authenticate(&mut reader, &mut out, token, auth_timeout);
// Authenticated or refused, the connection no longer counts as waiting.
drop(place);
if !allowed {
return;
}
let mut buf = Vec::new();
@@ -294,7 +368,7 @@ mod tests {
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default()));
std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default(), AUTH_TIMEOUT, None));
}
});
addr
@@ -346,6 +420,81 @@ mod tests {
assert_eq!(got[1]["ok"], json!(false));
}
/// Whether the server closed `c` (end of stream, or a refusal and then end of stream) within
/// `within`, and how long it took.
#[allow(clippy::disallowed_methods)] // a native-only test of the desktop app
fn closed_within(c: TcpStream, within: Duration) -> (bool, Duration) {
let start = Instant::now();
c.set_read_timeout(Some(within)).unwrap();
let mut r = BufReader::new(c);
let mut line = String::new();
loop {
line.clear();
match r.read_line(&mut line) {
Ok(0) => return (true, start.elapsed()),
Ok(_) => continue,
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => return (false, start.elapsed()),
Err(_) => return (true, start.elapsed()),
}
}
}
/// The token deadline is for the whole first line: neither a silent peer nor one sending a
/// byte at a time keeps the connection (and its thread) past it.
#[test]
fn a_silent_or_slow_peer_is_closed_at_the_auth_deadline() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let limits = AuthLimits { timeout: Duration::from_millis(300), max_pending: MAX_PENDING_AUTH };
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
let silent = TcpStream::connect(addr).unwrap();
let mut slow = TcpStream::connect(addr).unwrap();
let mut drip = slow.try_clone().unwrap();
std::thread::spawn(move || {
for b in control_auth::auth_line(1, TOKEN).bytes() {
if drip.write_all(&[b]).is_err() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
});
let (closed, took) = closed_within(silent, Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "silent peer kept for {took:?}");
let (closed, took) = closed_within(slow.try_clone().unwrap(), Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "byte-at-a-time peer kept for {took:?}");
let _ = slow.flush();
}
/// Peers without the token can't pile up threads: past the cap a new connection is closed at
/// once, and a waiting one that authenticates frees its place.
#[test]
fn connections_waiting_to_authenticate_are_capped() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let limits = AuthLimits { timeout: Duration::from_secs(20), max_pending: 2 };
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
let mut first = TcpStream::connect(addr).unwrap();
let _second = TcpStream::connect(addr).unwrap();
std::thread::sleep(Duration::from_millis(200));
let (closed, took) = closed_within(TcpStream::connect(addr).unwrap(), Duration::from_secs(5));
assert!(closed && took < Duration::from_secs(3), "a third waiting connection was kept");
first.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
first.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
let mut reply = String::new();
BufReader::new(first.try_clone().unwrap()).read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "{reply}");
std::thread::sleep(Duration::from_millis(200));
let mut next = TcpStream::connect(addr).unwrap();
next.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
next.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
let mut reply = String::new();
BufReader::new(next).read_line(&mut reply).unwrap();
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "a freed place was not reused: {reply}");
}
#[test]
fn a_chosen_token_must_be_long_enough() {
assert!(make_token(1, Some("short".into())).is_err());
+78 -2
View File
@@ -1,4 +1,5 @@
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
//! Graphics instance configuration, applied before wgpu can initialize any driver: Windows
//! backends and the DirectX 12 shader compiler, and the Intel Mac indirect-validation skip.
//!
//! Vulkan is never initialized unless `WGPU_BACKEND` asks for it: enumerating Vulkan adapters
//! crashes inside Intel's `igvk64.dll` on some UHD Graphics drivers (#120), and that access
@@ -8,12 +9,38 @@
//! whichever `dxcompiler.dll` the DLL search path happens to find (#339, #354): see
//! [`dx12_compiler`].
// On macOS only the indirect-validation items are used outside tests; on Windows the other way
// round, so those two carry their own `allow`.
#![cfg_attr(target_os = "macos", allow(dead_code))]
use eframe::{
NativeOptions,
egui_wgpu::WgpuSetup,
wgpu::{Backends, DeviceType, Dx12Compiler},
wgpu::{Backends, DeviceType, Dx12Compiler, InstanceFlags},
};
/// wgpu compiles its indirect-call validation compute shaders inside `request_device`. On Intel
/// Macs (Iris 5100 in a Mac mini 2014) Metal's compiler aborts on them ("Compiler encountered an
/// internal error"), the device is lost and eframe exits before the window opens. GridCraft issues
/// no indirect draws or dispatches, so Intel Macs skip them; every other GPU keeps wgpu's default.
/// Same as WordCraft (storytold/wordcraft#2652) and PhotoCraft (storytold/PhotoCraft#3171).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn skips_indirect_validation(macos: bool, intel: bool) -> bool {
macos && intel
}
/// Leaves wgpu's indirect-call validation out of the instance eframe creates when `skip`.
/// `WGPU_VALIDATION_INDIRECT_CALL=1` still turns it back on.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn configure_indirect_validation(options: &mut NativeOptions, skip: bool) {
if !skip {
return;
}
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.instance_descriptor.flags = create.instance_descriptor.flags.difference(InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
}
}
/// What the start-up probe learned about one DirectX 12 adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Dx12Adapter {
@@ -141,6 +168,55 @@ fn probe_dx12(options: &NativeOptions) -> Vec<Dx12Adapter> {
mod tests {
use super::*;
fn instance_flags(options: &NativeOptions) -> InstanceFlags {
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
create.instance_descriptor.flags
}
#[test]
fn intel_macs_skip_the_indirect_validation_shaders() {
// Metal's Intel compiler aborted on them, losing the device before the window opened.
assert!(skips_indirect_validation(true, true));
// Apple silicon, Windows and Linux keep wgpu's validation.
for (macos, intel) in [(true, false), (false, true), (false, false)] {
assert!(!skips_indirect_validation(macos, intel), "macos={macos} intel={intel}");
}
let mut options = NativeOptions::default();
let before = instance_flags(&options);
configure_indirect_validation(&mut options, false);
assert_eq!(instance_flags(&options), before, "flags untouched when not skipping");
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
configure_indirect_validation(&mut options, true);
assert!(!instance_flags(&options).contains(InstanceFlags::VALIDATION_INDIRECT_CALL));
}
}
/// `WGPU_VALIDATION_INDIRECT_CALL=1` turns the validation back on even when it is skipped.
/// Tests can't set environment variables (`set_var` is unsafe, and unsafe code is forbidden),
/// so this runs itself again as a child process with the variable set.
#[test]
fn the_environment_turns_indirect_validation_back_on() {
const NAME: &str = "graphics::tests::the_environment_turns_indirect_validation_back_on";
if std::env::var_os("GRIDCRAFT_INDIRECT_VALIDATION_CHILD").is_some() {
let mut options = NativeOptions::default();
configure_indirect_validation(&mut options, true);
assert!(instance_flags(&options).contains(InstanceFlags::VALIDATION_INDIRECT_CALL));
return;
}
let exe = std::env::current_exe().unwrap();
let out = std::process::Command::new(exe)
.args(["--exact", NAME, "--test-threads=1"])
.env("GRIDCRAFT_INDIRECT_VALIDATION_CHILD", "1")
.env("WGPU_VALIDATION_INDIRECT_CALL", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
// `--exact` matching nothing would pass too, so the child must report this one test.
assert!(out.status.success() && stdout.contains("1 passed"), "child test failed:\n{stdout}{}", String::from_utf8_lossy(&out.stderr));
}
fn configured_backends(backends: Backends) -> Backends {
let mut options = NativeOptions::default();
configure_backends(&mut options, backends);
+10 -6
View File
@@ -12,7 +12,7 @@
#[cfg(target_os = "macos")]
mod apple_events;
mod control_server;
#[cfg(any(target_os = "windows", test))]
#[cfg(any(target_os = "windows", target_os = "macos", test))]
mod graphics;
mod logging;
#[cfg(target_os = "macos")]
@@ -311,15 +311,16 @@ fn main() -> eframe::Result<()> {
{
log::warn!("sample {s}: {e}");
}
if session.documents().is_empty() {
session.new_workbook();
}
let mut app = SheetApp::new(session, services());
app.watch_desktop_theme();
app.start_update_check();
app.after_engine(); // Show warnings from the sample.
let control_port = control_port;
load_prefs(&mut app);
// Stamp the startup workbook's author from the persisted user name.
if app.session.documents().is_empty() {
app.session.new_workbook();
}
app.after_engine(); // Show warnings from the sample.
// Files named on the command line (a double-click on Windows and Linux) open as File › Open
// opens them: a password-protected one asks for its password, and errors are shown, not
// only logged. Each replaces the untouched blank Book1, as a file opened from Finder does.
@@ -340,8 +341,11 @@ fn main() -> eframe::Result<()> {
}
let window_builder = viewport.clone();
let options = eframe::NativeOptions { viewport, ..Default::default() };
#[cfg(all(unix, not(target_os = "macos")))]
#[cfg(unix)]
let mut options = options;
// Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs).
#[cfg(target_os = "macos")]
graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64")));
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1
// keeps the native Wayland backend.
+8 -7
View File
@@ -390,11 +390,12 @@ impl NativeMenu {
#[cfg(test)]
mod tests {
use super::*;
// No `use super::*`: tests/mac_menu_appkit.rs builds this file with cfg(test) but no test
// harness, so the #[test] functions are left out and a module-level import would be unused.
#[test]
fn file_menu_has_export_as_pdf_dispatching_the_command() {
let tree = tree();
let tree = super::tree();
let (_, file) = tree.iter().find(|(title, _)| *title == "File").expect("File menu");
let item = file.iter().find(|e| e.0 == "Export as PDF…").expect("Export as PDF… in the File menu");
assert_eq!(item.1, "file.exportPdf");
@@ -403,23 +404,23 @@ mod tests {
#[test]
fn help_menu_checks_for_updates_through_the_registered_command() {
let tree = tree();
let tree = super::tree();
let (_, help) = tree.iter().find(|(title, _)| *title == "Help").expect("Help menu");
let item = help.iter().find(|e| e.0 == "Check for Updates…").expect("Check for Updates… in the Help menu");
assert_eq!(item.1, "app.checkForUpdates");
let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default());
let mut app = super::SheetApp::new(gridcraft_engine::Session::new(), Default::default());
assert!(app.run(item.1, serde_json::json!({})).is_ok());
}
#[test]
fn theme_choices_use_the_shared_preference_command() {
let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default());
let mut app = super::SheetApp::new(gridcraft_engine::Session::new(), Default::default());
for mode in ["dark", "system", "light"] {
assert!(select_theme(&mut app, &format!("theme:{mode}")));
assert!(super::select_theme(&mut app, &format!("theme:{mode}")));
assert_eq!(app.ui.theme_mode(), mode);
assert!(app.message.is_none());
}
assert!(!select_theme(&mut app, "view.formulaBar"));
assert!(!super::select_theme(&mut app, "view.formulaBar"));
assert_eq!(app.ui.theme_mode(), "light");
}
}
+13 -2
View File
@@ -19,12 +19,23 @@ fn main() {
nsapp.finishLaunching();
let ctx = egui::Context::default();
let _menu = native_menu::NativeMenu::install(&ctx);
let mut menu = native_menu::NativeMenu::install(&ctx);
let bar = nsapp.mainMenu().expect("a main menu");
let tops: Vec<String> = (0..bar.numberOfItems()).filter_map(|i| bar.itemAtIndex(i)?.submenu()).map(|m| m.title().to_string()).collect();
assert_eq!(tops, ["GridCraft", "File", "Edit", "View", "Insert", "Format", "Tools", "Data", "Window", "Help"]);
assert_eq!(nsapp.windowsMenu().map(|m| m.title().to_string()).as_deref(), Some("Window"), "AppKit knows the Window menu");
let windows_menu = nsapp.windowsMenu().expect("AppKit knows the Window menu");
assert_eq!(windows_menu.title().to_string(), "Window");
// A poll lists the open workbook windows at the end of the Window menu (#716).
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = gridcraft_ui_egui::SheetApp::new(session, Default::default());
menu.poll(&mut app, &ctx, egui::ViewportId::ROOT);
let open = app.open_windows();
assert_eq!(open.len(), 1, "one workbook window");
let last = windows_menu.itemAtIndex(windows_menu.numberOfItems() - 1).expect("a Window menu item");
assert_eq!(last.title().to_string(), open[0].label(), "the Window menu lists the open workbook");
println!("mac_menu_appkit: ok");
}
+1 -1
View File
@@ -1,7 +1,7 @@
# GridCraft app icon (PLACEHOLDER)
**This icon is temporary.** Every Crafting App's icon is an engraved creature portrait that the
product owner makes (craftrules `standards/icon-design.md`); GridCraft's hasn't been made yet.
product owner makes; GridCraft's hasn't been made yet.
Until it is, this placeholder stands in: a simple ledger page with a header row, a row-number
column, a selected cell with its fill handle and a double rule under a total, on a full-bleed
GridCraft-green tile. It is original geometry written by hand for this repository, deliberately
+1 -1
View File
@@ -1,7 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- GridCraft PLACEHOLDER icon: a ledger page with a selected cell, on GridCraft green.
Original work; temporary until the owner's engraved creature portrait replaces it
(craftrules standards/icon-design.md). Palette: ink #0b0b0c, paper #efe9dc,
Palette: ink #0b0b0c, paper #efe9dc,
app colour #1f9d55 (proposed). -->
<defs>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

@@ -1,7 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- GridCraft PLACEHOLDER icon: a ledger page with a selected cell, on GridCraft green.
Original work; temporary until the owner's engraved creature portrait replaces it
(craftrules standards/icon-design.md). Palette: ink #0b0b0c, paper #efe9dc,
Palette: ink #0b0b0c, paper #efe9dc,
app colour #1f9d55 (proposed). -->
<defs>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

+8 -5
View File
@@ -1,13 +1,10 @@
# Contributor names for the About window (craftrules standards/contributors.md).
# Contributor names for the About window.
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
# Copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -106,3 +103,9 @@ sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Plutonium-fream]
sync_github_name = true
[people.maxm11]
sync_github_name = true
+29 -2
View File
@@ -89,8 +89,14 @@ pub fn zip2(a: &Value, b: &Value, f: impl Fn(&Value, &Value) -> Value) -> Value
/// Cell count of a `rows`×`cols` broadcast result, or `None` when it would exceed [`MAX_CELLS`].
/// Each operand passes its own size cap, but their broadcast product can be far larger
/// (`SEQUENCE(1048576)*SEQUENCE(1,16384)` is 17 billion cells), so it is checked before allocating.
/// The product is formed in `u64`: on wasm32 `usize` is 32 bits, where a `usize` product above
/// `u32::MAX` would wrap (2^32 cells → 0) and slip past the cap.
pub(super) fn broadcast_len(rows: usize, cols: usize) -> Option<usize> {
rows.checked_mul(cols).filter(|&n| n as u64 <= MAX_CELLS)
let cells = u64::try_from(rows).ok()?.checked_mul(u64::try_from(cols).ok()?)?;
if cells > MAX_CELLS {
return None;
}
usize::try_from(cells).ok()
}
fn broadcast_dim(a: usize, b: usize) -> usize {
@@ -124,7 +130,7 @@ pub(super) fn zip3(c: &Array, t: &Value, f: &Value, g: impl Fn(&Value, &Value, &
/// can't nest, so the whole helper gives `#CALC!`, as in Excel.
pub(super) fn single(v: Value) -> Option<Value> {
match v {
Value::Array(a) if a.rows * a.cols > 1 => None,
Value::Array(a) if a.data.len() > 1 => None,
v => Some(v.scalar()),
}
}
@@ -178,3 +184,24 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
BinOp::Range | BinOp::Union | BinOp::Intersect => Value::Error(CellError::Value),
}
}
#[cfg(test)]
mod tests {
use super::{MAX_CELLS, broadcast_len};
#[test]
fn broadcast_len_caps_at_max_cells() {
assert_eq!(broadcast_len(4_000, 4_000), Some(MAX_CELLS as usize));
assert_eq!(broadcast_len(4_000, 4_001), None);
assert_eq!(broadcast_len(1, MAX_CELLS as usize), Some(MAX_CELLS as usize));
}
/// `65_536 * 65_536` is 2^32. Multiplied as `usize` on wasm32 it wraps to 0, which a
/// `> MAX_CELLS` test would let through; the guard must reject the true product.
#[test]
fn broadcast_len_rejects_a_product_that_wraps_to_zero_on_32_bits() {
assert_eq!(65_536u32.wrapping_mul(65_536), 0);
assert_eq!(broadcast_len(65_536, 65_536), None);
assert_eq!(broadcast_len(1_048_576, 16_384), None);
}
}
+38
View File
@@ -614,6 +614,25 @@ fn lambda_calls_spend_one_work_budget_per_cell() {
assert_eq!(t.num("A2"), 4000.0 * 4001.0 / 2.0);
}
#[test]
fn lifted_lookups_stop_past_their_work_budget() {
// Security: each needle searched the whole lookup vector, so this one cell ran for hours
// (about 1.1e12 compares) and hung opening the file that held it. It is #NUM! at once now.
let mut t = T::new();
t.set("A1", "=ROWS(XMATCH(SEQUENCE(1048576),-SEQUENCE(1048576)))");
assert_eq!(t.get("A1"), Value::Error(CellError::Num));
// Ordinary lifted lookups are unaffected.
for (i, k) in [10, 20, 30, 40, 50].into_iter().enumerate() {
t.set(&format!("B{}", i + 1), &k.to_string());
t.set(&format!("C{}", i + 1), &(i + 1).to_string());
}
t.set("D1", "=SUM(XMATCH({30;50;10},B1:B5))");
t.set("D2", "=SUM(XLOOKUP({20;40},B1:B5,C1:C5))");
t.set("D3", "=SUM(VLOOKUP({30,10},B1:C5,2,FALSE))");
t.set("D4", "=SUM(MATCH({25,50},B1:B5))");
assert_eq!([t.num("D1"), t.num("D2"), t.num("D3"), t.num("D4")], [9.0, 6.0, 4.0, 7.0]);
}
#[test]
fn accounting_negative_text_coerces() {
let mut t = T::new();
@@ -1232,6 +1251,25 @@ fn array_broadcast_result_is_capped() {
assert_eq!(t.num("C3"), 5.0);
}
/// MAP refuses a result past `MAX_CELLS` by its checked product, before allocating it (the
/// 2^32-cell wrap that a 32-bit `usize` product would turn into 0 is pinned in
/// `broadcast_len_rejects_a_product_that_wraps_to_zero_on_32_bits`; `SEQUENCE` tops out at
/// 16384 columns, so the widest product it can build is 16384 squared).
#[test]
fn map_caps_its_result_size() {
let mut t = T::new();
for (at, formula) in
[("A1", "=MAP(SEQUENCE(4001),SEQUENCE(1,4000),LAMBDA(a,b,a))"), ("A2", "=MAP(SEQUENCE(16384),SEQUENCE(1,16384),LAMBDA(a,b,a))")]
{
t.set(at, formula);
assert_eq!(t.get(at), Value::Error(CellError::Num), "{formula}");
}
// Within the cap the broadcast shape is unchanged.
t.set("A3", "=ROWS(MAP(SEQUENCE(3),SEQUENCE(1,2),LAMBDA(a,b,a+b)))");
t.set("A4", "=COLUMNS(MAP(SEQUENCE(3),SEQUENCE(1,2),LAMBDA(a,b,a+b)))");
assert_eq!((t.num("A3"), t.num("A4")), (3.0, 2.0));
}
#[test]
fn text_function() {
let mut t = T::new();
+5 -2
View File
@@ -20,7 +20,7 @@ mod paste_special;
mod selection;
use cell::{cell_set, range_fill, range_set_values};
pub(crate) use cell::{check_arg_counts, input_to_cell, json_to_input, parse_typed_formula};
pub(crate) use cell::{check_arg_counts, input_to_cell, is_formula_input, json_to_input, parse_typed_formula};
#[cfg(test)]
pub(crate) use clipboard::parse_tsv;
use clipboard::{clear_clipboard, copy, cut, paste};
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Values",
[],
None,
"{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives)}",
"{range?: \"A1\", values: [[...]] (rows of numbers/strings/bools/null; strings starting with = are formulas), parse?: bool (default true: a string goes through typed input, so \"05.04.2026\" becomes a date and \"2.500\" a number, by en-US rules; false stores every other string as the text it is, so a dd.mm.yyyy date or a thousands separator survives, a leading ' is kept and an empty string clears the cell)} → {cells, convertedCount, converted: [{cell, input, stored}] (up to 20 of the strings typed input read as a number, date, time, boolean or error, so a script can notice)}",
has_doc,
range_set_values
),
@@ -183,6 +183,8 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
label = e.label.clone();
d.wb = e.wb;
d.selection = e.selection;
// Step by step: a rename and a new sheet undone together match up only one step apart.
super::extra::keep_view_modes(d, &cur_wb);
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
@@ -203,6 +205,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
label = e.label.clone();
d.wb = e.wb;
d.selection = e.selection;
super::extra::keep_view_modes(d, &cur_wb);
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
+67 -12
View File
@@ -5,6 +5,16 @@ use super::{
// ---------------------------------------------------------------- entry
/// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or
/// a parenthesis (not a number), as Excel takes `+SUM(1)`.
pub(crate) fn is_formula_input(input: &str) -> bool {
input.starts_with('=')
|| (input.len() > 1
&& (input.starts_with('+') || input.starts_with('-'))
&& gridcraft_core::parse::parse_number_text(input).is_none()
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('))
}
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
/// format). Inherits the destination's cell, row or column style, including its number
/// format, before parsing. Errors when the formula can't be parsed.
@@ -18,12 +28,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
if fmt_is_text {
return Ok(Some(Cell { value: Value::text(input), formula: None, style }));
}
let is_formula = input.starts_with('=')
|| (input.len() > 1
&& (input.starts_with('+') || input.starts_with('-'))
&& gridcraft_core::parse::parse_number_text(input).is_none()
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('));
if is_formula {
if is_formula_input(input) {
let body = input.strip_prefix('=').unwrap_or(input);
let expr = wb.name_call_case(parse_typed_formula(body)?);
check_arg_counts(&expr)?;
@@ -183,6 +188,22 @@ pub(crate) fn json_to_input(v: &Json) -> String {
}
}
/// How many converted strings `range.setValues` reports back, and how much of each input and
/// stored text: the report is a diagnostic, so a big write must not put a second copy of its data
/// in the result.
const MAX_REPORTED_CONVERSIONS: usize = 20;
const MAX_REPORTED_CHARS: usize = 32;
/// `text` cut to [`MAX_REPORTED_CHARS`] characters for the conversion report, with `…` when it was
/// cut. Counting characters keeps a multi-byte input whole.
fn clipped(text: &str) -> String {
let mut out: String = text.chars().take(MAX_REPORTED_CHARS).collect();
if out.len() < text.len() {
out.push('…');
}
out
}
pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let start = target_range(s, p)?.start;
@@ -200,6 +221,10 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
return Err(bad("range.setValues", "too many rows"));
}
let mut count = 0;
// The strings typed input read as something other than the text given, for the result: a
// caller can notice a "05.04.2026" that became a date without reading the file back (#2255).
let mut converted: Vec<(CellRef, String)> = Vec::new();
let mut converted_count = 0;
edit(s, |cx| {
for (ri, row) in rows.iter().enumerate() {
let cols: Vec<&Json> = match row.as_array() {
@@ -222,15 +247,35 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
// text rather than the marker that makes it text. A formula is still a
// formula, which is what the ticket asks for and what `=` means in a cell.
Json::String(text) if !parse && !text.starts_with('=') => {
let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default();
// Line breaks still turn on Wrap Text, as typed input does.
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
if text.is_empty() {
// An empty string clears the cell, as `null` and the default path do:
// an empty text cell is not blank, and a script clearing cells with
// `""` would leave cells `COUNTA` counts. The cell keeps its formatting.
input_to_cell("", sheet, at, &mut cx.wb)?
} else {
let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default();
// Line breaks still turn on Wrap Text, as typed input does.
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
}
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style })
}
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style })
}
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
};
// A string that became a formula was written as one (`=`), which is deliberate;
// only a number (dates and times included), boolean or error is a reading of the
// string and worth reporting.
if let Some(c) = &cell
&& matches!(v, Json::String(_))
&& c.formula.is_none()
&& matches!(c.value, Value::Number(_) | Value::Bool(_) | Value::Error(_))
{
converted_count += 1;
if converted.len() < MAX_REPORTED_CONVERSIONS {
converted.push((at, input.clone()));
}
}
let sh = cx.sheet_mut(sheet)?;
match cell {
Some(c) => sh.set_cell(at, c),
@@ -245,7 +290,17 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
}
Ok(())
})?;
Ok(json!({"cells": count}))
let d = s.doc()?;
let reported: Vec<Json> =
d.wb.sheet(sheet)
.map(|sh| {
converted
.iter()
.map(|(at, input)| json!({"cell": at.a1(), "input": clipped(input), "stored": clipped(&crate::display::cell_text(&d.wb, sh, *at))}))
.collect()
})
.unwrap_or_default();
Ok(json!({"cells": count, "convertedCount": converted_count, "converted": reported}))
}
pub(super) fn range_fill(s: &mut Session, p: &Json) -> Result<Json> {
+68
View File
@@ -192,6 +192,74 @@ fn set_values_can_store_strings_as_the_text_they_are() {
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A9").unwrap())).align.wrap);
}
/// The result names the strings typed input read as something else, so a script notices without
/// reading the file back (#2255). A formula and a leading apostrophe are not conversions.
#[test]
fn set_values_reports_the_strings_typed_input_read() {
let mut s = Session::new();
s.new_workbook();
let row = json!(["05.04.2026", "02/11/2026", "2.500", "4.25 %", "=1+1", "'keep"]);
let r = s.execute("range.setValues", json!({"range": "A1", "values": [row.clone()]})).unwrap();
assert_eq!(r["cells"], 6, "{r}");
assert_eq!(r["convertedCount"], 4, "{r}");
assert_eq!(r["converted"][0], json!({"cell": "A1", "input": "05.04.2026", "stored": "5/4/2026"}), "{r}");
assert_eq!(r["converted"][1], json!({"cell": "B1", "input": "02/11/2026", "stored": "2/11/2026"}), "{r}");
assert_eq!(r["converted"][2], json!({"cell": "C1", "input": "2.500", "stored": "2.5"}), "{r}");
assert_eq!(r["converted"][3], json!({"cell": "D1", "input": "4.25 %", "stored": "4.25%"}), "{r}");
// The report is a diagnostic, not a second copy of the data: a long input is cut.
let long = s.execute("range.setValues", json!({"range": "J1", "values": [["9".repeat(100)]]})).unwrap();
assert_eq!(long["convertedCount"], 1, "{long}");
let input = long["converted"][0]["input"].as_str().unwrap_or_default();
assert_eq!(input.chars().count(), 33, "32 characters and the ellipsis: {input}");
assert!(input.ends_with('…'), "{input}");
// Nothing is read with `parse: false`, so nothing is reported.
let verbatim = s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [row]})).unwrap();
assert_eq!(verbatim["convertedCount"], 0, "{verbatim}");
assert_eq!(verbatim["converted"], json!([]), "{verbatim}");
}
/// An empty string clears the cell with `parse: false` too, as `null` and the default path do: a
/// script clearing cells with "" must not leave cells `COUNTA` counts.
#[test]
fn set_values_parse_false_clears_an_empty_string() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1:B1", "values": [["keep", "keep"]]})).unwrap();
s.execute("home.bold", json!({"range": "A1"})).unwrap();
s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": [["", ""]]})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
assert_eq!(get(&mut s, "A1")["type"], "empty");
assert_eq!(get(&mut s, "B1")["type"], "empty");
let d = s.doc().unwrap();
let sh = d.wb.sheet(0).unwrap();
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("A1").unwrap())).font.bold, "clearing with \"\" keeps the formatting");
assert_eq!(s.execute("formulas.evaluate", json!({"formula": "=COUNTA(A1:B1)"})).unwrap(), json!(0.0));
}
/// The text `parse: false` stores is still text after the workbook is saved and reopened, and the
/// default's reading of a date survives as a date (#2255).
#[test]
fn set_values_text_survives_an_xlsx_roundtrip() {
let mut s = Session::new();
s.new_workbook();
let values = json!([["05.04.2026", "2.500", "4.25 %", "=1+1", 3, true]]);
s.execute("range.setValues", json!({"range": "A1", "parse": false, "values": values})).unwrap();
s.execute("range.setValues", json!({"range": "A3", "values": [["05.04.2026"]]})).unwrap();
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
let (wb, _) = crate::io::open_bytes("book.xlsx", &bytes).unwrap();
let sh = wb.sheet(0).unwrap();
for (col, want) in [(0, "05.04.2026"), (1, "2.500"), (2, "4.25 %")] {
assert_eq!(sh.value(CellRef::new(0, col)), Value::text(want), "column {col} is the text it was given");
}
assert_eq!(sh.value(CellRef::new(0, 3)), Value::number(2.0), "=1+1 is still a formula");
assert_eq!(sh.value(CellRef::new(0, 4)), Value::number(3.0));
assert_eq!(sh.value(CellRef::new(0, 5)), Value::Bool(true));
// The default read the date, and the file keeps it as one.
let at = CellRef::new(2, 0);
assert_eq!(crate::display::cell_text(&wb, sh, at), "5/4/2026");
assert_eq!(wb.styles.get(sh.style_id(at)).num_fmt.as_str(), "m/d/yyyy");
}
#[test]
fn legacy_array_entry() {
let mut s = Session::new();
+2 -2
View File
@@ -28,7 +28,7 @@ use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}
pub(crate) use scripts::has_scripts;
use scripts::{all_scripts, delete_script, new_script, record, run_script, stop_action, trust_scripts};
use window::{arrange_all, custom_views, hide_window, new_window, ruler, set_view, split, switch_windows, unhide_window, watch_window};
pub(crate) use window::{keep_watch_list, window_param};
pub(crate) use window::{keep_view_modes, keep_watch_list, window_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -310,7 +310,7 @@ pub fn specs() -> Vec<CommandSpec> {
new_cell_style
),
cmd!(query "home.addIns", "Add-ins", ["Home", "Add-ins"], None, "{} → GridCraft extends through MCP and scripts instead of add-ins", always, |_, _| Ok(json!({"addIns": [], "hint": "Use gridcraft-cli mcp or Automate › scripts"}))),
cmd!(query "formulas.recentlyUsed", "Recently Used", ["Formulas", "Function Library"], None, "{} → recently used functions in this workbook", has_doc, recently_used),
cmd!(query "formulas.recentlyUsed", "Recently Used", ["Formulas", "Function Library"], None, "{} → the functions most recently entered in formulas, newest first", has_doc, recently_used),
cmd!(query "formulas.financial", "Financial", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Financial"}))),
cmd!(query "formulas.logical", "Logical", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Logical"}))),
cmd!(query "formulas.text", "Text", ["Formulas", "Function Library"], None, "{}", always, |s, _| s.execute("formulas.functions", json!({"category": "Text"}))),
+3 -18
View File
@@ -122,25 +122,10 @@ pub(super) fn new_cell_style(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Formulas › Recently Used: the functions most recently entered in a formula, newest first
/// ([`crate::Prefs::recent_functions`]).
pub(super) fn recently_used(s: &mut Session, _: &Json) -> Result<Json> {
let mut seen: Vec<String> = Vec::new();
for (id, p) in s.journal.iter().rev() {
if id != "cell.set" {
continue;
}
let input = p.get("input").and_then(Json::as_str).unwrap_or("");
if let Ok(e) = gridcraft_formula::parse(input.trim_start_matches('=')) {
for f in e.functions() {
if !seen.iter().any(|x| x == f) {
seen.push(f.to_string());
}
}
}
if seen.len() >= 10 {
break;
}
}
Ok(json!(seen))
Ok(json!(s.prefs.recent_functions))
}
pub(super) fn use_in_formula(s: &mut Session, p: &Json) -> Result<Json> {
+29
View File
@@ -38,6 +38,35 @@ pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>
wb.names.extend(keep);
}
/// Normal, Page Layout and Page Break Preview belong to the window, not to the edits: Excel doesn't
/// undo a switch between them, and `set_view` is no undo step. So undo and redo keep each sheet's
/// current view when they swap in another snapshot of the workbook, and a view kept this way
/// doesn't make a saved workbook dirty.
pub(crate) fn keep_view_modes(d: &mut crate::DocState, now: &Workbook) {
// Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which
// keeps the sheet count and position: the sheet is the one at the same index, under a name the
// restored snapshot doesn't have.
let renamed = |i: usize| {
(now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name))
};
let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.view);
let changed: Vec<(usize, SheetViewMode)> =
d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|v| *v != sh.view).map(|v| (i, v))).collect();
if changed.is_empty() {
return;
}
let dirty = d.is_dirty();
let wb = std::sync::Arc::make_mut(&mut d.wb);
for (i, v) in changed {
if let Some(sh) = wb.sheet_mut(i) {
sh.view = v;
}
}
if !dirty {
d.saved = d.wb.clone();
}
}
pub(super) fn custom_views(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let mut views = stash_map(&d.wb, VIEWS_NAME);
+6 -2
View File
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool, document?: bool} (closes the active window, or with `document` the workbook and all its windows; the workbook closes with its last window)", has_doc, close),
cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?}", has_doc, |s, p| export(s, p, "csv")),
cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?, values?: bool} → {path, bytes}: writes the cells as displayed, like Excel's Save As CSV; `values: true` writes raw values instead (full-precision numbers, ISO 8601 dates and times, TRUE/FALSE)", has_doc, |s, p| export(s, p, "csv")),
cmd!(noundo "file.exportHtml", "Save as Web Page", ["File", "Export"], None, "{path}", has_doc, |s, p| export(s, p, "html")),
cmd!("file.properties", "Properties", ["File"], None, "{title?, subject?, author?, company?, keywords?, description?}", has_doc, properties),
cmd!(
@@ -191,7 +191,11 @@ fn export(s: &mut Session, p: &Json, ext: &str) -> Result<Json> {
wb.set_active_sheet(target_sheet(s, p)?);
}
let target = if path.ends_with(&format!(".{ext}")) { path.clone() } else { format!("{path}.{ext}") };
let bytes = crate::io::save_bytes(&wb, &target)?;
let bytes = if ext == "csv" && bool_param(p, "values").unwrap_or(false) {
crate::io::csv_values_bytes(&wb)?
} else {
crate::io::save_bytes(&wb, &target)?
};
crate::io::write_file(&target, &bytes)?;
Ok(json!({"path": target, "bytes": bytes.len()}))
}
+36 -2
View File
@@ -2,8 +2,8 @@ use super::layout::{DENSE_BLOCK, SheetLayout};
use super::objects::draw_cell_picture;
use super::text::{TextPlacement, draw_text};
use super::{
BorderLine, BorderStyle, Borders, CellRef, Color, Font, Page, PatternType, Point, RangeRef, Rgb, Sheet, Style, StyleId, Underline, Workbook,
split_sheet,
BorderLine, BorderStyle, Borders, CellRef, Color, Font, Page, PatternType, Point, RangeRef, Rgb, Sheet, Style, StyleId, Underline, Value,
Workbook, split_sheet,
};
// ---------------------------------------------------------------- drawing
@@ -280,6 +280,7 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Opt
|| merges.iter().any(|m| m.start == *c)
|| !sh.value(*c).is_empty()
|| l.style.borders != Borders::default()
|| l.style.num_fmt.as_str() == "checkbox"
})
.collect();
let rect_of = |c: CellRef| -> (f32, f32, f32, f32, bool) {
@@ -343,6 +344,8 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Opt
}
if let Some(picture) = sh.cell_pictures.get(c) {
draw_cell_picture(pg, &picture.data, (x, y, w, h), b.k);
} else if let Some(on) = checkbox_state(l, &sh.value(*c)) {
draw_checkbox(pg, (x, y, w, h), b.k, on);
} else {
draw_text(pg, b, TextPlacement { cell: *c, look: l, rect: (x, y, w, h), merged, merges: &merges, limits: (bx, bx + bw) });
}
@@ -350,6 +353,37 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Opt
pg.restore();
}
/// A checkbox cell prints TRUE/FALSE (and empty) as a box, as on screen (#2972); other values
/// print as text.
fn checkbox_state(l: &Look, v: &Value) -> Option<bool> {
if l.style.num_fmt.as_str() != "checkbox" || l.cf.as_ref().is_some_and(|cf| cf.hide_value) {
return None;
}
match v {
Value::Bool(on) => Some(*on),
Value::Empty => Some(false),
_ => None,
}
}
/// A checkbox centred in the cell: white with a grey outline, or green with a white tick.
fn draw_checkbox(pg: &mut Page, (x, y, w, h): (f32, f32, f32, f32), k: f32, on: bool) {
let s = (13.2 * k).min(w - 2.0 * k).min(h - 2.0 * k);
if s <= 0.0 {
return;
}
let (bx, by) = (x + (w - s) / 2.0, y + (h - s) / 2.0);
let corners = [[bx, by], [bx + s, by], [bx + s, by + s], [bx, by + s]];
if on {
let green = [0x10, 0x7C, 0x41];
pg.polygon(&corners, Some(green), Some((green, 0.75 * k)));
let tick = [[bx + 0.22 * s, by + 0.52 * s], [bx + 0.42 * s, by + 0.72 * s], [bx + 0.78 * s, by + 0.30 * s]];
pg.polyline(&tick, 0.14 * s, [0xFF, 0xFF, 0xFF], &[]);
} else {
pg.polygon(&corners, Some([0xFF, 0xFF, 0xFF]), Some(([110, 110, 110], 0.75 * k)));
}
}
pub(super) struct PendingPdfLink {
pub(super) page: usize,
pub(super) sheet: usize,
+16
View File
@@ -565,3 +565,19 @@ fn rotated_wrapped_text_prints_rotated() {
assert_eq!(up + down, blocks.len(), "a header line printed flat: {blocks:?}");
assert!((1..=3).contains(&up) && (1..=3).contains(&down), "up {up}, down {down}: {blocks:?}");
}
#[test]
fn checkbox_cells_print_as_boxes_not_true_false() {
// #2972: a checkbox cell printed its value as TRUE or FALSE.
let mut s = s();
s.execute("insert.checkbox", json!({"range": "A1:A2"})).unwrap();
s.execute("cell.toggleCheckbox", json!({"cell": "A2"})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": "TRUE"})).unwrap();
let (pdf, _) = pdf_of(&mut s, json!({}));
assert!(!contains(&pdf, "(FALSE) Tj"), "the unchecked box printed as FALSE");
// Only the plain TRUE in C1 prints as text; the checked box is a filled box.
let text = String::from_utf8_lossy(&pdf);
assert_eq!(text.matches("(TRUE) Tj").count(), 1, "the checked box printed as TRUE");
assert!(contains(&pdf, "0.063 0.486 0.255 rg"), "the checked box is not filled");
assert!(contains(&pdf, "0.431 0.431 0.431 RG"), "the unchecked box is not outlined");
}
+2 -2
View File
@@ -298,7 +298,7 @@ fn check_push_off_sheet(s: &Session, sheet: usize, axis: Axis, at: u32, count: u
if let Some(u) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()) {
let last = if axis == Axis::Rows { u.end.row } else { u.end.col };
if last >= at && last as u64 + count as u64 >= limit as u64 {
return Err(EngineError::Other("To prevent possible loss of data, Excel cannot shift nonblank cells off of the worksheet.".into()));
return Err(EngineError::Other("To prevent possible loss of data, GridCraft cannot shift nonblank cells off of the worksheet.".into()));
}
}
Ok(())
@@ -521,7 +521,7 @@ fn insert_cells(s: &mut Session, p: &Json) -> Result<Json> {
RangeRef::new(CellRef::new(r.start.row.max(MAX_ROWS.saturating_sub(r.height())), r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col))
};
if sh.cells.iter_range(doomed).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) {
return Err(EngineError::Other("To prevent possible loss of data, Excel cannot shift nonblank cells off of the worksheet.".into()));
return Err(EngineError::Other("To prevent possible loss of data, GridCraft cannot shift nonblank cells off of the worksheet.".into()));
}
}
let right = shift == "right";
+33 -7
View File
@@ -36,6 +36,7 @@ use gridcraft_core::split_sheet;
mod evolutionary;
mod lp;
mod model;
mod model_range;
mod nlp;
mod problem;
mod reports;
@@ -44,12 +45,15 @@ use evolutionary::{EvoEnd, evolutionary};
use lp::{Outcome, Sense, branch_and_bound, linearize, solve_lp};
pub use model::saved_model;
use model::{Goal, Method, Model, model_params, parse_model, save_model};
use model_range::{load_model_cells, reset_model, save_model_cells};
use nlp::{nlp, project};
use problem::{Evaluator, as_num, build_problem};
use reports::{ReportInput, insert_report_selections, prepare_reports, report, report_kinds, write_reports};
const CMD: &str = "data.solver";
const REPORT_CMD: &str = "data.solverReport";
const SAVE_CMD: &str = "data.solverSaveModel";
const LOAD_CMD: &str = "data.solverLoadModel";
/// Excel's limit on decision variables.
const MAX_VARS: usize = 200;
/// Most scalar constraints (after expanding ranges).
@@ -74,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Solver…",
["Data", "Analysis"],
None,
"{objective: \"B10\" (formula cell), goal?: max|min|value (default max), value?: number (for goal value), variables: \"B2:B4,D1\" (≤200 constant cells, same sheet), constraints?: [\"B5 <= 10\", \"B2:B4 >= C2:C4\", \"B2 int\", \"B3 bin\", {lhs: \"B6\", op: \"=\", rhs: 3 | \"C6\"}], nonNegative?: bool (default true: variables without a lower bound get 0), method?: grg|simplex|evolutionary (default grg), populationSize?: 100, mutationRate?: 0.075, randomSeed?: 0 (a fixed seed, so runs repeat), convergence?: 0.0001, generationsWithoutImprovement?: 50, requireBounds?: bool (default true: every variable needs both bounds; false searches within ±100 of the start) (Evolutionary options), keep?: bool (default true; false restores the original values), saveModel?: bool (default true: hidden solver_* names), maxEvaluations?: 20000, integerOptimality?: percent (default 0), saved?: bool (solve the sheet's saved model; other params override), reports?: [answer|limits] (written on new sheets when a solution is found)} → {status: optimal|converged|cannotImprove|iterationLimit|infeasible|unbounded|notLinear, message, objective, values: {cell: value}, original: {cell: value}, model: the model as params, evaluations, changed, reports?: [sheet names]}. No `objective` → {model: the saved model} (the menu opens the dialog).",
"{objective: \"B10\" (formula cell), goal?: max|min|value (default max), value?: number (for goal value), variables: \"B2:B4,D1\" (≤200 constant cells, same sheet), constraints?: [\"B5 <= 10\", \"B2:B4 >= C2:C4\", \"B2 int\", \"B3 bin\", {lhs: \"B6\", op: \"=\", rhs: 3 | \"C6\"}], nonNegative?: bool (default true: variables without a lower bound get 0), method?: grg|simplex|evolutionary (default grg), populationSize?: 100, mutationRate?: 0.075, randomSeed?: 0 (a fixed seed, so runs repeat), convergence?: 0.0001, generationsWithoutImprovement?: 50, requireBounds?: bool (default true: every variable needs both bounds; false searches within ±100 of the start) (Evolutionary options), keep?: bool (default true; false restores the original values), saveModel?: bool (default true: hidden names, solver_* as Excel names them, with the options; the evaluation limit and generations without improvement, which Excel lacks, as gridcraft_solver_evals and gridcraft_solver_stall), maxEvaluations?: 20000 (at most 200000), integerOptimality?: percent (default 0), saved?: bool (solve the sheet's saved model; other params override), reports?: [answer|limits] (written on new sheets when a solution is found)} → {status: optimal|converged|cannotImprove|iterationLimit|infeasible|unbounded|notLinear, message, objective, values: {cell: value}, original: {cell: value}, model: the model as params, evaluations, changed, reports?: [sheet names]}. No `objective` → {model: the saved model} (the menu opens the dialog).",
has_doc,
run
),
@@ -87,6 +91,33 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
report
),
cmd!(
"data.solverSaveModel",
"Save Model",
[],
None,
"{to: \"H1\" (the first cell, on the model's sheet), model?: data.solver params (default the sheet's saved model), overwrite?: false} → {range}. Writes the model down a column as formulas: =MAX(objective), =MIN(objective) or =objective=value; =COUNT(variables); one =AND(relation) per constraint (=AND(x=INT(x)) for integer, =AND((x=0)+(x=1)) for binary), which shows TRUE while it holds; and the options as an array constant {method (1 GRG Nonlinear, 2 Simplex LP, 3 Evolutionary), non-negative (1 yes, 2 no), population size, mutation rate, random seed, require bounds (1 yes, 2 no), convergence, generations without improvement, maximum evaluations, integer optimality %}, which spills into the cells to its right. Refused, with the sheet unchanged, when the model's cells, content, another formula's spilled values, merged cells or a table are in the way of the options' spill, or it would run off the sheet, and when the column would cover another formula's spilled values. A column that holds a value or a formula (a model saved there before included) is replaced only with overwrite: true; without it the command is refused (\"already holds data\"), as Excel asks first. One undo step.",
has_doc,
save_model_cells
),
cmd!(
"data.solverLoadModel",
"Load Model",
[],
None,
"{from: \"H1:H6\" (a range on the active sheet; one cell reads down to the first cell without a formula; a range needs a formula in every cell up to its last formula, and may end in empty cells)} → {model}. Reads a model written by Save Model and makes it the sheet's Solver model. The model must end with its options row ({…}), which Save Model writes last; a model cut short (a cell before the options row without a formula, or the options row cleared) is refused and the sheet's model stays as it was.",
has_doc,
load_model_cells
),
cmd!(
"data.solverReset",
"Reset All",
[],
None,
"{} → {removed, masked}. Removes the active sheet's Solver model. A model read from workbook-level names stays for the other sheets and is masked on this one by an empty sheet-level solver_opt (masked: true).",
has_doc,
reset_model
),
]
}
@@ -182,12 +213,7 @@ fn run(s: &mut Session, p: &Json) -> Result<Json> {
return Ok(json!({"model": model}));
}
let model = parse_model(s, &params)?;
let budget = params
.get("maxEvaluations")
.and_then(Json::as_f64)
.filter(|v| v.is_finite() && *v >= 1.0)
.map_or(DEFAULT_EVALS, |v| (v as u64).min(MAX_EVALS));
let gap = params.get("integerOptimality").and_then(Json::as_f64).filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(0.0, 100.0) / 100.0);
let (budget, gap) = (model.max_evals, model.gap);
let keep = bool_param(&params, "keep").unwrap_or(true);
let save = bool_param(&params, "saveModel").unwrap_or(true);
let reports = report_kinds(CMD, &params)?;
+279 -31
View File
@@ -1,6 +1,6 @@
use super::{
CMD, CellRef, DefinedName, EngineError, Json, MAX_CONSTRAINTS, MAX_POPULATION, MAX_VARS, MIN_POPULATION, RangeRef, Result, Session, Workbook,
bad, bool_param, f64_param, json, split_sheet, str_param,
CMD, CellRef, DEFAULT_EVALS, DefinedName, EngineError, Json, MAX_CONSTRAINTS, MAX_EVALS, MAX_POPULATION, MAX_VARS, MIN_POPULATION, RangeRef,
Result, Session, Workbook, bad, bool_param, f64_param, json, split_sheet, str_param,
};
// ---------------------------------------------------------------- model
@@ -128,6 +128,10 @@ pub(super) struct Model {
pub(super) non_negative: bool,
pub(super) method: Method,
pub(super) evo: EvoOptions,
/// The evaluation limit (in place of Excel's iterations and time limits).
pub(super) max_evals: u64,
/// Integer Optimality, as a fraction.
pub(super) gap: f64,
}
/// Cells of `"B2:B4,D1"` on one sheet (row-major per area, in order), at most `cap`.
@@ -288,13 +292,24 @@ pub(super) fn parse_model(s: &Session, p: &Json) -> Result<Model> {
"evolutionary" | "evo" | "genetic" => Method::Evolutionary,
m => return Err(bad(CMD, format!("unknown method `{m}` (grg, simplex or evolutionary)"))),
};
Ok(Model { sheet, objective, goal, vars, vars_text, cons, non_negative, method, evo: evo_options(p) })
let num = |k: &str| p.get(k).and_then(Json::as_f64).or_else(|| str_param(p, k).and_then(num_text)).filter(|v| v.is_finite());
let max_evals = num("maxEvaluations").filter(|v| *v >= 1.0).map_or(DEFAULT_EVALS, |v| (v as u64).min(MAX_EVALS));
// Integer Optimality is in percent: "5" and "5%" both mean 5 % (number parsing would read
// "5%" as 0.05).
let percent = p
.get("integerOptimality")
.and_then(Json::as_f64)
.or_else(|| str_param(p, "integerOptimality").and_then(|t| num_text(t.trim().trim_end_matches('%'))))
.filter(|v| v.is_finite());
let gap = percent.map_or(0.0, |v| v.clamp(0.0, 100.0) / 100.0);
Ok(Model { sheet, objective, goal, vars, vars_text, cons, non_negative, method, evo: evo_options(p), max_evals, gap })
}
// ---------------------------------------------------------------- saved model
fn ref_text(sheet_name: &str, cells: &str) -> String {
let q = crate::pivot::quote_sheet(sheet_name);
/// `"B2:B4,D1"` as absolute references, each qualified by `sheet_name` when given.
fn abs_text(sheet_name: Option<&str>, cells: &str) -> String {
let q = sheet_name.map(|n| format!("{}!", crate::pivot::quote_sheet(n))).unwrap_or_default();
cells
.split(',')
.map(str::trim)
@@ -302,16 +317,49 @@ fn ref_text(sheet_name: &str, cells: &str) -> String {
.filter_map(|part| {
let r = RangeRef::parse(split_sheet(part).1.trim())?;
let abs = |c: CellRef| format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row as u64 + 1);
Some(if r.is_single() { format!("{q}!{}", abs(r.start)) } else { format!("{q}!{}:{}", abs(r.start), abs(r.end)) })
Some(if r.is_single() { format!("{q}{}", abs(r.start)) } else { format!("{q}{}:{}", abs(r.start), abs(r.end)) })
})
.collect::<Vec<_>>()
.join(",")
}
fn ref_text(sheet_name: &str, cells: &str) -> String {
abs_text(Some(sheet_name), cells)
}
/// The evaluation limit and the generations without improvement have no Excel equivalent:
/// Excel's `solver_itr` counts iterations (100 by default) and `solver_mni` seconds, so a
/// workbook from Excel would cut GridCraft's search short. They are saved under GridCraft's own
/// names, which Excel ignores.
const EVALS_NAME: &str = "gridcraft_solver_evals";
const STALL_NAME: &str = "gridcraft_solver_stall";
/// The names of a saved model after `solver_`, as Excel's Solver writes them (GridCraft writes
/// some of them). Saving a model and Reset All remove these and no other `solver_` names.
const SOLVER_KEYS: [&str; 28] = [
"adj", "cvg", "drv", "eng", "est", "itr", "lin", "mip", "mni", "mrt", "msl", "neg", "nod", "num", "nwt", "opt", "pre", "rbv", "rlx", "rsd",
"scl", "sho", "ssz", "tim", "tol", "typ", "val", "ver",
];
/// Whether `name` is one of the names of a saved model: Excel's Solver names (`solver_opt`,
/// `solver_lhs1` and so on) and GridCraft's own. A user's name such as `solver_budget` is not.
pub(super) fn is_model_name(name: &str) -> bool {
let name = name.to_ascii_lowercase();
if name == EVALS_NAME || name == STALL_NAME {
return true;
}
let Some(key) = name.strip_prefix("solver_") else { return false };
if SOLVER_KEYS.contains(&key) {
return true;
}
// One name per constraint: solver_lhs1, solver_rel1, solver_rhs1, …
["lhs", "rel", "rhs"].iter().filter_map(|p| key.strip_prefix(p)).any(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
/// The model as hidden names scoped to its sheet (replacing any saved before).
pub(super) fn save_model(wb: &mut Workbook, m: &Model) {
let Some(sheet_name) = wb.sheet(m.sheet).map(|s| s.name.clone()) else { return };
wb.names.retain(|n| !(n.scope == Some(m.sheet) && n.name.to_ascii_lowercase().starts_with("solver_")));
wb.names.retain(|n| !(n.scope == Some(m.sheet) && is_model_name(&n.name)));
let mut put = |name: String, formula: String| {
wb.names.push(DefinedName { name, scope: Some(m.sheet), formula, comment: String::new(), hidden: true });
};
@@ -349,26 +397,31 @@ pub(super) fn save_model(wb: &mut Workbook, m: &Model) {
Method::Evolutionary => "3",
};
put("solver_eng".into(), eng.into());
if m.method == Method::Evolutionary {
put("solver_ssz".into(), m.evo.population.to_string());
put("solver_mrt".into(), m.evo.mutation.to_string());
put("solver_rsd".into(), m.evo.seed.to_string());
put("solver_rbv".into(), if m.evo.require_bounds { "1" } else { "2" }.into());
}
put(EVALS_NAME.into(), m.max_evals.to_string());
put("solver_tol".into(), m.gap.to_string());
// The Evolutionary options are kept whatever the method, as Solver Options sets them, so
// switching methods doesn't lose them.
put("solver_ssz".into(), m.evo.population.to_string());
put("solver_mrt".into(), m.evo.mutation.to_string());
put("solver_rsd".into(), m.evo.seed.to_string());
put("solver_rbv".into(), if m.evo.require_bounds { "1" } else { "2" }.into());
put("solver_cvg".into(), m.evo.convergence.to_string());
put(STALL_NAME.into(), m.evo.stall.to_string());
put("solver_ver".into(), "3".into());
}
/// The saved model of a sheet as `data.solver` params, if any.
///
/// A sheet's own (sheet-level) model wins over one saved as workbook-level names, and its names
/// are read alone, so the two never mix. A sheet-level `solver_opt` of `""` (written by Reset
/// All over a workbook-level model) means the sheet has no model.
pub fn saved_model(wb: &Workbook, sheet: usize) -> Option<Json> {
let get = |n: &str| {
wb.names
.iter()
.find(|d| d.name.eq_ignore_ascii_case(n) && (d.scope == Some(sheet) || d.scope.is_none()))
.map(|d| d.formula.trim().trim_start_matches('=').to_string())
};
let named = |n: &str, scope: Option<usize>| wb.names.iter().find(|d| d.name.eq_ignore_ascii_case(n) && d.scope == scope);
let scope = if named("solver_opt", Some(sheet)).is_some() { Some(sheet) } else { None };
let get = |n: &str| named(n, scope).map(|d| d.formula.trim().trim_start_matches('=').to_string());
let local = |t: String| -> String { t.split(',').map(|p| split_sheet(p.trim()).1.replace('$', "")).collect::<Vec<_>>().join(",") };
let objective = local(get("solver_opt")?);
if objective.is_empty() {
if objective.trim_matches('"').trim().is_empty() {
return None;
}
let goal = match get("solver_typ").as_deref().map(str::trim) {
@@ -407,11 +460,21 @@ pub fn saved_model(wb: &Workbook, sheet: usize) -> Option<Json> {
"nonNegative": get("solver_neg").as_deref().map(str::trim) != Some("2"),
"method": method,
});
for (name, key) in [("solver_ssz", "populationSize"), ("solver_mrt", "mutationRate"), ("solver_rsd", "randomSeed")] {
for (name, key) in [
("solver_ssz", "populationSize"),
("solver_mrt", "mutationRate"),
("solver_rsd", "randomSeed"),
("solver_cvg", "convergence"),
(STALL_NAME, "generationsWithoutImprovement"),
(EVALS_NAME, "maxEvaluations"),
] {
if let Some(v) = get(name).and_then(|v| num_text(&v)) {
model[key] = json!(v);
model[key] = number(v);
}
}
if let Some(v) = get("solver_tol").and_then(|v| num_text(&v)) {
model["integerOptimality"] = number(percent(v));
}
if let Some(v) = get("solver_rbv") {
model["requireBounds"] = json!(v.trim() != "2");
}
@@ -448,15 +511,200 @@ pub(super) fn model_params(wb: &Workbook, m: &Model) -> Json {
"constraints": constraints,
"nonNegative": m.non_negative,
"method": method,
"maxEvaluations": m.max_evals,
"integerOptimality": number(percent(m.gap)),
});
if m.method == Method::Evolutionary {
let e = &m.evo;
out["populationSize"] = json!(e.population);
out["mutationRate"] = json!(e.mutation);
out["randomSeed"] = json!(e.seed);
out["convergence"] = json!(e.convergence);
out["generationsWithoutImprovement"] = json!(e.stall);
out["requireBounds"] = json!(e.require_bounds);
}
let e = &m.evo;
out["populationSize"] = json!(e.population);
out["mutationRate"] = json!(e.mutation);
out["randomSeed"] = json!(e.seed);
out["convergence"] = json!(e.convergence);
out["generationsWithoutImprovement"] = json!(e.stall);
out["requireBounds"] = json!(e.require_bounds);
out
}
// ---------------------------------------------------------------- model on cells
/// The cells Save Model writes, top to bottom, as formula text.
pub(super) fn model_formulas(m: &Model) -> Result<Vec<String>> {
let one_area = |t: &str| !t.contains(',');
let mut rows = Vec::with_capacity(m.cons.len() + 3);
let obj = abs_text(None, &m.objective.a1());
rows.push(match m.goal {
Goal::Max => format!("=MAX({obj})"),
Goal::Min => format!("=MIN({obj})"),
Goal::Value(v) => format!("={obj}={}", gridcraft_core::number_to_text(v)),
});
rows.push(format!("=COUNT({})", abs_text(None, &m.vars_text)));
for c in &m.cons {
if !one_area(&c.lhs_text) || !one_area(&c.rhs_text) {
return Err(EngineError::Other("Save Model needs each side of a constraint to be one range.".into()));
}
let lhs = abs_text(None, &c.lhs_text);
rows.push(match (c.rel, &c.rhs) {
(Rel::Int, _) => format!("=AND({lhs}=INT({lhs}))"),
(Rel::Bin, _) => format!("=AND(({lhs}=0)+({lhs}=1))"),
(rel, Rhs::Cells(_)) => format!("=AND({lhs}{}{})", rel.text(), abs_text(None, &c.rhs_text)),
(rel, Rhs::Const(v)) => format!("=AND({lhs}{}{})", rel.text(), gridcraft_core::number_to_text(*v)),
(rel, Rhs::None) => format!("=AND({lhs}{}0)", rel.text()),
});
}
let e = &m.evo;
let n = gridcraft_core::number_to_text;
let eng = match m.method {
Method::Grg => 1,
Method::Simplex => 2,
Method::Evolutionary => 3,
};
let yes = |b: bool| if b { 1 } else { 2 };
rows.push(format!(
"={{{eng},{},{},{},{},{},{},{},{},{}}}",
yes(m.non_negative),
e.population,
n(e.mutation),
e.seed,
yes(e.require_bounds),
n(e.convergence),
e.stall,
m.max_evals,
n(percent(m.gap))
));
Ok(rows)
}
/// `NAME(inner)` → inner, ignoring case.
fn call_args(t: &str, name: &str) -> Option<String> {
let head = t.get(..name.len() + 1)?;
(head.eq_ignore_ascii_case(&format!("{name}(")) && t.ends_with(')')).then(|| t.get(name.len() + 1..t.len() - 1).map(str::to_string))?
}
/// References without sheet names or `$`.
fn local_refs(t: &str) -> String {
t.split(',').map(|p| split_sheet(p.trim()).1.replace('$', "")).collect::<Vec<_>>().join(",")
}
fn not_a_model() -> EngineError {
EngineError::Other("The range doesn't hold a Solver model saved with Save Model.".into())
}
/// How many values the options row of Save Model holds at least: method, non-negative,
/// population size, mutation rate, random seed, require bounds, convergence and generations
/// without improvement.
const OPTIONS_FIELDS: usize = 8;
/// The options row of Save Model, `{method, non-negative, …}`, into `model`. Refused when it
/// holds fewer than [`OPTIONS_FIELDS`] values or a value that isn't a number: a row cut short
/// or edited by hand would otherwise load with default options in place of the saved ones.
fn read_options_row(model: &mut Json, list: &str) -> Result<()> {
let incomplete = || {
EngineError::Other(format!(
"The model's options row doesn't hold the {OPTIONS_FIELDS} or more numbers Save Model writes, so the range isn't a complete model saved with Save Model."
))
};
// Every value is checked; only the first ones are kept (the row is one formula, so its
// length is bounded by the formula's).
let mut v: Vec<f64> = Vec::with_capacity(16);
let mut count = 0usize;
for t in list.split([',', ';']) {
let x = num_text(t).ok_or_else(incomplete)?;
count = count.saturating_add(1);
if v.len() < 16 {
v.push(x);
}
}
if count < OPTIONS_FIELDS {
return Err(incomplete());
}
let get = |k: usize| v.get(k).copied();
model["method"] = json!(match get(0).map(|x| x as i64) {
Some(2) => "simplex",
Some(3) => "evolutionary",
_ => "grg",
});
model["nonNegative"] = json!(get(1) != Some(2.0));
for (k, key) in [
(2, "populationSize"),
(3, "mutationRate"),
(4, "randomSeed"),
(6, "convergence"),
(7, "generationsWithoutImprovement"),
(8, "maxEvaluations"),
(9, "integerOptimality"),
] {
if let Some(x) = get(k) {
model[key] = json!(x);
}
}
model["requireBounds"] = json!(get(5) != Some(2.0));
Ok(())
}
/// One constraint row of Save Model (`AND(relation)`) as a `data.solver` constraint.
fn read_constraint_row(t: String) -> Result<String> {
let t = call_args(&t, "AND").unwrap_or(t);
if let Some((x, y)) = t.split_once("=INT(").or_else(|| t.split_once("=int(")) {
if y.strip_suffix(')') != Some(x) {
return Err(not_a_model());
}
return Ok(format!("{} int", local_refs(x)));
}
if let Some(x) = t.strip_prefix('(').and_then(|x| x.strip_suffix("=1)")).and_then(|x| x.split_once("=0)+(")).filter(|(a, b)| a == b) {
return Ok(format!("{} bin", local_refs(x.0)));
}
let (l, rel, r) = split_constraint(&t).ok_or_else(not_a_model)?;
let r = r.trim_matches('"');
Ok(match r.to_ascii_lowercase().as_str() {
"integer" => format!("{} int", local_refs(&l)),
"binary" => format!("{} bin", local_refs(&l)),
_ if num_text(r).is_some() => format!("{} {} {r}", local_refs(&l), rel.text()),
_ => format!("{} {} {}", local_refs(&l), rel.text(), local_refs(r)),
})
}
/// Reads formula text written by Save Model back into `data.solver` params.
pub(super) fn parse_model_formulas(rows: &[String]) -> Result<Json> {
let body = |t: &str| t.trim().trim_start_matches('=').replace(' ', "");
let first = body(rows.first().ok_or_else(not_a_model)?);
let (goal, objective, value) = if let Some(o) = call_args(&first, "MAX") {
("max", o, 0.0)
} else if let Some(o) = call_args(&first, "MIN") {
("min", o, 0.0)
} else {
let (o, v) = first.split_once('=').ok_or_else(not_a_model)?;
("value", o.to_string(), num_text(v).ok_or_else(not_a_model)?)
};
let variables = call_args(&body(rows.get(1).ok_or_else(not_a_model)?), "COUNT").ok_or_else(not_a_model)?;
let mut model = json!({"objective": local_refs(&objective), "goal": goal, "value": value, "variables": local_refs(&variables)});
let mut constraints = Vec::new();
let rest = rows.get(2..).unwrap_or(&[]);
for (i, row) in rest.iter().enumerate() {
let t = body(row);
if let Some(list) = t.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
// The options: the last row.
if i + 1 != rest.len() {
return Err(not_a_model());
}
read_options_row(&mut model, list)?;
break;
}
constraints.push(json!(read_constraint_row(t)?));
}
model["constraints"] = json!(constraints);
Ok(model)
}
/// Integer Optimality as a percent from its stored fraction. The product is rounded to 1E-10 %,
/// so a fraction such as 0.07 reads back as 7 and not 7.000000000000001.
fn percent(fraction: f64) -> f64 {
let p = fraction * 100.0;
let rounded = (p * 1e10).round() / 1e10;
if rounded.is_finite() { rounded } else { p }
}
/// A number read from a hidden name as JSON: a whole number as an integer, so the Solver dialog
/// shows 20000 and not 20000.0.
fn number(v: f64) -> Json {
// Whole numbers below 2^53 are exact as integers.
if v.fract() == 0.0 && v.abs() < 9_007_199_254_740_992.0 { json!(v as i64) } else { json!(v) }
}
+305
View File
@@ -0,0 +1,305 @@
//! Load/Save Model and Reset All: the model written on cells of its sheet, read back from them,
//! and removed from the sheet.
use super::model::{Rhs, is_model_name, model_formulas, parse_model, parse_model_formulas, save_model, saved_model};
use super::{
Cell, CellRef, DefinedName, EngineError, Json, LOAD_CMD, MAX_CONSTRAINTS, RangeRef, Result, SAVE_CMD, Session, Sheet, Value, bad, bool_param,
edit, json, split_sheet, str_param,
};
use crate::cmd::analysis::OVERWRITE_ERROR;
use crate::cmd::cell_param_on;
/// Most cells a model written by Save Model takes: the objective, the variables, the options
/// and one per constraint.
const MAX_MODEL_ROWS: usize = MAX_CONSTRAINTS + 3;
fn is_options_row(formula: &str) -> bool {
formula.trim().trim_start_matches('=').trim_start().starts_with('{')
}
/// The formulas from `start` down: to the first cell without a formula, or through the options
/// row (`{…}`) that ends a model written by Save Model; at most [`MAX_MODEL_ROWS`] cells.
fn formulas_down(sheet: &Sheet, start: CellRef) -> Vec<(CellRef, String)> {
let mut out = Vec::new();
for k in 0..MAX_MODEL_ROWS as u32 {
let Some(c) = start.row.checked_add(k).map(|row| CellRef::new(row, start.col)) else { break };
let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref()).map(|f| f.text.clone()) else { break };
let last = is_options_row(&f);
out.push((c, f));
if last {
break;
}
}
out
}
/// The cells of a model written by Save Model that starts at `start` (none if the cells there
/// don't hold one).
fn saved_model_cells(sheet: &Sheet, start: CellRef) -> Vec<CellRef> {
let old = formulas_down(sheet, start);
let rows: Vec<String> = old.iter().map(|(_, f)| f.clone()).collect();
if rows.last().is_some_and(|f| is_options_row(f)) && parse_model_formulas(&rows).is_ok() {
old.into_iter().map(|(c, _)| c).collect()
} else {
Vec::new()
}
}
/// How many cells the options row of Save Model (`={…}`, one row) spans.
fn options_width(formula: &str) -> u32 {
u32::try_from(formula.split(',').count()).unwrap_or(u32::MAX)
}
/// The options row is an array constant that spills `width - 1` cells to the right of `anchor`.
/// Refused, before anything is written, when the spill would run off the sheet or be blocked
/// (the anchor would show `#SPILL!`): a cell there holds content or another formula's spilled
/// values, or a merged area or a table meets the row. `ours` are the cells Save Model
/// writes or clears (a model saved at the same place before, whose options spill may be
/// replaced); `used` are the model's own cells, which the spill must not cover.
fn check_options_spill(sheet: &Sheet, anchor: CellRef, width: u32, ours: &[CellRef], used: &[CellRef]) -> Result<()> {
if width <= 1 {
return Ok(());
}
let end = anchor.col.checked_add(width - 1).filter(|c| *c < gridcraft_core::MAX_COLS).ok_or_else(|| {
EngineError::Other(format!(
"The saved model's options need {width} cells to the right from {}; choose another place to save it.",
anchor.a1()
))
})?;
let full = RangeRef::new(anchor, CellRef::new(anchor.row, end));
let spill = RangeRef::new(CellRef::new(anchor.row, anchor.col.saturating_add(1)), CellRef::new(anchor.row, end));
let blocked =
|why: String| EngineError::Other(format!("The saved model's options fill {}, but {why}; choose another place to save it.", spill.a1()));
if let Some(c) = used.iter().find(|c| spill.contains(**c)) {
return Err(blocked(format!("{} is a cell of the model", c.a1())));
}
for c in spill.iter() {
if sheet.cells.has(c) {
return Err(blocked(format!("{} isn't empty", c.a1())));
}
if sheet.spill.contains_key(&c) && sheet.spill_anchor(c).is_none_or(|a| !ours.contains(&a)) {
return Err(blocked(format!("{} holds the values of another formula", c.a1())));
}
}
if sheet.merges.iter().any(|m| m.intersects(&full)) {
return Err(blocked("merged cells are in the way".into()));
}
// A dynamic array can't spill into a table.
if sheet.tables.iter().any(|t| t.range.intersects(&full)) {
return Err(blocked("a table is in the way".into()));
}
Ok(())
}
/// Refused when a cell of the model's column holds another formula's spilled values: the
/// formula written there would block that spill (the other formula would show `#SPILL!`).
/// `ours` are as in [`check_options_spill`]: a model saved at the same place before may be
/// replaced.
fn check_column_spills(sheet: &Sheet, column: RangeRef, ours: &[CellRef]) -> Result<()> {
for c in column.iter() {
if sheet.spill.contains_key(&c) && sheet.spill_anchor(c).is_none_or(|a| !ours.contains(&a)) {
return Err(EngineError::Other(format!(
"The saved model would cover {}, which holds the values of another formula; choose another place to save it.",
c.a1()
)));
}
}
Ok(())
}
/// Refused, unless `overwrite`, when a cell of the model's column holds a value or a formula
/// (a model saved there before included): Save Model then asks before it replaces data, as
/// Excel does. The message carries [`OVERWRITE_ERROR`], which the dialog turns into its
/// question.
fn check_column_empty(sheet: &Sheet, column: RangeRef, overwrite: bool) -> Result<()> {
let taken = column.iter().find(|c| sheet.cell(*c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()));
match taken {
Some(c) if !overwrite => Err(EngineError::Other(format!(
"The range {} {OVERWRITE_ERROR} ({} isn't empty); pass overwrite: true to replace it.",
column.a1(),
c.a1()
))),
_ => Ok(()),
}
}
/// `data.solverSaveModel`: writes the model on cells of its sheet, in one step. Saving over a
/// longer model saved at the same cell clears the rest of it, so Load Model reads the new one.
pub(super) fn save_model_cells(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let params = match p.get("model") {
Some(m @ Json::Object(_)) => m.clone(),
Some(Json::Null) | None => {
saved_model(&d.wb, d.wb.active_sheet()).ok_or_else(|| EngineError::Other("This sheet has no saved Solver model.".into()))?
}
Some(_) => return Err(bad(SAVE_CMD, "`model` must be data.solver params")),
};
let model = parse_model(s, &params)?;
let to = cell_param_on(s, p, "to", model.sheet)?.ok_or_else(|| bad(SAVE_CMD, "missing `to` (the first cell of the saved model)"))?;
let rows = model_formulas(&model)?;
let count = u32::try_from(rows.len()).unwrap_or(u32::MAX);
let last = to
.row
.checked_add(count.saturating_sub(1))
.filter(|r| *r < gridcraft_core::MAX_ROWS)
.ok_or_else(|| EngineError::Other("The saved model doesn't fit below that cell.".into()))?;
let range = RangeRef::new(to, CellRef::new(last, to.col));
// The model's own cells are never overwritten.
let mut used = vec![model.objective];
used.extend(&model.vars);
for c in &model.cons {
used.extend(&c.lhs);
if let Rhs::Cells(r) = &c.rhs {
used.extend(r);
}
}
if used.iter().any(|c| range.contains(*c)) {
return Err(EngineError::Other(format!("{} overlaps the model's cells; choose another place to save it.", range.a1())));
}
let sheet = model.sheet;
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// What is left of a model saved here before; the new model's own cells stay.
let stale: Vec<CellRef> = saved_model_cells(sh, to).into_iter().filter(|c| !range.contains(*c) && !used.contains(c)).collect();
let ours: Vec<CellRef> = range.iter().chain(stale.iter().copied()).collect();
let width = rows.last().map_or(1, |f| options_width(f));
check_column_spills(sh, range, &ours)?;
check_options_spill(sh, CellRef::new(last, to.col), width, &ours, &used)?;
// Last, so the question is asked only when replacing the data would succeed.
check_column_empty(sh, range, bool_param(p, "overwrite").unwrap_or(false))?;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let cells: Vec<CellRef> = range.iter().collect();
for (c, f) in cells.iter().zip(&rows) {
let mut cell = Cell::formula(gridcraft_model::Formula::new(f));
cell.style = sh.style_id(*c);
sh.set_cell(*c, cell);
}
for c in &stale {
let style = sh.style_id(*c);
sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style });
}
for c in cells.into_iter().chain(stale) {
cx.touch(sheet, c);
}
Ok(())
})?;
Ok(json!({"range": range.a1()}))
}
/// The formulas of a model range, in order. Every cell up to the last formula must hold one: a
/// cell without a formula there (a constraint overwritten by a constant, say) would shift the
/// rows below it and drop a constraint or the options. Empty cells after the last formula are
/// allowed.
fn cells_with_formulas(r: RangeRef, formula: impl Fn(CellRef) -> Option<String>) -> Result<Vec<String>> {
let cells: Vec<(CellRef, Option<String>)> = r.iter().map(|c| (c, formula(c))).collect();
let end = cells.iter().rposition(|(_, f)| f.is_some()).map_or(0, |i| i + 1);
let mut rows = Vec::with_capacity(end);
for (c, f) in cells.into_iter().take(end) {
let f = f.ok_or_else(|| EngineError::Other(format!("{} holds no formula, so the range isn't a model saved with Save Model.", c.a1())))?;
rows.push(f);
}
Ok(rows)
}
/// A model read down from `start` must end with its options row, which Save Model always
/// writes last: a cell without a formula before it (a constraint cleared, say) would otherwise
/// end the read early and load the rows above it as the whole model, with default options.
fn complete_from_cell(start: CellRef, down: &[(CellRef, String)]) -> Result<()> {
match down.last() {
Some((_, f)) if is_options_row(f) => Ok(()),
_ if down.len() >= MAX_MODEL_ROWS => Err(EngineError::Other(format!(
"No options row ends the model within {MAX_MODEL_ROWS} cells of {}, so it isn't a model saved with Save Model.",
start.a1()
))),
last => {
let gap = last.map_or(Some(start), |(c, _)| c.row.checked_add(1).map(|row| CellRef::new(row, c.col)));
Err(EngineError::Other(match gap {
Some(gap) => format!(
"{} holds no formula before the model's options row, so {} doesn't start a complete model saved with Save Model.",
gap.a1(),
start.a1()
),
None => format!("{} doesn't start a complete model saved with Save Model.", start.a1()),
}))
}
}
}
/// `data.solverLoadModel`: makes a model written by Save Model the active sheet's model.
pub(super) fn load_model_cells(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let active = d.wb.active_sheet();
let text = str_param(p, "from").ok_or_else(|| bad(LOAD_CMD, "missing `from` (the saved model's range)"))?;
let (sh, body) = split_sheet(text);
if sh.is_some_and(|n| d.wb.sheet_index(&n) != Some(active)) {
return Err(EngineError::Other("Load Model reads a model saved on the active sheet.".into()));
}
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(LOAD_CMD, format!("not a range: `{text}`")))?;
let cap = MAX_MODEL_ROWS;
let sheet = d.wb.sheet(active).ok_or(EngineError::NoDocument)?;
let formula = |c: CellRef| sheet.cell(c).and_then(|x| x.formula.as_ref()).map(|f| f.text.clone());
let rows: Vec<String> = if r.is_single() {
let down = formulas_down(sheet, r.start);
complete_from_cell(r.start, &down)?;
down.into_iter().map(|(_, f)| f).collect()
} else {
if r.count() > cap as u64 {
return Err(EngineError::Other(format!("The range is too large for a saved model (at most {cap} cells).")));
}
let rows = cells_with_formulas(r, formula)?;
if !rows.last().is_some_and(|f| is_options_row(f)) {
return Err(EngineError::Other(format!(
"{} doesn't end with the model's options row, so it isn't a complete model saved with Save Model.",
r.a1()
)));
}
rows
};
let params = parse_model_formulas(&rows)?;
let model = parse_model(s, &params)?;
if model.sheet != active {
return Err(EngineError::Other("Load Model reads a model of the active sheet.".into()));
}
edit(s, |cx| {
save_model(&mut cx.wb, &model);
Ok(())
})?;
Ok(json!({"model": saved_model(&s.doc()?.wb, active)}))
}
/// Whether a defined name belongs to the saved model of `sheet`.
fn is_sheet_model_name(n: &DefinedName, sheet: usize) -> bool {
n.scope == Some(sheet) && is_model_name(&n.name)
}
/// `data.solverReset`: Reset All removes the active sheet's model. A model the sheet reads from
/// workbook-level names (which other sheets may read too) is left in place and masked by an
/// empty sheet-level `solver_opt`, so no other sheet's model changes.
pub(super) fn reset_model(s: &mut Session, _p: &Json) -> Result<Json> {
let d = s.doc()?;
let active = d.wb.active_sheet();
let removed = d.wb.names.iter().filter(|n| is_sheet_model_name(n, active)).count();
let mut after = d.wb.names.clone();
after.retain(|n| !is_sheet_model_name(n, active));
let masked = {
let mut probe = (*d.wb).clone();
probe.names = after;
saved_model(&probe, active).is_some()
};
if removed > 0 || masked {
edit(s, |cx| {
cx.wb.names.retain(|n| !is_sheet_model_name(n, active));
if masked {
cx.wb.names.push(DefinedName {
name: "solver_opt".into(),
scope: Some(active),
formula: "\"\"".into(),
comment: String::new(),
hidden: true,
});
}
Ok(())
})?;
}
Ok(json!({"removed": removed, "masked": masked}))
}
+3 -7
View File
@@ -2,8 +2,8 @@ use super::lp::Outcome;
use super::model::{Constraint, Goal, Method, Model, Rel, Rhs, parse_model, saved_model};
use super::problem::{Evaluator, Problem, as_num, build_problem};
use super::{
Cell, CellRef, Ctx, DEFAULT_EVALS, DocState, EngineError, Json, MAX_EVALS, PRECISION, REPORT_CMD, Result, Session, Sheet, Trial, Value, bad,
edit, json, optimise, str_param,
Cell, CellRef, Ctx, DocState, EngineError, Json, PRECISION, REPORT_CMD, Result, Session, Sheet, Trial, Value, bad, edit, json, optimise,
str_param,
};
// ---------------------------------------------------------------- reports
@@ -362,11 +362,7 @@ pub(super) fn report(s: &mut Session, p: &Json) -> Result<Json> {
};
let solution = point("values")?;
let original = if p.get("original").is_some() { point("original")? } else { solution.clone() };
let budget = params
.get("maxEvaluations")
.and_then(Json::as_f64)
.filter(|v| v.is_finite() && *v >= 1.0)
.map_or(DEFAULT_EVALS, |v| (v as u64).min(MAX_EVALS));
let budget = model.max_evals;
let message = str_param(p, "message").unwrap_or("").chars().take(500).collect();
let inp = ReportInput { model: &model, prob: &prob, original, solution, message, budget };
let built = prepare_reports(s.doc()?, &kinds, &inp)?;
+532
View File
@@ -400,6 +400,538 @@ fn solver_report_insertion_keeps_variable_edit_guards() {
}
}
fn formula(s: &Session, a1: &str) -> String {
let d = s.doc().unwrap();
d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap_or_default()
}
#[test]
fn save_and_load_model_round_trip_through_cells() {
let mut s = s();
set(&mut s, &[("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2"), ("B3", "=A1+2*A2"), ("C2", "24")]);
let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= C2", "B3 <= 6", "A1:A2 int", "A2 bin", "A1 >= 1"], "method": "simplex"});
s.execute("data.solver", model.clone()).unwrap();
let out = s.execute("data.solverSaveModel", json!({"to": "H1"})).unwrap();
assert_eq!(out["range"], "H1:H8");
let rows: Vec<String> = (1..=8).map(|r| formula(&s, &format!("H{r}"))).collect();
assert_eq!(
rows,
[
"MAX($B$1)",
"COUNT($A$1:$A$2)",
"AND($B$2<=$C$2)",
"AND($B$3<=6)",
"AND($A$1:$A$2=INT($A$1:$A$2))",
"AND(($A$2=0)+($A$2=1))",
"AND($A$1>=1)",
"{2,1,100,0.075,0,1,0.0001,50,20000,0}",
]
);
// The constraint cells show whether each constraint holds at the solution (4, 0).
assert_eq!(at(&s, "Sheet1", "H3"), Value::Bool(true));
assert_eq!(at(&s, "Sheet1", "H2"), Value::number(2.0));
// Reset All removes the model; Load Model restores it from the range or its first cell.
assert_eq!(s.execute("data.solverReset", json!({})).unwrap()["removed"].as_u64().map(|n| n > 0), Some(true));
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null());
assert_eq!(s.execute("data.solverReset", json!({})).unwrap()["removed"], 0);
for from in ["H1:H8", "H1"] {
let loaded = s.execute("data.solverLoadModel", json!({"from": from})).unwrap();
assert_eq!(loaded["model"]["objective"], "B1", "{loaded}");
assert_eq!(loaded["model"]["constraints"], json!(["B2 <= C2", "B3 <= 6", "A1:A2 int", "A2 bin", "A1 >= 1"]));
assert_eq!(loaded["model"]["method"], "simplex");
}
set(&mut s, &[("A1", "0"), ("A2", "0")]);
let r = s.execute("data.solver", json!({"saved": true})).unwrap();
assert_eq!((r["status"].as_str(), n(&s, "A1"), n(&s, "A2")), (Some("optimal"), 4.0, 0.0), "{r}");
// A Value Of goal and the Evolutionary options survive too; an explicit model is saved
// as given.
let evo = json!({"objective": "B1", "goal": "value", "value": -2.5, "variables": "A1:A2", "constraints": ["A1:A2 <= 10"], "nonNegative": false, "method": "evolutionary", "populationSize": 40, "randomSeed": 3, "requireBounds": false});
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "J10", "model": evo})).unwrap()["range"], "J10:J13");
assert_eq!(formula(&s, "J10"), "$B$1=-2.5");
let m = s.execute("data.solverLoadModel", json!({"from": "J10:J13"})).unwrap()["model"].clone();
assert_eq!((m["goal"].as_str(), m["value"].as_f64(), m["nonNegative"].as_bool()), (Some("value"), Some(-2.5), Some(false)), "{m}");
assert_eq!((m["method"].as_str(), m["populationSize"].as_f64(), m["randomSeed"].as_f64()), (Some("evolutionary"), Some(40.0), Some(3.0)));
assert_eq!(m["requireBounds"], false);
// Each command is one undo step.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("data.solver", json!({})).unwrap()["model"]["method"], "simplex");
// Refused: no model or no target, overlapping the model, off the sheet, ranges that
// hold no model, other sheets and oversized ranges.
set(&mut s, &[("L1", "=1+1"), ("L2", "=SUM(A1:A2)")]);
for (cmd, p) in [
("data.solverSaveModel", json!({})),
("data.solverSaveModel", json!({"to": "A1"})),
("data.solverSaveModel", json!({"to": "B3"})),
("data.solverSaveModel", json!({"to": "A1048575"})),
("data.solverSaveModel", json!({"to": "H1", "model": {"objective": "B1", "variables": "A1,A2", "constraints": ["A1,A2 <= 3"]}})),
("data.solverSaveModel", json!({"to": "H1", "model": "B1"})),
("data.solverLoadModel", json!({})),
("data.solverLoadModel", json!({"from": "L1:L2"})),
("data.solverLoadModel", json!({"from": "Z1"})),
("data.solverLoadModel", json!({"from": "H2:H8"})),
("data.solverLoadModel", json!({"from": "H1:H1048576"})),
("data.solverLoadModel", json!({"from": "Nope!H1"})),
] {
assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p}");
}
s.execute("data.solverReset", json!({})).unwrap();
assert!(s.execute("data.solverSaveModel", json!({"to": "H1"})).is_err(), "no model to save");
}
#[test]
fn reset_all_masks_a_workbook_level_model_and_keeps_other_sheets_models() {
let mut s = s();
set(&mut s, &[("A1", "1"), ("B1", "=2*A1")]);
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
let (one, two) = {
let wb = &s.doc().unwrap().wb;
(wb.sheet_index("Sheet1").unwrap(), wb.sheet_index("Two").unwrap())
};
// A model saved as workbook-level names, which every sheet reads.
{
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
for (name, formula) in [
("solver_opt", "Sheet1!$B$1"),
("solver_adj", "Sheet1!$A$1"),
("solver_typ", "1"),
("solver_num", "0"),
("solver_eng", "2"),
("solver_ssz", "500"),
] {
wb.names.push(gridcraft_model::DefinedName {
name: name.into(),
scope: None,
formula: formula.into(),
comment: String::new(),
hidden: true,
});
}
}
let model = |s: &Session, sheet: usize| super::saved_model(&s.doc().unwrap().wb, sheet);
assert_eq!(model(&s, one).map(|m| m["objective"].clone()), Some(json!("B1")));
// Reset All empties this sheet's model, which the dialog then shows, and no other sheet's.
let r = s.execute("data.solverReset", json!({})).unwrap();
assert_eq!(model(&s, one), None, "{r}");
assert_eq!(r["masked"], true, "{r}");
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null());
assert_eq!(model(&s, two).map(|m| m["objective"].clone()), Some(json!("B1")));
assert_eq!(s.doc().unwrap().wb.names.iter().filter(|n| n.scope.is_none()).count(), 6);
// Undo brings the model back with its options; the mask survives XLSX.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(model(&s, one).and_then(|m| m["populationSize"].as_f64()), Some(500.0));
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(model(&s, one), None);
let b64 = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap()["base64"].as_str().unwrap().to_string();
s.execute("file.open", json!({"name": "r.xlsx", "base64": b64})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
assert_eq!(model(&s, one), None);
assert!(model(&s, two).is_some());
// A model saved on the sheet replaces the mask and is read alone: the workbook-level
// population size doesn't leak into it.
s.execute("data.solver", json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 3"], "method": "simplex"})).unwrap();
let m = model(&s, one).unwrap();
assert_eq!((m["objective"].as_str(), m["populationSize"].as_f64()), (Some("B1"), Some(100.0)), "{m}");
assert_eq!(s.execute("data.solverReset", json!({})).unwrap()["masked"], true);
assert_eq!(model(&s, one), None);
}
#[test]
fn saving_a_shorter_model_over_a_longer_one_clears_the_rest() {
let mut s = s();
set(&mut s, &[("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2"), ("B3", "=A1+2*A2"), ("H9", "=1+1")]);
let long = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24", "B3 <= 6", "A1 <= 3", "A2 <= 3"]});
let short = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24"]});
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "H1", "model": long})).unwrap()["range"], "H1:H7");
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "H1", "model": short, "overwrite": true})).unwrap()["range"], "H1:H4");
// The old model's last rows are cleared; a formula below it stays.
for r in 5..=7 {
assert_eq!(formula(&s, &format!("H{r}")), "", "H{r}");
}
assert_eq!(formula(&s, "H9"), "1+1");
let loaded = s.execute("data.solverLoadModel", json!({"from": "H1"})).unwrap();
assert_eq!(loaded["model"]["constraints"], json!(["B2 <= 24"]), "{loaded}");
// Reading down from one cell stops at the options row even with formulas right below it.
set(&mut s, &[("H5", "=2+2")]);
let loaded = s.execute("data.solverLoadModel", json!({"from": "H1"})).unwrap();
assert_eq!(loaded["model"]["constraints"], json!(["B2 <= 24"]), "{loaded}");
// Saving over cells that hold no model leaves the cells below them as they are.
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "H8", "model": short, "overwrite": true})).unwrap()["range"], "H8:H11");
assert_eq!(formula(&s, "H5"), "2+2");
}
#[test]
fn save_model_asks_before_it_replaces_data_and_is_one_undo_step() {
let mut s = s();
set(&mut s, &[("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2"), ("H2", "kept"), ("H3", "=1+1")]);
let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24"]});
// A value or a formula in the column: refused, the sheet unchanged, the cell named.
let e = s.execute("data.solverSaveModel", json!({"to": "H1", "model": model.clone()})).unwrap_err().to_string();
assert!(e.contains(crate::cmd::analysis::OVERWRITE_ERROR) && e.contains("H1:H4") && e.contains("H2"), "{e}");
assert_eq!((at(&s, "Sheet1", "H2"), formula(&s, "H3"), formula(&s, "H1")), (Value::text("kept"), "1+1".into(), String::new()));
// So is a model saved there before, and `overwrite` only as a true boolean.
assert!(s.execute("data.solverSaveModel", json!({"to": "J10", "model": model.clone()})).is_ok());
for overwrite in [json!(null), json!(false), json!("true"), json!(1)] {
let e = s.execute("data.solverSaveModel", json!({"to": "J10", "model": model.clone(), "overwrite": overwrite})).unwrap_err();
assert!(e.to_string().contains(crate::cmd::analysis::OVERWRITE_ERROR), "{overwrite}: {e}");
}
// overwrite: true replaces the data in one undo step, which brings it all back.
let out = s.execute("data.solverSaveModel", json!({"to": "H1", "model": model, "overwrite": true})).unwrap();
assert_eq!(out["range"], "H1:H4");
assert_eq!((formula(&s, "H1"), formula(&s, "H2"), formula(&s, "H3")), ("MAX($B$1)".into(), "COUNT($A$1:$A$2)".into(), "AND($B$2<=24)".into()));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(
(at(&s, "Sheet1", "H2"), formula(&s, "H3"), formula(&s, "H1"), formula(&s, "H4")),
(Value::text("kept"), "1+1".into(), String::new(), String::new())
);
assert_eq!(formula(&s, "J10"), "MAX($B$1)");
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(formula(&s, "H2"), "COUNT($A$1:$A$2)");
}
#[test]
fn saving_and_resetting_a_model_keep_the_users_own_solver_names() {
let mut s = s();
set(&mut s, &[("A1", "0"), ("B1", "=ABS(A1-3)"), ("C1", "100")]);
let name = |name: &str, scope: Option<usize>, formula: &str, hidden: bool| gridcraft_model::DefinedName {
name: name.into(),
scope,
formula: formula.into(),
comment: String::new(),
hidden,
};
{
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
// The user's own names, on the sheet and the workbook, and Excel's Solver names the
// model replaces.
wb.names.push(name("solver_budget", Some(0), "Sheet1!$C$1", false));
wb.names.push(name("Solver_Lhs_Total", Some(0), "Sheet1!$C$1", false));
wb.names.push(name("solver_budget", None, "Sheet1!$C$1", false));
wb.names.push(name("solver_lin", Some(0), "2", true));
wb.names.push(name("solver_lhs12", Some(0), "Sheet1!$A$1", true));
}
let names = |s: &Session| -> Vec<String> {
let mut v: Vec<String> = s.doc().unwrap().wb.names.iter().map(|n| format!("{}@{:?}", n.name, n.scope)).collect();
v.sort();
v
};
let mine = ["Solver_Lhs_Total@Some(0)", "solver_budget@None", "solver_budget@Some(0)"];
let model = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 4"], "method": "simplex"});
s.execute("data.solver", model.clone()).unwrap();
let after = names(&s);
assert!(mine.iter().all(|n| after.contains(&n.to_string())), "{after:?}");
assert!(!after.iter().any(|n| n.starts_with("solver_lin") || n.starts_with("solver_lhs12")), "{after:?}");
// Load Model saves the model again; Reset All removes it and nothing else.
s.execute("data.solverSaveModel", json!({"to": "H1"})).unwrap();
s.execute("data.solverLoadModel", json!({"from": "H1"})).unwrap();
assert!(mine.iter().all(|n| names(&s).contains(&n.to_string())), "{:?}", names(&s));
let model_names = names(&s).len() - mine.len();
let r = s.execute("data.solverReset", json!({})).unwrap();
assert_eq!((r["removed"].as_u64(), r["masked"].as_bool()), (Some(model_names as u64), Some(false)), "{r}");
assert_eq!(names(&s), mine);
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null());
}
#[test]
fn save_model_refuses_a_place_where_the_options_cannot_spill() {
let mut s = s();
set(&mut s, &[("B1", "=ABS(A1-3)"), ("H24", "=SEQUENCE(1,3)"), ("K30", "=SEQUENCE(3)"), ("M50", "=SEQUENCE(3)")]);
// Tables whose empty data rows meet an options row: one in its way, one holding the
// options cell.
for range in ["T59:U62", "W69:W71"] {
s.execute("insert.table", json!({"range": range, "header": true})).unwrap();
}
let model = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["F4 <= 5"]});
let save = |s: &mut Session, to: &str| s.execute("data.solverSaveModel", json!({"to": to, "model": model.clone()}));
// The options row (H4) spills into I4:Q4: a value in its last cell is in the way.
set(&mut s, &[("Q4", "x")]);
let e = save(&mut s, "H1").unwrap_err().to_string();
assert!(e.contains("I4:Q4") && e.contains("Q4 isn't empty"), "{e}");
assert_eq!((formula(&s, "H1"), formula(&s, "H4")), (String::new(), String::new()));
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null());
// With the row clear the options spill, and saving again at the same cell replaces them.
set(&mut s, &[("Q4", "")]);
for overwrite in [false, true] {
let p = json!({"to": "H1", "model": model.clone(), "overwrite": overwrite});
assert_eq!(s.execute("data.solverSaveModel", p).unwrap()["range"], "H1:H4");
assert_eq!(
(at(&s, "Sheet1", "H4"), at(&s, "Sheet1", "I4"), at(&s, "Sheet1", "O4"), at(&s, "Sheet1", "Q4")),
(Value::number(1.0), Value::number(1.0), Value::number(50.0), Value::number(0.0))
);
}
// Refused: in the options row, a formula (H24), another formula's spilled values (K31,
// from K30), a cell of the model (F4), merged cells, a table and the sheet's last columns;
// a column over another formula's spilled values (I24 of H24:J24, M51 of M50:M52) or with
// its options cell in a table.
s.execute("home.mergeCells", json!({"range": "S8:T9"})).unwrap();
for (to, why) in [
("G21", "H24 isn't empty"),
("J28", "K31 holds the values of another formula"),
("E1", "F4 is a cell of the model"),
("R5", "merged"),
("S57", "T60:AB60, but a table is in the way"),
("XFA1", "need 10 cells"),
("I21", "cover I24, which holds the values of another formula"),
("M51", "cover M51, which holds the values of another formula"),
("W67", "X70:AF70, but a table is in the way"),
] {
let e = save(&mut s, to).unwrap_err().to_string();
assert!(e.contains(why), "{to}: {e}");
assert_eq!(formula(&s, to), "", "{to}");
}
assert_eq!(
(at(&s, "Sheet1", "J24"), at(&s, "Sheet1", "K32"), at(&s, "Sheet1", "M52")),
(Value::number(3.0), Value::number(3.0), Value::number(3.0))
);
}
#[test]
fn load_model_refuses_a_range_with_a_cell_without_a_formula() {
let mut s = s();
set(&mut s, &[("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2"), ("B3", "=A1+2*A2")]);
let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24", "B3 <= 6", "A1 <= 3"], "method": "simplex"});
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "H1", "model": model})).unwrap()["range"], "H1:H6");
// A range with empty cells after the model loads it.
let loaded = s.execute("data.solverLoadModel", json!({"from": "H1:H9"})).unwrap();
assert_eq!(loaded["model"]["constraints"], json!(["B2 <= 24", "B3 <= 6", "A1 <= 3"]), "{loaded}");
s.execute("data.solverReset", json!({})).unwrap();
// A constraint overwritten by a constant would drop that constraint; a gap before the
// options row would drop the options. Both are refused, naming the cell.
for (cell, input) in [("H4", "7"), ("H5", "")] {
let before = formula(&s, cell);
set(&mut s, &[(cell, input)]);
let e = s.execute("data.solverLoadModel", json!({"from": "H1:H6"})).unwrap_err().to_string();
assert!(e.contains(cell), "{e}");
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null(), "{cell}");
set(&mut s, &[(cell, &format!("={before}"))]);
}
assert!(s.execute("data.solverLoadModel", json!({"from": "H1:H6"})).is_ok());
}
#[test]
fn load_model_refuses_a_model_cut_short_and_keeps_the_old_one() {
let mut s = s();
set(&mut s, &[("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2"), ("B3", "=A1+2*A2")]);
let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24", "B3 <= 6", "A1 <= 3"], "method": "simplex"});
s.execute("data.solver", model).unwrap();
assert_eq!(s.execute("data.solverSaveModel", json!({"to": "H1"})).unwrap()["range"], "H1:H6");
let kept = |s: &mut Session| {
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
assert_eq!((m["constraints"].clone(), m["method"].clone()), (json!(["B2 <= 24", "B3 <= 6", "A1 <= 3"]), json!("simplex")), "{m}");
};
// A constraint cleared (H4), the options row cleared (H6) or replaced by a constant: from
// the first cell or as a range, the rows above the gap are not loaded as the whole model.
for (cell, input) in [("H4", ""), ("H6", ""), ("H6", "7")] {
let before = formula(&s, cell);
set(&mut s, &[(cell, input)]);
for from in ["H1", "H1:H6", "H1:H9"] {
let e = s.execute("data.solverLoadModel", json!({"from": from})).unwrap_err().to_string();
assert!(e.contains("complete model") || e.contains(cell), "{cell} {from}: {e}");
kept(&mut s);
}
set(&mut s, &[(cell, &format!("={before}"))]);
}
// An options row cut short or edited by hand: fewer than the eight values Save Model
// writes, or a value that isn't a number (among the eight, after them or after the sixteenth).
let options = formula(&s, "H6");
for row in [
"={1}",
"={2,1,100,0.075,0,1,0.0001}",
"={2,1,100,0.075,0,1,\"x\",50}",
"={2,TRUE,100,0.075,0,1,0.0001,50}",
"={2,1,100,0.075,0,1,0.0001,50,\"x\"}",
"={2,1,100,0.075,0,1,0.0001,50,9,10,11,12,13,14,15,16,\"x\"}",
] {
set(&mut s, &[("H6", row)]);
for from in ["H1", "H1:H6"] {
let e = s.execute("data.solverLoadModel", json!({"from": from})).unwrap_err().to_string();
assert!(e.contains("complete model"), "{row} {from}: {e}");
kept(&mut s);
}
}
// More values than eight (as a later version may write) still load.
set(&mut s, &[("H6", &format!("={}", options.trim_end_matches('}').to_string() + ",7,8}"))]);
assert!(s.execute("data.solverLoadModel", json!({"from": "H1"})).is_ok());
kept(&mut s);
set(&mut s, &[("H6", &format!("={options}"))]);
// The gap is named when reading down from one cell.
set(&mut s, &[("H4", "")]);
let e = s.execute("data.solverLoadModel", json!({"from": "H1"})).unwrap_err().to_string();
assert!(e.contains("H4 holds no formula"), "{e}");
s.execute("edit.undo", json!({})).unwrap();
assert!(s.execute("data.solverLoadModel", json!({"from": "H1"})).is_ok());
kept(&mut s);
}
#[test]
fn load_model_reads_a_bounded_column_and_refuses_malformed_cells() {
let mut s = s();
set(&mut s, &[("B1", "=ABS(A1-3)")]);
let put = |s: &mut Session, col: u32, rows: std::ops::Range<u32>, f: &dyn Fn(u32) -> String| {
let d = s.doc_mut().unwrap();
let sh = std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut d.wb).sheets[0]);
for r in rows {
sh.set_cell(CellRef::new(r, col), gridcraft_model::Cell::formula(gridcraft_model::Formula::new(&f(r))));
}
};
// A column of formulas far longer than any model: read from its first cell, the read stops
// after the most rows a model takes and the column is refused; as a range, it is refused
// before any cell is read.
put(&mut s, 15, 0..5_000, &|r| format!("{r}+1"));
for from in ["P1", "P1:P5000", "P1:P1048576", "A1:XFD1048576"] {
assert!(s.execute("data.solverLoadModel", json!({"from": from})).is_err(), "{from}");
}
// Malformed and hostile cells and ranges: an error each, never a panic, no model.
let bad = ["AND(", "{", "{1e400,2", "MAX(Nope!A1)", "COUNT($A$1:$A$2", "AND($B$1<=", "MAX($B$1)&\"x\""];
put(&mut s, 17, 0..bad.len() as u32, &|r| bad[r as usize].to_string());
put(&mut s, 18, 0..1, &|_| format!("AND({})", "(".repeat(10_000)));
for r in 1..=bad.len() {
assert!(s.execute("data.solverLoadModel", json!({"from": format!("R{r}")})).is_err(), "R{r}");
}
for from in ["S1", "", ":", "P1:", "H0", "Sheet9!H1", "'Sheet1'!R1:R7", "R7:R1"] {
assert!(s.execute("data.solverLoadModel", json!({"from": from})).is_err(), "{from}");
}
assert!(s.execute("data.solverLoadModel", json!({"from": 7})).is_err());
assert!(s.execute("data.solver", json!({})).unwrap()["model"].is_null());
}
#[test]
fn load_model_keeps_the_evolutionary_convergence_and_generations() {
let mut s = s();
set(&mut s, &[("B1", "=ABS(A1-3)")]);
let evo = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 4"], "method": "evolutionary", "convergence": 0.001, "generationsWithoutImprovement": 20});
s.execute("data.solverSaveModel", json!({"to": "H1", "model": evo})).unwrap();
let m = s.execute("data.solverLoadModel", json!({"from": "H1"})).unwrap()["model"].clone();
assert_eq!((m["convergence"].as_f64(), m["generationsWithoutImprovement"].as_f64()), (Some(0.001), Some(20.0)), "{m}");
// They survive XLSX; Excel's time limit (solver_mni, in seconds) isn't written or read.
let b64 = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap()["base64"].as_str().unwrap().to_string();
s.execute("file.open", json!({"name": "c.xlsx", "base64": b64})).unwrap();
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
assert_eq!((m["convergence"].as_f64(), m["generationsWithoutImprovement"].as_f64()), (Some(0.001), Some(20.0)), "{m}");
assert!(!s.doc().unwrap().wb.names.iter().any(|n| n.name == "solver_mni"));
// Reset All removes the GridCraft name with the rest.
s.execute("data.solverReset", json!({})).unwrap();
assert!(s.doc().unwrap().wb.names.iter().all(|n| n.scope != Some(0)));
}
#[test]
fn solver_options_are_saved_with_the_model() {
let mut s = s();
set(&mut s, &[("B1", "=10*A1+13*A2"), ("B2", "=5*A1+6*A2")]);
let p = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 10", "A1:A2 bin"], "method": "evolutionary", "maxEvaluations": "3000", "integerOptimality": 5, "convergence": 0.001, "generationsWithoutImprovement": 20, "mutationRate": "0.1"});
let r = s.execute("data.solver", p).unwrap();
assert!(r["evaluations"].as_u64().unwrap() <= 3001, "{r}");
// The solve's own result gives whole numbers as integers too.
for k in ["maxEvaluations", "integerOptimality", "generationsWithoutImprovement", "populationSize", "randomSeed"] {
assert!(r["model"][k].is_i64() || r["model"][k].is_u64(), "{k}: {r}");
}
// The options survive XLSX in the hidden names, as given or as text.
let b64 = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap()["base64"].as_str().unwrap().to_string();
s.execute("file.open", json!({"name": "o.xlsx", "base64": b64})).unwrap();
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
let f = |k: &str| m[k].as_f64();
assert_eq!((f("maxEvaluations"), f("integerOptimality"), f("convergence")), (Some(3000.0), Some(5.0), Some(0.001)), "{m}");
assert_eq!((f("generationsWithoutImprovement"), f("mutationRate")), (Some(20.0), Some(0.1)));
// Whole numbers read back as integers, so the Solver dialog shows 3000 and not 3000.0.
for k in ["maxEvaluations", "integerOptimality", "generationsWithoutImprovement", "populationSize", "randomSeed"] {
assert!(m[k].is_i64(), "{k}: {m}");
}
assert_eq!(m["maxEvaluations"].to_string(), "3000");
// Out-of-range options are clamped, not refused.
let r = s.execute("data.solver", json!({"saved": true, "maxEvaluations": "1e300", "integerOptimality": -4})).unwrap();
assert_eq!((r["model"]["maxEvaluations"].as_f64(), r["model"]["integerOptimality"].as_f64()), (Some(200_000.0), Some(0.0)));
}
#[test]
fn excel_iteration_and_time_limits_are_not_read_as_gridcraft_options() {
let mut s = s();
set(&mut s, &[("A1", "0"), ("B1", "=ABS(A1-3)")]);
let model = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 4"], "method": "evolutionary"});
s.execute("data.solver", model.clone()).unwrap();
let names = |s: &Session| -> Vec<String> {
let d = s.doc().unwrap();
d.wb.names.iter().filter(|n| n.scope == Some(0)).map(|n| n.name.clone()).collect()
};
// GridCraft's evaluation limit and generations go under its own names, not Excel's.
let saved = names(&s);
assert!(saved.iter().all(|n| n != "solver_itr" && n != "solver_mni"), "{saved:?}");
assert!(saved.iter().any(|n| n == "gridcraft_solver_evals") && saved.iter().any(|n| n == "gridcraft_solver_stall"), "{saved:?}");
// Excel's own limits, as a workbook from Excel holds them: 100 iterations, 30 seconds.
{
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
wb.names.retain(|n| !n.name.starts_with("gridcraft_"));
for (name, formula) in [("solver_itr", "100"), ("solver_mni", "30")] {
wb.names.push(gridcraft_model::DefinedName {
name: name.into(),
scope: Some(0),
formula: formula.into(),
comment: String::new(),
hidden: true,
});
}
}
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
assert!(m["maxEvaluations"].is_null() && m["generationsWithoutImprovement"].is_null(), "{m}");
set(&mut s, &[("A1", "0")]);
let r = s.execute("data.solver", json!({"saved": true})).unwrap();
assert!(r["evaluations"].as_u64().unwrap() > 100, "{r}");
assert!((n(&s, "A1") - 3.0).abs() < 1e-3, "{r}");
// Saving again replaces GridCraft's names; Reset All removes them with the rest. Simplex
// LP refuses the nonlinear ABS model, but the model is saved before the solve.
let r = s.execute(
"data.solver",
json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 4"], "method": "simplex", "maxEvaluations": 700, "keep": false}),
);
let m = super::saved_model(&s.doc().unwrap().wb, 0).unwrap();
assert_eq!((m["method"].as_str(), m["maxEvaluations"].as_f64()), (Some("simplex"), Some(700.0)), "{m} {r:?}");
let saved = names(&s);
assert_eq!(
saved.iter().filter(|n| n.starts_with("gridcraft_")).collect::<Vec<_>>(),
["gridcraft_solver_evals", "gridcraft_solver_stall"],
"{saved:?}"
);
s.execute("data.solver", model).unwrap();
s.execute("data.solverReset", json!({})).unwrap();
assert!(names(&s).is_empty(), "{:?}", names(&s));
}
#[test]
fn integer_optimality_reads_a_percent_sign_as_percent() {
let mut s = s();
set(&mut s, &[("B1", "=3*A1")]);
for (given, want) in [(json!("5%"), 5.0), (json!(" 2.5 % "), 2.5), (json!("5"), 5.0), (json!(5), 5.0), (json!("150%"), 100.0)] {
let p = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 4", "A1 int"], "method": "simplex", "integerOptimality": given});
let r = s.execute("data.solver", p).unwrap();
assert_eq!(r["model"]["integerOptimality"].as_f64(), Some(want), "{given}: {r}");
}
// Percents whose fraction is not exact in binary read back as given, from the solve's
// result and from the saved model.
for given in [7.0, 29.0, 0.1] {
let p = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 4", "A1 int"], "method": "simplex", "integerOptimality": given});
let r = s.execute("data.solver", p).unwrap();
assert_eq!(r["model"]["integerOptimality"].as_f64(), Some(given), "{r}");
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
assert_eq!(m["integerOptimality"].as_f64(), Some(given), "{m}");
}
}
#[test]
fn evolutionary_options_survive_a_solve_with_another_method() {
let mut s = s();
set(&mut s, &[("B1", "=3*A1")]);
let p = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 4"], "method": "grg", "populationSize": 40, "mutationRate": 0.2, "randomSeed": 7, "convergence": 0.001, "generationsWithoutImprovement": 25, "requireBounds": false});
let r = s.execute("data.solver", p).unwrap();
assert_eq!(r["model"]["populationSize"].as_f64(), Some(40.0), "{r}");
// The saved model keeps them for the next time the method is Evolutionary.
let m = s.execute("data.solver", json!({})).unwrap()["model"].clone();
let f = |k: &str| m[k].as_f64();
assert_eq!((f("populationSize"), f("mutationRate"), f("randomSeed")), (Some(40.0), Some(0.2), Some(7.0)), "{m}");
assert_eq!((f("convergence"), f("generationsWithoutImprovement"), m["requireBounds"].as_bool()), (Some(0.001), Some(25.0), Some(false)));
}
#[test]
fn limits_report_of_a_nonlinear_model() {
// The largest rectangle with perimeter at most 20 (5 × 5): with the height held at 5, the
+16 -1
View File
@@ -593,7 +593,7 @@ pub fn series(cx: &mut Ctx, sheet: usize, options: SeriesOptions<'_>) -> Result<
};
// The stop value bounds the series in the direction it runs (a growth by 0.5 falls).
if let Some(s) = stop
&& ((v >= prev && v > s) || (v < prev && v < s))
&& ((v >= prev && round15(v) > s) || (v < prev && round15(v) < s))
{
break;
}
@@ -806,6 +806,21 @@ mod tests {
assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023"));
}
#[test]
fn series_keeps_value_equal_to_stop_after_float_drift() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", serde_json::json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("edit.fillSeries", serde_json::json!({"range": "A1:A6", "type": "linear", "step": 0.1, "stop": 1.3})).unwrap();
s.execute("cell.set", serde_json::json!({"cell": "B1", "input": "0.1"})).unwrap();
s.execute("edit.fillSeries", serde_json::json!({"range": "B1:B4", "type": "growth", "step": 3, "stop": 0.3})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
let col = |c: u32, n: u32| (0..n).map(|r| sh.value(CellRef::new(r, c))).collect::<Vec<_>>();
let n = Value::number;
assert_eq!(col(0, 6), vec![n(1.0), n(1.1), n(1.2), n(1.3), Value::Empty, Value::Empty]);
assert_eq!(col(1, 4), vec![n(0.1), n(0.3), Value::Empty, Value::Empty]);
}
#[test]
fn flash_programs() {
let p = learn(&[("John Smith".into(), "Smith, John".into())]).unwrap();
+39 -5
View File
@@ -153,7 +153,8 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
}
// Text named `.xlsx` is read as text.
if sniffed == gridcraft_xlsx::Format::Xlsx || (kind == Some(FileKind::Xlsx) && sniffed != gridcraft_xlsx::Format::Csv) {
let (wb, report) = gridcraft_xlsx::read_xlsx(bytes).map_err(|e| {
// Google Sheets' export wrapper is read as the formula inside when GridCraft calculates it (#2871).
let (wb, report) = gridcraft_xlsx::read_xlsx_with(bytes, &gridcraft_calc::is_known_function).map_err(|e| {
EngineError::Other(match (&e, gridcraft_xlsx::oversized_part(bytes)) {
(gridcraft_xlsx::IoError::TooLarge(_), Some((part, size))) => part_too_large_message(name, &part, size),
_ => format!("We can't open '{name}': {e}"),
@@ -182,17 +183,17 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
}
Some(FileKind::Tsv) => {
let opts = gridcraft_xlsx::CsvOptions { delimiter: b'\t', parse_values: !csv_as_text, ..Default::default() };
let mut wb = gridcraft_xlsx::read_csv(bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
let (mut wb, report) = gridcraft_xlsx::read_csv_with_report(bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
// Tab is what makes it a .tsv/.txt; saved as .csv it gets the CSV default.
wb.csv_delimiter = None;
rename_first_sheet(&mut wb, name);
Ok((wb, vec![]))
Ok((wb, report.warnings))
}
_ => {
let opts = gridcraft_xlsx::CsvOptions { delimiter: 0, parse_values: !csv_as_text, ..Default::default() };
let mut wb = gridcraft_xlsx::read_csv(bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
let (mut wb, report) = gridcraft_xlsx::read_csv_with_report(bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
rename_first_sheet(&mut wb, name);
Ok((wb, vec![]))
Ok((wb, report.warnings))
}
}
}
@@ -306,6 +307,39 @@ fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
.map_err(|e| EngineError::Other(e.to_string()))
}
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
/// times as ISO 8601, booleans `TRUE`/`FALSE`, errors as their text, text as stored. Save As CSV
/// writes displayed text instead ([`save_bytes`]) and stays the default.
pub fn csv_values_bytes(wb: &Workbook) -> Result<Vec<u8>> {
let Some(sh) = wb.sheet(wb.active_sheet()) else { return Ok(Vec::new()) };
gridcraft_xlsx::write_csv(sh, wb.csv_delimiter.unwrap_or(b','), |c| match sh.value(c) {
gridcraft_core::Value::Number(n) if n.is_finite() => {
let shape = crate::display::number_format(wb.styles.get(sh.style_id(c)).num_fmt.as_str()).date_shape(n);
match shape.zip(gridcraft_core::date::datetime_from_serial(wb.date_system, n)) {
Some(((date, time), d)) => iso(&d, date, time),
None => n.to_string(),
}
}
gridcraft_core::Value::Text(t) => t.to_string(),
v => crate::display::value_text_as(wb, &v, "General"),
})
.map_err(|e| EngineError::Other(e.to_string()))
}
/// `date` and `time` say which parts the cell's format shows; a format with neither is not a date.
fn iso(d: &gridcraft_core::date::DateTime, date: bool, time: bool) -> String {
let day = format!("{:04}-{:02}-{:02}", d.year, d.month, d.day);
let mut clock = format!("{:02}:{:02}:{:02}", d.hour, d.minute, d.second);
if d.milli != 0 {
clock.push_str(&format!(".{:03}", d.milli));
}
match (date, time) {
(true, true) => format!("{day}T{clock}"),
(false, true) => clock,
_ => day,
}
}
pub(crate) fn esc(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
+44
View File
@@ -19,6 +19,7 @@ fn copied(wb: &Workbook, range: &str) -> String {
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(unix)]
#[test]
fn save_fails_upfront_when_the_temp_name_is_taken() {
// Another local user who can write the directory must not be able to point the
@@ -290,6 +291,20 @@ fn csv_named_history_does_not_get_the_reserved_sheet_name() {
assert_eq!(wb.sheets[0].name, "Sales");
}
#[test]
fn csv_and_text_open_read_day_first_dates_and_report_a_guessed_order() {
let may = gridcraft_core::date::serial_from_ymd(gridcraft_core::DateSystem::D1900, 2026, 5, 31).unwrap();
let april = gridcraft_core::date::serial_from_ymd(gridcraft_core::DateSystem::D1900, 2026, 4, 3).unwrap();
for file in ["dates.csv", "dates.txt"] {
let (wb, warnings) = open_bytes(file, b"When\n31/05/2026\n03/04/2026\n").unwrap();
assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(1, 0)), gridcraft_core::Value::Number(may), "{file}");
assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(2, 0)), gridcraft_core::Value::Number(april), "{file}");
assert!(warnings.is_empty(), "{file}: {warnings:?}");
}
let (_, warnings) = open_bytes("ambiguous.csv", b"When\n03/04/2026\n12/01/2026\n").unwrap();
assert!(warnings.iter().any(|w| w.contains("column A") && w.contains("ambiguous")), "{warnings:?}");
}
/// A save that can't be put in place (here a folder already has the workbook's name, as
/// with a file another app holds locked) fails without leaving `<name>.sctmp` behind.
#[cfg(not(target_arch = "wasm32"))]
@@ -560,3 +575,32 @@ fn content_wins_over_a_mismatched_extension() {
assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 1)), gridcraft_core::Value::text("b"), "{name}");
}
}
/// #2871: opening an XLSX reads Google Sheets' `IFERROR(__xludf.DUMMYFUNCTION("…"),cached)`
/// wrapper as the formula inside when GridCraft calculates every function it calls (including
/// the evaluator's own, such as ROW), and keeps the wrapper, and so the cached value, for a
/// Google-only function.
#[test]
fn opening_google_sheets_export_unwraps_only_formulas_gridcraft_calculates() {
use gridcraft_core::{CellRef, Value};
let mut wb = Workbook::new();
let sh = std::sync::Arc::make_mut(&mut wb.sheets[0]);
let wrapped = [
("A1", "IFERROR(__xludf.DUMMYFUNCTION(\"SUM(ROW(B1:B3))\"),6)", Value::Number(6.0)),
("A2", "IFERROR(__xludf.DUMMYFUNCTION(\"GOOGLETRANSLATE(\"\"hi\"\",\"\"en\"\",\"\"fr\"\")\"),\"salut\")", Value::text("salut")),
];
for (at, text, value) in &wrapped {
let cell = gridcraft_model::Cell {
value: value.clone(),
formula: Some(std::sync::Arc::new(gridcraft_model::Formula::new(text))),
..Default::default()
};
sh.cells.set(CellRef::parse(at).unwrap(), cell);
}
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
let (opened, _) = open_bytes("google.xlsx", &bytes).unwrap();
let text = |at: &str| opened.sheets[0].cells.get(CellRef::parse(at).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone());
assert_eq!(text("A1").as_deref(), Some("SUM(ROW(B1:B3))"));
assert_eq!(text("A2").as_deref(), Some("IFERROR(__XLUDF.DUMMYFUNCTION(\"GOOGLETRANSLATE(\"\"hi\"\",\"\"en\"\",\"\"fr\"\")\"),\"salut\")"));
assert_eq!(opened.sheets[0].cells.get(CellRef::parse("A2").unwrap()).map(|c| c.value.clone()), Some(Value::text("salut")));
}
+19
View File
@@ -20,6 +20,7 @@ pub mod outline;
pub mod paper;
pub mod pivot;
pub mod pivot_calc;
pub mod recent;
pub mod record;
pub mod sample;
pub mod selection;
@@ -390,6 +391,10 @@ pub struct Prefs {
pub formula_bar: bool,
/// The statistics the status bar shows for a selection (right-click the status bar).
pub status_bar: StatusBarStats,
/// Formulas › Recently Used: the functions most recently entered in a formula, newest first
/// (at most [`recent::MAX`]; see [`recent`]). An application list, as in Excel.
#[serde(deserialize_with = "recent::lenient")]
pub recent_functions: Vec<String>,
}
/// The selection statistics shown on the status bar, set with `view.statusBar`. Excel turns on
@@ -424,6 +429,7 @@ impl Default for Prefs {
user_dictionary: vec![],
formula_bar: true,
status_bar: StatusBarStats::default(),
recent_functions: recent::defaults(),
}
}
}
@@ -558,6 +564,17 @@ impl Session {
pub fn doc_mut(&mut self) -> Result<&mut DocState> {
self.active_mut().ok_or(EngineError::NoDocument)
}
/// The warning an edit of `at` on `sheet` gets from sheet protection, or `None` when the edit
/// is allowed. Front ends ask before opening an editor, so typing into a locked cell never
/// leaves a draft that can't be entered (and so blocks saving).
pub fn locked_cell_message(&self, sheet: usize, at: CellRef) -> Option<String> {
let d = self.active()?;
let sh = d.wb.sheet(sheet)?;
if !sh.is_protected() || !d.wb.styles.get(sh.style_id(at)).protection.locked {
return None;
}
cmd::locked_cell_error(sh, at, &d.unlocked_ranges)
}
/// Opens a workbook in a new window, which becomes the active one.
pub fn add_document(&mut self, d: DocState) -> usize {
let uid = d.uid;
@@ -587,6 +604,7 @@ impl Session {
pub fn new_workbook(&mut self) -> usize {
let n = (1..).find(|n| !self.docs.iter().any(|d| d.title == format!("Book{n}") && d.path.is_none())).unwrap_or(1);
let mut wb = Workbook::new();
wb.props.author = self.prefs.user_name.clone();
for _ in 1..self.prefs.sheets_in_new_workbook.clamp(1, 255) {
let name = wb.next_sheet_name();
wb.sheets.push(Arc::new(gridcraft_model::Sheet::new(name)));
@@ -789,6 +807,7 @@ impl Session {
}
if self.journal_paused == 0 {
self.push_journal(id, cmd::journal_params(&params));
recent::note(&mut self.prefs.recent_functions, id, &params);
}
}
// Inside an undo group the group owns the step. A command that ended a group open before
+205
View File
@@ -0,0 +1,205 @@
//! Formulas › Recently Used: the functions most recently entered in a formula.
//!
//! The list is [`crate::Prefs::recent_functions`], an application list like Excel's, saved with
//! the other preferences. [`crate::Session::execute`] calls [`note`] for each `cell.*` and
//! `range.*` command it journals, from any source (the interface, the control channel, MCP or a
//! script), so the list never depends on the journal, which drops its oldest entries.
use std::collections::HashSet;
use std::sync::OnceLock;
use crate::cmd::edit::is_formula_input;
use gridcraft_formula::lexer::{Tok, tokenize};
use gridcraft_formula::normalize_function_name;
use serde::Deserialize;
use serde_json::Value as Json;
/// How many functions the list keeps.
pub const MAX: usize = 10;
/// The longest formula read (Excel's formula length limit): a longer one was not typed.
const FORMULA_MAX: usize = 8_192;
/// The most formulas read from one command: a large paste needs only its last few.
const SCAN_BUDGET: usize = 2_000;
/// What the list holds before any function has been used.
pub fn defaults() -> Vec<String> {
["SUM", "AVERAGE", "IF", "COUNT", "MAX", "MIN", "SUMIF", "XLOOKUP", "PMT", "TODAY"].map(String::from).to_vec()
}
/// Whether `name` (upper case, without `_xlfn.`) is a function of the catalog.
fn known(name: &str) -> bool {
static NAMES: OnceLock<HashSet<String>> = OnceLock::new();
NAMES
.get_or_init(|| crate::cmd::formulas::function_list().iter().filter_map(|f| f["name"].as_str().map(str::to_ascii_uppercase)).collect())
.contains(name)
}
/// The functions a formula calls, outermost first, known functions only. A formula is what a
/// cell takes as one (`=…`, or `+…`/`-…` as Excel takes `+SUM(1)`).
pub fn functions_in_formula(text: &str) -> Vec<String> {
if !is_formula_input(text) {
return vec![];
}
let body = text.strip_prefix('=').unwrap_or(text);
if body.len() > FORMULA_MAX {
return vec![];
}
let mut out: Vec<String> = Vec::new();
for t in tokenize(body).unwrap_or_default() {
if let Tok::Func(name) = t.tok {
let name = normalize_function_name(&name);
if known(&name) && !out.contains(&name) {
out.push(name);
}
}
}
out
}
/// The formula texts a command's params enter, the last first, at most `budget` of them.
fn formulas_newest_first<'a>(id: &str, params: &'a Json, budget: usize) -> Vec<&'a str> {
fn walk<'a>(v: &'a Json, out: &mut Vec<&'a str>, depth: usize, budget: usize) {
match v {
Json::String(s) if is_formula_input(s) && out.len() < budget => out.push(s),
// A range's values are rows of cells; anything deeper is not a cell value.
Json::Array(a) if depth < 2 => {
for x in a.iter().rev() {
if out.len() >= budget {
return;
}
walk(x, out, depth + 1, budget);
}
}
_ => {}
}
}
let mut out = Vec::new();
if id.starts_with("cell.") || id.starts_with("range.") {
for key in ["formula", "values", "value", "input"] {
if let Some(v) = params.get(key) {
walk(v, &mut out, 0, budget);
}
}
}
out
}
/// Moves `names` (most recent first) to the front of `recent`, keeping at most [`MAX`].
pub fn push(recent: &mut Vec<String>, names: &[String]) {
let mut next: Vec<String> = Vec::with_capacity(MAX);
for n in names.iter().chain(recent.iter()) {
if next.len() == MAX {
break;
}
if !next.contains(n) {
next.push(n.clone());
}
}
*recent = next;
}
/// Moves the functions that the formulas a command entered call to the front of `recent`. The
/// last formulas are read first (they are the most recent), within [`SCAN_BUDGET`].
pub(crate) fn note(recent: &mut Vec<String>, id: &str, params: &Json) {
let mut names: Vec<String> = Vec::new();
for f in formulas_newest_first(id, params, SCAN_BUDGET) {
for n in functions_in_formula(f) {
if !names.contains(&n) {
names.push(n);
}
}
if names.len() >= MAX {
break;
}
}
if !names.is_empty() {
push(recent, &names);
}
}
/// Reads a saved list leniently: known function names only, at most [`MAX`]. A value that is not
/// a list gives the default list, so a hand-edited or hostile `prefs.json` loses this list, never
/// the other preferences.
pub(crate) fn lenient<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
let raw = Json::deserialize(d)?;
let Some(list) = raw.as_array() else { return Ok(defaults()) };
let mut out = Vec::new();
for name in list.iter().filter_map(Json::as_str) {
if out.len() == MAX {
break;
}
let name = name.to_ascii_uppercase();
if known(&name) && !out.contains(&name) {
out.push(name);
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn formulas_name_their_functions_outermost_first() {
assert_eq!(functions_in_formula("=IF(SUM(A1:A3)>2,_xlfn.XLOOKUP(1,B:B,C:C),sum(1))"), ["IF", "SUM", "XLOOKUP"]);
assert!(functions_in_formula("=MYLAMBDA(1)+A1").is_empty(), "only known functions");
assert!(functions_in_formula("SUM(1)").is_empty(), "not a formula");
assert!(functions_in_formula("=\"SUM(\"").is_empty(), "inside a string");
assert!(functions_in_formula(&format!("=SUM({})", "1+".repeat(9000))).is_empty(), "too long");
assert!(functions_in_formula("=((((").is_empty());
assert!(functions_in_formula("=").is_empty());
// A formula may be typed with + or - instead of =, as input_to_cell takes it.
assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]);
assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]);
assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers");
assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas");
}
#[test]
fn commands_give_their_formulas_newest_first() {
let read = |id: &str, params: Json| formulas_newest_first(id, &params, SCAN_BUDGET).into_iter().map(String::from).collect::<Vec<_>>();
assert_eq!(read("range.setValues", json!({"values": [["=SUM(1)", 2], ["x", "=PMT(1,2,3)"]]})), ["=PMT(1,2,3)", "=SUM(1)"]);
assert_eq!(read("cell.set", json!({"input": "=NPV(1,2)"})), ["=NPV(1,2)"]);
assert_eq!(read("range.setValues", json!({"values": [["+SUM(1)", "-5", "-ABS(2)"]]})), ["-ABS(2)", "+SUM(1)"]);
assert!(read("home.bold", json!({"input": "=IRR(1)"})).is_empty(), "only cell.* and range.* enter formulas");
assert!(read("range.setValues", json!({"values": [[["=FV(1,2,3)"]]]})).is_empty(), "deeper than rows of cells");
// A large paste is read from its end, within the budget.
let rows: Vec<Json> = (0..5_000).map(|i| json!([format!("=ABS({i})")])).collect();
let paste = json!({ "values": rows });
let last = formulas_newest_first("range.setValues", &paste, 3);
assert_eq!(last, ["=ABS(4999)", "=ABS(4998)", "=ABS(4997)"]);
}
#[test]
fn recent_keeps_ten_distinct_newest_first() {
let mut r = defaults();
assert!(r.iter().all(|n| known(n)), "the default list names known functions");
push(&mut r, &["PMT".into(), "NPV".into()]);
assert_eq!(r.len(), MAX);
assert_eq!(&r[..3], ["PMT", "NPV", "SUM"]);
assert_eq!(r.iter().filter(|n| *n == "PMT").count(), 1);
let many: Vec<String> =
["ABS", "ACOS", "AND", "CHOOSE", "DATE", "EXP", "FIND", "INDEX", "LEFT", "LN", "MOD", "NOW"].map(String::from).to_vec();
push(&mut r, &many);
assert_eq!(r, many[..MAX]);
}
#[test]
fn a_saved_list_is_read_leniently() {
let prefs = |v: Json| serde_json::from_value::<crate::Prefs>(v).unwrap();
assert_eq!(prefs(json!({"r1c1": true})).recent_functions, defaults(), "a prefs.json from before the list gets the default");
// A hostile value loses only itself, never the other preferences.
let bad = prefs(json!({"r1c1": true, "recentFunctions": 5}));
assert!(bad.r1c1);
assert_eq!(bad.recent_functions, defaults());
let mut odd: Vec<Json> = ["npv", "NOT_A_FUNCTION", "SUM", "NPV"].iter().map(|n| json!(n)).chain([json!(3), json!(null)]).collect();
odd.extend(crate::cmd::formulas::function_list().into_iter().take(40).map(|f| f["name"].clone()));
let odd = prefs(json!({ "recentFunctions": odd }));
assert_eq!(&odd.recent_functions[..2], ["NPV", "SUM"]);
assert_eq!(odd.recent_functions.len(), MAX);
let back = prefs(serde_json::to_value(&odd).unwrap());
assert_eq!(back.recent_functions, odd.recent_functions, "the list survives a save and reload");
}
}
+167
View File
@@ -1400,6 +1400,17 @@ fn protection_refuses_edits_of_locked_cells() {
assert_eq!(v(&s, "A1"), Value::Number(1.0));
}
#[test]
fn locked_cell_message_matches_what_an_edit_would_be_refused_with() {
let s = protected(json!({}));
let locked = CellRef::parse("A1").unwrap();
let unlocked = CellRef::parse("D1").unwrap();
assert!(s.locked_cell_message(0, locked).is_some_and(|m| m.contains("protected sheet")));
assert_eq!(s.locked_cell_message(0, unlocked), None, "an unlocked cell stays editable");
assert_eq!(s.locked_cell_message(9, locked), None, "no such sheet");
}
#[test]
fn protection_allows_permitted_row_and_column_edits() {
let mut s = protected(json!({"insertRows": true, "deleteRows": true, "insertColumns": true}));
@@ -2007,6 +2018,15 @@ fn a_whole_column_table_without_headers_stays_on_the_sheet() {
assert!(e.to_string().contains("pushed off the end"), "{e}");
}
#[test]
fn inserting_a_column_next_to_far_right_data_names_gridcraft_in_the_refusal() {
let mut sess = s();
sess.execute("cell.set", json!({"cell": "XFD1", "input": "2"})).unwrap();
let e = sess.execute("home.insertColumns", json!({"cols": "A:A"})).unwrap_err();
assert!(e.to_string().contains("GridCraft cannot shift nonblank cells"), "{e}");
assert!(!e.to_string().contains("Excel"), "{e}");
}
#[test]
fn inserting_cells_refuses_to_push_values_off_the_sheet() {
for (shift, edge, last_fit, last_ok) in [("right", "XFD1", "XFC1", "XFD1"), ("down", "A1048576", "A1048575", "A1048576")] {
@@ -2015,6 +2035,7 @@ fn inserting_cells_refuses_to_push_values_off_the_sheet() {
sess.execute("cell.set", json!({"cell": edge, "input": "2"})).unwrap();
let e = sess.execute("home.insertCells", json!({"range": "A1", "shift": shift})).unwrap_err();
assert!(e.to_string().contains("loss of data"), "{e}");
assert!(e.to_string().contains("GridCraft") && !e.to_string().contains("Excel"), "{e}");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
assert_eq!(v(&sess, edge), Value::Number(2.0));
// A value that still fits moves to the last valid cell.
@@ -2393,6 +2414,36 @@ fn deleting_a_3d_span_end_sheet_keeps_the_rest() {
}
}
#[test]
fn workbook_view_roundtrips_after_sheet_deletion_and_reordering() {
let view = gridcraft_model::WorkbookView { show_sheet_tabs: false, show_horizontal_scroll: true, show_vertical_scroll: false, tab_ratio: 350 };
for (initial_active, command, params, expected_order, expected_active) in [
("Third", "home.deleteSheet", json!({"sheet": "First"}), vec!["Second", "Third"], 1),
("Third", "home.deleteSheet", json!({"sheet": "Third"}), vec!["First", "Second"], 1),
("First", "home.deleteSheet", json!({"sheet": "Third"}), vec!["First", "Second"], 0),
("Third", "sheet.move", json!({"sheet": "Third", "to": 0}), vec!["Third", "First", "Second"], 0),
("Third", "sheet.move", json!({"sheet": "First", "to": 2}), vec!["Second", "Third", "First"], 2),
] {
let mut session = s();
session.execute("sheet.rename", json!({"name": "First"})).unwrap();
for name in ["Second", "Third"] {
session.execute("home.insertSheet", json!({"name": name})).unwrap();
}
std::sync::Arc::make_mut(&mut session.doc_mut().unwrap().wb).view = view;
session.execute("sheet.activate", json!({"sheet": initial_active})).unwrap();
session.execute(command, params).unwrap();
let wb = &session.doc().unwrap().wb;
assert_eq!(wb.active_sheet(), expected_active, "{command}");
assert_eq!(wb.sheets.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), expected_order, "{command}");
let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(wb).unwrap()).unwrap();
assert_eq!(back.sheets.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), expected_order, "{command} after reopening");
assert_eq!(back.active_sheet(), expected_active, "activeTab follows {command}");
assert_eq!(back.active().unwrap().name, expected_order[expected_active], "the active sheet is not a stale index");
assert_eq!(back.view, view, "workbook display settings survive {command}");
}
}
#[test]
fn xlsx_roundtrip_through_engine() {
let mut s = s();
@@ -2500,6 +2551,53 @@ fn saving_an_opened_semicolon_csv_keeps_semicolons() {
std::fs::remove_dir_all(dir).unwrap();
}
/// `file.exportCsv` writes displayed text by default (Excel's Save As CSV); `values: true` writes the
/// raw values for automation: full precision, ISO dates and times.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn export_csv_values_writes_raw_values_and_the_default_stays_displayed_text() {
let mut s = s();
for (cell, input, code) in [
("A1", "1234.5", "$#,##0.00"),
("B1", "0.123456789", "0.00"),
("C1", "46023", "d-mmm-yy"),
("D1", "46023.5", "yyyy-mm-dd hh:mm"),
("E1", "0.75", "h:mm"),
("F1", "TRUE", "General"),
("G1", "a,b", "General"),
("H1", "=1/0", "General"),
("I1", "1", "h:mm"),
("J1", "1.5", "h:mm"),
("K1", "46023", "yyyy-mm-dd hh:mm"),
("L1", "1.5", "[h]:mm"),
("M1", "2.5", "[>=3]yyyy-mm-dd;[<3]hh:mm"),
] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
s.execute("home.numberFormat", json!({"range": cell, "code": code})).unwrap();
}
#[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("gridcraft-csv-values-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let displayed = dir.join("displayed.csv");
s.execute("file.exportCsv", json!({"path": displayed})).unwrap();
s.execute("file.exportCsv", json!({"path": dir.join("off.csv"), "values": false})).unwrap();
let raw = dir.join("raw.csv");
s.execute("file.exportCsv", json!({"path": raw, "values": true})).unwrap();
let saved = s.execute("file.saveBytes", json!({"format": "csv"})).unwrap();
let default = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap();
// The default export is byte for byte what Save As CSV writes, and `values: false` is the default.
assert_eq!(std::fs::read(&displayed).unwrap(), default);
assert_eq!(std::fs::read(dir.join("off.csv")).unwrap(), default);
let default = String::from_utf8(default).unwrap();
assert!(default.starts_with("\"$1,234.50\",0.12,1-Jan-26,"), "{default}");
assert_eq!(
std::fs::read_to_string(&raw).unwrap(),
"1234.5,0.123456789,2026-01-01,2026-01-01T12:00:00,18:00:00,TRUE,\"a,b\",#DIV/0!,00:00:00,12:00:00,2026-01-01T00:00:00,1.5,12:00:00\r\n"
);
std::fs::remove_dir_all(dir).unwrap();
}
/// A workbook whose B1 is `=[1]Sheet1!A1`, linked to `link` (an external relationship target).
fn linked_workbook(link: &str) -> Vec<u8> {
use std::io::{Cursor, Write};
@@ -5177,3 +5275,72 @@ fn unique_nonce() -> u64 {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
/// Normal, Page Layout and Page Break Preview are not undo steps (as in Excel), so undoing or
/// redoing an edit keeps each sheet in the view it is in now, instead of putting back the view
/// of the snapshot it swaps in. Found through the command-sequence fuzz (seed 177).
#[test]
fn undo_and_redo_keep_each_sheets_view() {
use gridcraft_model::SheetViewMode;
let view = |s: &Session, i: usize| s.doc().unwrap().wb.sheet(i).unwrap().view;
let mut s = s();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(v(&s, "A1"), Value::Empty);
assert_eq!(view(&s, 0), SheetViewMode::PageBreakPreview, "undo leaves the view alone");
s.execute("view.pageLayout", json!({})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(v(&s, "A1"), Value::Number(1.0));
assert_eq!(view(&s, 0), SheetViewMode::PageLayout, "redo leaves the view alone");
// Undoing a rename: the sheet is found at its position under the restored name.
s.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap();
s.execute("view.normal", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_ne!(s.doc().unwrap().wb.sheet(0).unwrap().name, "Renamed");
assert_eq!(view(&s, 0), SheetViewMode::Normal);
// Undoing a new sheet: the other sheets keep theirs.
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("home.insertSheet", json!({"name": "Extra"})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets.len(), 1);
assert_eq!(view(&s, 0), SheetViewMode::PageBreakPreview);
}
#[test]
fn a_multi_step_undo_keeps_views_through_each_step() {
// A rename and a new sheet undone in one call: neither the name nor the sheet count matches
// between the first and last workbook, so the view is carried step by step.
let mut s = s();
let first = s.doc().unwrap().wb.sheet(0).unwrap().name.clone();
s.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap();
s.execute("view.pageBreakPreview", json!({"sheet": 0})).unwrap();
s.execute("home.insertSheet", json!({"name": "Extra"})).unwrap();
s.execute("edit.undo", json!({"steps": 2})).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.wb.sheets.len(), 1);
assert_eq!(d.wb.sheet(0).unwrap().name, first);
assert_eq!(d.wb.sheet(0).unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview);
s.execute("edit.redo", json!({"steps": 2})).unwrap();
let d = s.doc().unwrap();
assert_eq!((d.wb.sheets.len(), d.wb.sheet(0).unwrap().name.as_str()), (2, "Renamed"));
assert_eq!(d.wb.sheet(0).unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview);
}
#[test]
fn a_view_kept_through_redo_doesnt_make_the_saved_workbook_dirty() {
let mut s = s();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
{
let d = s.doc_mut().unwrap();
d.saved = d.wb.clone();
}
s.execute("edit.undo", json!({})).unwrap();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.wb.active().unwrap().view, gridcraft_model::SheetViewMode::PageBreakPreview);
assert!(!d.is_dirty(), "back at the saved edits, the view alone isn't a change");
}
@@ -34,7 +34,7 @@ use std::sync::Arc;
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, col_to_letters};
use gridcraft_engine::calc::Calc;
use gridcraft_engine::model::{CalcMode, Formula, Sheet, Workbook};
use gridcraft_engine::model::{CalcMode, Formula, Sheet, SheetViewMode, Workbook};
use gridcraft_engine::{EngineError, Session, command_specs, find_command, io};
use serde_json::{Value as Json, json};
@@ -486,8 +486,9 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
wb.names.iter().find(|n| n.name == WATCH_NAME).map(|n| n.formula.as_str())
}
/// The workbook with view state (active sheet, scroll, active cell) and the Watch Window list
/// reset: undo restores view state as it was, but switching sheets isn't an undoable edit.
/// The workbook with view state (active sheet, scroll, active cell, Normal / Page Layout / Page
/// Break Preview) and the Watch Window list reset: undo restores view state as it was, but
/// switching sheets or views isn't an undoable edit.
fn canonical(wb: &Workbook) -> Workbook {
let mut wb = wb.clone();
wb.set_active_sheet(0);
@@ -496,6 +497,7 @@ fn canonical(wb: &Workbook) -> Workbook {
let sh = Arc::make_mut(sh);
sh.view_active = CellRef::default();
sh.view_top_left = CellRef::default();
sh.view = SheetViewMode::Normal;
}
wb
}
@@ -1089,3 +1091,13 @@ fn params_docs_parse_into_keys() {
assert!(find_command(id).is_some(), "CURATED names unknown command `{id}`");
}
}
/// Seed 177: switching a sheet to Page Break Preview isn't an undo step (as in Excel), so undoing
/// everything leaves the view mode alone and the undo check must not count it as an edit.
#[test]
fn view_mode_switch_is_not_an_undo_difference() {
for id in ["view.pageBreakPreview", "view.pageLayout"] {
let failure = replay("sales", &[(id.to_string(), json!({"sheet": 0}))]);
assert!(failure.is_none(), "`{id}`: {failure:?}");
}
}
+3
View File
@@ -22,10 +22,13 @@ mod percent_entry;
mod pivot_unknown_func;
mod pivotchart_link;
mod range_fill_formats;
mod recently_used;
mod row_autofit;
mod sheet_copy_spill;
mod sheet_name_quoting;
mod sparse_clear_invalidation;
mod stored_list_shape;
mod table_resize_overlap;
mod table_total_row_last_row;
mod workbook_author;
mod wrap_row_height;
+58
View File
@@ -0,0 +1,58 @@
//! Formulas › Recently Used: the functions most recently entered in a formula, from any command
//! that enters one, kept in the preferences rather than read back from the journal.
use gridcraft_engine::Session;
use serde_json::{Value as Json, json};
fn recent(s: &mut Session) -> Vec<String> {
let list = s.execute("formulas.recentlyUsed", json!({})).unwrap();
list.as_array().unwrap().iter().filter_map(Json::as_str).map(String::from).collect()
}
#[test]
fn formulas_entered_by_any_command_lead_the_list() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "=NPV(0.1,1,2)"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "=IRR({-10,6,6})+ROUND(1,0)"})).unwrap();
s.execute("range.setValues", json!({"range": "B1", "values": [["=FV(0.1,2,-1)", 4, "text"]]})).unwrap();
s.execute("cell.set", json!({"cell": "A3", "input": "PMT is just text"})).unwrap();
assert_eq!(&recent(&mut s)[..4], ["FV", "IRR", "ROUND", "NPV"]);
// A command that fails enters nothing.
assert!(s.execute("cell.set", json!({"cell": "not a cell", "input": "=DB(1,2,3,4)"})).is_err());
assert_ne!(recent(&mut s)[0], "DB");
}
#[test]
fn formulas_typed_with_a_plus_or_minus_count() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "+ROUND(1.5,0)"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "-SLN(100,10,5)"})).unwrap();
s.execute("cell.set", json!({"cell": "A3", "input": "-5"})).unwrap();
assert_eq!(&recent(&mut s)[..2], ["SLN", "ROUND"]);
}
#[test]
fn the_list_does_not_depend_on_the_journal() {
// The journal drops its oldest entries past its caps (and is public); the list stays.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "=NPV(0.1,1,2)"})).unwrap();
s.journal.clear();
assert_eq!(recent(&mut s)[0], "NPV");
s.execute("cell.set", json!({"cell": "A2", "input": "=SLN(100,10,5)"})).unwrap();
assert_eq!(&recent(&mut s)[..2], ["SLN", "NPV"]);
}
#[test]
fn the_list_is_kept_with_the_preferences() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "=SYD(100,10,5,1)"})).unwrap();
let saved = serde_json::to_value(&s.prefs).unwrap();
let mut next = Session::new();
next.new_workbook();
next.prefs = serde_json::from_value(saved).unwrap();
assert_eq!(recent(&mut next)[0], "SYD");
}
@@ -0,0 +1,33 @@
use gridcraft_core::{CellRef, Value};
use gridcraft_engine::Session;
use gridcraft_engine::calc::Calc;
use serde_json::{Value as Json, json};
fn run(s: &mut Session, command: &str, params: Json) {
s.execute(command, params).unwrap();
}
fn value(s: &Session, sheet: &str, cell: &str) -> Value {
let wb = &s.doc().unwrap().wb;
wb.sheet(wb.sheet_index(sheet).unwrap()).unwrap().value(CellRef::parse(cell).unwrap())
}
/// Issue #2053: the copy of a sheet holding a spill keeps the spill's values, in memory and after a full recalc.
#[test]
fn copied_sheet_keeps_spill_values_through_full_recalc() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"sample": "grades"}));
run(&mut s, "home.mergeCells", json!({"range": "F:H"}));
run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"}));
run(&mut s, "selection.set", json!({"range": "15:15"}));
run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1}));
run(&mut s, "cell.set", json!({"array": true, "cell": "D3", "input": "=SUM('Grades (2)'!J54#)"}));
let before = value(&s, "Grades (2)", "J55");
assert!(matches!(before, Value::Number(_)), "J55 should hold a spilled number, got {before:?}");
let mut fresh = (*s.doc().unwrap().wb).clone();
Calc::new().recalc_all(&mut fresh);
let after = fresh.sheet(fresh.sheet_index("Grades (2)").unwrap()).unwrap().value(CellRef::parse("J55").unwrap());
assert_eq!(before, after);
}
+50
View File
@@ -0,0 +1,50 @@
//! Regression tests for the default author of newly created workbooks.
use gridcraft_engine::{DocState, Session, Trust, io, model::Workbook};
#[test]
fn new_workbook_stamps_the_configured_user_name_at_creation() {
let mut session = Session::new();
session.prefs.user_name = "Ada Lovelace".into();
let first = session.new_workbook();
assert_eq!(session.documents()[first].wb.props.author, "Ada Lovelace");
// Changing the preference must not rewrite an existing workbook.
session.prefs.user_name = "Grace Hopper".into();
assert_eq!(session.documents()[first].wb.props.author, "Ada Lovelace");
// A new workbook uses the preference as it exists at creation.
let second = session.new_workbook();
assert_eq!(session.documents()[second].wb.props.author, "Grace Hopper");
assert_eq!(session.documents()[first].wb.props.author, "Ada Lovelace");
}
#[test]
fn opening_and_resaving_preserves_the_existing_workbook_author() {
// An existing XLSX has its own author metadata.
let mut source = Workbook::new();
source.props.author = "Original Spreadsheet Author".into();
let bytes = io::save_bytes(&source, "source.xlsx").unwrap();
let (opened, _) = io::open_bytes("source.xlsx", &bytes).unwrap();
let mut session = Session::new();
session.prefs.user_name = "Current GridCraft User".into();
session.add_document(DocState::new(opened, None, "source".into(), Trust::FromFile));
// Opening an existing workbook must not replace its author.
assert_eq!(session.doc().unwrap().wb.props.author, "Original Spreadsheet Author");
// The original author must survive another XLSX save and reopen.
let saved = io::save_bytes(&session.doc().unwrap().wb, "saved.xlsx").unwrap();
let (reopened, _) = io::open_bytes("saved.xlsx", &saved).unwrap();
assert_eq!(reopened.props.author, "Original Spreadsheet Author");
}
+2 -2
View File
@@ -175,8 +175,8 @@ fn write_struct_ref(s: &StructRef, at_shorthand: bool) -> String {
let _ = write!(out, "[{}]", s.specifiers.first().map(item).unwrap_or(""));
}
(Some(c), None) if s.specifiers.is_empty() => {
// Excel writes a name with spaces at its edges in the double-bracket form.
if c.trim() == c {
// Names with spaces at their edges, or starting with `@` (this-row shorthand), use the double-bracket form.
if c.trim() == c && !c.starts_with('@') {
let _ = write!(out, "[{}]", esc(c));
} else {
let _ = write!(out, "[[{}]]", esc(c));
+9
View File
@@ -558,3 +558,12 @@ fn reference_shapes_print_unchanged() -> Result<(), Box<dyn std::error::Error>>
}
Ok(())
}
#[test]
fn column_starting_with_at_round_trips() {
for name in ["@a", "a@b"] {
let s = StructRef { table: "T".into(), specifiers: vec![], col_start: Some(name.into()), col_end: None };
let text = format!("={}", printer::struct_ref(&s));
assert_eq!(parse(&text).ok(), Some(Expr::Struct(s)), "printed as {text}");
}
}
+10 -3
View File
@@ -449,13 +449,15 @@ pub(crate) fn yearfrac_core(sys: DateSystem, s: i64, e: i64, basis: i64) -> R<f6
Ok(match basis {
0 => {
let (mut a, mut b) = (d1.day as i64, d2.day as i64);
// Excel tests the end-31 rule against the original start day, before a February end moves to 30.
let start_30 = a >= 30;
if last_of_feb(&d1) && last_of_feb(&d2) {
b = 30;
}
if last_of_feb(&d1) || a == 31 {
a = 30;
}
if a == 30 && b == 31 {
if start_30 && b == 31 {
b = 30;
}
((d2.year as i64 - d1.year as i64) * 360 + (d2.month as i64 - d1.month as i64) * 30 + b - a) as f64 / 360.0
@@ -817,8 +819,13 @@ mod tests {
#[test]
fn yearfrac_basis0_feb_end_to_31() {
close(ev("YEARFRAC", vec![n(d(2021.0, 2.0, 28.0)), n(d(2021.0, 3.0, 31.0)), n(0.0)]), 30.0 / 360.0);
close(ev("YEARFRAC", vec![n(d(2020.0, 2.0, 29.0)), n(d(2020.0, 3.0, 31.0)), n(0.0)]), 30.0 / 360.0);
// Excel 16: a February-end start keeps its original day for the end-31 test, so 31 days.
close(ev("YEARFRAC", vec![n(d(2021.0, 2.0, 28.0)), n(d(2021.0, 3.0, 31.0)), n(0.0)]), 0.086_111_111_111_111_11);
close(ev("YEARFRAC", vec![n(d(2020.0, 2.0, 29.0)), n(d(2020.0, 3.0, 31.0)), n(0.0)]), 0.086_111_111_111_111_11);
close(ev("YEARFRAC", vec![n(d(2021.0, 3.0, 31.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 0.086_111_111_111_111_11);
close(ev("YEARFRAC", vec![n(d(2021.0, 1.0, 31.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 0.077_777_777_777_777_78);
close(ev("YEARFRAC", vec![n(d(2021.0, 1.0, 30.0)), n(d(2021.0, 3.0, 31.0)), n(0.0)]), 1.0 / 6.0);
close(ev("YEARFRAC", vec![n(d(2020.0, 2.0, 29.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 1.0);
close(ev("YEARFRAC", vec![n(d(2021.0, 2.0, 28.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 0.0);
}
+105 -14
View File
@@ -25,7 +25,7 @@ fn base_source(a: &[Arg]) -> R<String> {
Ok(number_to_text(n))
}
Value::Empty => Ok(String::new()),
v => Ok(v.to_text()?.trim().to_string()),
v => Ok(v.to_text()?.to_string()),
}
}
@@ -62,6 +62,15 @@ fn format_base(v: i64, radix: u32, places: Option<f64>) -> R<Value> {
if v < min || v > max {
return Err(CellError::Num);
}
let places = places
.map(|p| {
let p = p.trunc();
if !(1.0..=10.0).contains(&p) {
return Err(CellError::Num);
}
Ok(p as usize)
})
.transpose()?;
if v < 0 {
let u = v + (1i64 << bits);
return text_val(to_radix(u, radix));
@@ -70,11 +79,6 @@ fn format_base(v: i64, radix: u32, places: Option<f64>) -> R<Value> {
match places {
None => text_val(s),
Some(p) => {
let p = p.trunc();
if !(1.0..=10.0).contains(&p) {
return Err(CellError::Num);
}
let p = p as usize;
if s.len() > p {
return Err(CellError::Num);
}
@@ -97,7 +101,13 @@ fn to_radix(mut v: i64, radix: u32) -> String {
}
fn places_arg(a: &[Arg]) -> R<Option<f64>> {
if has(a, 1) { Ok(Some(num(a, 1)?)) } else { Ok(None) }
if !has(a, 1) {
return Ok(None);
}
if matches!(a.get(1).map(scalar), Some(Value::Bool(_))) {
return Err(CellError::Value);
}
Ok(Some(num(a, 1)?))
}
fn convert_base(a: &[Arg], from: u32, to: u32) -> R<Value> {
@@ -175,6 +185,9 @@ fn bitxor(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
fn shift(a: &[Arg], left: bool) -> R<Value> {
let n = bit_operand(a, 0)?;
let s = num(a, 1)?.trunc();
if n == 0 {
return Ok(Value::Number(0.0));
}
if s.abs() > 53.0 {
return Err(CellError::Num);
}
@@ -248,11 +261,26 @@ im1!(imexp, |z: Cx| Ok(z.exp()));
im1!(imln, |z: Cx| z.ln());
im1!(imlog10, |z: Cx| z.ln().map(|l| Cx::new(l.re / std::f64::consts::LN_10, l.im / std::f64::consts::LN_10)));
im1!(imlog2, |z: Cx| z.ln().map(|l| Cx::new(l.re / std::f64::consts::LN_2, l.im / std::f64::consts::LN_2)));
// Excel takes the polar route, so IMSQRT("-4") is 1.22514845490862E-16+2i, not 2i. Its cosine
// reduces its argument with a 64-bit-mantissa pi, which is PI/2 + 2.5e-20 and shows up as the
// stray real part. `+ 0.0` turns a -0 imaginary part into +0, so the angle stays +pi.
// shortcut: parts above ~1E154 or below ~1E-155 keep the exact result (Excel gives #NUM! or 0), no known use.
const HALF_PI_EXCESS: f64 = 2.508_278_806_33e-20;
im1!(imsqrt, |z: Cx| {
let m = z.abs();
let re = ((m + z.re) / 2.0).sqrt();
let im = ((m - z.re) / 2.0).sqrt();
Ok(Cx::new(re, if z.im < 0.0 { -im } else { im }))
let im = z.im + 0.0;
let theta = match z.re {
0.0 => {
if im == 0.0 {
0.0
} else {
std::f64::consts::FRAC_PI_2.copysign(im)
}
}
x if x > 0.0 => (im / x).atan(),
x => (im / x).atan() + if im < 0.0 { -std::f64::consts::PI } else { std::f64::consts::PI },
};
let (half, root) = (theta / 2.0, z.abs().sqrt());
Ok(Cx::new(root * (half.cos() + HALF_PI_EXCESS * half.abs().sin()), root * half.sin()))
});
im1!(imsin, |z: Cx| Ok(z.sin()));
im1!(imcos, |z: Cx| Ok(z.cos()));
@@ -387,6 +415,12 @@ mod tests {
is_text(ev("BIN2OCT", vec![n(1111111111.0)]), "7777777777");
is_text(ev("DEC2BIN", vec![n(9.0), n(4.0)]), "1001");
is_text(ev("DEC2BIN", vec![n(-100.0)]), "1110011100");
is_err(ev("DEC2BIN", vec![n(-1.0), n(0.0)]), CellError::Num);
is_err(ev("DEC2HEX", vec![n(-1.0), n(11.0)]), CellError::Num);
is_err(ev("DEC2OCT", vec![n(-1.0), n(-1.0)]), CellError::Num);
is_err(ev("DEC2BIN", vec![n(1.0), crate::Arg::val(Value::Bool(true))]), CellError::Value);
is_text(ev("DEC2BIN", vec![n(-1.0), n(1.0)]), "1111111111");
is_text(ev("DEC2HEX", vec![n(-1.0), n(10.0)]), "FFFFFFFFFF");
is_err(ev("DEC2BIN", vec![n(512.0)]), CellError::Num);
is_text(ev("DEC2HEX", vec![n(100.0), n(4.0)]), "0064");
is_text(ev("DEC2HEX", vec![n(-54.0)]), "FFFFFFFFCA");
@@ -411,6 +445,21 @@ mod tests {
is_text(ev("OCT2HEX", vec![n(100.0), n(4.0)]), "0040");
is_text(ev("OCT2HEX", vec![n(7777777533.0)]), "FFFFFFFF5B");
is_err(ev("BIN2DEC", vec![n(102.0)]), CellError::Num);
for (f, input) in [
("BIN2DEC", " 10"),
("BIN2DEC", "10 "),
("BIN2DEC", "\t10"),
("BIN2HEX", " 10"),
("BIN2OCT", "10 "),
("HEX2DEC", " 10"),
("HEX2BIN", "10 "),
("HEX2OCT", "\t10"),
("OCT2DEC", " 10"),
("OCT2BIN", "10 "),
("OCT2HEX", "\t10"),
] {
is_err(ev(f, vec![t(input)]), CellError::Num);
}
is_err(ev("HEX2DEC", vec![t("GG")]), CellError::Num);
is_err(ev("BIN2DEC", vec![t("11111111111")]), CellError::Num);
is_err(ev("DEC2BIN", vec![t("abc")]), CellError::Value);
@@ -431,6 +480,21 @@ mod tests {
is_err(ev("BITAND", vec![n(1.5), n(5.0)]), CellError::Num);
is_err(ev("BITLSHIFT", vec![n(1.0), n(54.0)]), CellError::Num);
is_err(ev("BITLSHIFT", vec![n(2f64.powi(47)), n(1.0)]), CellError::Num);
for f in ["BITLSHIFT", "BITRSHIFT"] {
for shift in [-100.0, -54.0, -53.0, 53.0, 54.0, 100.0] {
close(ev(f, vec![n(0.0), n(shift)]), 0.0);
}
for shift in [-100.0, -54.0, 54.0, 100.0] {
is_err(ev(f, vec![n(1.0), n(shift)]), CellError::Num);
}
if f == "BITLSHIFT" {
is_err(ev(f, vec![n(1.0), n(53.0)]), CellError::Num);
} else {
close(ev(f, vec![n(1.0), n(53.0)]), 0.0);
}
is_err(ev(f, vec![n(0.0), t("bad")]), CellError::Value);
}
is_err(ev("BITRSHIFT", vec![n(-1.0), n(100.0)]), CellError::Num);
}
#[test]
@@ -509,9 +573,36 @@ mod tests {
cx(ev("IMLOG10", vec![t("3+4i")]), 0.698_970_004_336_018_8, 0.402_719_196_273_373_2);
cx(ev("IMLOG2", vec![t("3+4i")]), 2.321_928_094_887_362, 1.337_804_212_450_976_8);
cx(ev("IMSQRT", vec![t("1+i")]), 1.098_684_113_467_809_9, 0.455_089_860_562_227_3);
cx(ev("IMSQRT", vec![t("-4")]), 0.0, 2.0);
is_text(ev("IMSQRT", vec![t("-4")]), "2i");
is_text(ev("IMSQRT", vec![t("-9")]), "3i");
// Strings read back from Excel (16.0): its stray real part on negative reals included.
for (input, want) in [
("-4", "1.22514845490862E-16+2i"),
("-9", "1.83772268236293E-16+3i"),
("-1", "6.1257422745431E-17+i"),
("-2", "8.66310780426106E-17+1.4142135623731i"),
("-100", "6.1257422745431E-16+10i"),
("-1E10", "6.1257422745431E-12+100000i"),
("-1E-10", "6.1257422745431E-22+0.00001i"),
("-4+0j", "1.22514845490862E-16+2j"),
("-4-0i", "1.22514845490862E-16+2i"),
("-4-1E-20i", "1.22514845490862E-16-2i"),
("-1+1E-10i", "5.00000653944413E-11+i"),
("-0.5-1E-12i", "7.07212958930194E-13-0.707106781186548i"),
("4", "2"),
("2", "1.4142135623731"),
("0", "0"),
("3+4i", "2+i"),
("3+4j", "2+j"),
("-3+4i", "1+2i"),
("-3-4i", "1-2i"),
("-2i", "1-i"),
("2i", "1+i"),
("i", "0.707106781186548+0.707106781186547i"),
("5-12i", "3-2i"),
("-5+12i", "2+3i"),
("1E10+1E10i", "109868.411346781+45508.9860562227i"),
] {
is_text(ev("IMSQRT", vec![t(input)]), want);
}
is_text(ev("IMSQRT", vec![t("4")]), "2");
is_text(ev("IMSQRT", vec![t("-2i")]), "1-i");
is_text(ev("IMPOWER", vec![t("2+3i"), n(3.0)]), "-46+9i");
+8 -5
View File
@@ -311,11 +311,8 @@ fn hyperlink(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let v = a.get(1).map(scalar).unwrap_or(Value::Empty);
return Ok(empty_to_zero(v));
}
let link = a.first().map(scalar).unwrap_or(Value::Empty);
if let Value::Error(e) = link {
return Err(e);
}
Ok(link)
// Excel returns the link as text, so HYPERLINK(1) is "1" and ISTEXT is TRUE.
Ok(Value::Text(text(a, 0)?.into()))
}
fn encodeurl(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
@@ -608,6 +605,12 @@ mod tests {
is_text(ev("HYPERLINK", vec![t("http://x.com")]), "http://x.com");
is_text(ev("HYPERLINK", vec![t("http://x.com"), t("Click")]), "Click");
close(ev("HYPERLINK", vec![t("http://x.com"), n(5.0)]), 5.0);
// Excel 16: without a friendly name the result is the link as text.
is_text(ev("HYPERLINK", vec![n(1.0)]), "1");
is_text(ev("HYPERLINK", vec![n(1.5)]), "1.5");
is_text(ev("HYPERLINK", vec![b(true)]), "TRUE");
is_text(ev("HYPERLINK", vec![rf(Value::Empty)]), "");
is_err(ev("HYPERLINK", vec![e(CellError::Div0)]), CellError::Div0);
is_text(ev("ENCODEURL", vec![t("a b&c/é")]), "a%20b%26c%2F%C3%A9");
is_err(ev("WEBSERVICE", vec![t("http://x")]), CellError::Value);
is_err(ev("FILTERXML", vec![t("<a/>"), t("//a")]), CellError::Value);
+61 -1
View File
@@ -58,6 +58,35 @@ fn reject_multi_cell_refs(spec: &FnSpec, args: &[Arg]) -> Option<Vec<Arg>> {
)
}
/// Lookups whose every call searches a lookup vector from its start, so a call lifted over `n`
/// needles does `n` x (vector length) work. Their search arguments don't lift.
const SCANS: &[&str] = &["VLOOKUP", "HLOOKUP", "LOOKUP", "MATCH", "XLOOKUP", "XMATCH"];
/// Work budget of a lifted [`SCANS`] lookup: needle cells times the length of the longest vector
/// it searches (the longest dimension of its largest non-lifted array). Each needle re-reads and
/// scans the vector (about 8 ns per entry), so without a cap a one-cell formula such as
/// `XMATCH(SEQUENCE(1048576), -SEQUENCE(1048576))` runs for hours and hangs opening the file.
/// Past the budget the call is `#NUM!`, as MMULT is past 2e9 multiply-adds. 5e8 keeps the worst
/// case to a few seconds and still admits 5,000 needles over a 100,000-row table.
const LIFTED_SCAN_BUDGET: usize = 500_000_000;
/// The length of the longest vector a lifted call of `spec` searches per needle: 0 unless `spec`
/// is one of the [`SCANS`] lookups and a non-lifted argument is an array.
fn scan_len(spec: &FnSpec, args: &[Arg]) -> usize {
if !SCANS.contains(&spec.name) {
return 0;
}
args.iter()
.enumerate()
.filter(|(i, _)| !spec.is_scalar_arg(*i))
.filter_map(|(_, a)| match &a.value {
Value::Array(arr) => Some(arr.rows.max(arr.cols)),
_ => None,
})
.max()
.unwrap_or(0)
}
pub(crate) fn call_lifted(spec: &FnSpec, args: &[Arg], ctx: &mut dyn Ctx) -> Value {
let rejected = if spec.value_args.is_empty() { None } else { reject_multi_cell_refs(spec, args) };
let args = rejected.as_deref().unwrap_or(args);
@@ -76,7 +105,8 @@ pub(crate) fn call_lifted(spec: &FnSpec, args: &[Arg], ctx: &mut dyn Ctx) -> Val
if !any {
return (spec.imp)(args, ctx);
}
if rows.saturating_mul(cols) > MAX_CELLS {
let needles = rows.saturating_mul(cols);
if needles > MAX_CELLS || needles.saturating_mul(scan_len(spec, args)) > LIFTED_SCAN_BUDGET {
return Value::Error(CellError::Num);
}
let mut cell_args: Vec<Arg> = args.to_vec();
@@ -149,6 +179,36 @@ mod tests {
is_err(huge, CellError::Num);
}
/// Security: a lifted lookup searches its whole lookup vector once per needle, so needles x
/// vector length past `LIFTED_SCAN_BUDGET` is `#NUM!` at once.
/// `XMATCH(SEQUENCE(1048576), -SEQUENCE(1048576))` used to run for hours (and hung opening
/// the 1.6 KB file holding it).
#[test]
fn lifted_lookups_stop_past_their_work_budget() {
use gridcraft_core::Array;
let tall = |n: usize| av(Array::filled(n, 1, nv(-1.0)).into());
let wide = |n: usize| av(Array::filled(1, n, nv(-1.0)).into());
is_err(ev("XMATCH", vec![tall(1_048_576), tall(1_048_576)]), CellError::Num);
// Just past the budget, for every lookup: 501 needles over 1,000,000 entries.
assert_eq!(super::LIFTED_SCAN_BUDGET, 500 * 1_000_000);
is_err(ev("XMATCH", vec![tall(501), tall(1_000_000)]), CellError::Num);
is_err(ev("MATCH", vec![tall(501), tall(1_000_000), n(0.0)]), CellError::Num);
is_err(ev("XLOOKUP", vec![tall(501), tall(1_000_000), tall(1_000_000)]), CellError::Num);
is_err(ev("VLOOKUP", vec![tall(501), tall(1_000_000), n(1.0), b(false)]), CellError::Num);
is_err(ev("HLOOKUP", vec![tall(501), wide(1_000_000), n(1.0), b(false)]), CellError::Num);
is_err(ev("LOOKUP", vec![tall(501), tall(1_000_000)]), CellError::Num);
// Within the budget lifted lookups work as before.
let keys = || av(col(&[10.0, 20.0, 30.0]));
let pos = ev("XMATCH", vec![av(col(&[30.0, 10.0, 99.0])), keys()]);
assert_eq!(rows_of(&pos), vec![vec![nv(3.0)], vec![nv(1.0)], vec![Value::Error(CellError::NA)]]);
let found = ev("XLOOKUP", vec![av(row(&[20.0, 30.0])), keys(), av(col(&[1.0, 2.0, 3.0]))]);
assert_eq!(rows_of(&found), vec![vec![nv(2.0), nv(3.0)]]);
// Other lifted functions aren't metered: INDEX reads one entry per position.
let picks: Vec<f64> = (1..=1000u32).map(f64::from).collect();
let out = ev("INDEX", vec![tall(1_048_576), av(col(&picks))]);
assert_eq!(rows_of(&out), vec![vec![nv(-1.0)]; 1000]);
}
#[test]
fn value_params_reject_multi_cell_references() {
let s = FnSpec { value_args: &[true, false], ..spec() };
+14
View File
@@ -314,6 +314,10 @@ fn modulo(x: f64, d: f64) -> R<f64> {
if d == 0.0 {
return Err(CellError::Div0);
}
// Excel returns #NUM! once the quotient magnitude reaches 1.1259E12 (checked against Excel 16).
if (x / d).abs() >= 1.1259e12 {
return Err(CellError::Num);
}
// `%` is an exact remainder (truncated), so |r| < |d| even for tiny divisors.
let r = x % d;
// Keep the sign of the divisor and avoid returning |d| from rounding.
@@ -694,6 +698,16 @@ pub(crate) fn specs() -> Vec<FnSpec> {
f!("ROUNDDOWN", 2, 2, MathTrig, S, "ROUNDDOWN(number, num_digits)", "Rounds a number toward zero to a given number of digits.", rounddown),
f!("MROUND", 2, 2, MathTrig, S, "MROUND(number, multiple)", "Rounds a number to the nearest multiple.", mround),
f!("CEILING", 2, 2, Compatibility, S, "CEILING(number, significance)", "Rounds a number up to a multiple of significance.", ceiling),
f!(
"ECMA.CEILING",
2,
2,
Compatibility,
S,
"ECMA.CEILING(number, significance)",
"Rounds a number up to a multiple of significance.",
ceiling
),
f!(
"CEILING.MATH",
1,
+20 -9
View File
@@ -101,6 +101,11 @@ fn rounding() {
close(ev2("CEILING", 1.5, 0.1), 1.5);
close(ev2("CEILING", 0.234, 0.01), 0.24);
is_err(ev2("CEILING", 2.5, -1.0), Num);
// ECMA.CEILING is CEILING under a second name (Excel table from #2776).
close(ev2("ECMA.CEILING", 1.5, 1.0), 2.0);
close(ev2("ECMA.CEILING", -2.5, -2.0), -4.0);
close(ev2("ECMA.CEILING", 2.5, 0.0), 0.0);
is_err(ev2("ECMA.CEILING", 1.5, -1.0), Num);
close(ev2("FLOOR", 3.7, 2.0), 2.0);
close(ev2("FLOOR", -2.5, -2.0), -2.0);
close(ev2("FLOOR", -2.5, 2.0), -4.0);
@@ -135,16 +140,22 @@ fn rounding() {
}
#[test]
fn mod_tiny_divisor_stays_in_range() {
for (x, d) in [(3.0, 1e-300), (-1.0, 1e-300), (3.0, -1e-300), (-1.0, -1e-300)] {
match ev2("MOD", x, d) {
Value::Number(r) => {
assert!(r == 0.0 || (r < 0.0) == (d < 0.0), "MOD({x}, {d}) = {r}");
assert!(r.abs() < d.abs(), "MOD({x}, {d}) = {r}");
}
other => panic!("MOD({x}, {d}) = {other:?}"),
}
fn mod_quotient_limit() {
// Excel 16: #NUM! whenever |number / divisor| >= 1.1259E12.
for (x, d) in [
(3.0, 1e-300),
(-1.0, 1e-300),
(3.0, -1e-300),
(-1.0, -1e-300),
(1e15, 7.0),
(1e10, 0.001),
(1_125_900_000_000.0, 1.0),
(-1_125_900_000_000.0, 1.0),
] {
is_err(ev2("MOD", x, d), Num);
}
close(ev2("MOD", 1e12 * 7.0 + 3.0, 7.0), 3.0);
close(ev2("MOD", 1_125_899_999_999.99, 1.0), 0.989_990_234_375);
}
#[test]
+12 -1
View File
@@ -336,6 +336,10 @@ pub(super) fn percentrank_impl(a: &[Arg], exc: bool) -> R<Value> {
if sig < 1.0 || s.is_empty() {
return Err(CellError::Num);
}
// Excel: 10^significance overflows from 309 up.
if sig >= 309.0 {
return Err(CellError::Div0);
}
let (first, last) = (s.first().copied().unwrap_or(0.0), s.last().copied().unwrap_or(0.0));
if x < first || x > last {
return Err(CellError::NA);
@@ -359,6 +363,10 @@ pub(super) fn percentrank_impl(a: &[Arg], exc: bool) -> R<Value> {
let (rl, rh) = (rank_of(lo), rank_of(hi));
rl + (x - lo) / (hi - lo) * (rh - rl)
};
// From significance 15 up Excel returns 15 significant digits, rounded.
if sig >= 15.0 {
return num_val(format!("{r:.14e}").parse().unwrap_or(r));
}
num_val(trunc_digits(r, sig))
}
@@ -420,7 +428,10 @@ pub(super) fn geomean(v: &[f64]) -> R<f64> {
}
pub(super) fn harmean(v: &[f64]) -> R<f64> {
if v.is_empty() || v.iter().any(|&x| x <= 0.0) {
if v.is_empty() {
return Err(CellError::NA);
}
if v.iter().any(|&x| x <= 0.0) {
return Err(CellError::Num);
}
Ok(v.len() as f64 / v.iter().map(|x| 1.0 / x).sum::<f64>())
+40 -14
View File
@@ -22,7 +22,14 @@ fn t_cdf(t: f64, v: f64) -> f64 {
}
fn t_pdf(t: f64, v: f64) -> f64 {
(ln_gamma((v + 1.0) / 2.0) - ln_gamma(v / 2.0) - 0.5 * (v * std::f64::consts::PI).ln() - (v + 1.0) / 2.0 * (1.0 + t * t / v).ln()).exp()
let z = v / 2.0;
let log_gamma_ratio = if z >= 16.0 {
let inv_z = 1.0 / z;
0.5 * z.ln() - inv_z / 8.0 + inv_z.powi(3) / 192.0 - inv_z.powi(5) / 640.0 + 17.0 * inv_z.powi(7) / 14_336.0
} else {
ln_gamma(z + 0.5) - ln_gamma(z)
};
(log_gamma_ratio - 0.5 * (v.ln() + std::f64::consts::PI.ln()) - (v + 1.0) / 2.0 * (t * t / v).ln_1p()).exp()
}
/// t ≥ 0 with P(T > t) = q, q in (0, 0.5].
@@ -51,6 +58,12 @@ fn f_cdf(x: f64, d1: f64, d2: f64) -> f64 {
if x <= 0.0 {
return 0.0;
}
if x == 1.0 && d1 == d2 {
return 0.5;
}
if d1 >= 1e8 && d2 / d1 <= 1e-8 {
return reg_gamma_q(d2 / 2.0, d2 / (2.0 * (x + d2 / d1)));
}
reg_inc_beta(d1 * x / (d1 * x + d2), d1 / 2.0, d2 / 2.0)
}
@@ -58,6 +71,10 @@ fn f_upper(x: f64, d1: f64, d2: f64) -> f64 {
if x <= 0.0 {
return 1.0;
}
if d1 >= 1e8 && d2 / d1 <= 1e-8 {
// With a much larger numerator degree, the scaled beta tail converges to a gamma tail.
return reg_gamma_p(d2 / 2.0, d2 / (2.0 * (x + d2 / d1)));
}
reg_inc_beta(d2 / (d2 + d1 * x), d2 / 2.0, d1 / 2.0)
}
@@ -74,6 +91,8 @@ fn f_pdf(x: f64, d1: f64, d2: f64) -> f64 {
((d1 / 2.0) * (d1 / d2).ln() + (d1 / 2.0 - 1.0) * x.ln() - ((d1 + d2) / 2.0) * (1.0 + d1 * x / d2).ln() - ln_beta(d1 / 2.0, d2 / 2.0)).exp()
}
const MAX_BINOM_TRIALS: f64 = 2_147_483_646.0;
fn binom_pmf(k: f64, n: f64, p: f64) -> f64 {
if k < 0.0 || k > n {
return 0.0;
@@ -176,8 +195,14 @@ fn df_arg(a: &[Arg], i: usize) -> R<f64> {
pub(super) fn t_dist(a: &[Arg], _: C) -> R<Value> {
let x = num(a, 0)?;
let v = df_arg(a, 1)?;
let v = num(a, 1)?.trunc();
let cum = boolean(a, 2)?;
if v == 0.0 {
return Err(if cum { CellError::Num } else { CellError::Div0 });
}
if v < 0.0 {
return Err(CellError::Num);
}
num_val(if cum { t_cdf(x, v) } else { t_pdf(x, v) })
}
@@ -209,6 +234,9 @@ pub(super) fn tdist_legacy(a: &[Arg], _: C) -> R<Value> {
pub(super) fn t_inv(a: &[Arg], _: C) -> R<Value> {
let p = num(a, 0)?;
let v = df_arg(a, 1)?;
if p == 0.0 {
return Err(CellError::Div0);
}
if !(p > 0.0 && p < 1.0) {
return Err(CellError::Num);
}
@@ -347,7 +375,7 @@ fn f_args(a: &[Arg]) -> R<(f64, f64, f64)> {
let x = num(a, 0)?;
let d1 = num(a, 1)?.trunc();
let d2 = num(a, 2)?.trunc();
if d1 < 1.0 || d2 < 1.0 || d1 >= 1e10 || d2 >= 1e10 {
if d1 < 1.0 || d2 < 1.0 || d1 > 1e10 || d2 > 1e10 {
return Err(CellError::Num);
}
Ok((x, d1, d2))
@@ -378,7 +406,8 @@ pub(super) fn f_inv(a: &[Arg], _: C) -> R<Value> {
if p == 0.0 {
return num_val(0.0);
}
num_val(invert(|x| f_cdf(x, d1, d2), p, 0.0, 1.0, 1e60))
let value = if p < 0.5 { invert(|x| f_cdf(x, d1, d2), p, 0.0, 1.0, 1e60) } else { invert(|x| f_upper(x, d1, d2), 1.0 - p, 0.0, 1.0, 1e60) };
num_val(value)
}
pub(super) fn f_inv_rt(a: &[Arg], _: C) -> R<Value> {
@@ -410,7 +439,7 @@ pub(super) fn binom_dist(a: &[Arg], _: C) -> R<Value> {
let n = num(a, 1)?.trunc();
let p = num(a, 2)?;
let cum = boolean(a, 3)?;
if k < 0.0 || k > n || !(0.0..=1.0).contains(&p) {
if k < 0.0 || n > MAX_BINOM_TRIALS || k > n || !(0.0..=1.0).contains(&p) {
return Err(CellError::Num);
}
num_val(if cum { binom_cdf(k, n, p) } else { binom_pmf(k, n, p) })
@@ -421,7 +450,7 @@ pub(super) fn binom_dist_range(a: &[Arg], _: C) -> R<Value> {
let p = num(a, 1)?;
let s1 = num(a, 2)?.trunc();
let s2 = if has(a, 3) { num(a, 3)?.trunc() } else { s1 };
if !(0.0..=1e15).contains(&n) || !(0.0..=1.0).contains(&p) || s1 < 0.0 || s1 > n || s2 < s1 || s2 > n {
if !(0.0..=MAX_BINOM_TRIALS).contains(&n) || !(0.0..=1.0).contains(&p) || s1 < 0.0 || s1 > n || s2 < s1 || s2 > n {
return Err(CellError::Num);
}
if s2 - s1 > 10_000.0 {
@@ -499,13 +528,7 @@ pub(super) fn gamma_dist(a: &[Arg], _: C) -> R<Value> {
return num_val(reg_gamma_p(al, x / be));
}
if x == 0.0 {
return if al < 1.0 {
Err(CellError::Num)
} else if al == 1.0 {
num_val(1.0 / be)
} else {
num_val(0.0)
};
return if al <= 1.0 { Err(CellError::Num) } else { num_val(0.0) };
}
num_val(((al - 1.0) * x.ln() - x / be - al * be.ln() - ln_gamma(al)).exp())
}
@@ -548,7 +571,7 @@ pub(super) fn beta_dist(a: &[Arg], _: C) -> R<Value> {
if cum {
return num_val(reg_inc_beta(z, al, be));
}
if (z == 0.0 && al < 1.0) || (z == 1.0 && be < 1.0) {
if (z == 0.0 && al <= 1.0) || (z == 1.0 && be <= 1.0) {
return Err(CellError::Num);
}
let lp = if z == 0.0 || z == 1.0 {
@@ -608,6 +631,9 @@ pub(super) fn weibull_dist(a: &[Arg], _: C) -> R<Value> {
if x < 0.0 || al <= 0.0 || be <= 0.0 {
return Err(CellError::Num);
}
if x == 0.0 {
return num_val(0.0);
}
let t = (x / be).powf(al);
num_val(if cum { -(-t).exp_m1() } else { al / be.powf(al) * x.powf(al - 1.0) * (-t).exp() })
}
+115 -4
View File
@@ -151,6 +151,19 @@ fn spread() {
let g = [4.0, 5.0, 8.0, 7.0, 11.0, 4.0, 3.0];
close_tol(ev("GEOMEAN", vec![c(&g)]), 5.476986969, 1e-9);
close_tol(ev("HARMEAN", vec![c(&g)]), 5.028375962, 1e-9);
let text_values = arr(vec![vec![tv("1"), tv("2")]]);
let bool_values = arr(vec![vec![Value::Bool(true), Value::Bool(false)]]);
let mixed_values = arr(vec![vec![nv(2.0), tv("ignored"), Value::Bool(true)]]);
is_err(ev("HARMEAN", vec![av(text_values.clone())]), CellError::NA);
is_err(ev("HARMEAN", vec![av(bool_values.clone())]), CellError::NA);
is_err(ev("HARMEAN", vec![rf(text_values)]), CellError::NA);
is_err(ev("HARMEAN", vec![rf(bool_values)]), CellError::NA);
close(ev("HARMEAN", vec![av(mixed_values.clone())]), 2.0);
close(ev("HARMEAN", vec![rf(mixed_values)]), 2.0);
close(ev("HARMEAN", vec![b(true)]), 1.0);
close(ev("HARMEAN", vec![n(2.0), n(4.0)]), 8.0 / 3.0);
is_err(ev("HARMEAN", vec![av(arr(vec![vec![nv(0.0)]]))]), CellError::Num);
is_err(ev("HARMEAN", vec![av(arr(vec![vec![nv(-1.0)]]))]), CellError::Num);
is_err(ev("GEOMEAN", vec![c(&[1.0, 0.0])]), CellError::Num);
close_tol(ev("TRIMMEAN", vec![c(&[4.0, 5.0, 6.0, 7.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0]), n(0.2)]), 3.777777778, 1e-9);
is_err(ev("TRIMMEAN", vec![c(&[1.0]), n(1.0)]), CellError::Num);
@@ -214,10 +227,19 @@ fn percentiles() {
close(ev("PERCENTRANK.EXC", vec![e9.clone(), n(5.43)]), 0.381);
close(ev("PERCENTRANK.EXC", vec![e9, n(5.43), n(1.0)]), 0.3);
let t = c(&[1.0, 2.0, 3.0]);
close(ev("PERCENTRANK", vec![t.clone(), n(2.0), n(400.0)]), 0.5);
close(ev("PERCENTRANK.INC", vec![t.clone(), n(2.0), n(400.0)]), 0.5);
close(ev("PERCENTRANK.INC", vec![t.clone(), n(1.0), n(400.0)]), 0.0);
close(ev("PERCENTRANK.EXC", vec![t, n(2.0), n(400.0)]), 0.5);
// Excel 16: significance 309 and up is #DIV/0!, 308 still works.
for name in ["PERCENTRANK", "PERCENTRANK.INC", "PERCENTRANK.EXC"] {
is_err(ev(name, vec![t.clone(), n(2.0), n(309.0)]), CellError::Div0);
is_err(ev(name, vec![t.clone(), n(1.0), n(400.0)]), CellError::Div0);
close(ev(name, vec![t.clone(), n(2.0), n(308.0)]), 0.5);
}
// From significance 15 up the result has 15 significant digits.
let k = c(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]);
for sig in [15.0, 16.0, 308.0] {
close_tol(ev("PERCENTRANK.INC", vec![k.clone(), n(2.123_456_789), n(sig)]), 0.187_242_798_166_667, 1e-16);
}
close_tol(ev("PERCENTRANK.INC", vec![k.clone(), n(2.123_456_789), n(14.0)]), 0.187_242_798_166_66, 1e-15);
close(ev("PERCENTRANK.EXC", vec![k, n(2.123_456_789), n(16.0)]), 0.265_432_098_625);
}
#[test]
@@ -360,6 +382,7 @@ fn normal() {
#[test]
fn t_chi_f() {
close_tol(ev("T.DIST", vec![n(0.0), n(6e307), b(false)]), 0.3989422804, 1e-10);
close_tol(ev("T.DIST", vec![n(60.0), n(1.0), b(true)]), 0.99469533, D7);
close_tol(ev("T.DIST", vec![n(8.0), n(3.0), b(false)]), 0.00073691, 1e-5);
close_tol(ev("T.DIST.2T", vec![n(1.959999998), n(60.0)]), 0.054644930, D7);
@@ -397,6 +420,7 @@ fn t_chi_f() {
close_tol(ev("F.DIST.RT", vec![n(15.2069), n(6.0), n(4.0)]), 0.01, 1e-6);
close_tol(ev("FDIST", vec![n(15.2069), n(6.0), n(4.0)]), 0.01, 1e-6);
close_tol(ev("F.INV", vec![n(0.01), n(6.0), n(4.0)]), 0.10930991, D7);
close_tol(ev("F.INV", vec![n(0.99), n(6.0), n(4.0)]), 15.20686, D7);
close_tol(ev("F.INV.RT", vec![n(0.01), n(6.0), n(4.0)]), 15.20686, D7);
close_tol(ev("FINV", vec![n(0.01), n(6.0), n(4.0)]), 15.20686, D7);
close_tol(ev("F.TEST", vec![c(&[6.0, 7.0, 9.0, 15.0, 21.0]), c(&[20.0, 28.0, 31.0, 38.0, 40.0])]), 0.64831785, D7);
@@ -404,6 +428,48 @@ fn t_chi_f() {
is_err(ev("F.DIST", vec![n(1.0), n(0.0), n(4.0), b(true)]), CellError::Num);
}
#[test]
fn f_distributions_accept_ten_billion_degrees() {
close_tol(ev("F.DIST", vec![n(0.0), n(10_000_000_000.0), n(1.0), b(false)]), 0.0, 0.0);
close_tol(ev("F.DIST.RT", vec![n(0.0), n(1.0), n(10_000_000_000.0)]), 1.0, 0.0);
close_tol(ev("F.DIST", vec![n(0.01), n(1_000_000_000.0), n(1.0), b(true)]), 1.52397e-23, 1e-28);
close_tol(ev("F.DIST", vec![n(1.0), n(10_000_000_000.0), n(10_000_000_000.0), b(true)]), 0.5, 0.0);
close_tol(ev("F.DIST", vec![n(1_000_000.0), n(10_000_000_000.0), n(1.0), b(true)]), 0.999202115, 1e-8);
close_tol(ev("F.INV", vec![n(0.5), n(10_000_000_000.0), n(1.0)]), 2.198110953542527, 2e-6);
close_tol(ev("F.DIST.RT", vec![n(0.0), n(9_999_999_999.0), n(1.0)]), 1.0, 0.0);
is_err(ev("F.DIST.RT", vec![n(0.0), n(10_000_000_001.0), n(1.0)]), CellError::Num);
is_err(ev("F.DIST.RT", vec![n(0.0), n(1.0), n(10_000_000_001.0)]), CellError::Num);
}
#[test]
fn t_dist_zero_degrees_error_depends_on_mode() {
for df in [0.0, 0.9, -0.1] {
is_err(ev("T.DIST", vec![n(0.0), n(df), b(false)]), CellError::Div0);
is_err(ev("T.DIST", vec![n(0.0), n(df), b(true)]), CellError::Num);
}
is_err(ev("T.DIST", vec![n(0.0), n(-1.0), b(false)]), CellError::Num);
close_tol(ev("T.DIST", vec![n(0.0), n(1.99), b(false)]), 1.0 / std::f64::consts::PI, 1e-15);
close_tol(ev("T.DIST", vec![n(0.0), n(1.0), b(false)]), 1.0 / std::f64::consts::PI, 1e-15);
}
#[test]
fn t_density_is_stable_for_large_degrees() {
close_tol(ev("T.DIST", vec![n(0.0), n(100_000_000.0), b(false)]), 0.398942279404077, 1e-12);
close_tol(ev("T.DIST", vec![n(0.0), n(10_000_000_000.0), b(false)]), 0.3989422803914591, 1e-12);
close_tol(ev("T.DIST", vec![n(1.0), n(10_000_000_000_000_000.0), b(false)]), 0.24197072451914337, 1e-12);
}
#[test]
fn t_inv_zero_probability_returns_div0() {
is_err(ev("T.INV", vec![n(-0.1), n(1.0)]), CellError::Num);
is_err(ev("T.INV", vec![n(0.0), n(1.0)]), CellError::Div0);
close_tol(ev("T.INV", vec![n(0.75), n(2.0)]), 0.8164966, D7);
is_err(ev("T.INV", vec![n(1.0), n(1.0)]), CellError::Num);
is_err(ev("T.INV", vec![n(1.1), n(1.0)]), CellError::Num);
is_err(ev("T.INV", vec![n(0.0), n(0.0)]), CellError::Num);
is_err(ev("T.INV.2T", vec![n(0.0), n(1.0)]), CellError::Num);
}
#[test]
fn binom_inv_huge_trials_returns() {
// Above 2^53 neighbouring f64 values are more than 1 apart; the bisection must still end.
@@ -427,7 +493,15 @@ fn discrete() {
close_tol(ev("BINOM.DIST", vec![n(6.0), n(10.0), n(0.5), b(false)]), 0.205078125, 1e-12);
close_tol(ev("BINOM.DIST", vec![n(6.0), n(10.0), n(0.5), b(true)]), 0.828125, 1e-12);
close_tol(ev("BINOMDIST", vec![n(6.0), n(10.0), n(0.5), b(false)]), 0.205078125, 1e-12);
close(ev("BINOM.DIST", vec![n(1.0), n(2_147_483_646.0), n(0.0), b(false)]), 0.0);
close(ev("BINOM.DIST", vec![n(1.0), n(2_147_483_646.9), n(0.0), b(false)]), 0.0);
is_err(ev("BINOM.DIST", vec![n(1.0), n(2_147_483_647.0), n(0.0), b(false)]), CellError::Num);
is_err(ev("BINOM.DIST", vec![n(1.0), n(2_147_483_647.9), n(0.0), b(false)]), CellError::Num);
is_err(ev("BINOM.DIST", vec![n(11.0), n(10.0), n(0.5), b(false)]), CellError::Num);
close(ev("BINOM.DIST.RANGE", vec![n(2_147_483_646.0), n(0.0), n(1.0)]), 0.0);
close(ev("BINOM.DIST.RANGE", vec![n(2_147_483_646.9), n(0.0), n(1.0)]), 0.0);
is_err(ev("BINOM.DIST.RANGE", vec![n(2_147_483_647.0), n(0.0), n(1.0)]), CellError::Num);
is_err(ev("BINOM.DIST.RANGE", vec![n(2_147_483_647.9), n(0.0), n(1.0)]), CellError::Num);
close_tol(ev("BINOM.DIST.RANGE", vec![n(60.0), n(0.75), n(48.0)]), 0.083974967, 1e-6);
close_tol(ev("BINOM.DIST.RANGE", vec![n(60.0), n(0.75), n(45.0), n(50.0)]), 0.523629793, 1e-6);
close(ev("BINOM.INV", vec![n(6.0), n(0.5), n(0.75)]), 4.0);
@@ -466,6 +540,19 @@ fn continuous() {
is_err(ev("GAMMA", vec![n(0.0)]), CellError::Num);
close_tol(ev("BETA.DIST", vec![n(2.0), n(8.0), n(10.0), b(true), n(1.0), n(3.0)]), 0.6854706, D7);
close_tol(ev("BETA.DIST", vec![n(2.0), n(8.0), n(10.0), b(false), n(1.0), n(3.0)]), 1.4837646, D7);
is_err(ev("BETA.DIST", vec![n(0.0), n(1.0), n(1.0), b(false)]), CellError::Num);
is_err(ev("BETA.DIST", vec![n(1.0), n(1.0), n(1.0), b(false)]), CellError::Num);
is_err(ev("BETA.DIST", vec![n(0.0), n(0.5), n(2.0), b(false)]), CellError::Num);
is_err(ev("BETA.DIST", vec![n(1.0), n(2.0), n(0.5), b(false)]), CellError::Num);
close(ev("BETA.DIST", vec![n(0.0), n(2.0), n(1.0), b(false)]), 0.0);
close(ev("BETA.DIST", vec![n(1.0), n(1.0), n(2.0), b(false)]), 0.0);
close(ev("BETA.DIST", vec![n(0.0), n(1.0), n(1.0), b(true)]), 0.0);
close(ev("BETA.DIST", vec![n(1.0), n(1.0), n(1.0), b(true)]), 1.0);
is_err(ev("BETA.DIST", vec![n(2.0), n(1.0), n(2.0), b(false), n(2.0), n(6.0)]), CellError::Num);
is_err(ev("BETA.DIST", vec![n(6.0), n(2.0), n(1.0), b(false), n(2.0), n(6.0)]), CellError::Num);
close(ev("BETA.DIST", vec![n(4.0), n(1.0), n(1.0), b(false), n(2.0), n(6.0)]), 0.25);
close(ev("BETA.DIST", vec![n(2.0), n(1.0), n(1.0), b(true), n(2.0), n(6.0)]), 0.0);
close(ev("BETA.DIST", vec![n(6.0), n(1.0), n(1.0), b(true), n(2.0), n(6.0)]), 1.0);
close_tol(ev("BETADIST", vec![n(2.0), n(8.0), n(10.0), n(1.0), n(3.0)]), 0.6854706, D7);
close_tol(ev("BETA.INV", vec![n(0.685470581), n(8.0), n(10.0), n(1.0), n(3.0)]), 2.0, D7);
close_tol(ev("BETAINV", vec![n(0.685470581), n(8.0), n(10.0), n(1.0), n(3.0)]), 2.0, D7);
@@ -479,6 +566,30 @@ fn continuous() {
close_tol(r[0][1].clone(), 0.841344746, 1e-8);
}
#[test]
fn gamma_density_at_zero_shape_one_is_num() {
for scale in [0.1, 0.9, 1.0, 1.9, 2.0, 10_000_000_000.0] {
is_err(ev("GAMMA.DIST", vec![n(0.0), n(1.0), n(scale), b(false)]), CellError::Num);
}
is_err(ev("GAMMA.DIST", vec![n(0.0), n(0.5), n(1.0), b(false)]), CellError::Num);
close_tol(ev("GAMMA.DIST", vec![n(0.0), n(2.0), n(1.0), b(false)]), 0.0, 0.0);
close_tol(ev("GAMMA.DIST", vec![n(0.0), n(1.0), n(2.0), b(true)]), 0.0, 0.0);
close_tol(ev("GAMMA.DIST", vec![n(2.0), n(1.0), n(2.0), b(false)]), 0.5 * (-1.0f64).exp(), 1e-15);
close_tol(ev("GAMMA.DIST", vec![n(2.0), n(1.0), n(2.0), b(true)]), 1.0 - (-1.0f64).exp(), 1e-15);
is_err(ev("GAMMA.DIST", vec![n(-0.1), n(1.0), n(2.0), b(false)]), CellError::Num);
}
#[test]
fn weibull_density_at_zero_is_zero() {
for shape in [0.5, 1.0, 2.0] {
close_tol(ev("WEIBULL.DIST", vec![n(0.0), n(shape), n(1.0), b(false)]), 0.0, 0.0);
close_tol(ev("WEIBULL.DIST", vec![n(0.0), n(shape), n(1.0), b(true)]), 0.0, 0.0);
}
close_tol(ev("WEIBULL.DIST", vec![n(1.0), n(1.0), n(1.0), b(false)]), (-1.0f64).exp(), 1e-15);
close_tol(ev("WEIBULL.DIST", vec![n(1.0), n(1.0), n(1.0), b(true)]), 1.0 - (-1.0f64).exp(), 1e-15);
is_err(ev("WEIBULL.DIST", vec![n(-0.1), n(1.0), n(1.0), b(false)]), CellError::Num);
}
#[test]
fn aggregate_helper() {
let vals = vec![nv(1.0), nv(2.0), tv("x"), Value::Empty, Value::Bool(true), nv(6.0)];
+113 -12
View File
@@ -111,12 +111,31 @@ fn len(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
num_val(text(a, 0)?.chars().count() as f64)
}
fn lower_char(ch: char) -> char {
match ch.to_lowercase().next() {
Some(lower) => lower,
None => ch,
}
}
fn upper_char(ch: char) -> char {
let mut uppercase = ch.to_uppercase();
match uppercase.next() {
Some(upper) if uppercase.next().is_none() => upper,
_ => ch,
}
}
fn proper_upper_char(ch: char) -> char {
if ch == '\u{130}' { 'I' } else { upper_char(ch) }
}
fn lower(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
text_val(text(a, 0)?.to_lowercase())
text_val(text(a, 0)?.chars().map(lower_char).collect::<String>())
}
fn upper(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
text_val(text(a, 0)?.to_uppercase())
text_val(text(a, 0)?.chars().map(upper_char).collect::<String>())
}
fn proper(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
@@ -126,9 +145,9 @@ fn proper(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
for ch in s.chars() {
if ch.is_alphabetic() {
if prev_letter {
out.extend(ch.to_lowercase());
out.push(lower_char(ch));
} else {
out.extend(ch.to_uppercase());
out.push(proper_upper_char(ch));
}
prev_letter = true;
} else {
@@ -281,7 +300,11 @@ fn unichar(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
if !(1.0..=1_114_111.0).contains(&n) {
return Err(CellError::Value);
}
match char::from_u32(n as u32) {
let cp = n as u32;
if (0xFDD0..=0xFDEF).contains(&cp) || cp & 0xFFFE == 0xFFFE {
return Err(CellError::NA);
}
match char::from_u32(cp) {
Some(c) => text_val(c.to_string()),
None => Err(CellError::NA),
}
@@ -350,10 +373,10 @@ fn numbervalue(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
/// Formats `x` (already rounded) with `decimals` places and optional thousands separators.
fn format_fixed(x: f64, decimals: i64, commas: bool) -> String {
let d = decimals.max(0) as usize;
let s = format!("{:.*}", d, x.abs());
let s = x.abs().to_string();
let (int_part, frac) = match s.split_once('.') {
Some((i, f)) => (i.to_string(), Some(f.to_string())),
None => (s.clone(), None),
Some((i, f)) => (i, f),
None => (s.as_str(), ""),
};
let int_part = if commas {
let b = int_part.as_bytes();
@@ -366,12 +389,14 @@ fn format_fixed(x: f64, decimals: i64, commas: bool) -> String {
}
o
} else {
int_part
int_part.to_string()
};
let mut out = int_part;
if let Some(f) = frac {
if d > 0 {
let frac_len = frac.len().min(d);
out.push('.');
out.push_str(&f);
out.push_str(&frac[..frac_len]);
out.extend(std::iter::repeat_n('0', d - frac_len));
}
out
}
@@ -394,13 +419,21 @@ fn fixed(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let (r, d) = rounded(a, 2.0)?;
let no_commas = opt_bool(a, 2, false)?;
let body = format_fixed(r, d, !no_commas);
if body.len() + if r < 0.0 { 1 } else { 0 } > 255 {
return Err(CellError::Value);
}
text_val(if r < 0.0 { format!("-{body}") } else { body })
}
fn dollar(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let (r, d) = rounded(a, 2.0)?;
let negative = r < 0.0 || (r == 0.0 && d >= 0 && num(a, 0)? < 0.0);
let body = format_fixed(r, d, true);
text_val(if r < 0.0 { format!("(${body})") } else { format!("${body}") })
let out = if negative { format!("(${body})") } else { format!("${body}") };
if out.len() > 254 {
return Err(CellError::Value);
}
text_val(out)
}
// ---------------------------------------------------------------------------------------------
@@ -1123,6 +1156,20 @@ mod tests {
fn case_and_cleanup() {
is_text(ev("UPPER", vec![t("abc")]), "ABC");
is_text(ev("LOWER", vec![t("ABC")]), "abc");
is_text(ev("UPPER", vec![t("Straße")]), "STRAßE");
is_text(ev("LOWER", vec![t("İ")]), "i");
is_text(ev("PROPER", vec![t("İSTANBUL")]), "Istanbul");
is_text(ev("PROPER", vec![t("ß")]), "ß");
is_text(ev("PROPER", vec![t("ÉCOLE")]), "École");
let proper = ev("PROPER", vec![t("İSTANBUL Straße")]);
is_text(proper.clone(), "Istanbul Straße");
assert_eq!(
match proper {
Value::Text(s) => s.chars().count(),
_ => 0,
},
"Istanbul Straße".chars().count()
);
is_text(ev("PROPER", vec![t("this is a TITLE")]), "This Is A Title");
is_text(ev("PROPER", vec![t("2-way street's")]), "2-Way Street'S");
is_text(ev("TRIM", vec![t(" a b c ")]), "a b c");
@@ -1181,8 +1228,15 @@ mod tests {
close(ev("CODE", vec![t("€")]), 128.0);
is_err(ev("CODE", vec![t("")]), CellError::Value);
is_text(ev("UNICHAR", vec![n(9731.0)]), "☃");
for cp in [0xFDD0, 0xFDEF, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x10FFFE, 0x10FFFF] {
is_err(ev("UNICHAR", vec![n(f64::from(cp))]), CellError::NA);
}
for (cp, expected) in [(0xFDCF, "\u{FDCF}"), (0xFDF0, "\u{FDF0}"), (0xFFFD, "\u{FFFD}"), (0x1FFFD, "\u{1FFFD}")] {
is_text(ev("UNICHAR", vec![n(f64::from(cp))]), expected);
}
close(ev("UNICODE", vec![t("☃")]), 9731.0);
is_err(ev("UNICHAR", vec![n(0.0)]), CellError::Value);
is_err(ev("UNICHAR", vec![n(1_114_112.0)]), CellError::Value);
is_err(ev("UNICHAR", vec![n(55296.0)]), CellError::NA);
}
@@ -1237,10 +1291,57 @@ mod tests {
is_text(ev("DOLLAR", vec![n(0.5), n(0.0)]), "$1");
is_text(ev("USDOLLAR", vec![n(1.0)]), "$1.00");
is_text(ev("USDOLLAR", vec![n(-1234.567), n(1.0)]), "($1,234.6)");
let fixed_16 = format!("1.1{}", "0".repeat(15));
let dollar_16 = format!("$1.1{}", "0".repeat(15));
let fixed_20 = format!("1.005{}", "0".repeat(17));
let dollar_20 = format!("$1.005{}", "0".repeat(17));
let fixed_127 = format!("1.1{}", "0".repeat(126));
let dollar_127 = format!("$1.1{}", "0".repeat(126));
is_text(ev("FIXED", vec![n(1.1), n(16.0)]), &fixed_16);
is_text(ev("DOLLAR", vec![n(1.1), n(16.0)]), &dollar_16);
is_text(ev("FIXED", vec![n(1.005), n(20.0)]), &fixed_20);
is_text(ev("DOLLAR", vec![n(1.005), n(20.0)]), &dollar_20);
is_text(ev("FIXED", vec![n(1.1), n(127.0)]), &fixed_127);
is_text(ev("DOLLAR", vec![n(1.1), n(127.0)]), &dollar_127);
is_text(ev("T", vec![t("x")]), "x");
is_text(ev("T", vec![n(1.0)]), "");
}
#[test]
fn fixed_and_dollar_output_limits() {
assert!(matches!(ev("FIXED", vec![n(1e191), n(0.0)]), Value::Text(ref s) if s.len() == 255));
is_err(ev("FIXED", vec![n(1e192), n(0.0)]), CellError::Value);
assert!(matches!(ev("FIXED", vec![n(-1e253), n(0.0), b(true)]), Value::Text(ref s) if s.starts_with('-')));
is_err(ev("FIXED", vec![n(-1e191), n(0.0)]), CellError::Value);
assert!(matches!(ev("FIXED", vec![n(1e189), n(1.0)]), Value::Text(ref s) if s.len() == 255));
is_err(ev("FIXED", vec![n(1e190), n(1.0)]), CellError::Value);
assert!(matches!(ev("DOLLAR", vec![n(1e189), n(0.0)]), Value::Text(ref s) if s.len() == 254));
is_err(ev("DOLLAR", vec![n(1e190), n(0.0)]), CellError::Value);
assert!(matches!(ev("DOLLAR", vec![n(-1e188), n(0.0)]), Value::Text(ref s) if s.len() == 254));
is_err(ev("DOLLAR", vec![n(-1e189), n(0.0)]), CellError::Value);
assert!(matches!(ev("DOLLAR", vec![n(1.23456789e187), n(2.0)]), Value::Text(ref s) if s.len() == 254));
is_err(ev("DOLLAR", vec![n(1.23456789e188), n(2.0)]), CellError::Value);
is_err(ev("DOLLAR", vec![n(-1.23456789e186), n(2.0)]), CellError::Value);
assert!(matches!(ev("DOLLAR", vec![n(1e189), n(-1.0)]), Value::Text(ref s) if s.len() == 254));
is_err(ev("DOLLAR", vec![n(1e190), n(-1.0)]), CellError::Value);
}
#[test]
fn dollar_keeps_negative_sign_when_nonnegative_precision_rounds_to_zero() {
is_text(ev("DOLLAR", vec![n(-0.0001), n(0.0)]), "($0)");
is_text(ev("DOLLAR", vec![n(-0.0001), n(2.0)]), "($0.00)");
is_text(ev("DOLLAR", vec![n(0.0), n(0.0)]), "$0");
is_text(ev("DOLLAR", vec![n(-0.0), n(0.0)]), "$0");
is_text(ev("DOLLAR", vec![n(0.0001), n(0.0)]), "$0");
is_text(ev("DOLLAR", vec![n(-0.0001), n(-1.0)]), "$0");
is_text(ev("DOLLAR", vec![n(-4.0), n(-1.0)]), "$0");
is_text(ev("DOLLAR", vec![n(-5.0), n(-1.0)]), "($10)");
is_text(ev("DOLLAR", vec![n(-0.4), n(0.0)]), "($0)");
is_text(ev("DOLLAR", vec![n(-0.5), n(0.0)]), "($1)");
is_text(ev("FIXED", vec![n(-0.0001), n(0.0)]), "0");
}
#[test]
fn before_after() {
is_text(ev("TEXTBEFORE", vec![t("Red riding hood"), t(" ")]), "Red");
+16
View File
@@ -252,6 +252,22 @@ fn save_and_open_roundtrip() {
let _ = std::fs::remove_file(path);
}
/// #2255: `parse: false` on `write_range` stores strings as the text they are, so a dd.mm.yyyy
/// date or a thousands separator survives, and the result names the strings the default read.
#[test]
fn write_range_can_store_strings_as_text() {
let mut s = server();
let row = json!([["05.04.2026", "2.500", "4.25 %", "=1+1"]]);
let stored = ok(&mut s, "write_range", json!({"range": "A1", "parse": false, "values": row}));
assert_eq!(stored["convertedCount"], 0, "nothing was read: {stored}");
let v = ok(&mut s, "read_range", json!({"range": "A1:D1"}));
assert_eq!(v["values"], json!([["05.04.2026", "2.500", "4.25 %", 2.0]]), "{v}");
// Without it the strings are read like typed input, and the result says which.
let read = ok(&mut s, "write_range", json!({"range": "A3", "values": row}));
assert_eq!(read["convertedCount"], 3, "{read}");
assert_eq!(read["converted"][0], json!({"cell": "A3", "input": "05.04.2026", "stored": "5/4/2026"}), "{read}");
}
/// An agent builds a small monthly budget through MCP tool calls only.
#[test]
fn agent_builds_a_budget() {
+4 -2
View File
@@ -190,11 +190,13 @@ fn base_tool_definitions() -> Vec<Value> {
"Write range",
"Write a 2-D array of values starting at the top-left cell of `range` (rows of cells). Numbers, booleans, null (clears) \
and strings are accepted; strings starting with = are formulas (\"=SUM(B2:B4)\"), other strings are parsed like typed \
input (\"12%\", \"1/2/2024\", \"$5\"). One undo step. Example: {\"range\":\"A1\",\"values\":[[\"Item\",\"Cost\"],[\"Rent\",1200]]}.",
input (\"12%\", \"1/2/2024\", \"$5\") unless `parse` is false, which stores them as the text they are. The result's \
`converted` lists the strings that were read as something else. One undo step. Example: {\"range\":\"A1\",\"values\":[[\"Item\",\"Cost\"],[\"Rent\",1200]]}.",
obj(
json!({
"range": string("Top-left cell or range, e.g. \"A1\" or \"Sheet2!B3\""),
"values": {"type": "array", "description": "Rows of cell values", "items": {"type": "array", "items": {"type": ["string", "number", "boolean", "null"]}}},
"parse": boolean("Read strings not starting with = like typed input, so \"05.04.2026\" becomes a date (default true); false stores them as the text they are, and \"\" clears the cell"),
}),
&["range", "values"],
),
@@ -637,7 +639,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<Value, String>
"list_windows" => exec(b, "window.list", json!({})),
"inspect_workbook" => b.call("document.inspect", json!({})),
"read_range" => b.call("sheet.read", pick(a, &["range", "sheet", "formulas", "formatted"])),
"write_range" => exec(b, "range.setValues", pick(a, &["range", "values"])),
"write_range" => exec(b, "range.setValues", pick(a, &["range", "values", "parse"])),
"set_cell" => exec(b, "cell.set", pick(a, &["cell", "input"])),
"get_cell" => exec(b, "cell.get", pick(a, &["cell"])),
"evaluate_formula" => {
+1 -1
View File
@@ -27,7 +27,7 @@ pub use style::{
Alignment, BorderLine, BorderStyle, Borders, Color, Fill, Font, HAlign, NumFmt, PatternType, Style, StyleId, StyleTable, Theme, Underline,
VAlign, VertAlign,
};
pub use workbook::{CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook};
pub use workbook::{CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook, WorkbookView};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
/// (e.g. the metric-compatible Carlito) when it isn't installed.
+49
View File
@@ -30,6 +30,51 @@ pub enum ShowObjects {
None,
}
/// The workbook window's display settings from `<workbookView>` (Excel: File › Options ›
/// Advanced, "Display options for this workbook"): whether the window shows the sheet tabs
/// and the two scroll bars, and how much of the horizontal bar the tabs take (`tabRatio`,
/// thousandths of the bar; the format's default is 600). XLSX I/O normalizes this
/// share to 0–1000, including values supplied directly through the model.
///
/// The values are modelled so an open + save keeps them — a workbook Excel saved with the
/// tabs hidden must not come back with them shown and the settings gone. The app does not
/// act on them yet and there is no Options control for them; that is the other half of
/// storytold/gridcraft#3057.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkbookView {
#[serde(default = "yes")]
pub show_sheet_tabs: bool,
#[serde(default = "yes")]
pub show_horizontal_scroll: bool,
#[serde(default = "yes")]
pub show_vertical_scroll: bool,
#[serde(default = "default_tab_ratio")]
pub tab_ratio: u32,
}
fn yes() -> bool {
true
}
fn default_tab_ratio() -> u32 {
600
}
impl Default for WorkbookView {
fn default() -> Self {
WorkbookView { show_sheet_tabs: true, show_horizontal_scroll: true, show_vertical_scroll: true, tab_ratio: default_tab_ratio() }
}
}
impl WorkbookView {
/// The entire bar, in thousandths: the upper bound used by XLSX I/O.
pub const MAX_TAB_RATIO: u32 = 1000;
fn is_default(&self) -> bool {
*self == WorkbookView::default()
}
}
/// File › Options › Formulas › Calculation options, stored per workbook (`<calcPr>`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CalcSettings {
@@ -150,6 +195,9 @@ pub struct Workbook {
pub show_objects: ShowObjects,
/// Read and set with [`Workbook::active_sheet`] and [`Workbook::set_active_sheet`].
pub active_sheet: ActiveSheet,
/// The workbook window's display settings (`<workbookView>`), kept across an open + save.
#[serde(default, skip_serializing_if = "WorkbookView::is_default")]
pub view: WorkbookView,
pub props: DocProps,
/// Workbook structure protection.
pub protected_structure: bool,
@@ -284,6 +332,7 @@ impl Workbook {
calc: CalcSettings::default(),
show_objects: ShowObjects::All,
active_sheet: ActiveSheet::default(),
view: WorkbookView::default(),
props: DocProps::default(),
protected_structure: false,
structure_password: None,
+13 -1
View File
@@ -15,7 +15,7 @@ use gridcraft_core::{CellError, DateSystem, Value};
pub use builtin::{builtin_format, builtin_id};
pub use decimal::format_general_fit;
use parse::{SecKind, Section, Tok};
use parse::{DatePart, SecKind, Section, Tok};
use render::Out;
/// Width (in characters) of General output in a cell.
@@ -193,6 +193,18 @@ impl NumberFormat {
self.num_sections().iter().any(|s| s.kind == SecKind::Date)
}
/// For a date or time format, whether the section that formats `value` shows calendar parts (year, month,
/// day) and whether it shows time parts, as `(date, time)`. `None` for any other format and for
/// elapsed-time codes like `[h]:mm`, whose value is a duration, not a moment.
pub fn date_shape(&self, value: f64) -> Option<(bool, bool)> {
let s = self.select(value).map(|(s, _)| s).filter(|s| s.kind == SecKind::Date)?;
let parts = || s.toks.iter().filter_map(|t| if let Tok::Date(d) = t { Some(*d) } else { None });
if parts().any(|d| matches!(d, DatePart::ElapsedH(_) | DatePart::ElapsedM(_) | DatePart::ElapsedS(_))) {
return None;
}
Some((parts().any(DatePart::is_calendar), parts().any(|d| !d.is_calendar())))
}
pub fn is_percent(&self) -> bool {
self.num_sections().iter().any(|s| s.kind == SecKind::Number && s.percent > 0)
}
+1 -1
View File
@@ -11,7 +11,7 @@ workspace = true
[dependencies]
# The shared capture slot (`craft_ui::capture`) comes from the one craft-libs revision every
# craft-libs dependency uses (see the root Cargo.toml).
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
gridcraft-engine = { workspace = true }
gridcraft-chart = { workspace = true }
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
+3 -4
View File
@@ -1,8 +1,7 @@
//! Bake the contributor credits into the binary as static Rust tables (craftrules
//! standards/contributors.md). Nothing is read at run time.
//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time.
//!
//! - contributors/contributors.json: commit stats per GitHub username, generated by craftrules
//! scripts/contributors.py, which also marks whose people.toml entry it verified.
//! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose
//! people.toml entry is verified.
//! - contributors/people.toml: the names people chose for themselves. A name is used only when the
//! JSON says the entry was verified (`people_entry`).
//!
+1
View File
@@ -75,6 +75,7 @@ impl SheetApp {
macros: macro_ui::MacroUi::default(),
started: now_ms(),
allow_close: false,
bring_forward: false,
open_switch_windows: false,
ui_window: None,
parked: HashMap::new(),
+9
View File
@@ -55,6 +55,15 @@ impl SheetApp {
// Requests the command made (a dialog, a draft) belong to the window it left active.
self.follow_active_window();
self.after_engine();
if id == "formulas.autoSum"
&& let Some(ed) = self.editor.as_mut()
&& ed.text.starts_with('=')
&& ed.text.ends_with("()")
{
ed.caret = ed.text.chars().count().saturating_sub(1);
ed.anchor = ed.caret;
ed.sync_caret = true;
}
if id == "view.arrangeAll"
&& self.native_windows
&& let Ok(r) = &r
+88
View File
@@ -15,6 +15,13 @@ impl SheetApp {
let Some(d) = self.session.active() else { return };
let Some(sh) = d.wb.active() else { return };
let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active);
// A locked cell on a protected sheet can't be entered (Excel's warning, and the engine
// refuses `cell.set` anyway): refuse before a draft exists, rather than leaving one that
// can never be committed and blocks Save (#2945).
if let Some(m) = self.session.locked_cell_message(d.wb.active_sheet(), at) {
self.message = Some(("GridCraft".into(), m));
return;
}
// A picture has no editable scalar text. Selecting it, F2, or clicking
// the formula bar must not turn its fallback value into a text edit.
// Typing still starts an intentional replacement.
@@ -102,6 +109,13 @@ impl SheetApp {
}
return true;
}
// A draft on a cell sheet protection now locks (the sheet was protected while it was
// open) can't be entered: drop it with the warning instead of keeping it, which would
// block Save with a draft that can never be committed (#2945).
if let Some(m) = self.session.locked_cell_message(ed.sheet, ed.cell) {
self.message = Some(("GridCraft".into(), m));
return true;
}
let text = match self.session.active().map(|d| formula_locale::canonical(&text, ed.locale, &d.wb, ed.sheet, ed.cell)) {
Some(Ok(text)) => text,
Some(Err(error)) => {
@@ -209,3 +223,77 @@ impl SheetApp {
self.grid.ensure_visible = true;
}
}
#[cfg(test)]
mod protected_cell_tests {
use super::*;
use gridcraft_engine::Session;
use gridcraft_engine::core::{CellRef, Value};
/// A protected sheet whose C2 is unlocked; C2 holds "keep" as the last undo step.
fn protected_book() -> SheetApp {
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("cell.set", json!({"cell": "C2", "input": "keep"})).unwrap();
app.run("home.formatCells", json!({"range": "C2", "style": {"protection": {"locked": false}}})).unwrap();
app.run("review.protectSheet", json!({})).unwrap();
app
}
fn value(app: &SheetApp, a1: &str) -> Value {
let at = CellRef::parse(a1).unwrap();
app.session.active().and_then(|d| d.wb.sheet(0)).map(|sh| sh.value(at)).unwrap_or_default()
}
fn protected_message(app: &SheetApp) -> Option<&str> {
app.message.as_ref().map(|(_, m)| m.as_str())
}
#[test]
fn typing_in_a_locked_cell_does_not_leave_a_draft_that_blocks_undo_and_save() {
let mut app = protected_book();
assert_eq!(app.session.active().unwrap().selection.active.a1(), "A1", "the locked A1 is the active cell");
let undo = app.session.active().unwrap().undo.len();
let dirty = app.session.active().unwrap().is_dirty();
app.begin_edit(Some("locked".into()), false);
assert!(app.editor.is_none(), "a locked cell must not open an editor");
assert!(protected_message(&app).is_some_and(|m| m.contains("protected sheet")), "the warning names the protected sheet");
assert_eq!(app.session.active().unwrap().undo.len(), undo, "a refused edit adds no undo step");
assert_eq!(app.session.active().unwrap().is_dirty(), dirty, "a refused edit leaves the workbook as it was");
assert!(app.run("file.saveBytes", json!({"format": "xlsx"})).is_ok(), "Save is not blocked by a draft that can never be entered");
}
#[test]
fn an_unlocked_cell_on_a_protected_sheet_still_edits_undoes_and_saves() {
let mut app = protected_book();
app.run("selection.set", json!({"cell": "C2"})).unwrap();
app.begin_edit(Some("typed".into()), false);
assert!(app.editor.is_some(), "an unlocked cell opens its editor");
assert!(app.commit_edit(0, 0, false, false));
assert_eq!(value(&app, "C2"), Value::text("typed"));
assert!(app.run("edit.undo", json!({})).is_ok());
assert_eq!(value(&app, "C2"), Value::text("keep"), "Undo of the typed edit still works");
assert!(app.run("file.saveBytes", json!({"format": "xlsx"})).is_ok());
}
#[test]
fn a_draft_that_becomes_locked_is_cancelled_instead_of_staying_open() {
let mut app = protected_book();
app.run("selection.set", json!({"cell": "C2"})).unwrap();
app.begin_edit(Some("typed".into()), false);
// The sheet is unprotected, C2 locked, and the sheet protected again while the draft is open.
app.run("review.unprotectSheet", json!({})).unwrap();
app.run("home.formatCells", json!({"range": "C2", "style": {"protection": {"locked": true}}})).unwrap();
app.run("review.protectSheet", json!({})).unwrap();
assert!(app.commit_edit(0, 0, false, false), "the refused draft is handled, not left open");
assert!(app.editor.is_none());
assert!(protected_message(&app).is_some_and(|m| m.contains("protected sheet")));
assert_eq!(value(&app, "C2"), Value::text("keep"));
assert!(app.run("file.saveBytes", json!({"format": "xlsx"})).is_ok());
}
}
+1
View File
@@ -42,6 +42,7 @@ impl SheetApp {
self.enter_window(window);
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
self.open_dialog("saveChanges", json!({"title": title, "quit": true}));
self.bring_forward = true;
}
None => {
self.allow_close = true;
+5 -1
View File
@@ -114,6 +114,8 @@ pub struct Backstage {
pub page: Page,
/// Info: property drafts while a field is being edited (committed when it loses focus).
props: [String; 6],
/// Focus at the end of the previous frame, before egui clears it on Esc.
text_edit_focused: bool,
/// Print: the whole workbook rather than the active sheet.
pub print_all: bool,
/// Print: fit each sheet on one page.
@@ -138,6 +140,7 @@ impl Backstage {
Backstage {
page,
props: Default::default(),
text_edit_focused: false,
print_all: false,
fit_to_page: false,
preview_page: 0,
@@ -160,7 +163,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
let Some(mut bs) = app.backstage.take() else { return };
let ctx = ui.ctx().clone();
// Esc inside a text field leaves the field; it closes the view only from outside one.
let typing = ctx.text_edit_focused();
let typing = bs.text_edit_focused;
let t = Tokens::get(&ctx);
let lang = app.ui.language;
let mut out = Outcome::default();
@@ -229,6 +232,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing
&& app.dialog.is_none()
&& app.message.is_none()
+17 -16
View File
@@ -264,6 +264,23 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Workboo
if objects_hidden(wb) {
return painted;
}
// Source outlines stay in cell space beneath every floating object.
if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart == Some(ch.id))
&& anchor_rect(geo, sh, &ch.anchor).intersects(p.clip_rect())
{
for s in &ch.series {
if let Ok(gridcraft_engine::formula::Expr::Ref(rf)) = gridcraft_engine::formula::parse(&s.values)
&& rf.sheet_name().is_none_or(|n| n.eq_ignore_ascii_case(&sh.name))
{
let rr = geo.range_rect(sh, rf.range());
let color = Tokens::get(p.ctx()).ref_color(0, true);
for pane in geo.range_panes(rf.range()) {
let pp = p.with_clip_rect(pane.intersect(p.clip_rect()));
pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside);
}
}
}
}
let mut done = |start: egui::layers::ShapeIdx, rect: Rect| painted.push(PaintedObject { shapes: start.0..p.add(egui::Shape::Noop).0, rect });
// The grid paints the active workbook: its pictures are cached under it.
let doc = app.session.active().map_or(0, |d| d.uid);
@@ -365,23 +382,7 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Workboo
if app.selected_chart == Some(ch.id) {
selection_frame(p, r);
}
// The source-data highlight below is in cell space: mirrored with the cells.
done(start, r);
if app.selected_chart == Some(ch.id) {
// Highlight the source data like Excel does.
for s in &ch.series {
if let Ok(gridcraft_engine::formula::Expr::Ref(rf)) = gridcraft_engine::formula::parse(&s.values)
&& rf.sheet_name().is_none_or(|n| n.eq_ignore_ascii_case(&sh.name))
{
let rr = geo.range_rect(sh, rf.range());
let color = Tokens::get(p.ctx()).ref_color(0, true);
for pane in geo.range_panes(rf.range()) {
let pp = p.with_clip_rect(pane.intersect(p.clip_rect()));
pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside);
}
}
}
}
}
paint_slicers(app, p, geo, wb, si, sh);
painted
+1 -2
View File
@@ -1,7 +1,6 @@
//! The About window's credits: every contributor (GitHub login always; display and real names only
//! with recorded consent) and the AI models that helped. The tables are baked into the binary by
//! build.rs from contributors/contributors.json (craftrules standards/contributors.md); nothing is
//! read at run time.
//! build.rs from contributors/contributors.json; nothing is read at run time.
use std::cmp::Ordering;
+54 -16
View File
@@ -72,6 +72,8 @@ pub struct Dialog {
focus_initialized: bool,
/// The formula box that takes references clicked or dragged on the grid (New Formatting Rule).
pick: Option<RefPick>,
/// The linked cell's initial display text; unchanged text must not replace a number or formula.
original_link_text: Option<String>,
}
/// A formula box in point mode, as in Excel: a click on the grid writes the cell's absolute
@@ -165,6 +167,7 @@ impl Dialog {
self.values.insert(pick.key.into(), json!(ed.text));
}
/// Creates a command-backed form with its initial field values.
fn form(name: &str, title: &str, command: &'static str, fields: Vec<Field>, defaults: Json) -> Dialog {
Dialog {
name: name.into(),
@@ -183,9 +186,11 @@ impl Dialog {
back: None,
focus_initialized: false,
pick: None,
original_link_text: None,
}
}
/// Creates a dialog whose body handles its own controls instead of a standard form.
pub(crate) fn custom(name: &str, title: &str, defaults: Json) -> Dialog {
Dialog {
name: name.into(),
@@ -204,9 +209,11 @@ impl Dialog {
back: None,
focus_initialized: false,
pick: None,
original_link_text: None,
}
}
/// Opens the named dialog with defaults from the active workbook, including a cell's stored hyperlink.
pub fn open(app: &mut SheetApp, name: &str, params: Json) -> Option<Dialog> {
let sel = app.session.active().map(|d| d.selection.current().a1()).unwrap_or_default();
let active = app.session.active().map(|d| d.selection.active.a1()).unwrap_or_default();
@@ -494,17 +501,30 @@ impl Dialog {
json!({"url": url}),
)
}
"insertLink" => Dialog::form(
"insertLink",
"Insert Hyperlink",
"insert.link",
vec![
Text { key: "text", label: "Display:" },
Text { key: "target", label: "Link to (web address, e-mail or Sheet!A1):" },
Text { key: "tooltip", label: "ScreenTip:" },
],
json!({"target": "https://"}),
),
"insertLink" => {
let mut d = Dialog::form(
"insertLink",
"Insert Hyperlink",
"insert.link",
vec![
Text { key: "text", label: "Display:" },
Text { key: "target", label: "Link to (web address, e-mail or Sheet!A1):" },
Text { key: "tooltip", label: "ScreenTip:" },
],
json!({"target": "https://"}),
);
if let Some(doc) = app.session.active()
&& let Some(sheet) = doc.wb.active()
&& let Some(link) = sheet.hyperlinks.get(&doc.selection.active)
{
let text = gridcraft_engine::display::cell_text(&doc.wb, sheet, doc.selection.active);
d.values.insert("target".into(), json!(link.target));
d.values.insert("text".into(), json!(text));
d.values.insert("tooltip".into(), json!(link.tooltip));
d.original_link_text = Some(text);
}
d
}
"sparkline" => Dialog::form(
"sparkline",
"Create Sparklines",
@@ -643,19 +663,31 @@ impl Dialog {
d
}
"solver" => {
// Starts from the sheet's saved model, else the active cell as objective.
// Starts from the sheet's saved model, else the active cell as objective; fields
// given when opening it go over either.
let saved = app.session.active().and_then(|doc| gridcraft_engine::cmd::solver::saved_model(&doc.wb, doc.wb.active_sheet()));
let mut values = json!({"objective": active, "goal": "max", "value": "0", "variables": "", "constraints": [], "nonNegative": true, "method": "grg"});
if let (Some(m), Some(v)) = (saved.as_ref().and_then(Json::as_object), values.as_object_mut()) {
for (k, x) in m {
v.insert(k.clone(), if k == "value" { json!(x.to_string()) } else { x.clone() });
for m in [saved.as_ref(), Some(&params)].into_iter().flatten().filter_map(Json::as_object) {
if let Some(v) = values.as_object_mut() {
for (k, x) in m {
v.insert(
k.clone(),
if k == "value" { json!(x.as_str().map_or_else(|| x.to_string(), str::to_string)) } else { x.clone() },
);
}
}
}
if let Some(v) = values.as_object_mut() {
v.insert("newOp".into(), json!("<="));
}
let options = values.get("optionsView").and_then(Json::as_bool) == Some(true);
let mut d = Dialog::custom("solver", "Solver Parameters", values);
d.command = Some("data.solver");
// Straight into the Solver Options: the same setup as the Options button, so the
// fields show their defaults and Cancel restores what was there.
if options {
analysis::open_solver_options(&mut d);
}
d
}
"solverResults" => Dialog::custom("solverResults", "Solver Results", params.clone()),
@@ -833,7 +865,13 @@ impl Dialog {
}
d
}
"insertFunction" => Dialog::custom("insertFunction", "Formula Builder", json!({"category": "Most Recently Used"})),
"insertFunction" => {
// A Function Library menu opens it on its own category.
let category = p("category").as_str().unwrap_or(crate::function_library::MOST_RECENTLY_USED).to_string();
let mut d = Dialog::custom("insertFunction", "Insert Function", json!({"category": category}));
d.focus_first_field = true;
d
}
"find" => {
let mut d = Dialog::custom("find", "Find and Replace", json!({"what": "", "with": "", "within": "sheet", "lookIn": "formulas"}));
d.tab = if p("replace").as_bool() == Some(true) { "Replace".into() } else { "Find".into() };
+220 -12
View File
@@ -1,4 +1,4 @@
use super::show::{form_fields, ok_cancel};
use super::show::{build_params, form_fields, ok_cancel};
use super::{Dialog, Field, Json, Map, SheetApp, json, vec2};
pub(super) fn goal_seek(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
@@ -169,9 +169,122 @@ pub(super) fn analysis_toolpak(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Di
ok_cancel(ui, confirm, open);
}
/// The Solver Options fields: (key, label, default).
const SOLVER_OPTIONS: [(&str, &str, &str); 7] = [
("maxEvaluations", "Max Evaluations:", "20000"),
("integerOptimality", "Integer Optimality (%):", "0"),
("convergence", "Convergence:", "0.0001"),
("mutationRate", "Mutation Rate:", "0.075"),
("populationSize", "Population Size:", "100"),
("randomSeed", "Random Seed:", "0"),
("generationsWithoutImprovement", "Maximum Generations without Improvement:", "50"),
];
/// Data › Solver › Options: the Solver Options in the Solver Parameters window. OK keeps the
/// changes for the next solve; Cancel restores them.
fn solver_options(ui: &mut egui::Ui, d: &mut Dialog, edit: impl Fn(&mut egui::Ui, &mut Dialog, &str, f32, &str)) {
let mut done = false;
egui::Grid::new("solverOptions").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| {
for (title, keys) in [("All Methods", &SOLVER_OPTIONS[..2]), ("Evolutionary", &SOLVER_OPTIONS[2..])] {
ui.label(egui::RichText::new(title).strong());
ui.end_row();
for (key, label, _) in keys {
ui.label(*label);
edit(ui, d, key, 100.0, label);
ui.end_row();
}
}
});
let mut bounds = d.values.get("requireBounds").and_then(Json::as_bool).unwrap_or(true);
if ui.checkbox(&mut bounds, "Require Bounds on Variables").changed() {
d.values.insert("requireBounds".into(), json!(bounds));
}
ui.add_space(8.0);
// A row as tall as the buttons (see `ok_cancel`): a right-to-left layout straight in the
// window takes all the height it is offered.
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(" Cancel ").clicked() {
cancel_solver_options(d);
}
if ui.button(" OK ").clicked() {
done = true;
}
});
});
if done {
close_solver_options(d);
}
}
/// Whether the Solver dialog shows its Solver Options.
pub(super) fn in_solver_options(d: &Dialog) -> bool {
d.name == "solver" && d.values.get("optionsView").and_then(Json::as_bool) == Some(true)
}
/// Solver Options › Cancel (also Escape or closing the window there): back to the parameters
/// with the options as they were.
pub(super) fn cancel_solver_options(d: &mut Dialog) {
if let Some(old) = d.values.get("optionsBackup").and_then(Json::as_object).cloned() {
for (k, v) in old {
d.values.insert(k, v);
}
}
close_solver_options(d);
}
/// Solver Parameters › Options (also opening the dialog with `optionsView`): shows the Solver
/// Options, each field with its value or its default, and keeps the values for Cancel.
pub(super) fn open_solver_options(d: &mut Dialog) {
let mut backup = serde_json::Map::new();
for (key, _, default) in SOLVER_OPTIONS {
let v = d.values.get(key).cloned().unwrap_or_else(|| json!(default));
backup.insert(key.into(), v.clone());
d.values.insert(key.into(), v);
}
backup.insert("requireBounds".into(), d.values.get("requireBounds").cloned().unwrap_or(json!(true)));
d.values.insert("optionsBackup".into(), Json::Object(backup));
d.values.insert("optionsView".into(), json!(true));
d.title = "Solver Options".into();
}
fn close_solver_options(d: &mut Dialog) {
d.values.insert("optionsView".into(), json!(false));
d.values.remove("optionsBackup");
d.title = "Solver Parameters".into();
}
/// Removes the model's options (the Solver Options fields and Require Bounds) from the form. A
/// key that is absent means the option's default, so Reset All and Load Model remove them all
/// before a model of their own; an option of the model before would otherwise go with the next
/// solve.
fn clear_solver_options(d: &mut Dialog) {
for (key, _, _) in SOLVER_OPTIONS {
d.values.remove(key);
}
d.values.remove("requireBounds");
}
/// Save Model from the Solver Parameters form: writes the form's model down from `range`. A
/// range that holds data is replaced only with `overwrite`; without it the form asks first.
fn save_solver_model(app: &mut SheetApp, d: &mut Dialog, range: &str, overwrite: bool) {
d.values.remove("askModelOverwrite");
let note = match app.run("data.solverSaveModel", json!({"to": range.trim(), "model": build_params(d), "overwrite": overwrite})) {
Ok(r) => format!("The model was saved to {}.", r.get("range").and_then(Json::as_str).unwrap_or("")),
Err(e) if !overwrite && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => {
d.values.insert("askModelOverwrite".into(), json!(range.trim()));
crate::clean_error(&e)
}
Err(e) => crate::clean_error(&e),
};
d.values.insert("modelNote".into(), json!(note));
}
/// Data › Solver: the Solver Parameters form. Solve runs `data.solver` through the dialog's
/// command; the result opens Solver Results.
pub(super) fn solver(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
/// command; the result opens Solver Results. Reset All clears the form and the sheet's model;
/// Load/Save reads or writes the model on cells of the sheet; Options shows the Solver Options
/// in the same window.
pub(super) fn solver(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
let lang = crate::i18n::current(ui.ctx());
let text = |d: &Dialog, k: &str| d.values.get(k).map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).unwrap_or_default();
let edit = |ui: &mut egui::Ui, d: &mut Dialog, k: &str, width: f32, label: &str| {
@@ -180,6 +293,10 @@ pub(super) fn solver(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open
d.values.insert(k.into(), json!(t));
}
};
if d.values.get("optionsView").and_then(Json::as_bool) == Some(true) {
solver_options(ui, d, edit);
return;
}
ui.horizontal(|ui| {
ui.label("Set Objective:");
edit(ui, d, "objective", 200.0, "Set Objective:");
@@ -282,16 +399,107 @@ pub(super) fn solver(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open
})
.small(),
);
ui.add_space(4.0);
ui.horizontal(|ui| {
if ui.button("Reset All").clicked() {
match app.run("data.solverReset", json!({})) {
Ok(_) => {
for (k, v) in [
("objective", json!("")),
("goal", json!("max")),
("value", json!("0")),
("variables", json!("")),
("constraints", json!([])),
("nonNegative", json!(true)),
("method", json!("grg")),
] {
d.values.insert(k.into(), v);
}
// The options go back to their defaults too.
clear_solver_options(d);
for key in ["optionsBackup", "modelNote", "askModelOverwrite"] {
d.values.remove(key);
}
}
Err(e) => {
d.values.insert("modelNote".into(), json!(crate::clean_error(&e)));
}
}
}
let shown = d.values.get("modelArea").and_then(Json::as_bool).unwrap_or(false);
if ui.selectable_label(shown, "Load/Save").clicked() {
d.values.insert("modelArea".into(), json!(!shown));
}
if ui.button("Options").clicked() {
open_solver_options(d);
}
});
if d.values.get("modelArea").and_then(Json::as_bool) == Some(true) {
ui.horizontal(|ui| {
ui.label("Model Range:");
edit(ui, d, "modelRange", 140.0, "Model Range:");
let range = text(d, "modelRange");
let ready = !range.trim().is_empty();
if ui.add_enabled(ready, egui::Button::new("Load")).clicked() {
d.values.remove("askModelOverwrite");
match app.run("data.solverLoadModel", json!({"from": range.trim()})) {
Ok(r) => {
if let Some(m) = r.get("model").and_then(Json::as_object) {
// The loaded model's options only: one it omits takes its default.
clear_solver_options(d);
for (k, x) in m {
d.values.insert(k.clone(), if k == "value" { json!(x.to_string()) } else { x.clone() });
}
}
d.values.insert("modelNote".into(), json!("The model was loaded."));
}
Err(e) => {
d.values.insert("modelNote".into(), json!(crate::clean_error(&e)));
}
}
}
if ui.add_enabled(ready, egui::Button::new("Save")).clicked() {
save_solver_model(app, d, &range, false);
}
});
// Save Model asks before it replaces data in the model range; the question goes when
// the range is edited, so Replace writes only where it asked about.
let asked = d.values.get("askModelOverwrite").and_then(Json::as_str).map(str::to_string);
if asked.as_deref().is_some_and(|a| a != text(d, "modelRange").trim()) {
d.values.remove("askModelOverwrite");
d.values.remove("modelNote");
} else if let Some(asked) = asked {
ui.horizontal_wrapped(|ui| {
ui.label(format!("{asked} already holds data. Replace it with the model?"));
if ui.button("Replace").clicked() {
save_solver_model(app, d, &asked, true);
}
if ui.button("Don't Replace").clicked() {
d.values.remove("askModelOverwrite");
d.values.remove("modelNote");
}
});
}
}
let note = text(d, "modelNote");
if !note.is_empty() {
ui.label(egui::RichText::new(note).small());
}
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let t = crate::theme::Tokens::get(ui.ctx());
let solve = ui.add(egui::Button::new(egui::RichText::new(" Solve ").color(t.on_accent)).fill(t.accent));
if solve.clicked() && !text(d, "objective").trim().is_empty() {
*confirm = true;
}
if ui.button(" Close ").clicked() {
*open = false;
}
// A row as tall as the buttons (see `ok_cancel`): the Load/Save area and the notes can make
// the form shorter, and a right-to-left layout straight in the window would fill what is
// left.
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let t = crate::theme::Tokens::get(ui.ctx());
let solve = ui.add(egui::Button::new(egui::RichText::new(" Solve ").color(t.on_accent)).fill(t.accent));
if solve.clicked() && !text(d, "objective").trim().is_empty() {
*confirm = true;
}
if ui.button(" Close ").clicked() {
*open = false;
}
});
});
}
+94 -38
View File
@@ -1,33 +1,97 @@
use super::show::ok_cancel;
use super::{Dialog, Json, SheetApp, vec2};
use super::show::{ok_cancel, take_first_focus};
use super::{Dialog, Json, SheetApp, json, vec2};
/// Insert Function: searches names (as the formula language spells them) and descriptions, shows
/// each hit's category and description, and starts editing `=NAME(` (or appends to the formula).
/// Insert Function: search names (as the formula language spells them) and descriptions, or pick
/// a category (Most Recently Used, All or one category), then a function; each hit shows its
/// category and description. OK starts editing `=NAME(` (or appends to the formula).
pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
use crate::function_library::{self as lib, ALL, MOST_RECENTLY_USED};
let language = app.ui.language;
ui.horizontal(|ui| {
ui.label(language.tr("Search:"));
let r = ui.add(egui::TextEdit::singleline(&mut d.search).desired_width(300.0).hint_text(language.tr("e.g. lookup, average, date")));
r.request_focus();
// Once only, so Tab can move on to the category list.
take_first_focus(d, &r);
});
// A new search (typed, or set through the control channel) looks through every function, as
// Excel's does.
if d.values.get("searched").and_then(Json::as_str) != Some(d.search.as_str()) {
d.list_index = 0;
if !d.search.trim().is_empty() {
d.values.insert("category".into(), json!(ALL));
}
d.values.insert("searched".into(), json!(d.search));
}
// The category may be given by label or by engine id (a Function Library menu, `ui.dialog.set`).
let saved = d.values.get("category").and_then(Json::as_str).unwrap_or(MOST_RECENTLY_USED).to_string();
let mut category = if saved.eq_ignore_ascii_case(ALL) {
ALL.to_string()
} else {
lib::category_id(&saved).map(lib::category_label).unwrap_or(MOST_RECENTLY_USED).to_string()
};
// The category list is the dialog's only menu, so a menu open as the frame starts is its own
// (Enter on a row picks it and closes the menu in this frame).
let menu_was_open = egui::Popup::is_any_open(ui.ctx());
let picker = ui.horizontal(|ui| {
let label = ui.label(language.tr("Or select a category:"));
craft_ui::ComboBox::from_id_salt("insertFunctionCategory")
.width(220.0)
.selected_text(language.tr(&category))
.show_ui(ui, |ui| {
for c in [MOST_RECENTLY_USED, ALL].into_iter().chain(lib::CATEGORIES.iter().map(|(_, l)| *l)) {
ui.selectable_value(&mut category, c.to_string(), language.tr(c));
}
})
.response
.labelled_by(label.id)
});
// Enter on the category list or in its menu opens it or picks a category, as Space does
// (egui clicks a focused control on either key); it does not also confirm the dialog.
let picker = picker.inner;
if menu_was_open || picker.has_focus() || craft_ui::ComboBox::is_open(ui.ctx(), picker.id) {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
if category != saved {
d.list_index = 0;
}
d.values.insert("category".into(), json!(category));
let locale = language.formula_locale();
let list = gridcraft_engine::cmd::formulas::function_list();
// The names and descriptions searched are the ones shown, so in the interface language.
let q = d.search.to_lowercase();
let hits: Vec<&Json> = list
.iter()
.filter(|f| {
q.is_empty()
|| f["name"].as_str().is_some_and(|n| locale.function_name(n).to_lowercase().contains(&q))
|| f["description"].as_str().is_some_and(|n| language.function_description(n).unwrap_or(n).to_lowercase().contains(&q))
})
.take(300)
.collect();
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
for (i, f) in hits.iter().enumerate() {
let name = locale.function_name(f["name"].as_str().unwrap_or(""));
let category = language.tr(function_category_label(f["category"].as_str().unwrap_or("")));
let r = ui.add(egui::Button::selectable(i == d.list_index, format!("{name:<18} {category}")).min_size(vec2(480.0, 20.0)));
let q = d.search.trim().to_lowercase();
let matches = |f: &lib::FnEntry| {
q.is_empty()
|| locale.function_name(&f.name).to_lowercase().contains(&q)
|| language.function_description(&f.description).unwrap_or(&f.description).to_lowercase().contains(&q)
};
let hits: Vec<&lib::FnEntry> = if category == MOST_RECENTLY_USED {
lib::recent(app).iter().filter_map(|n| lib::find(n)).filter(|f| matches(f)).collect()
} else {
let id = lib::category_id(&category);
// The catalog is fixed (some 500 functions), so All lists every one.
lib::all().iter().filter(|f| id.is_none_or(|id| f.category == id) && matches(f)).collect()
};
let t = crate::theme::Tokens::get(ui.ctx());
let font = egui::TextStyle::Body.resolve(ui.style());
let rows: Vec<(&str, &str)> = hits.iter().map(|f| (locale.function_name(&f.name), language.tr(lib::category_label(&f.category)))).collect();
// The category column starts after the widest name shown, so a long name in any formula
// language or font never runs into it.
let name_w = rows.iter().map(|(n, _)| ui.painter().layout_no_wrap(n.to_string(), font.clone(), t.text).size().x).fold(0.0_f32, f32::max);
egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, false]).show(ui, |ui| {
if rows.is_empty() {
ui.label(egui::RichText::new(language.tr("No functions match.")).italics());
}
let row_h = ui.text_style_height(&egui::TextStyle::Body) + 4.0;
for (i, (name, category)) in rows.iter().enumerate() {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width().max(name_w + 120.0), row_h), egui::Sense::click());
if i == d.list_index {
ui.painter().rect_filled(rect, 3.0, ui.visuals().selection.bg_fill);
} else if r.hovered() {
ui.painter().rect_filled(rect, 3.0, t.hover);
}
let color = if i == d.list_index { ui.visuals().selection.stroke.color } else { t.text };
ui.painter().text(rect.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, *name, font.clone(), color);
ui.painter().text(rect.left_center() + vec2(6.0 + name_w + 16.0, 0.0), egui::Align2::LEFT_CENTER, *category, font.clone(), t.text_dim);
r.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, i == d.list_index, format!("{name} ({category})")));
if r.clicked() {
d.list_index = i;
}
@@ -38,15 +102,19 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
}
});
if let Some(f) = hits.get(d.list_index) {
let name = f["name"].as_str().unwrap_or("");
ui.separator();
ui.label(egui::RichText::new(crate::formula_locale::signature(name, locale, language).unwrap_or_default()).strong());
ui.label(crate::formula_locale::description(name, locale, language).unwrap_or_default());
ui.label(egui::RichText::new(crate::formula_locale::signature(&f.name, locale, language).unwrap_or_default()).strong());
ui.label(crate::formula_locale::description(&f.name, locale, language).unwrap_or_default());
}
let mut open = true;
ok_cancel(ui, confirm, &mut open);
if *confirm && let Some(n) = hits.get(d.list_index).and_then(|f| f["name"].as_str()) {
let n = app.session.active().map(|doc| crate::formula_locale::completion_name(n, locale, &doc.wb, doc.wb.active_sheet())).unwrap_or(n);
// The function counts as recently used once the formula is entered (the engine notes it).
if *confirm && let Some(f) = hits.get(d.list_index) {
let n = app
.session
.active()
.map(|doc| crate::formula_locale::completion_name(&f.name, locale, &doc.wb, doc.wb.active_sheet()))
.unwrap_or(&f.name);
let cur = app.editor.as_ref().map(|e| e.text.clone());
let text = match cur {
Some(t) if t.starts_with('=') => format!("{t}{n}("),
@@ -58,15 +126,3 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
*confirm = true;
}
}
/// Excel's name for a function category, given the catalog's id (`MathTrig`).
fn function_category_label(id: &str) -> &str {
match id {
"DateTime" => "Date & Time",
"Lookup" => "Lookup & Reference",
"MathTrig" => "Math & Trig",
"AddIn" => "Add-in and Automation",
// Financial, Logical, Text, Statistical, Engineering, Database, Information, …
other => other,
}
}
+17 -4
View File
@@ -1,5 +1,5 @@
use super::about::about;
use super::analysis::{analysis_toolpak, goal_seek, solver, solver_results};
use super::analysis::{analysis_toolpak, cancel_solver_options, goal_seek, in_solver_options, solver, solver_results};
use super::charts::{recommended_charts, select_data};
use super::command_search::command_search;
use super::cond_format_rules::manage_rules;
@@ -15,9 +15,17 @@ use super::{Dialog, Field, Json, Key, Map, RefPick, SheetApp, json, vec2};
/// Builds the command params from form values for dialogs that need translation.
/// The parameters OK sends to the dialog's command: its field values, reshaped per dialog.
/// Unchanged hyperlink display text is omitted so its number or formula stays intact.
pub(crate) fn build_params(d: &Dialog) -> Json {
let mut v = Json::Object(d.values.clone());
match d.name.as_str() {
"insertLink" => {
if d.original_link_text.as_deref().is_some_and(|text| d.values.get("text").and_then(Json::as_str) == Some(text))
&& let Some(m) = v.as_object_mut()
{
m.remove("text");
}
}
"advancedFilter" => {
if let Some(m) = v.as_object_mut() {
m.remove("action");
@@ -173,7 +181,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
"goalSeek" => goal_seek(app, ui, &mut d, &mut confirm),
"pasteSpecial" => paste_special(app, ui, &mut d, &mut confirm, &mut open),
"analysisToolPak" => analysis_toolpak(app, ui, &mut d, &mut confirm, &mut open),
"solver" => solver(ui, &mut d, &mut confirm, &mut open),
"solver" => solver(app, ui, &mut d, &mut confirm, &mut open),
"solverResults" => solver_results(app, ui, &mut d, &mut open),
"spelling" => spelling(app, ui, &mut d, &mut open),
"agents" => {
@@ -368,7 +376,12 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
}
}
if ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
open = false;
// In Solver Options, Escape (or closing the window) cancels the options only.
if in_solver_options(&d) {
cancel_solver_options(&mut d);
} else {
open = false;
}
}
if confirm && d.name == "insertPicture" && d.picture_target != app.view_key() {
app.message = Some((d.title.clone(), "Return to the original worksheet to insert this picture, or cancel and choose another cell.".into()));
@@ -456,7 +469,7 @@ fn form(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool)
/// Enter sets the width, as in Excel.
/// Keeps asking until the field really has focus: a new window's first frame is an invisible
/// sizing pass where a focus request is ignored.
fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
pub(super) fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
if !d.focus_first_field {
return;
}
+9
View File
@@ -160,6 +160,15 @@ impl DocWindows {
self.list.focus(id);
self.viewports.focus(ctx, id);
}
// macOS ignores Focus for a minimized window or a hidden app, so restore and show first.
if std::mem::take(&mut app.bring_forward)
&& let Some(id) = self.list.active()
{
let vp = self.viewports.viewport_id(id);
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::Focus);
}
}
/// Draws every window. Call from the root viewport's UI each frame, in place of
+24 -5
View File
@@ -518,9 +518,23 @@ fn editor_arrow_keys(
ed: &mut crate::editor::EditState,
mut action: Option<EditorAction>,
) -> (Option<EditorAction>, bool) {
let (up, down, left, right, shift) = ui.input(|i| {
(i.key_pressed(Key::ArrowUp), i.key_pressed(Key::ArrowDown), i.key_pressed(Key::ArrowLeft), i.key_pressed(Key::ArrowRight), i.modifiers.shift)
// The modifiers come with the key event: an arrow pressed and released within one frame (a
// control client's or an automation tool's keystroke) has already lost them from `i.modifiers`.
let arrow = ui.input(|i| {
i.events.iter().find_map(|e| match e {
egui::Event::Key { key: key @ (Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight), pressed: true, modifiers, .. } => {
Some((*key, *modifiers))
}
_ => None,
})
});
let (up, down, left, right) = (
arrow.is_some_and(|(k, _)| k == Key::ArrowUp),
arrow.is_some_and(|(k, _)| k == Key::ArrowDown),
arrow.is_some_and(|(k, _)| k == Key::ArrowLeft),
arrow.is_some_and(|(k, _)| k == Key::ArrowRight),
);
let (shift, jump) = arrow.map_or((false, false), |(_, m)| (m.shift, m.command));
if (up || down) && !ed.autocomplete.is_empty() {
ui.input_mut(|i| {
i.consume_key(egui::Modifiers::NONE, Key::ArrowUp);
@@ -545,13 +559,18 @@ fn editor_arrow_keys(
let rtl = app.session.active().and_then(|d| d.wb.active()).is_some_and(|s| s.right_to_left);
let dc = if rtl { -dc } else { dc };
if ed.can_point() {
// Ctrl+arrow (⌘arrow) jumps the pointed cell to the edge of its data, Ctrl+Shift+arrow
// extends the pointed range there, as the same keys do on the selection.
ui.input_mut(|i| {
for key in [Key::ArrowUp, Key::ArrowDown, Key::ArrowLeft, Key::ArrowRight] {
i.consume_key(egui::Modifiers::NONE, key);
i.consume_key(egui::Modifiers::SHIFT, key);
for modifiers in
[egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::COMMAND, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT]
{
i.consume_key(modifiers, key);
}
}
});
crate::grid::point_move(app, ed, dr, dc, shift);
crate::grid::point_move(app, ed, dr, dc, shift, jump);
(action, false)
} else {
action = Some((dr, dc, false, false));
+191
View File
@@ -0,0 +1,191 @@
//! The Formulas tab's Function Library: the function categories, their menus, the AutoSum menu
//! (shared with Home › Editing), and the Recently Used menu, which lists what the engine's
//! `formulas.recentlyUsed` returns.
use std::sync::OnceLock;
use egui::{Ui, vec2};
use serde_json::json;
use crate::SheetApp;
/// The Insert Function category that lists [`recent`].
pub const MOST_RECENTLY_USED: &str = "Most Recently Used";
/// The Insert Function category that lists every function.
pub const ALL: &str = "All";
/// The function categories in the order the Insert Function dialog lists them: (the engine's
/// category id, the label people see).
pub const CATEGORIES: [(&str, &str); 14] = [
("Financial", "Financial"),
("DateTime", "Date & Time"),
("MathTrig", "Math & Trig"),
("Statistical", "Statistical"),
("Lookup", "Lookup & Reference"),
("Database", "Database"),
("Text", "Text"),
("Logical", "Logical"),
("Information", "Information"),
("Engineering", "Engineering"),
("Cube", "Cube"),
("Compatibility", "Compatibility"),
("Web", "Web"),
("AddIn", "Add-in and Automation"),
];
/// The categories under More Functions, each a cascading submenu.
pub const MORE_FUNCTIONS: [&str; 6] = ["Statistical", "Engineering", "Cube", "Information", "Compatibility", "Web"];
/// The label of an engine category id (the id itself if it is unknown).
pub fn category_label(id: &str) -> &str {
CATEGORIES.iter().find(|(c, _)| *c == id).map(|(_, l)| *l).unwrap_or(id)
}
/// The engine category id for a category given by id or label, in any case.
pub fn category_id(name: &str) -> Option<&'static str> {
CATEGORIES.iter().find(|(c, l)| c.eq_ignore_ascii_case(name) || l.eq_ignore_ascii_case(name)).map(|(c, _)| *c)
}
/// One function of the library.
#[derive(Clone, Debug)]
pub struct FnEntry {
pub name: String,
pub category: String,
pub description: String,
}
/// Every function, sorted by name (built once; the list is static).
pub fn all() -> &'static [FnEntry] {
static LIST: OnceLock<Vec<FnEntry>> = OnceLock::new();
LIST.get_or_init(|| {
let mut list: Vec<FnEntry> = gridcraft_engine::cmd::formulas::function_list()
.iter()
.filter_map(|f| {
Some(FnEntry {
name: f["name"].as_str()?.to_string(),
category: f["category"].as_str().unwrap_or("").to_string(),
description: f["description"].as_str().unwrap_or("").to_string(),
})
})
.collect();
list.sort_by(|a, b| a.name.cmp(&b.name));
list.dedup_by(|a, b| a.name == b.name);
list
})
}
/// The function named `name` (upper case), if the library knows it.
pub fn find(name: &str) -> Option<&'static FnEntry> {
let list = all();
list.binary_search_by(|f| f.name.as_str().cmp(name)).ok().and_then(|i| list.get(i))
}
/// The functions of one engine category, in name order.
pub fn in_category(id: &str) -> impl Iterator<Item = &'static FnEntry> + '_ {
all().iter().filter(move |f| f.category == id)
}
/// The name a function shows under in the interface language.
fn display_name<'a>(app: &SheetApp, name: &'a str) -> &'a str {
let locale = app.ui.language.formula_locale();
app.session.active().map(|d| crate::formula_locale::completion_name(name, locale, &d.wb, d.wb.active_sheet())).unwrap_or(name)
}
/// One menu row per function, with its description on hover; a click starts the formula.
fn function_items<'a>(app: &mut SheetApp, ui: &mut Ui, names: impl Iterator<Item = &'a str>) {
let language = app.ui.language;
let locale = language.formula_locale();
ui.set_max_height(420.0);
egui::ScrollArea::vertical().max_height(380.0).show(ui, |ui| {
for n in names {
let Some(entry) = find(n) else { continue };
let name = display_name(app, &entry.name);
let r = ui.add(egui::Button::new(name).frame(false).min_size(vec2(180.0, 20.0)));
// The description is looked up only while the row is hovered.
let r = r.on_hover_ui(|ui| {
ui.label(crate::formula_locale::description(&entry.name, locale, language).unwrap_or_default());
});
if r.clicked() {
app.run_or_alert("formulas.insertFunction", json!({"name": entry.name}));
ui.close();
}
}
});
}
/// The "Insert Function…" row that ends every category menu; it opens the dialog on `category`.
fn insert_function_item(app: &mut SheetApp, ui: &mut Ui, category: &str) {
ui.separator();
let label = app.ui.language.tr("Insert Function…");
if ui.add(egui::Button::new(label).frame(false).min_size(vec2(180.0, 22.0))).clicked() {
app.open_dialog("insertFunction", json!({"category": category}));
ui.close();
}
}
/// The menu of one category: its functions, then Insert Function….
pub fn category_menu(app: &mut SheetApp, ui: &mut Ui, id: &str) {
let names: Vec<&str> = in_category(id).map(|f| f.name.as_str()).collect();
function_items(app, ui, names.into_iter());
insert_function_item(app, ui, category_label(id));
}
/// The functions `formulas.recentlyUsed` lists, newest first (none without a workbook).
pub fn recent(app: &mut SheetApp) -> Vec<String> {
let list = app.session.execute("formulas.recentlyUsed", json!({})).unwrap_or_default();
list.as_array().map(|a| a.iter().filter_map(|n| n.as_str().map(String::from)).collect()).unwrap_or_default()
}
/// Recently Used: the most recent functions, newest first, then Insert Function….
pub fn recent_menu(app: &mut SheetApp, ui: &mut Ui) {
let recent = recent(app);
function_items(app, ui, recent.iter().map(String::as_str));
insert_function_item(app, ui, MOST_RECENTLY_USED);
}
/// More Functions: a cascading submenu per remaining category.
pub fn more_menu(app: &mut SheetApp, ui: &mut Ui) {
for id in MORE_FUNCTIONS {
let label = app.ui.language.tr(category_label(id)).to_string();
ui.menu_button(label, |ui| category_menu(app, ui, id));
}
}
/// The AutoSum menu, shared by Home › Editing and Formulas › Function Library: a function, or
/// the Insert Function dialog.
pub fn auto_sum_menu(app: &mut SheetApp, ui: &mut Ui) {
for (label, f) in [("Sum", "SUM"), ("Average", "AVERAGE"), ("Count Numbers", "COUNT"), ("Max", "MAX"), ("Min", "MIN")] {
let label = app.ui.language.tr(label);
if ui.add(egui::Button::new(label).frame(false).min_size(vec2(160.0, 22.0))).clicked() {
app.run_or_alert("formulas.autoSum", json!({"function": f}));
ui.close();
}
}
ui.separator();
let label = app.ui.language.tr("More Functions…");
if ui.add(egui::Button::new(label).frame(false).min_size(vec2(160.0, 22.0))).clicked() {
app.open_dialog("insertFunction", json!({}));
ui.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn categories_cover_every_function() {
for f in all() {
assert!(category_id(&f.category).is_some(), "{} is in an unknown category {}", f.name, f.category);
}
assert_eq!(category_id("date & time"), Some("DateTime"));
assert_eq!(category_id("Lookup"), Some("Lookup"));
assert_eq!(category_id("nope"), None);
for c in MORE_FUNCTIONS {
assert!(category_id(c).is_some());
}
assert!(all().windows(2).all(|w| w[0].name < w[1].name), "sorted by name, without duplicates");
assert_eq!(find("SUM").map(|f| f.category.as_str()), Some("MathTrig"));
assert!(find("NOT_A_FUNCTION").is_none());
}
}
+5 -3
View File
@@ -1014,11 +1014,13 @@ pub fn follow_link(app: &mut SheetApp, target: &str) {
}
}
/// Used by `EditState` users to keep the active cell visible while pointing.
pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, extend: bool) {
/// Moves the pointed cell one step, or with `jump` (Ctrl+arrow) to the edge of its data region;
/// `extend` (Shift) moves the far end of the pointed range instead. Keeps the pointed cell visible.
pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, extend: bool, jump: bool) {
let Some(d) = app.session.active() else { return };
let Some(sheet) = d.wb.active() else { return };
let from = ed.point_cell.unwrap_or(ed.cell);
let to = from.offset_clamped(dr, dc);
let to = if jump { gridcraft_engine::selection::jump(sheet, from, dr.signum(), dc.signum()) } else { from.offset_clamped(dr, dc) };
let anchor = if extend {
// The anchor is the corner opposite the moving end: the written range is normalized, so
// after extending up or left its first cell is the moving end, not the anchor.
+37 -3
View File
@@ -5,8 +5,8 @@ use super::cell_paint::{
use super::geo::Geo;
use super::tables::{filter_button_rect, paint_filter_button};
use super::{
CellRef, CfCache, CfLook, Color32, FontId, HAlign, MAX_COLS, Painter, Pos2, RangeRef, Rect, Sheet, Stroke, StrokeKind, Tokens, Underline, Value,
Workbook, pos2, theme, vec2,
CellRef, CfCache, CfLook, Color32, FontId, HAlign, MAX_COLS, Painter, Pos2, RangeRef, Rect, Sheet, Stroke, StrokeKind, Tokens, Underline, VAlign,
Value, Workbook, pos2, theme, vec2,
};
/// Mirror what the grid painted into `layer` (the shape indices in `range`) for a right-to-left
@@ -68,6 +68,30 @@ fn mirror_shape(shape: &mut egui::Shape, axis: f32) {
}
}
/// Restrict top-aligned wrapped text to complete lines inside the cell.
///
/// Preserve the cell and viewport clip when every line fits. Otherwise,
/// exclude overflowing lines while retaining the visible fitting lines.
fn wrapped_text_clip(p: &Painter, rect: Rect, galley: &egui::Galley, y: f32, valign: VAlign) -> Rect {
let mut clip = rect.intersect(p.clip_rect());
if valign != VAlign::Top {
return clip;
}
let Some(last_row) = galley.rows.last() else {
return clip;
};
if y + last_row.rect().bottom() <= rect.bottom() + 0.01 {
return clip;
}
let last_full_bottom = galley.rows.iter().map(|row| y + row.rect().bottom()).rfind(|bottom| *bottom <= rect.bottom() + 0.01);
clip.max.y = last_full_bottom.map(|bottom| clip.bottom().min(bottom)).unwrap_or(clip.top()).max(clip.top());
clip
}
pub(crate) struct QuadrantPaint<'a> {
pub(crate) painter: &'a Painter,
pub(crate) geo: &'a Geo,
@@ -80,6 +104,11 @@ pub(crate) struct QuadrantPaint<'a> {
pub(crate) tokens: &'a Tokens,
}
/// Paint a worksheet quadrant, including backgrounds, borders, and text.
///
/// For top-aligned wrapped text, painting is limited to complete lines
/// fitting within the cell height while respecting viewport clipping.
/// Other vertical alignment modes retain their existing behavior.
pub(crate) fn paint_quadrant(mut quadrant: QuadrantPaint<'_>) {
let (r0, r1) = quadrant.rows;
let (c0, c1) = quadrant.cols;
@@ -288,6 +317,10 @@ fn should_expand_text(filter_space: f32, overflows: bool, across_end: u32, col:
filter_space == 0.0 && (overflows || across_end > col) && !in_merge
}
/// Paint one worksheet cell using its computed appearance and visible geometry.
///
/// Handles text layout, wrapping, alignment, overflow into neighbouring cells,
/// and clipping, while preserving cell decoration and merged-cell constraints.
fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLook>), merges: &[RangeRef]) {
let (cell, rect, lk, cfl) = painted;
let c = *cell;
@@ -363,7 +396,8 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
_ => text_left + pad + indent,
};
let y = wrapped_cell_text_y(st.align.v, *rect, galley.size().y, z);
p.with_clip_rect(rect.intersect(p.clip_rect())).galley(pos2(x, y), galley, color);
let text_clip = wrapped_text_clip(p, *rect, &galley, y, st.align.v);
p.with_clip_rect(text_clip).galley(pos2(x, y), galley, color);
return;
}
// Wrap Text off: Excel ignores the line breaks and draws the whole string on one line.
+5 -4
View File
@@ -417,11 +417,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Dlouhé datum",
"More Number Formats…" => "Další formáty čísel…",
"Financial" => "Finanční",
"Recently Used" => "Naposledy použité",
"Logical" => "Logické",
"Date &\nTime" => "Datum a\nčas",
"Lookup &\nReference" => "Vyhledávání\na odkazy",
"Math &\nTrig" => "Matematika a\ntrigonometrie",
"More\nFunctions" => "Další\nfunkce",
"Date & Time" => "Datum a čas",
"Lookup & Reference" => "Vyhledávání a odkazy",
"Math & Trig" => "Matematika a trigonometrie",
"More Functions" => "Další funkce",
"Sheet Options|View" => "Zobrazit",
"Print" => "Tisknout",
"Print What" => "Co tisknout",
+5 -4
View File
@@ -420,11 +420,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Langes Datum",
"More Number Formats…" => "Weitere Zahlenformate…",
"Financial" => "Finanzmathematik",
"Recently Used" => "Zuletzt verwendet",
"Logical" => "Logisch",
"Date &\nTime" => "Datum &\nUhrzeit",
"Lookup &\nReference" => "Nachschlagen &\nVerweisen",
"Math &\nTrig" => "Mathematik &\nTrigonometrie",
"More\nFunctions" => "Weitere\nFunktionen",
"Date & Time" => "Datum & Uhrzeit",
"Lookup & Reference" => "Nachschlagen & Verweisen",
"Math & Trig" => "Mathematik & Trigonometrie",
"More Functions" => "Weitere Funktionen",
"Page Layout|Orientation" => "Seitenausrichtung",
"Display theme" => "Anzeigedesign",
"System" => "System",
+1 -5
View File
@@ -389,10 +389,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Περισσότερες μορφές αριθμών…",
"Financial" => "Οικονομικές",
"Logical" => "Λογικές",
"Date &\nTime" => "Ημερομηνία και\nώρα",
"Lookup &\nReference" => "Αναζήτηση και\nαναφορά",
"Math &\nTrig" => "Μαθηματικά και\nτριγωνομετρία",
"More\nFunctions" => "Περισσότερες\nσυναρτήσεις",
"More Functions" => "Περισσότερες συναρτήσεις",
"Page Layout|Orientation" => "Προσανατολισμός σελίδας",
"Display theme" => "Θέμα εμφάνισης",
"System" => "Σύστημα",
@@ -580,7 +577,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Επεξεργασία ονόματος",
"New Name" => "Νέο όνομα",
"Format Cells" => "Μορφοποίηση κελιών",
"Formula Builder" => "Δημιουργός τύπων",
"Find and Replace" => "Εύρεση και αντικατάσταση",
"Go To" => "Μετάβαση",
"Insert Calculated Field" => "Εισαγωγή υπολογιζόμενου πεδίου",
+5 -4
View File
@@ -417,11 +417,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Fecha larga",
"More Number Formats…" => "Más formatos de número…",
"Financial" => "Financieras",
"Recently Used" => "Usadas recientemente",
"Logical" => "Lógicas",
"Date &\nTime" => "Fecha\ny hora",
"Lookup &\nReference" => "Búsqueda y\nreferencia",
"Math &\nTrig" => "Matemáticas y\ntrigonométricas",
"More\nFunctions" => "Más\nfunciones",
"Date & Time" => "Fecha y hora",
"Lookup & Reference" => "Búsqueda y referencia",
"Math & Trig" => "Matemáticas y trigonométricas",
"More Functions" => "Más funciones",
"Page Layout|Orientation" => "Orientación",
"Display theme" => "Tema de la interfaz",
"System" => "Sistema",
+5 -4
View File
@@ -308,11 +308,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Date longue",
"More Number Formats…" => "Autres formats numériques…",
"Financial" => "Financières",
"Recently Used" => "Récemment utilisées",
"Logical" => "Logiques",
"Date &\nTime" => "Date et\nheure",
"Lookup &\nReference" => "Recherche et\nréférence",
"Math &\nTrig" => "Maths et\ntrigonométrie",
"More\nFunctions" => "Autres\nfonctions",
"Date & Time" => "Date et heure",
"Lookup & Reference" => "Recherche et référence",
"Math & Trig" => "Maths et trigonométrie",
"More Functions" => "Autres fonctions",
"Sheet Options|View" => "Affichage",
"Print" => "Impression",
"Print What" => "Quoi imprimer",
+1 -5
View File
@@ -291,10 +291,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Altri formati numero…",
"Financial" => "Finanziarie",
"Logical" => "Logiche",
"Date &\nTime" => "Data e\nora",
"Lookup &\nReference" => "Ricerca e\nriferimento",
"Math &\nTrig" => "Matematiche e\ntrigonometriche",
"More\nFunctions" => "Altre\nfunzioni",
"More Functions" => "Altre funzioni",
"Page Layout|Orientation" => "Orientamento",
"Display theme" => "Tema di visualizzazione",
"Animations" => "Animazioni",
@@ -456,7 +453,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Modifica nome",
"New Name" => "Nuovo nome",
"Format Cells" => "Formato celle",
"Formula Builder" => "Generatore di formule",
"Find and Replace" => "Trova e sostituisci",
"Go To" => "Vai a",
"Insert Calculated Field" => "Inserisci campo calcolato",
+2 -5
View File
@@ -304,10 +304,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("More Number Formats…", "その他の表示形式…"),
("Financial", "財務"),
("Logical", "論理"),
("Date &\nTime", "日付/時刻"),
("Lookup &\nReference", "検索/行列"),
("Math &\nTrig", "数学/三角"),
("More\nFunctions", "その他の関数"),
("Recently Used", "最近使用した関数"),
("More Functions", "その他の関数"),
("Sheet Options|View", "画面"),
("Print", "印刷"),
("Print What", "印刷する内容"),
@@ -477,7 +475,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Edit Name", "名前の編集"),
("New Name", "新しい名前"),
("Format Cells", "セルの書式設定"),
("Formula Builder", "数式ビルダー"),
("Find and Replace", "検索と置換"),
("Go To", "ジャンプ"),
("Insert Calculated Field", "計算のフィールドの挿入"),
+5 -4
View File
@@ -295,11 +295,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "자세한 날짜",
"More Number Formats…" => "숫자 서식 더 보기…",
"Financial" => "재무",
"Recently Used" => "최근 사용 항목",
"Logical" => "논리",
"Date &\nTime" => "날짜 및\n시간",
"Lookup &\nReference" => "조회 및\n참조",
"Math &\nTrig" => "수학 및\n삼각",
"More\nFunctions" => "기타\n함수",
"Date & Time" => "날짜 및 시간",
"Lookup & Reference" => "조회 및 참조",
"Math & Trig" => "수학 및 삼각",
"More Functions" => "기타 함수",
"Page Layout|Orientation" => "용지 방향",
"Display theme" => "표시 테마",
"Animations" => "애니메이션",
+4 -4
View File
@@ -300,10 +300,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Meer getalnotaties…",
"Financial" => "Financieel",
"Logical" => "Logisch",
"Date &\nTime" => "Datum en\ntijd",
"Lookup &\nReference" => "Zoeken en\nverwijzen",
"Math &\nTrig" => "Wiskunde en\ntrigonometrie",
"More\nFunctions" => "Meer\nfuncties",
"Date & Time" => "Datum en tijd",
"Lookup & Reference" => "Zoeken en verwijzen",
"Math & Trig" => "Wiskunde en trigonometrie",
"More Functions" => "Meer functies",
"Sheet Options|View" => "Weergeven",
"Print" => "Afdrukken",
"Print What" => "Wat afdrukken",
+1 -5
View File
@@ -287,10 +287,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Więcej formatów liczb…",
"Financial" => "Finansowe",
"Logical" => "Logiczne",
"Date &\nTime" => "Data i\ngodzina",
"Lookup &\nReference" => "Wyszukiwanie\ni odwołania",
"Math &\nTrig" => "Matematyczne i\ntrygonometryczne",
"More\nFunctions" => "Więcej\nfunkcji",
"More Functions" => "Więcej funkcji",
"Page Layout|Orientation" => "Orientacja",
"Display theme" => "Motyw wyświetlania",
"Animations" => "Animacje",
@@ -450,7 +447,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Edytowanie nazwy",
"New Name" => "Nowa nazwa",
"Format Cells" => "Formatowanie komórek",
"Formula Builder" => "Konstruktor formuł",
"Find and Replace" => "Znajdowanie i zamienianie",
"Go To" => "Przechodzenie do",
"Insert Calculated Field" => "Wstawianie pola obliczeniowego",
+2 -5
View File
@@ -291,11 +291,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Data Por Extenso",
"More Number Formats…" => "Mais Formatos de Número…",
"Financial" => "Financeira",
"Recently Used" => "Usadas Recentemente",
"Logical" => "Lógica",
"Date &\nTime" => "Data e\nHora",
"Lookup &\nReference" => "Pesquisa e\nReferência",
"Math &\nTrig" => "Matemática e\nTrigonometria",
"More\nFunctions" => "Mais\nFunções",
"More Functions" => "Mais Funções",
"Page Layout|Orientation" => "Orientação",
"Display theme" => "Tema de exibição",
"Animations" => "Animações",
@@ -471,7 +469,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Editar Nome",
"New Name" => "Novo Nome",
"Format Cells" => "Formatar Células",
"Formula Builder" => "Construtor de Fórmulas",
"Find and Replace" => "Localizar e Substituir",
"Go To" => "Ir para",
"Insert Calculated Field" => "Inserir Campo Calculado",
+1 -5
View File
@@ -294,10 +294,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Mai multe formate de număr…",
"Financial" => "Financiare",
"Logical" => "Logice",
"Date &\nTime" => "Dată și\noră",
"Lookup &\nReference" => "Căutare și\nreferință",
"Math &\nTrig" => "Matematică și\ntrigonometrie",
"More\nFunctions" => "Mai multe\nfuncții",
"More Functions" => "Mai multe funcții",
"Page Layout|Orientation" => "Orientare",
"Display theme" => "Temă de afișare",
"Animations" => "Animații",
@@ -456,7 +453,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Editare nume",
"New Name" => "Nume nou",
"Format Cells" => "Formatare celule",
"Formula Builder" => "Generator de formule",
"Find and Replace" => "Găsire și înlocuire",
"Go To" => "Salt la",
"Insert Calculated Field" => "Inserare câmp calculat",
+5 -4
View File
@@ -295,11 +295,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Long Date" => "Длинная дата",
"More Number Formats…" => "Другие числовые форматы…",
"Financial" => "Финансовые",
"Recently Used" => "Последние",
"Logical" => "Логические",
"Date &\nTime" => "Дата и\nвремя",
"Lookup &\nReference" => "Поиск и\nссылки",
"Math &\nTrig" => "Математические и\nтригонометрические",
"More\nFunctions" => "Другие\nфункции",
"Date & Time" => "Дата и время",
"Lookup & Reference" => "Поиск и ссылки",
"Math & Trig" => "Математические и тригонометрические",
"More Functions" => "Другие функции",
"Page Layout|Orientation" => "Ориентация",
"Display theme" => "Тема оформления",
"Animations" => "Анимация",
+4 -4
View File
@@ -299,10 +299,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Još formata brojeva…",
"Financial" => "Finansijsko",
"Logical" => "Logičko",
"Date &\nTime" => "Datum i\nvreme",
"Lookup &\nReference" => "Pretraga i\nreference",
"Math &\nTrig" => "Matematika i\ntrigonometrija",
"More\nFunctions" => "Još\nfunkcija",
"Date & Time" => "Datum i vreme",
"Lookup & Reference" => "Pretraga i reference",
"Math & Trig" => "Matematika i trigonometrija",
"More Functions" => "Još funkcija",
"Sheet Options|View" => "Prikaz",
"Print" => "Štampaj",
"Print What" => "Šta štampati",
+4 -4
View File
@@ -403,10 +403,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Diğer Sayı Biçimleri…",
"Financial" => "Finansal",
"Logical" => "Mantıksal",
"Date &\nTime" => "Tarih ve\nSaat",
"Lookup &\nReference" => "Arama ve\nBaşvuru",
"Math &\nTrig" => "Matematik ve\nTrigonometri",
"More\nFunctions" => "Diğer\nİşlevler",
"Date & Time" => "Tarih ve Saat",
"Lookup & Reference" => "Arama ve Başvuru",
"Math & Trig" => "Matematik ve Trigonometri",
"More Functions" => "Diğer İşlevler",
"Page Layout|Orientation" => "Sayfa Yönü",
"Display theme" => "Görüntü teması",
"System" => "Sistem",
+4 -8
View File
@@ -289,10 +289,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Інші числові формати…",
"Financial" => "Фінансові",
"Logical" => "Логічні",
"Date &\nTime" => "Дата і\nчас",
"Lookup &\nReference" => "Пошук і\nпосилання",
"Math &\nTrig" => "Математичні і\nтригонометричні",
"More\nFunctions" => "Інші\nфункції",
"More Functions" => "Інші функції",
"Page Layout|Orientation" => "Орієнтація",
"Display theme" => "Тема оформлення",
"Animations" => "Анімація",
@@ -454,7 +451,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Edit Name" => "Edit Name",
"New Name" => "New Name",
"Format Cells" => "Format Cells",
"Formula Builder" => "Formula Builder",
"Find and Replace" => "Find and Replace",
"Go To" => "Go To",
"Insert Calculated Field" => "Insert Calculated Field",
@@ -711,9 +707,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Hidden" => "Hidden",
"Search:" => "Search:",
"e.g. lookup, average, date" => "e.g. lookup, average, date",
"Date & Time" => "Date & Time",
"Lookup & Reference" => "Lookup & Reference",
"Math & Trig" => "Math & Trig",
"Date & Time" => "Дата і час",
"Lookup & Reference" => "Пошук і посилання",
"Math & Trig" => "Математичні і тригонометричні",
"Statistical" => "Statistical",
"Engineering" => "Engineering",
"Database" => "Database",
+4 -4
View File
@@ -303,10 +303,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"More Number Formats…" => "Định dạng số khác…",
"Financial" => "Tài chính",
"Logical" => "Logic",
"Date &\nTime" => "Ngày &\nGiờ",
"Lookup &\nReference" => "Tra cứu &\nTham chiếu",
"Math &\nTrig" => "Toán &\nLượng giác",
"More\nFunctions" => "Hàm\nkhác",
"Date & Time" => "Ngày & Giờ",
"Lookup & Reference" => "Tra cứu & Tham chiếu",
"Math & Trig" => "Toán & Lượng giác",
"More Functions" => "Hàm khác",
"Sheet Options|View" => "Xem",
"Print" => "In",
"Print What" => "Nội dung in",
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more