diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index e4fcf55709..ee05e54e5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,62 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # GridCraft — instructions for agents 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). ## 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. - -`plan/` is gitignored (local only). +Read [`ROADMAP.md`](ROADMAP.md) and [`docs/gaps.md`](docs/gaps.md). `plan/` is an optional gitignored notebook (status, execution notes, `plan/excel/*.md`). Do not ask for it and do not stop when it is absent. Screenshots of Microsoft software stay in that notebook and are never committed. ## Assets and iconography — absolute rule **No Microsoft, Adobe, Avid, Autodesk (or any other vendor's) iconography, images, artwork, fonts, templates, themes or sample files — ever.** This is the most important rule in this repository; breaking it is a serious failure. @@ -35,7 +85,6 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr - **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.** - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math). A crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: borders gallery`). @@ -44,8 +93,8 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr - Drive it: `gridcraft-cli send 7979 ''` (reads the token file the app printed on stderr), or JSON lines on `127.0.0.1:7979` whose first line is `{"id":0,"method":"auth","params":{"token":"…"}}` (token: `$XDG_RUNTIME_DIR/gridcraft/control-7979.token`, or your own `GRIDCRAFT_CONTROL_TOKEN`), e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. - **Offscreen UI render** (no window, from a source checkout): `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. - Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli run --in book.xlsx --cmd 'home.bold={"range":"A1:C1"}' --out book.xlsx`, `gridcraft-cli mcp`. -- **For UI work, look at the result** (snapshot PNG) and compare with `plan/excel/observed-ui.md`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. macOS has no `timeout`; use `perl -e 'alarm 60; exec @ARGV' cmd`. +- **For UI work, look at the result** (snapshot PNG) and, when available, compare with `plan/excel/observed-ui.md`. Without that optional notebook, verify the intended behaviour against the task and committed documentation. +- macOS has no `timeout`; use `perl -e 'alarm 60; exec @ARGV' cmd`. - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done. ## Roadmap @@ -70,3 +119,5 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. diff --git a/CLAUDE.md b/CLAUDE.md index 3297f122ad..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,56 +1 @@ -# GridCraft — instructions for agents - -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). - -## 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. - -`plan/` is gitignored (local only). - -## Assets and iconography — absolute rule -**No Microsoft, Adobe, Avid, Autodesk (or any other vendor's) iconography, images, artwork, fonts, templates, themes or sample files — ever.** This is the most important rule in this repository; breaking it is a serious failure. -- Every asset in the repo is original work by GridCraft contributors, or public domain / CC0, or open source / Creative Commons that allows redistribution (or licensed open source by the contributor who created it). -- Every asset file has a row in [`ATTRIBUTION.md`](ATTRIBUTION.md) (author, source, licence). `cargo xtask assets` enforces it. Adding an asset without a row is a bug. -- Prefer art generated in code: the UI icon set (`crates/ui-egui/src/icons.rs`), table and cell style palettes, themes and sample workbooks are drawn/defined in code and original. -- Never copy Office's icons, ribbon artwork, theme XML, table-style definitions, templates, clip art or wording beyond feature names. Excel feature *names* (menu labels, function names) are fine. -- Screenshots of Microsoft software are never committed (they live only in `plan/excel/screenshots/`). -- 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.** -- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). -- **Errors are `Result`** through the crate's error type and `?`. -- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references). -- **Bound recursion** (formula nesting, dependency chains, names referring to names). -- **Last-resort guard:** `Session::execute` catches escaped panics and restores the workbook. It's a safety net, not a licence. -- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/it/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`). -- Production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. - -## Non-negotiables -- **Clean-room.** Microsoft Excel is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic workbooks, take screenshots (by window id) stored only under `plan/excel/screenshots/`. Never read, disassemble or copy anything inside the Office bundle, never commit files produced by Excel, never copy GPL/AGPL/LGPL code (LibreOffice, Gnumeric…). Function behaviour comes from public documentation and observation. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`); without it the app uses system fonts and egui's defaults. -- **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.** -- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). One task id per commit (`M2.1: borders gallery`). - -## Running and looking at the app -- `cargo run --release -p gridcraft -- --sample sales --control 7979` (sample workbook + control channel). -- Drive it: `gridcraft-cli send 7979 ''` (reads the token file the app printed on stderr), or JSON lines on `127.0.0.1:7979` whose first line is `{"id":0,"method":"auth","params":{"token":"…"}}` (token: `$XDG_RUNTIME_DIR/gridcraft/control-7979.token`, or your own `GRIDCRAFT_CONTROL_TOKEN`), e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **Offscreen UI render** (no window, from a source checkout): `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. -- Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli run --in book.xlsx --cmd 'home.bold={"range":"A1:C1"}' --out book.xlsx`, `gridcraft-cli mcp`. -- **For UI work, look at the result** (snapshot PNG) and compare with `plan/excel/observed-ui.md`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. macOS has no `timeout`; use `perl -e 'alarm 60; exec @ARGV' cmd`. -- 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 points at the detail in `docs/`: `target-app-parity.md` (authoritative assessment), `gaps.md` (ranked work list: pick from it), `roadmap.md` (current focus, beta gates, milestones), `architecture.md`, and the area checklists `function-parity.md`, `chart-parity.md`, `file-format-parity.md`, `ui-parity.md`, `hardware-parity.md`, `localization-parity.md`. Update the affected docs (and their timestamp lines and revision history) whenever work lands. `cargo xtask parity` regenerates `docs/parity-checklist.md` from `crates/engine/src/catalog.rs`. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock index dfdde30e7d..a39620f96a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -995,10 +995,21 @@ dependencies = [ "zip 9.1.0", ] +[[package]] +name = "craft-web-api" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +dependencies = [ + "js-sys", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", +] + [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" dependencies = [ "wasm-bindgen", "web-sys", @@ -2195,6 +2206,7 @@ dependencies = [ name = "gridcraft-web" version = "0.16.0" dependencies = [ + "craft-web-api", "craft-web-host", "eframe", "egui", diff --git a/ROADMAP.md b/ROADMAP.md index 73f5729087..a67b16d52a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) | | 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `` and VML), alongside the form controls GridCraft keeps unchanged | | 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors | | 2026-11-02 | Python mode in the formula bar: Ctrl+Alt+Shift+P, `=PY` then Tab, or editing a Python cell edits its code in the formula bar, with Enter for a new line, Tab to indent and Ctrl+Enter to commit through `python.set`. The code still doesn't run | @@ -261,6 +262,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| | 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences | +| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) | | 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row | | 2026-11-02 | minor | Progress log: RefEdit reference boxes in dialogs | | 2026-11-02 | minor | Progress log: Python mode in the formula bar | diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index e5c599bd89..09c6d7e2ae 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -17,7 +17,9 @@ path = "src/main.rs" gridcraft-engine = { workspace = true } gridcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } +# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel. +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/gridcraft-web/src/api.rs b/apps/gridcraft-web/src/api.rs new file mode 100644 index 0000000000..34aca8c18b --- /dev/null +++ b/apps/gridcraft-web/src/api.rs @@ -0,0 +1,151 @@ +//! `window.gridcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the +//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`). +//! +//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, +//! `screenshot`, as promises with a timeout). This module is GridCraft's part: a [`Request`] that +//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the +//! reply. A call the page gave up on is released ([`Pending`]), so the app skips it if it has not started it, instead of +//! applying a command the page was told had failed. + +use std::sync::Arc; +use std::sync::atomic::AtomicU8; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use gridcraft_ui_egui::ControlRequest; +use serde_json::{Value, json}; + +/// How often a waiting call looks for the app's reply, in milliseconds (about a frame). +#[cfg(target_arch = "wasm32")] +const POLL_MS: i32 = 16; + +/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's +/// timeout fired, or the call was abandoned) releases the request: the app skips it if it has not started it (one it has taken still finishes). +struct Pending { + reply: Receiver, + state: Arc, + answered: bool, +} + +impl Pending { + /// `Some` once the app has answered or gone away; `None` while the request is still waiting. + fn poll(&mut self) -> Option { + match self.reply.try_recv() { + Ok(reply) => { + self.answered = true; + Some(reply) + } + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => { + self.answered = true; + Some(json!({"ok": false, "error": "the app dropped the request"})) + } + } + } +} + +impl Drop for Pending { + fn drop(&mut self) { + if !self.answered { + ControlRequest::abandon(&self.state); + } + } +} + +#[cfg(target_arch = "wasm32")] +pub use web::install; + +#[cfg(target_arch = "wasm32")] +mod web { + use std::rc::Rc; + use std::sync::mpsc::channel; + + use craft_web_api::methods::Methods; + use craft_web_api::page::{PageApi, Request}; + use gridcraft_ui_egui::{ControlRequest, SheetApp}; + use serde_json::json; + use wasm_bindgen_futures::JsFuture; + + use super::{POLL_MS, Pending}; + + /// The app id in `window.`. + const APP: &str = "gridcraft"; + + /// Give the app its control queue and put `window.gridcraft` on the page. An existing + /// `window.gridcraft` keeps the functions it already has. + pub fn install(app: &mut SheetApp, ctx: egui::Context) { + let (queue, requests) = channel::(); + app.control_rx = Some(requests); + let request: Request = Rc::new(move |method, params| { + let (control, reply) = ControlRequest::new(method, params); + let mut pending = Pending { reply, state: control.state.clone(), answered: false }; + if queue.send(control).is_err() { + pending.answered = true; + return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) }); + } + ctx.request_repaint(); + Box::pin(async move { + loop { + if let Some(reply) = pending.poll() { + return reply; + } + sleep(POLL_MS).await; + } + }) + }); + if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() { + log::warn!("couldn't install window.{APP}: {e:?}"); + } + } + + async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(window) = web_sys::window() { + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + } + }); + let _ = JsFuture::from(promise).await; + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::Ordering; + + use super::*; + + /// `ControlRequest`'s `state` values (`gridcraft_ui_egui::control`): the app has started it, or its + /// sender gave up. + const TAKEN: u8 = 1; + const ABANDONED: u8 = 2; + + fn pending() -> (Pending, ControlRequest) { + let (control, reply) = ControlRequest::new("document.inspect", json!({})); + (Pending { reply, state: control.state.clone(), answered: false }, control) + } + + #[test] + fn a_call_the_page_gave_up_on_is_released_so_the_app_skips_it() { + let (waiting, control) = pending(); + drop(waiting); + assert_eq!(control.state.load(Ordering::SeqCst), ABANDONED); + assert!(!control.take(), "the app must not run a request the page was told had failed"); + } + + #[test] + fn an_answered_call_is_not_released() { + let (mut waiting, control) = pending(); + assert!(control.take()); + control.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default(); + assert_eq!(waiting.poll(), Some(json!({"ok": true, "result": 1}))); + drop(waiting); + assert_eq!(control.state.load(Ordering::SeqCst), TAKEN); + } + + #[test] + fn a_request_the_app_never_runs_waits_until_it_is_dropped() { + let (mut waiting, control) = pending(); + assert_eq!(waiting.poll(), None); + drop(control); + assert_eq!(waiting.poll().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away"); + } +} diff --git a/apps/gridcraft-web/src/main.rs b/apps/gridcraft-web/src/main.rs index 2c701feb49..823a68e9b4 100644 --- a/apps/gridcraft-web/src/main.rs +++ b/apps/gridcraft-web/src/main.rs @@ -13,11 +13,16 @@ //! workbook to open and stores what GridCraft saves (`host`). A page can host GridCraft in its //! own document (no iframe) with `data-host="page"` on the canvas, talking over DOM `CustomEvent`s //! on the canvas. `&author=` names the user for notes and comments in either host mode. +//! `window.gridcraft` (`craft-web-api`) is the page command API in every mode: `request`, +//! `execute`, `commands`, `docInspect`, `uiInspect` and `screenshot` over the control methods +//! (`api`). //! `?chrome=none|notitlebar|nofiletab` leaves the title bar and/or the File tab undrawn for a host //! that embeds the sheet in its own window (see `Chrome`). Preferences (theme, interface size, //! editing options…) are kept in `localStorage` (`prefs`). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(any(target_arch = "wasm32", test))] +mod api; #[cfg(target_arch = "wasm32")] mod host; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/gridcraft-web/src/web.rs b/apps/gridcraft-web/src/web.rs index 2685605200..1108c4c11b 100644 --- a/apps/gridcraft-web/src/web.rs +++ b/apps/gridcraft-web/src/web.rs @@ -99,6 +99,7 @@ pub fn start() { } bridge.post_ready(); } + crate::api::install(&mut app, cc.egui_ctx.clone()); Ok(Box::new(WebShell { app, inbox, bridge: app_bridge, prefs })) }), ) diff --git a/crates/engine/src/cmd/edit/selection.rs b/crates/engine/src/cmd/edit/selection.rs index 8115f63900..f171c65a89 100644 --- a/crates/engine/src/cmd/edit/selection.rs +++ b/crates/engine/src/cmd/edit/selection.rs @@ -66,7 +66,14 @@ pub(super) fn selection_move(s: &mut Session, p: &Json) -> Result { // Extension moves the far corner, not the active cell. let from = if extend { sel.moving_end() } else { sel.active }; // Skip hidden rows/columns and step over merged areas. - let mut to = if jmp { + let mut to = if jmp && extend && (dr == 0) != (dc == 0) { + // Excel: Ctrl+Shift+arrow searches the active cell's column (or row) from the moving + // edge, so a header row selected with Ctrl+Shift+Right extends down to the end of the + // active column's data. + let probe = if dr != 0 { CellRef::new(from.row, sel.active.col) } else { CellRef::new(sel.active.row, from.col) }; + let edge = jump(sheet, probe, dr.signum(), dc.signum()); + if dr != 0 { CellRef::new(edge.row, from.col) } else { CellRef::new(from.row, edge.col) } + } else if jmp { jump(sheet, from, dr.signum(), dc.signum()) } else { let mut t = from.offset_clamped(dr, dc); diff --git a/crates/engine/tests/it/ctrl_shift_arrow_active_line.rs b/crates/engine/tests/it/ctrl_shift_arrow_active_line.rs new file mode 100644 index 0000000000..d296d50bbd --- /dev/null +++ b/crates/engine/tests/it/ctrl_shift_arrow_active_line.rs @@ -0,0 +1,56 @@ +//! Ctrl/Cmd+Shift+arrow searches the active cell's column (or row) from the moving edge (#3484). + +use gridcraft_engine::Session; +use serde_json::json; + +fn table() -> Session { + // Headers in A2:K2, a key column in A3:A13, nothing else filled. + let mut s = Session::new(); + s.new_workbook(); + let header: Vec = (1..=11).collect(); + s.execute("range.setValues", json!({"range": "A2:K2", "values": [header]})).unwrap(); + let keys: Vec> = (1..=11).map(|i| vec![i]).collect(); + s.execute("range.setValues", json!({"range": "A3:A13", "values": keys})).unwrap(); + s +} + +fn ctrl_shift(s: &mut Session, dr: i64, dc: i64) -> String { + s.execute("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": true})).unwrap(); + s.doc().unwrap().selection.a1() +} + +#[test] +fn ctrl_shift_down_after_ctrl_shift_right_follows_the_active_column() { + let mut s = table(); + s.execute("selection.set", json!({"cell": "A2"})).unwrap(); + assert_eq!(ctrl_shift(&mut s, 0, 1), "A2:K2"); + assert_eq!(ctrl_shift(&mut s, 1, 0), "A2:K13", "column A's data ends on row 13; column K's ends on row 2"); + // From the end of column A's data the next press runs to the sheet's last row. + assert_eq!(ctrl_shift(&mut s, 1, 0), "A2:K1048576"); +} + +#[test] +fn ctrl_shift_right_after_ctrl_shift_down_follows_the_active_row() { + let mut s = table(); + s.execute("selection.set", json!({"cell": "A2"})).unwrap(); + assert_eq!(ctrl_shift(&mut s, 1, 0), "A2:A13"); + assert_eq!(ctrl_shift(&mut s, 0, 1), "A2:K13", "row 2's data ends in column K; row 13's ends in column A"); +} + +#[test] +fn ctrl_shift_down_after_ctrl_shift_left_follows_the_active_column() { + // The active cell is on the right: column K, empty below the header, decides, not column A. + let mut s = table(); + s.execute("selection.set", json!({"cell": "K2"})).unwrap(); + assert_eq!(ctrl_shift(&mut s, 0, -1), "A2:K2"); + assert_eq!(ctrl_shift(&mut s, 1, 0), "A2:K1048576"); +} + +#[test] +fn ctrl_shift_right_after_ctrl_shift_up_follows_the_active_row() { + // The active cell is at the bottom: row 13, empty right of the key, decides, not row 2. + let mut s = table(); + s.execute("selection.set", json!({"cell": "A13"})).unwrap(); + assert_eq!(ctrl_shift(&mut s, -1, 0), "A2:A13"); + assert_eq!(ctrl_shift(&mut s, 0, 1), "2:13", "row 13's data ends in column A, so the rows extend to the last column"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a9cd7cbfea..0ba7c0db8a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -7,6 +7,7 @@ mod chart_workbook_names; mod command_sequence_fuzz; mod cross_sheet_cut; mod csv_export_budget; +mod ctrl_shift_arrow_active_line; mod custom_filter_blanks; mod custom_view_freeze; mod dynamicmetadata; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 4aba800245..6dff45cb2b 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -302,6 +302,7 @@ impl SheetApp { // The requests belong to the window the command left active. self.follow_active_window(); self.prune_selected_object(); + self.prune_views(); for req in self.session.take_ui_requests() { match req { UiRequest::Dialog(name, params) => self.open_dialog(&name, params), diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index aea36abc2a..4823724488 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -7,8 +7,8 @@ impl SheetApp { } /// The active window and sheet: each window scrolls on its own. - fn scroll_key(&self) -> Option<(u64, usize)> { - Some((self.session.active_window()?, self.session.active()?.wb.active_sheet())) + fn scroll_key(&self) -> Option<(u64, u64)> { + Some((self.session.active_window()?, self.session.active()?.wb.active()?.uid.get())) } pub fn view(&self) -> SheetView { @@ -41,8 +41,10 @@ impl SheetApp { let window = self.session.active_window(); let Some(d) = self.session.active_mut() else { return }; let mut tops = Vec::new(); - for (&(w, si), v) in &self.views { - let Some(sh) = d.wb.sheets.get(si).filter(|sh| Some(w) == window && sh.view == gridcraft_engine::model::SheetViewMode::Normal) else { + for (si, sh) in d.wb.sheets.iter().enumerate() { + let Some(v) = + window.and_then(|w| self.views.get(&(w, sh.uid.get()))).filter(|_| sh.view == gridcraft_engine::model::SheetViewMode::Normal) + else { continue; }; let (fr, fc) = sh.freeze.unwrap_or((0, 0)); @@ -53,4 +55,10 @@ impl SheetApp { } d.store_view(&tops); } + + /// Drops the scroll positions of windows that have closed: window ids are never reused. + pub(super) fn prune_views(&mut self) { + let session = &self.session; + self.views.retain(|&(w, _), _| session.window(w).is_some()); + } } diff --git a/crates/ui-egui/src/dialogs/data.rs b/crates/ui-egui/src/dialogs/data.rs index e3eabda790..e57a90c4e5 100644 --- a/crates/ui-egui/src/dialogs/data.rs +++ b/crates/ui-egui/src/dialogs/data.rs @@ -218,8 +218,11 @@ pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confir if columns.is_empty() { ui.add(egui::TextEdit::singleline(&mut col).desired_width(50.0)).labelled_by(label.id); } else { + // The closed box shows the same "B: Revenue" label as the list, not the bare letter (#3446). + let shown = + columns.iter().find(|(letter, _)| letter.eq_ignore_ascii_case(&col)).map_or_else(|| col.clone(), |(_, label)| label.clone()); craft_ui::ComboBox::from_id_salt(("sort_col", i)) - .selected_text(col.clone()) + .selected_text(shown) .show_ui(ui, |ui| { for (letter, label) in &columns { ui.selectable_value(&mut col, letter.clone(), label.as_str()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e773a207de..dffe3ed89e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -222,8 +222,9 @@ pub struct SheetApp { pub ui: UiState, /// The window chrome to draw (see [`Chrome`]). pub chrome: Chrome, - /// Scroll position per (window id, sheet index). - pub views: HashMap<(u64, usize), SheetView>, + /// Scroll position per (window id, sheet uid): each sheet keeps its own when sheets are + /// inserted, deleted or moved. + pub views: HashMap<(u64, u64), SheetView>, pub editor: Option, pub text_box_editor: Option, pub dialog: Option, diff --git a/crates/ui-egui/tests/it/scroll_position.rs b/crates/ui-egui/tests/it/scroll_position.rs index 520bb1691b..ffcb56dd64 100644 --- a/crates/ui-egui/tests/it/scroll_position.rs +++ b/crates/ui-egui/tests/it/scroll_position.rs @@ -1,4 +1,6 @@ //! The saved scroll position (`sheetView topLeftCell`) is restored on open and saved back (#378). +//! Each window keeps each sheet's own scroll position while sheets are inserted, deleted or +//! moved (#3485). use gridcraft_engine::core::{CellRef, Value}; use gridcraft_engine::model::Workbook; @@ -58,3 +60,84 @@ fn saved_scroll_position_is_restored_and_saved_back() { assert!(!d.is_dirty(), "scrolling and saving view state does not dirty the workbook"); } } + +#[test] +fn a_pivottable_sheet_opens_at_the_top_and_its_source_sheet_keeps_its_place() { + // A new PivotTable sheet goes in front of its source sheet. Scroll positions were kept by + // sheet index, so the new sheet took over the source sheet's position and opened at row 51. + let mut h = harness(None); + h.state_mut().run("range.setValues", json!({"range": "C1:D3", "values": [["Region", "Sales"], ["North", 10], ["South", 20]]})).unwrap(); + { + let app = h.state_mut(); + let sh = app.session.active().unwrap().wb.active().unwrap().clone(); + app.view_mut().unwrap().scroll.y = sh.row_top(50) as f32; + } + h.run_steps(2); + assert_eq!(first_scrolled_row(&h), 50, "setup: Sheet1 is scrolled to row 51"); + h.state_mut().run("insert.pivotTable", json!({"source": "Sheet1!$C$1:$D$3", "rows": ["Region"]})).unwrap(); + h.run_steps(4); + let wb = &h.state().session.active().unwrap().wb; + assert!(!wb.active().unwrap().pivots.is_empty(), "setup: the PivotTable's new sheet is active"); + assert_eq!(first_scrolled_row(&h), 0, "the new sheet opens at row 1"); + h.state_mut().run("sheet.next", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Sheet1"); + assert_eq!(first_scrolled_row(&h), 50, "Sheet1 is still scrolled to row 51"); +} + +/// Scrolls the active sheet so `row` (0-based) is the first one in view. +fn scroll_to_row(h: &mut Harness, row: u32) { + let app = h.state_mut(); + let sh = app.session.active().unwrap().wb.active().unwrap().clone(); + app.view_mut().unwrap().scroll.y = sh.row_top(row) as f32; + h.run_steps(2); +} + +fn activate(h: &mut Harness, sheet: &str) { + h.state_mut().run("sheet.activate", json!({"sheet": sheet})).unwrap(); + h.run_steps(4); + assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, sheet); +} + +#[test] +fn a_sheet_keeps_its_scroll_position_when_sheets_are_inserted_deleted_or_moved() { + let mut h = harness(None); + scroll_to_row(&mut h, 50); + h.state_mut().run("home.insertSheet", json!({"name": "Two", "before": 0})).unwrap(); + h.run_steps(4); + assert_eq!(first_scrolled_row(&h), 0, "the inserted sheet opens at row 1"); + scroll_to_row(&mut h, 10); + activate(&mut h, "Sheet1"); + assert_eq!(first_scrolled_row(&h), 50, "Sheet1 moved one place right and is still at row 51"); + h.state_mut().run("home.deleteSheet", json!({"sheet": "Two"})).unwrap(); + h.run_steps(4); + assert_eq!(first_scrolled_row(&h), 50, "Sheet1 moved back and is still at row 51"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(4); + activate(&mut h, "Two"); + assert_eq!(first_scrolled_row(&h), 10, "the sheet undo brings back is where it was left"); + h.state_mut().run("sheet.move", json!({"sheet": 0, "to": 1})).unwrap(); + h.run_steps(4); + activate(&mut h, "Two"); + assert_eq!(first_scrolled_row(&h), 10, "a moved sheet keeps its place"); + activate(&mut h, "Sheet1"); + assert_eq!(first_scrolled_row(&h), 50, "and so does the sheet it moved past"); +} + +#[test] +fn each_window_scrolls_on_its_own_and_a_closed_windows_positions_are_dropped() { + let mut h = harness(None); + scroll_to_row(&mut h, 50); + let first = h.state().session.active_window().unwrap(); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(4); + let second = h.state().session.active_window().unwrap(); + assert_ne!(first, second); + scroll_to_row(&mut h, 10); + assert!(h.state().views.keys().any(|(w, _)| *w == second), "setup: the second window has its own position"); + h.state_mut().run("window.close", json!({"window": second})).unwrap(); + h.run_steps(4); + assert_eq!(h.state().session.active_window(), Some(first)); + assert_eq!(first_scrolled_row(&h), 50, "the first window kept its own position"); + assert!(h.state().views.keys().all(|(w, _)| *w == first), "nothing is kept for the closed window: {:?}", h.state().views.keys()); +} diff --git a/crates/ui-egui/tests/it/sort_dialog_columns.rs b/crates/ui-egui/tests/it/sort_dialog_columns.rs index b6cbb54f6a..098f9c3e60 100644 --- a/crates/ui-egui/tests/it/sort_dialog_columns.rs +++ b/crates/ui-egui/tests/it/sort_dialog_columns.rs @@ -34,6 +34,18 @@ fn sort_dialog_seeds_the_active_column() { assert_eq!(col(&h), "B", "Sort by starts on the column the cursor is in, not A"); } +/// #3446: the closed "Sort by" box shows the column's name next to its letter, +/// as the open list does ("B: Revenue", not just "B"). +#[test] +fn closed_column_box_shows_the_column_name() { + use egui::accesskit::Role; + let mut h = harness(sales()); + h.state_mut().open_dialog("sort", json!({})); + h.run_steps(2); + let shown: Vec = h.get_all_by_role(Role::ComboBox).filter_map(|n| n.value()).collect(); + assert!(shown.iter().any(|v| v == "B: Revenue"), "the Sort by box shows the column name: {shown:?}"); +} + #[test] fn add_level_picks_a_column_no_level_uses_yet() { let mut h = harness(sales()); diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 93efb7f024..5bdc982163 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -35,6 +35,9 @@ pub struct Ctx<'a> { pub cell_pictures: Vec>>, /// x14 conditional-format ids of the current sheet's data bars, with the index of the rule in `cond_formats`. pub cf_ext_ids: Vec<(String, usize)>, + /// Bytes charged so far for shared formulas expanded into dependent cells (see + /// [`crate::sheet_read::MAX_SHARED_FORMULA_BYTES`]). + pub shared_formula_bytes: u64, /// Whether GridCraft calculates a function, when the caller says: cell formulas wrapped by /// Google Sheets' export are then read as the formula inside (see [`crate::read_xlsx_with`]). pub known_function: Option<&'a dyn Fn(&str) -> bool>, @@ -255,6 +258,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], known_function: Option<&'a dyn Fn(&str) -> num_fmts: Default::default(), cell_pictures: vec![], cf_ext_ids: vec![], + shared_formula_bytes: 0, known_function, python: Default::default(), }; diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index f2047b6ee8..e68d143892 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -31,6 +31,16 @@ struct Shared { anchor: CellRef, expr: Option, text: String, + /// Approximate bytes one dependent cell costs (its printed text plus its expression tree); + /// what exceeds [`SHARED_FORMULA_FREE_COST`] is charged against [`MAX_SHARED_FORMULA_BYTES`]. + cost: u64, +} + +/// What one sheet's hyperlinks have copied so far, across all its `` blocks. +#[derive(Default)] +struct LinkBudget { + cells: u64, + bytes: u64, } #[derive(Default)] @@ -120,10 +130,23 @@ fn settle_python_spills_past_budget(st: &RowState, sheet: &mut Sheet) { } } -const MAX_HYPERLINK_CELLS: u64 = 10_000; /// Target and tooltip bytes kept for hyperlinks of one sheet, over all cells: the same URL is /// copied for every cell of its range, so length × cells must stay bounded whatever the file. const MAX_HYPERLINK_BYTES: u64 = 8 * 1024 * 1024; +/// Most cells one sheet's hyperlinks may cover (each cell gets its own copy of the link). +const MAX_HYPERLINK_CELLS: u64 = 10_000; +/// Longest hyperlink target kept, in bytes (Excel's own limit is about 2,079 characters). +const MAX_HYPERLINK_TARGET: usize = 8_192; +/// Longest hyperlink ScreenTip kept, in characters (Excel's limit). +const MAX_TOOLTIP_CHARS: usize = 255; +/// What a dependent of a shared formula may cost for free: an ordinary formula cell's worth (by +/// [`shared_cost`], a formula of about 40 operators and operands), so a sheet of many ordinary +/// shared formulas is never cut short however many cells share them. +const SHARED_FORMULA_FREE_COST: u64 = 4096; +/// Budget, per workbook, for what shared formulas cost beyond [`SHARED_FORMULA_FREE_COST`] per +/// dependent cell: a long master copied into many cells is where the expansion multiplies the +/// file's bytes, and this bounds it to well within a web build's memory. +pub const MAX_SHARED_FORMULA_BYTES: u64 = 256 << 20; const MAX_COLUMN_ASSIGNMENTS: u64 = 1_000_000; /// Most dynamic-array and legacy-array ranges of one sheet. const MAX_DYNAMIC_RANGES: usize = 65_536; @@ -182,6 +205,8 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr drop(bytes); let mut fit_to_page = false; + let mut link_budget = LinkBudget::default(); + let mut cf_kept_cells = 0u64; let mut column_assignments_left = MAX_COLUMN_ASSIGNMENTS; cx.cf_ext_ids.clear(); for e in &root.children { @@ -208,7 +233,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "conditionalFormatting" => read_cf(cx, e, &mut sheet), + "conditionalFormatting" => read_cf(cx, e, &mut sheet, &mut cf_kept_cells), "dataValidations" => { for v in e.kids("dataValidation") { if let Some(v) = read_validation(v) { @@ -216,7 +241,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet), + "hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_budget), "autoFilter" => sheet.autofilter = read_autofilter(cx, e), "printOptions" => { sheet.print.gridlines = e.flag("gridLines", false); @@ -641,13 +666,30 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, let si = f.attr_u32("si")?; if !text.is_empty() { let expr = gridcraft_formula::parse(text).ok(); - st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string() }); + let cost = shared_cost(text, expr.as_ref()); + st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string(), cost }); Some(Formula::new(text)) } else { let Some(sh) = st.shared.get(&si) else { cx.warn("a shared formula refers to a missing master cell; kept the cached value"); return None; }; + // The parser's own test: bytes first (cheap), then characters, so a multibyte + // master that failed to parse for another reason gets no false length warning. + if sh.expr.is_none() + && sh.text.len() > gridcraft_formula::MAX_FORMULA_LEN + && sh.text.chars().count() > gridcraft_formula::MAX_FORMULA_LEN + { + cx.warn(format!( + "a shared formula is longer than {} characters; kept the cached values of the cells that share it", + gridcraft_formula::MAX_FORMULA_LEN + )); + return None; + } + if !charge(&mut cx.shared_formula_bytes, extra_shared_cost(sh.cost), MAX_SHARED_FORMULA_BYTES) { + cx.warn("shared formulas expand to too much data; kept the cached values of the remaining cells that share them"); + return None; + } Some(match &sh.expr { Some(e) => { let dr = pos.row as i64 - sh.anchor.row as i64; @@ -720,6 +762,41 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { Some(serial) } +/// What one dependent of a shared formula costs: its printed text plus its expression tree. +fn shared_cost(text: &str, expr: Option<&Expr>) -> u64 { + let mut nodes = 0u64; + if let Some(e) = expr { + e.walk(&mut |_| nodes = nodes.saturating_add(1)); + } + let node = std::mem::size_of::() as u64; + (text.len() as u64).saturating_mul(2).saturating_add(nodes.saturating_mul(node)).saturating_add(64) +} + +/// What one dependent of a shared formula costing `cost` is charged: its cost beyond an ordinary +/// formula cell's. +fn extra_shared_cost(cost: u64) -> u64 { + cost.saturating_sub(SHARED_FORMULA_FREE_COST) +} + +/// Adds `cost` to `used` when that stays within `cap`; `false` (and `used` unchanged) otherwise. +fn charge(used: &mut u64, cost: u64, cap: u64) -> bool { + match used.checked_add(cost) { + Some(total) if total <= cap => { + *used = total; + true + } + _ => false, + } +} + +/// The first `max` characters of `s`. +fn truncate_chars(s: &str, max: usize) -> String { + match s.char_indices().nth(max) { + Some((at, _)) => s.get(..at).unwrap_or(s).to_string(), + None => s.to_string(), + } +} + pub fn parse_sqref(s: Option<&str>) -> Vec { s.unwrap_or("").split_whitespace().filter_map(RangeRef::parse).collect() } @@ -780,6 +857,40 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { mod tests { use super::*; + #[test] + fn shared_formula_budget_stops_expansion() { + let expr = gridcraft_formula::parse("SUM(1,2,3)").ok(); + let cost = shared_cost("SUM(1,2,3)", expr.as_ref()); + assert!(cost > 64 + 4 * std::mem::size_of::() as u64); + let cap = cost * 3; + let mut used = 0; + assert!((0..3).all(|_| charge(&mut used, cost, cap))); + assert!(!charge(&mut used, cost, cap)); + assert_eq!(used, cap); + assert!(!charge(&mut used, u64::MAX, u64::MAX)); + } + + #[test] + fn ordinary_shared_formulas_are_free_and_long_ones_pay_their_excess() { + let text = r#"IF(AND(A1>0,B1<>""),VLOOKUP(C1,Sheet2!$A$1:$D$500,4,FALSE)*SUM(D1:D10)/COUNT(D1:D10),IFERROR(E1/F1,0))"#; + let expr = gridcraft_formula::parse(text).ok(); + assert!(expr.is_some()); + assert_eq!(extra_shared_cost(shared_cost(text, expr.as_ref())), 0, "an ordinary formula costs nothing extra"); + let long = vec![format!("SUM({}1)", "1,".repeat(199)); 10].join("+"); + let expr = gridcraft_formula::parse(&long).ok(); + assert!(expr.is_some()); + let cost = shared_cost(&long, expr.as_ref()); + assert_eq!(extra_shared_cost(cost), cost - SHARED_FORMULA_FREE_COST); + // A few thousand copies of a long master no longer fit the budget. + assert!(extra_shared_cost(cost).saturating_mul(10_000) > MAX_SHARED_FORMULA_BYTES); + } + + #[test] + fn truncate_keeps_whole_characters() { + assert_eq!(truncate_chars("ab\u{e9}d", 3), "ab\u{e9}"); + assert_eq!(truncate_chars("ab", 3), "ab"); + } + #[test] fn iso_dates() { assert_eq!(parse_iso_datetime("1900-01-01", DateSystem::D1900), Some(1.0)); diff --git a/crates/xlsx/src/sheet_read/parts.rs b/crates/xlsx/src/sheet_read/parts.rs index 3ff6722899..309ab4a025 100644 --- a/crates/xlsx/src/sheet_read/parts.rs +++ b/crates/xlsx/src/sheet_read/parts.rs @@ -1,17 +1,25 @@ use super::{ - AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS, MAX_ROWS, - NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr, from_file, xml, + AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, LinkBudget, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS, + MAX_HYPERLINK_TARGET, MAX_ROWS, MAX_TOOLTIP_CHARS, NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr, + from_file, truncate_chars, xml, }; -pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet) { - let mut cells = 0u64; - let mut bytes = 0u64; +/// `budget` counts the cells and bytes this sheet's hyperlinks have copied so far, across +/// `` blocks. +pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, budget: &mut LinkBudget) { for h in e.kids("hyperlink") { let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue }; - let mut target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.clone()).unwrap_or_default(); + let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or(""); + let location = h.attr("location").filter(|l| !l.is_empty()); + // Each covered cell gets its own copy of the link: refuse oversized targets before copying. + if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET { + cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped")); + continue; + } + let mut target = rel_target.to_string(); // A relationship is a file or web page; a bare `location` is a place in this workbook. let external = !target.is_empty(); - if let Some(loc) = h.attr("location").filter(|l| !l.is_empty()) { + if let Some(loc) = location { if target.is_empty() { target = loc.trim_start_matches('#').to_string(); } else { @@ -21,19 +29,20 @@ pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel] if target.is_empty() { continue; } - let link = Hyperlink { target: target.clone(), tooltip: h.attr("tooltip").map(str::to_string), external }; - let link_bytes = (target.len() + link.tooltip.as_ref().map_or(0, |t| t.len())) as u64; + let tooltip = h.attr("tooltip").map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS)); + let link_bytes = (target.len() + tooltip.as_ref().map_or(0, String::len)) as u64; + let link = Hyperlink { target, tooltip, external }; for c in range.iter() { - if cells >= MAX_HYPERLINK_CELLS { + if budget.cells >= MAX_HYPERLINK_CELLS { cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped")); return; } - if bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { + if budget.bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { cx.warn(format!("sheet \"{name}\": hyperlink targets past {MAX_HYPERLINK_BYTES} bytes were dropped")); return; } - cells += 1; - bytes += link_bytes; + budget.cells += 1; + budget.bytes += link_bytes; sheet.hyperlinks.insert(c, link.clone()); } } diff --git a/crates/xlsx/src/sheet_read/rules.rs b/crates/xlsx/src/sheet_read/rules.rs index 4e45007070..c3a3f04f65 100644 --- a/crates/xlsx/src/sheet_read/rules.rs +++ b/crates/xlsx/src/sheet_read/rules.rs @@ -45,11 +45,15 @@ fn cfvos(e: &El) -> Vec { .collect() } -pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { +/// One `conditionalFormatting` block. Every rule keeps its own copy of the block's ranges, so +/// `kept_cells` counts the range cells the sheet's retained rules hold so far, across blocks; a +/// rule that would take it past [`MAX_COND_CELLS`] is dropped. Unsupported rules cost nothing. +pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &mut u64) { let ranges = parse_sqref(e.attr("sqref")); if ranges.is_empty() { return; } + let block_cells = ranges.iter().map(RangeRef::count).fold(0u64, u64::saturating_add); for r in e.kids("cfRule") { let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default()); let formulas: Vec = r.kids("formula").map(|f| from_file(f.text.trim())).collect(); @@ -111,15 +115,15 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { continue; } }; - if let Some(id) = ext_id { - cx.cf_ext_ids.push((id, sheet.cond_formats.len())); - } - let rules = sheet.cond_formats.len(); - let area = ranges.iter().map(RangeRef::count).sum::().saturating_mul(1 + rules as u64); - if area > MAX_COND_CELLS { + let total = kept_cells.saturating_add(block_cells); + if total > MAX_COND_CELLS { cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped")); break; } + *kept_cells = total; + if let Some(id) = ext_id { + cx.cf_ext_ids.push((id, sheet.cond_formats.len())); + } sheet.cond_formats.push(CondFormat { ranges: ranges.clone(), rule, diff --git a/crates/xlsx/src/styles.rs b/crates/xlsx/src/styles.rs index c1f93aca9b..04c9fcdf2a 100644 --- a/crates/xlsx/src/styles.rs +++ b/crates/xlsx/src/styles.rs @@ -1,7 +1,7 @@ //! `styles.xml`: reading cell formats and differential formats into model styles, and writing //! the workbook's style table. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fmt::Write as _; use gridcraft_model::style::{DxfStated, Protection}; @@ -14,6 +14,9 @@ use crate::xml::{El, esc_attr, num}; // ---------------------------------------------------------------- reading +/// Longest font name kept, in characters (Excel's own limit is 31). +pub const MAX_FONT_NAME_CHARS: usize = 255; + /// Styles read from a file. #[derive(Debug, Default)] pub struct StylesIn { @@ -63,7 +66,11 @@ const MAX_FONT_FAMILY: u8 = 14; pub fn read_font(e: &El, palette: &[u32]) -> Font { let mut f = Font::default(); if let Some(n) = e.child("name").or_else(|| e.child("rFont")).and_then(|n| n.attr("val")) { - f.name = n.to_string(); + // Every cell format that uses the font copies its name: keep it short. + f.name = match n.char_indices().nth(MAX_FONT_NAME_CHARS) { + Some((at, _)) => n.get(..at).unwrap_or_default().to_string(), + None => n.to_string(), + }; } if let Some(sz) = e.child("sz").and_then(|s| s.attr_f64("val")) { f.size = sz.clamp(1.0, 409.0) as f32; @@ -277,14 +284,16 @@ fn read_protection(p: &El) -> Protection { Protection { locked: p.flag("locked", true), hidden: p.flag("hidden", false) } } -fn num_fmt_code(id: u32, custom: &HashMap) -> NumFmt { +/// A number format by id. Custom formats are built once and shared (`NumFmt` is an `Arc`), so +/// many cell formats naming one long code don't each copy it. +fn num_fmt_code(id: u32, custom: &HashMap) -> NumFmt { if let Some(c) = custom.get(&id) { - return NumFmt::new(c); + return c.clone(); } NumFmt::new(builtin_format(id).unwrap_or("General")) } -fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap, checkboxes: &[bool]) -> Style { +fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap, checkboxes: &[bool]) -> Style { let mut s = Style::default(); if let Some(f) = xf.attr_u32("fontId").and_then(|i| fonts.get(i as usize)) { s.font = f.clone(); @@ -336,6 +345,20 @@ pub fn read_styles(root: &El, checkboxes: &[bool], minor_font: &str) -> StylesIn } } } + // One shared `NumFmt` per custom id a cell format or differential format refers to (`NumFmt` + // is an `Arc`); declared but unused codes get no second copy. + let mut used: HashSet = HashSet::new(); + for list in ["cellXfs", "cellStyleXfs"] { + if let Some(x) = root.child(list) { + used.extend(x.kids("xf").map(|xf| xf.attr_u32("numFmtId").unwrap_or(0))); + } + } + if let Some(d) = root.child("dxfs") { + used.extend( + d.kids("dxf").filter_map(|x| x.child("numFmt")).filter(|n| n.attr("formatCode").is_none()).filter_map(|n| n.attr_u32("numFmtId")), + ); + } + let shared_fmts: HashMap = fmts.iter().filter(|(id, _)| used.contains(id)).map(|(&id, code)| (id, NumFmt::new(code))).collect(); // The scheme link only means something on a font in the body face; elsewhere it stays as a new font has it. let body_font = |e: &El| { let mut f = read_font(e, &palette); @@ -345,10 +368,14 @@ pub fn read_styles(root: &El, checkboxes: &[bool], minor_font: &str) -> StylesIn let fonts: Vec = root.child("fonts").map(|f| f.kids("font").map(body_font).collect()).unwrap_or_default(); let fills: Vec = root.child("fills").map(|f| f.kids("fill").map(|e| read_fill(e, &palette, false)).collect()).unwrap_or_default(); let borders: Vec = root.child("borders").map(|f| f.kids("border").map(|e| read_border(e, &palette)).collect()).unwrap_or_default(); - let xfs = - root.child("cellXfs").map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &fmts, checkboxes)).collect()).unwrap_or_default(); - let style_xfs: Vec