Compare commits

...
580 Commits
Author SHA1 Message Date
Brandon ThomasandClaude Opus 5.5 fc45b7f6d8 Release 0.6.1: rebuild with the fixed shared release workflow
The previous release build failed in craft-common-actions, not in this
repo: riscv64 packaging got --formats deb,rpm,tar (fixed in
craft-common-actions#3), Linux jobs lacked the ALSA headers
(craft-common-actions#5), and Windows signing needed the AZURE_* secrets
listed in the caller.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 11:11:15 -04:00
Brandon ThomasandClaude Opus 5.5 9cb931bac9 Release workflow: pass the Azure signing secrets so Windows builds are signed (#440)
Since the release workflow moved to storytold/craft-common-actions, it has
passed only the Apple and WINDOWS_CERTIFICATE secrets. The signing job reads
values from the release environment, but only for names the caller lists, so
the AZURE_* names that Trusted Signing uses came through empty and Windows
builds would ship unsigned. Same fix as storytold/craft-launcher#174.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-12 11:08:25 -04:00
skylar taylor-barrick 85bfcdfcfd Merge pull request #459 from storytold/codex/craft-print-onboarding
Print: select printers and submit jobs through craft-print
2026-10-12 09:05:31 -06:00
skylar taylor-barrick 9fc4108899 Printing: expose native commands through control discovery 2026-10-12 16:50:03 +02:00
Brandon ThomasandClaude Opus 5.5 b3acae6b77 Release prep: 0.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 05:44:31 -04:00
skylar taylor-barrick 587d879f13 Print: adopt craft-print with native settings and job feedback 2026-10-12 03:25:47 +02:00
Brandon ThomasandClaude Opus 5.5 3926d21aa9 Fix-up: #423's table-name round-trip test sets #433's Table.filter
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 18:08:49 -04:00
Brandon Thomas 3b19cb80e6 Merge pull request #412 from jsymes21-byte/keytips-table-refactor
Keytips: full Excel sequential Alt table — 364 sequences, badges on every control, generated tests (fixes #33, #49)

# Conflicts:
#	contributors/people.toml
2026-10-11 18:06:06 -04:00
Brandon Thomas 63e60de76c Merge pull request #413 from pechnikov2026-star/i18n-fr
i18n: add French (fr) interface
2026-10-11 18:06:05 -04:00
Brandon Thomas a34fe4a7af Merge pull request #436 from LloydNicholson/feat/open-encrypted
Open password-encrypted workbooks (Agile and Standard encryption) (#11)

# Conflicts:
#	ROADMAP.md
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/target-app-parity.md
2026-10-11 18:06:04 -04:00
Brandon Thomas 0a54876e2c Merge pull request #425 from neilcawse/test/command-sequence-fuzz
Engine: command-sequence fuzz harness (undo/redo, XLSX round-trip, full-recalc invariants) and the bugs it found
2026-10-11 18:06:03 -04:00
Brandon Thomas 61e3dd99f7 Merge pull request #416 from neilcawse/feat/oracle-check
CLI: check subcommand - cached-value calc oracle and XLSX round-trip fidelity on any corpus
2026-10-11 18:06:02 -04:00
Brandon Thomas 69b5f78e86 Merge pull request #424 from neilcawse/fix/trendlines
Charts: read, write and draw trendlines

# Conflicts:
#	docs/gaps.md
2026-10-11 18:06:01 -04:00
Brandon Thomas dcd469d12e Merge pull request #419 from neilcawse/fix/function-fixes
Functions: MODE/VALUE/SUMPRODUCT text args, ADDRESS [Book]Sheet, Excel-style lookup bisection, SUBTOTAL skips filtered rows

# Conflicts:
#	docs/file-format-parity.md
#	docs/function-parity.md
2026-10-11 18:05:41 -04:00
Brandon Thomas f170b89a92 Merge pull request #420 from neilcawse/fix/structref
Formulas: trim-reference operators (A1:.E10, A1.:E10, A1.:.E10); read unbracketed [[#This Row],Col]

# Conflicts:
#	docs/function-parity.md
#	docs/gaps.md
2026-10-11 18:05:40 -04:00
Brandon Thomas 80c2efe0f1 Merge pull request #421 from neilcawse/fix/iterative-calc
Calc: iterative calculation for circular references (Maximum Iterations, Maximum Change)

# Conflicts:
#	docs/function-parity.md
2026-10-11 18:05:39 -04:00
Brandon Thomas 74d57ea9fd Merge pull request #422 from neilcawse/fix/csv-display
File formats: CSV/TSV export writes displayed values; templates and .xlsm saved with their own content types

# Conflicts:
#	crates/engine/src/io.rs
#	crates/xlsx/src/tests/roundtrip.rs
#	docs/file-format-parity.md
2026-10-11 18:05:33 -04:00
Brandon Thomas 47b2cfbcd0 Merge pull request #415 from neilcawse/ci/pr-gate
CI: run cargo xtask ci on pull requests and pushes to main
2026-10-11 18:05:19 -04:00
Brandon Thomas a96f19f02b Merge pull request #409 from shrshk/fix/formula-arg-count-363
Refuse formulas with the wrong argument count on entry (#363)
2026-10-11 18:05:18 -04:00
Brandon Thomas e2bcb712fd Merge pull request #418 from neilcawse/fix/numfmt-text
Numfmt: fraction literals and zero fractions, `?` pads thousands separator, TEXT booleans through text section
2026-10-11 18:05:17 -04:00
Brandon Thomas 936c6a055a Merge pull request #423 from neilcawse/fix/xlsx-names-xlpm
XLSX: strip _xlpm. from LET/LAMBDA parameters on read, keep line breaks in table columns, allow leading backslash in table names

# Conflicts:
#	docs/file-format-parity.md
2026-10-11 18:05:16 -04:00
Brandon Thomas 5432419cd5 Merge pull request #427 from vedran-dobos/csv-keep-delimiter
CSV: saving keeps the separator the file was opened with (#426)
2026-10-11 18:05:14 -04:00
Vedran DobosandClaude Opus 5.5 b13ea3e2f3 CSV: saving keeps the separator the file was opened with (#426)
A `;`-separated CSV (the usual CSV where `,` is the decimal separator) was
rewritten with `,` on save: read_csv sniffed the delimiter but the result was
dropped, and save_bytes passed a hard-coded b','. file.save, Save As .csv,
file.exportCsv, file.saveBytes and gridcraft-cli convert all went through it.

The workbook now remembers the separator it was read with
(Workbook::csv_delimiter, set by read_csv) and a CSV save writes it back.
Workbooks not read from CSV, and .tsv/.txt sources saved as .csv, keep `,`.

Regression tests: `;`, `,` and tab .csv round trips byte for byte, new and
.xlsx-origin workbooks save with `,`, and open-by-path + edit + file.save on a
`;` file keeps `;` (also through exportCsv and saveBytes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:46:27 -07:00
Brandon Thomas e6773dac3c Merge pull request #433 from derechopiano/fix/autofit-filter-button-spacing
Fix AutoFit width for table and AutoFilter dropdowns
2026-10-11 18:05:13 -04:00
Brandon Thomas 1841658978 Merge pull request #439 from itrycodinganditsbad/rotated-text-align
Rotated text follows the cell's alignment
2026-10-11 18:05:12 -04:00
Brandon Thomas f38b17fb67 Merge pull request #438 from MarekSpodBiedry/issue-428
Scatter charts of two unlabelled columns plot the first as X for one series (#428)
2026-10-11 18:05:11 -04:00
Fabio LussiandClaude Opus 5.5 dbc04ddae0 Rotated text follows the cell's alignment (Fixes #435)
Text turned by an angle was drawn at a fixed anchor (bottom-left for upward,
top-left for downward text) and ignored the horizontal and vertical alignment,
so upright text with Middle Align in a tall merged cell sat at the bottom.

rotated_text_pos places the turned galley's bounding box in the cell per the
alignment, then derives the TextShape anchor from it. General/Bottom keep the
old placement for upright text.

Fixes #435

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 00:00:56 +02:00
MarekSpodBiedry 88df1670ba Scatter charts of two unlabelled columns plot the first as X for one series (#428) 2026-10-11 23:38:27 +02:00
lloydandClaude Opus 5.5 83d6a6fbe7 App: files on the command line open like File › Open (#11)
A password-protected file named on the command line (a Windows or Linux
double-click) now asks for its password, and open errors are shown
instead of only logged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 009364e72e XLSX: pin the UTF-16LE password encoding with a msoffcrypto known answer (#11)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 1532349227 Encrypted workbooks no password opens are named before asking for one (#11)
gridcraft_xlsx::check_encryption parses EncryptionInfo without a
password, so RC4, Extensible, certificate-only and rights-management
(IRM) files, and damaged ones, get their real message instead of a
password prompt first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 312b4c056e UI: password dialog fixes from review (#11)
OK on the untouched field says the password is incorrect instead of
asking again; the Backstage closes once the workbook opens; app.open on
the control channel takes a password and never opens the dialog. Control
protocol docs cover file.open {password}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 8de8bc187a Docs: encrypted workbooks open with their password (#11)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 c882d169ff UI: ask for the password of an encrypted workbook (#11)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 aad58d4c75 Engine: file.open decrypts password-protected workbooks (#11)
Without a password, file.open returns an error carrying
io::PASSWORD_REQUIRED (never a dialog). A decrypted workbook gets no save
path, so Save never replaces the encrypted original.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 c9f03cc36a XLSX: build encrypted workbooks in code for tests (test-support feature) (#11)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
lloydandClaude Opus 5.5 70d857a699 XLSX: decrypt Agile and Standard encrypted packages (#11)
Clean-room from [MS-OFFCRYPTO]: EncryptionInfo parsing, SHA-1/SHA-2 key
derivation with a capped spin count, AES-ECB/CBC. RC4, Extensible and
certificate-only encryption are reported as unsupported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 23:29:28 +02:00
Shirish Veerabattini 3936f3b79c engine: correct which functions the entry check skips
IF, IFERROR, CHOOSE, SWITCH and INDEX are in the registry and are checked; the comment listed IF as skipped.

Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 16:10:04 -05:00
derechopiano 1a6c864235 home.autofitColumnWidth: reserve filter dropdown space 2026-10-11 22:09:51 +01:00
Shirish Veerabattini 478f01d236 functions: keep DATEDIF's original description, add the units
Restores "Counts whole years, months or days between two dates." and
appends the units, in the multi-line form rustfmt gives a long entry.

Drops the 256-argument test case: the parser already refuses more than
255 arguments, so it never reached the entry check. (993c108's message
says entry "also refuses" them; it already did.)

Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 15:57:33 -05:00
James 7a2361de7f T10: resolve conflicts with main; new upstream commands go live (slicer, pivot chart, forecast sheet, show comments) 2026-10-11 23:54:15 +03:00
James 9e9f9aec84 T9: contributor credit and ui-parity docs for the keytip work 2026-10-11 23:41:24 +03:00
James 8e7e247589 Resolve James's real-Excel checks: drop QAT/Backstage and nonexistent View sequences; arrow navigation in the colour palette
- Side-by-side and synchronous-scrolling keytips removed (do not exist in
  James's Excel); Copy H,C / Spelling R,S / Fill H,H / Sparklines N,Z,K
  confirmed already correct
- QAT digits 0-9 and Backstage account/home/options + legacy Share Workbook
  sequences dropped (no meaningful GridCraft target; not left as trash)
- Colour palette (H,H fill and F,C font colour): arrow keys move a highlight
  through the swatches, Enter applies; key events are stripped so the grid
  behind the popup does not react
2026-10-11 23:40:23 +03:00
James d2a691aea8 Fix combo navigation edge cases and wire Page Layout Sheet Options badges
- Arrows/Enter while a keytip combo is open now navigate the list instead
  of moving the filter field's text cursor (events stripped from TextEdit)
- Reopening a combo resets the filter: the reset frame requests a repaint
  so the stale filtered list never lingers on screen
- Page Layout Sheet Options: Gridlines View/Print and Headings View/Print
  checkboxes painted with VG/PG/VH/PH badges and keytip toggles
- Background rebound from PG to PGB (Excel's Page Setup GB badge); PG is
  no longer terminal
2026-10-11 23:40:23 +03:00
James 7ba871c6f2 Excel-style combo navigation (type to filter, arrows to move) and complete tab badges
- editable_combo: every dropdown keytip opens with a filter field focused;
  typing narrows the list, Up/Down move the highlight (wrapping), Enter or
  click applies, custom text applies where valid (font size). Fixes arrows
  and typing in ALT+H FF/FS/N.
- Audited all 54 painted ribbon ids against the table: real mismatches fixed
  (Data Sort/Text-to-Columns/Remove-Duplicates/Subtotal, Review Spelling/
  Accessibility/New Comment/Notes, View Zoom/Freeze, Formulas Insert Function/
  Name Manager/Define Name/Use-in-Formula/Error Checking/Evaluate, Insert Link/
  Comment/Header-Footer/Sparklines, Home Protect Sheet).
- keytips.json: dialog kind for real dialog openers; control kind for the 6
  chart-type buttons, 7 formula-category buttons, and Orientation (HFQ added,
  was missing); M-family restructured to Excel semantics (ML/MT/ME/MO/MG/MQ
  fire directly, MI1 opens Financial) with 14 unreachable children dropped;
  383 entries total.
2026-10-11 23:40:23 +03:00
James cbd9bb51c6 Dropdown keytips open their controls instead of firing empty commands; complete View badges
- New Action::Control routes a keytip to its ribbon control (popup/dropdown
  open, checkbox toggle, button handler) instead of an engine command with
  empty params. Fixes ALT+H FF/FS/N/H/H error boxes.
- Ribbon consumes a one-shot ui.keytip_invoke: font/size/number combos
  converted to the popup pattern (ComboBox has no open_memory), fill/font
  color menus force-open via SetOpenCommand, 100% zoom and Formula Bar run
  their handlers.
- keytips.json: FF/FS/N/H/H -> control kind; View/Formulas/Data dialog
  openers (WQ zoom, HFM format cells, HO*, MV, AWG, sparkline types) and
  control WVF; MSP/HVP re-targeted; dropped 15 unreachable Home sub-items
  and non-Excel HWS shrink-to-fit.
- View tab: badges on workbook views, gridlines/headings, formula bar.
- Generated suite: 399 tests incl control-kind arm; direct tests 18.
2026-10-11 23:40:23 +03:00
James 7591fca086 T7: generated per-sequence regression tests (412 tests, catalog-probed)
cargo xtask keytips now emits tests/keytips_generated.rs alongside the
table: one end-to-end test per sequence, asserting exactly what its
action does today. The generator probes the live engine catalog at
generation time (blank workbook, empty params), so each live command
asserts journaled / ran clean / surfaced its missing-params error;
pending asserts silence; dialogs assert the dialog opens; tabs assert
the ribbon switch; group levels assert the prefix stays armed.

- pending-but-landed targets get live assertions and a generation
  warning (HWS home.shrinkToFit and MAA formulas.removeArrows had
  landed since population - flipped to live)
- unreachable-sequence validation: any seq with a terminal prefix
  entry is rejected (HCP dropped - HC Copy fires first)
- ENV_SENSITIVE list keeps the checked-in file byte-stable across
  machines (review.spelling uses the system dictionary)
- sample_sequences_work_with_text_before_key covers IME text-first
  event order for one representative of each action kind
- generated_test_count_matches_the_table pins the table size

518 ui-egui tests green; all 8 CI gates pass.
2026-10-11 23:40:04 +03:00
James cd5f3f0a71 T6: pending keytips resolve at runtime and go live when their command lands
- Action::Pending now consults the engine catalog at fire time: silent
  no-op while the command is missing, runs it once it exists - no table
  edit needed when a future feature lands.
- Stripped stray backticks from 7 pending target ids so catalog lookup
  can ever match them.
- gridcraft-engine: doc(hidden) register_test_command hook so UI tests
  can prove the go-live path without touching production code.
- Tests: pending_sequences_are_silent_no_ops (no dialog/toast/journal),
  pending_sequences_go_live_when_the_command_lands (fake command fires
  via its reserved sequence), every_sequence_terminates_without_panicking
  (all 413 sequences pressed end-to-end).
2026-10-11 23:40:04 +03:00
James 659a4d5bd3 Real-Excel keytip corrections from James (Home/Insert/Formulas)
- HP -> home.percent (was wrongly numberFormat); HN stays the Number dropdown.
- H3 -> home.underline fires directly; H3U/H3D dropped as unreachable.
- HAT/HAM/HAB -> Top/Middle/Bottom Align (were unbound).
- NCM/NZT/NZS -> modern Comment/Text Box/Symbol (NC2/NZTX/NU kept as
  legacy aliases); MI1 -> Financial first item.
- Badges on the three dropdowns (font FF, font size FS, number format N)
  and the vertical alignment buttons; Print Titles paints PI.
2026-10-11 23:39:35 +03:00
neilcawseandClaude Opus 5.5 828efab385 Engine: command-sequence fuzz harness (undo/redo, XLSX round-trip, full-recalc invariants) and the bugs it found
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 8ea2342703 Charts: read, write and draw trendlines
Model: Series.trendlines (Vec<Trendline>, serde default) with kind
(linear, exponential, logarithmic, polynomial 2..6, power, moving
average 2..255), name, forward/backward forecast, set intercept,
equation / R² display and line colour, width and dash.

XLSX: read and write <c:trendline> in CT_Trendline child order, placed
after dLbls and before the data references in line, bar, area, scatter,
bubble and stock series; unknown types are skipped.

Chart: least-squares fits (transformed for exp/log/power, skipping
non-positive values; polynomials via normal equations on centred,
scaled x with partial pivoting), moving averages, forecasts that widen
the category or x axis, clipping to the plot, equation and R² labels and
legend entries ("Linear (Sales)"). Degenerate data draws nothing.

Engine: chart.addElement element="trendline" adds (type, series, order,
period, forward, backward, displayEquation, displayRSquared) or removes
trendlines; document.inspect lists each chart's trendlines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 53690bace0 Functions: oracle fixes - MODE/VALUE/SUMPRODUCT text args, ADDRESS [Book]Sheet, Excel-style lookup bisection, SUBTOTAL skips filtered rows (table filter criteria kept)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 9ce910f87f Formulas: trim-reference operators (A1:.E10, A1.:E10, A1.:.E10); read unbracketed [[#This Row],Col]
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 fdb74c27dd Calc: iterative calculation for circular references (Maximum Iterations, Maximum Change)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 eecfa4074d File formats: CSV/TSV export writes displayed values; templates and .xlsm saved with their own content types
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 13afa8c773 XLSX: read cell formulas via file→model conversion (_xlpm), keep line breaks in table columns, allow leading backslash in table names
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:31 -04:00
neilcawseandClaude Opus 5.5 f7bc97b378 CLI: check subcommand - cached-value calc oracle and XLSX round-trip fidelity on any corpus
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:30 -04:00
neilcawseandClaude Opus 5.5 ba830cacf8 CI: run cargo xtask ci on pull requests and pushes to main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:30 -04:00
neilcawseandClaude Opus 5.5 737999f182 Numfmt: fraction literals and zero fractions, ? pads thousands separator, TEXT booleans through text section
Checked against Excel-cached TEXT() results in number- and text-format test workbooks: 226 of 352 TEXT cells mismatched before, 0 after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:39:30 -04:00
James 95b3641725 Paint keytip badges on every ribbon control (issue #49)
The badge painter only covered five sites, so pressing Alt+H showed
nothing past the tab letter. Now every control with a catalog command id
paints its badge automatically:

- control_badge(prefix, id): the rest of a control's unique sequence
  (HFC -> "FC" on Font Color), or the common group letter when many
  variants land on one control (HBA..HBW -> "B" on Borders).
- anchor_badge(prefix, targets): menu anchors resolve to the dominant
  group-level candidate (Pictures shows "P", not SmartArt's "M").
- ribbon.rs: 90+ control sites now paint through control_keytip/
  anchor_keytip (mechanical sweep + hand-wired anchors); split buttons
  paint at their arrow rect.
- Offscreen snapshot verified: at prefix H the Home ribbon paints
  V/X/C/FP/1/2/3U/FC/H/FG/FK/AL/AC/AR/5/6/WW/MC/K/0/9/L/T/J/I/D/O.
- Tests: 29 lib + 14 keytips, all 8 CI gates green.
2026-10-11 23:39:11 +03:00
James f11d74ee7c Populate the full Excel keytip table (408 sequences, issues #33 and #49)
Population of keytips.json from the collected Excel Alt-sequence set:
- 408 curated entries: 10 tabs, 354 command binds (64 reserved pending,
  290 live catalog commands), 2 dialog openers, 42 group levels.
- Bind-all policy: sequences whose command does not exist yet bind to the
  canonical future id as Action::Pending -- badge shows, invocation is a
  silent no-op until the command lands (ids from docs/parity-checklist).
- Group levels: 46 command entries that are strict prefixes of deeper
  sequences were demoted to menu openers so the trie never fires early
  (HV must not paste; it waits for the variant letter).
- Fire-immediately restores: HC Copy, HAN Accounting, FA Save As, FO Open,
  FI Info. Unreachable legacy aliases (HCC, HANM, FA1, FAY3, FOC, FOO, FIP)
  dropped: the parent fires first.
- ES stays a terminal dialog opener as in Excel: the A/F/T/V variants are
  dialog mnemonics, not trie sequences.
- Escape pops one trie level and returns to the armed root at a single
  letter; keytips.json is the single modifiable source; xtask keytips now
  emits through rustfmt so --check is byte-stable.
- Tests: 99 pass (27 lib + 14 keytips + suite), all 8 CI gates green.
2026-10-11 23:37:45 +03:00
James 82cf8a6bb3 Keytips: table-driven matcher and badge painting (issues #33, #49)
Move the hardcoded keytip sequence list into keytip_table.rs as the single
source of truth for both the matcher and the ribbon badge painter.

- Generalize Action::Home into Action::Tab(&'static str); the legacy
  Edit/Format prefix special-case in lib.rs is absorbed into the table.
- Badge helpers: tab_sequence (tabs), group_extension (menu anchors),
  item_letter (menu items), control_badges (command controls).
- Add tab letters for Insert (N), Page Layout (P), Formulas (M), Data (A),
  Review (R), View (W); Draw/Automate stay unbadged until contextual
  letters land.
- Tests: 5 table unit tests + tab_letters_switch_to_their_ribbon_tabs
  integration test. All 7 xtask ci gates green.
2026-10-11 23:37:24 +03:00
Shirish Veerabattini 1d1d27f9a4 ui: argument hint shows the function's description
Inside DATEDIF( the hint showed only the signature, so the values unit
takes weren't visible while typing it (#363). The hint now adds the
function's description under the signature, wrapped to the hint's
width, the same text the autocomplete list shows (translated where a
Spanish entry exists).

Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 15:37:09 -05:00
Shirish Veerabattini 993c108660 functions: share the argument-count rule between call and entry
FnSpec::accepts holds the arity check (including Excel's 255-argument
limit) that functions::call and the entry check both use, so entry also
refuses 256 arguments to a variadic function. The evaluator's own check
in calc is unchanged.

Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 15:37:09 -05:00
James e90ebbbbe2 Keytips: keytips.json source + xtask generator (issues #33, #49)
The sequence table is no longer hand-maintained Rust: keytips.json is the
single human-edited source (one line per sequence, grouped by tab, pending
reserves sequences for future commands), and `cargo xtask keytips`
regenerates keytip_table/generated.rs deterministically. `cargo xtask ci`
now fails if the generated table is stale.

- Action::Pending: reserved sequences show their badge and invoke silently
  until the command exists (bind-all policy).
- Intermediate group levels are implicit: the matcher waits whenever a
  pressed letter starts a deeper sequence; only terminal entries are
  listed (two-letter units like Draw's "JI" work with no extra rows).
- First populated sequence beyond the legacy set: W,V,G toggles gridlines,
  proven end-to-end by view_gridlines_sequence_runs_end_to_end.
2026-10-11 23:36:02 +03:00
James eba3957a21 Keytips: multi-letter units and implicit wait levels (Draw = "JI")
Excel shows some access keys as one multi-letter unit (Draw's "JI") that
fires only once complete. The matcher now follows the trie shape:

- A pressed letter that matches a complete sequence fires immediately.
- If it only starts deeper sequences, the matcher waits for more input
  (implicit group level, no table entry required).
- A tab with deeper sequences stays as an active level so group badges
  show; a terminal unit clears the prefix.
- tab_sequence() returns multi-letter tab units as one badge.

Draw: Alt+JI switches to the Draw tab; deeper Draw letters are left
blank for future contributors (GridCraft's Draw differs from Excel's).
2026-10-11 23:36:02 +03:00
James b415d2e835 Keytips: table-driven matcher and badge painting (issues #33, #49)
Move the hardcoded keytip sequence list into keytip_table.rs as the single
source of truth for both the matcher and the ribbon badge painter.

- Generalize Action::Home into Action::Tab(&'static str); the legacy
  Edit/Format prefix special-case in lib.rs is absorbed into the table.
- Badge helpers: tab_sequence (tabs), group_extension (menu anchors),
  item_letter (menu items), control_badges (command controls).
- Add tab letters for Insert (N), Page Layout (P), Formulas (M), Data (A),
  Review (R), View (W); Draw/Automate stay unbadged until contextual
  letters land.
- Tests: 5 table unit tests + tab_letters_switch_to_their_ribbon_tabs
  integration test. All 7 xtask ci gates green.
2026-10-11 23:36:02 +03:00
sanches 2f22346807 i18n: add French (fr) interface
A complete 379-entry catalog covering every JAPANESE key (the coverage
reference), registered as a Fr variant in the Language enum. The
uniqueness/coverage test now asserts French alongside the other
languages; locale tags fr-FR and fr_CA resolve.
2026-10-11 23:27:39 +03:00
Shirish Veerabattini 9b59966cc9 Merge upstream main into fix/formula-arg-count-363
Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 15:20:56 -05:00
Brandon Thomas a5137872c1 Merge pull request #401 from vangel76/fix/text-box-formatting
Drawing: text box formatting — run size/bold/font/outline, alignment, anchor, no outline (#377)
2026-10-11 16:14:44 -04:00
Brandon ThomasandClaude Opus 5.5 3054babe0e Text boxes: their typefaces count as used workbook fonts, so an installed one is bound; restore image_ext's doc comment (review fix-up for #401)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:14:41 -04:00
Brandon Thomas 1c3beb2a95 Merge branch 'land' into fix-401
# Conflicts:
#	ROADMAP.md
2026-10-11 16:09:03 -04:00
Brandon Thomas 4a23b9cf4b Merge pull request #404 from vangel76/fix/header-footer-variants
Headers and footers: first-page and even-page variants, Insert › Header & Footer edits in place (#344)

# Conflicts:
#	ROADMAP.md
2026-10-11 16:08:56 -04:00
Brandon Thomas 7cd96b945f Merge pull request #402 from vangel76/fix/ui-font-hebrew-fallback
UI fonts: formula bar falls back to the cell font, so Hebrew isn't boxes (#349)

# Conflicts:
#	ROADMAP.md
2026-10-11 16:08:55 -04:00
Brandon Thomas 773f7e6b76 Merge pull request #388 from itrycodinganditsbad/fix-373
Draw the outline band for grouped rows and columns (#373)
2026-10-11 16:06:48 -04:00
Brandon Thomas b2101947ca Merge branch 'land' into fix-388
# Conflicts:
#	docs/ui-parity.md
2026-10-11 16:01:53 -04:00
Brandon Thomas 1ea549bfe4 Merge pull request #394 from vangel76/fix/print-save-as-pdf
File: desktop Print opens the system PDF viewer, Save As offers PDF/CSV/HTML (#370, #343)
2026-10-11 16:01:33 -04:00
Brandon ThomasandClaude Opus 5.5 5c26c963f8 Print PDF in the shared temp folder: create it exclusively (never follow or overwrite an existing file or symlink) and owner-only on Unix (review fix-up for #394)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:01:30 -04:00
Brandon Thomas 6cc69494ca Merge branch 'land' into fix-394
# Conflicts:
#	ROADMAP.md
2026-10-11 15:55:10 -04:00
Brandon Thomas 0065485fc0 Merge pull request #390 from GhostMitra (rebased head; the wanted part is already on main) 2026-10-11 15:54:44 -04:00
Brandon Thomas c3f6b51055 Merge pull request #392 from GhostMitra (rebased head; the wanted part is already on main) 2026-10-11 15:54:44 -04:00
Brandon Thomas bf63a8dd5e Merge pull request #391 from GhostMitra/feat/web-save-file-picker
Web: native Save and Save As file picker with download fallback
2026-10-11 15:52:09 -04:00
Brandon ThomasandClaude Opus 5.5 6fb99ef5e1 Web save: any picker refusal but a cancel, or a failed write, falls back to a download (review fix-up for #391)
A save without a recent user gesture (e.g. over the control channel) is refused with SecurityError and would otherwise fail silently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:52:08 -04:00
Brandon Thomas fc4a74001b Merge branch 'land' into fix-391 2026-10-11 15:51:44 -04:00
debarghaya 173245a5b0 Web: add favicon to web app index and disable dev incremental compilation 2026-10-12 01:21:22 +05:30
debarghaya 159e057a28 Web & UI: resolve system theme preference and default web to system theme 2026-10-12 01:20:53 +05:30
Brandon Thomas 2d54f56724 Merge pull request #390 from GhostMitra
Web: follow the browser's light/dark appearance (the unused resolve_theme and raster_to_alpha_mask helpers from the PR are left out)
2026-10-11 15:50:21 -04:00
Brandon Thomas 80f2a75f58 Merge pull request #392 from GhostMitra/fix/web-favicon
Web: add favicon to web app index
2026-10-11 15:50:01 -04:00
Brandon ThomasandClaude Opus 5.5 35e317ae3a Keep incremental dev builds; the favicon change stands on its own (review fix-up for #392)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:49:44 -04:00
Brandon Thomas 479377304f Merge branch 'land' into fix-392 2026-10-11 15:49:38 -04:00
Brandon Thomas baaa606036 Merge pull request #396 from nihilist-narwhal/fix-xlookup-reference
XLOOKUP: return a reference when the result range is one
2026-10-11 15:49:34 -04:00
Brandon ThomasandClaude Opus 5.5 6d59233e62 XLOOKUP reference path: an empty match_mode keeps the search_mode after it (review fix-up for #396)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:49:32 -04:00
Brandon Thomas c7bd7deebb Merge branch 'land' into fix-396 2026-10-11 15:49:00 -04:00
debarghaya 937bf63315 Web: native Save and Save As file picker with download fallback 2026-10-12 01:18:44 +05:30
vangel76andClaude Opus 5.5 cdd71b4d5d Headers and footers: first-page and even-page variants, Insert › Header & Footer edits in place (#344)
XLSX headerFooter kept only oddHeader/oddFooter: a workbook whose header is on a
different first page (differentFirst + firstHeader) or on even pages showed no
header, and saving dropped it. The model now keeps the first/even headers and
footers and the differentFirst / differentOddEven / scaleWithDoc / alignWithMargins
flags; XLSX reads and writes them; the PDF and the Page Layout view use the right
pair per page; in-place editing edits the page's own pair, and the Header & Footer
tab has Different First Page and Different Odd & Even Pages. pageLayout.headerFooter
takes the variants and a page: odd|even|first for one-section edits.

Insert › Header & Footer now switches to Page Layout view and edits the first
page's centre header, as in Excel, instead of opening the codes dialog.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:44:49 +02:00
Brandon Thomas f173d6733d Merge pull request #387 from vangel76/fix/sheet-protection-password
Review: Protect Sheet passwords use Excel-compatible hashes, kept in XLSX (#346)

# Conflicts:
#	ROADMAP.md
2026-10-11 15:43:46 -04:00
Brandon Thomas 283b06453e Merge pull request #383 from vangel76/fix/sheetview-top-left-cell
View: restore and save the scroll position (topLeftCell) (#378)

# Conflicts:
#	ROADMAP.md
2026-10-11 15:43:45 -04:00
Brandon Thomas 12b46e6bbe Merge pull request #395 from vangel76/fix/space-selection-shortcuts
Keyboard: Shift+Space and Ctrl+Space select without starting an edit (#338)

# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/grid.rs
2026-10-11 15:43:44 -04:00
Brandon Thomas 8498dedb7d Merge pull request #381 from vangel76/fix/shrink-to-fit
Grid: render Shrink to fit (#375)

# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/grid.rs
2026-10-11 15:43:32 -04:00
Brandon Thomas d90a072d90 Merge pull request #380 from vangel76/fix/merged-range-borders
Grid: merged ranges draw their right and bottom borders (#376)

# Conflicts:
#	ROADMAP.md
2026-10-11 15:43:31 -04:00
Brandon Thomas 39c3b04d0d Merge pull request #382 from vangel76/fix/dx12-dxc-startup
Windows: compile DirectX 12 shaders with FXC, no DXC runtime needed (#339, #354)
2026-10-11 15:43:30 -04:00
Brandon Thomas 380b355d77 Merge pull request #400 from nihilist-narwhal/fix-index-array-args
INDEX: arrays of row and column numbers pick a value each
2026-10-11 15:43:13 -04:00
Brandon ThomasandClaude Opus 5.5 fca801c17e INDEX: compare the result size with saturating u64 math, so it can't overflow on 32-bit targets (review fix-up for #400)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:43:11 -04:00
Brandon Thomas fbb2285532 Merge branch 'land' into fix-400 2026-10-11 15:42:32 -04:00
Brandon Thomas 437881f53a Merge pull request #399 from nihilist-narwhal/fix-future-function-prefixes
XLSX: write the _xlfn. prefix for GROUPBY, PIVOTBY, ENCODEURL and the REGEX functions
2026-10-11 15:42:27 -04:00
Brandon Thomas d821aa1409 Merge pull request #398 from nihilist-narwhal/fix-relative-names
Defined names: relative references follow the cell that uses the name
2026-10-11 15:42:26 -04:00
Brandon Thomas 2657cb2fa6 Merge pull request #397 from nihilist-narwhal/fix-validation-formulas
Data validation: relative formulas, checked with the value being entered
2026-10-11 15:42:25 -04:00
vangel76andClaude Opus 5.5 88bb5677a8 UI fonts: interface text falls back to the cell font (#349)
On macOS the UI font (SF) has no Hebrew and no Hebrew fallback face was
found, while cells in Arial drew it: the formula bar showed boxes. The
interface families now carry the cell face ahead of the script fallbacks,
and the macOS Hebrew candidates include ArialHB.ttc / SFHebrew.ttf /
LucidaGrande.ttc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:42:24 +02:00
vangel76andClaude Opus 5.5 da1d291d93 Drawing: text box run formatting, alignment, anchor and no-outline (#377)
Text boxes ignored a:rPr (size, bold, italic, typeface, fill, outline),
a:pPr algn, a:bodyPr anchor and spPr/a:ln/a:noFill. They are now read into
Shape::format, drawn on screen and in PDF, and written back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:39:53 +02:00
Brandon Thomas 4dca02c89b Merge pull request #9 from justinjohn0306/fix/system-fonts-in-list
Fix: list and render installed system fonts (#4)
2026-10-11 15:38:44 -04:00
Brandon ThomasandClaude Opus 5.5 e211f666a6 Merge main into installed-fonts: workbook fonts bind on top of main's per-language font set and fallback faces; only families that survive drop_unparseable_fonts count as bound; a language switch rebinds them (review fix-up for #9)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:38:42 -04:00
vangel76andClaude Opus 5.5 8587c2ba14 Review: Protect Sheet can't replace a sheet's password without unprotecting it
Re-protecting a password-protected sheet would drop its hash and let a
plain Unprotect succeed; it is now refused. The sheet tab menu offers
Unprotect Sheet on a protected sheet, like the ribbon.

Refs #346

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:36:05 +02:00
vangel76andClaude Sonnet 5.5 6290bf123a Keyboard: Shift+Space and Ctrl+Space select without starting an edit (#338)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 21:32:57 +02:00
vangel76andClaude Opus 5.5 ad48f1e3e1 File: desktop Print opens the system PDF viewer, Save As offers PDF/CSV/HTML (#370, #343)
Since #209, printing from the UI hands the print PDF to Services::print, which only
the web build set: on the desktop, Ctrl+P, More › Print, the macOS menu and the
Backstage Print button produced the PDF and dropped it. The desktop app now writes
it to the temporary folder and opens it in the system PDF viewer, whose Print
reaches the printer dialog.

Save As has a Save as type chooser (xlsx, csv, html, pdf); file.save and
file.saveAs with a .pdf path write a PDF of the sheet (they wrote XLSX bytes into
the .pdf and made it the workbook's file). The desktop save picker honours the
suggested type instead of always proposing .xlsx. The macOS Properties item opens
File › Info instead of running file.properties with no fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:32:38 +02:00
vangel76andClaude Opus 5.5 22978a7e62 Review: Protect Sheet passwords use Excel-compatible hashes, kept in XLSX
Sheet protection stored an internal FNV hash that was never written to
XLSX, and an Excel sheet password was dropped on import, so imported
protected sheets could be unprotected without it. Protect Sheet now
stores a salted SHA-512 hash (spin count 100000) via PasswordHash; the
XLSX sheetProtection password (iterated or legacy) is read and written,
and Unprotect Sheet really verifies it. Hashes from older GridCraft JSON
workbooks are still read and verified.

Refs #346

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:29:10 +02:00
Fabio LussiandClaude Opus 5.5 535c502fe7 Draw the outline band for grouped rows and columns
Grouped rows and columns now get Excel's outline band beside the headers:
a bracket per group, a -/+ button on the summary line and level buttons
in the corner. The buttons run data.hideDetail / data.showDetail and the
new data.showLevels, so they undo. Hide Detail marks the summary line
collapsed, Show Detail keeps inner groups that were collapsed on their
own, and Group / Ungroup take by: rows|cols. Show Detail and Hide Detail
are on the Data tab and in the Data menu, the group shortcuts are listed
as Alt+Shift+Right / Left, and shortcut lookup reads navigation keys by
their logical key so the numpad arrows work.

Fixes #373

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:29:03 +02:00
debarghaya cedfc5e44c Web: add favicon to web app index and disable dev incremental compilation 2026-10-12 00:54:49 +05:30
debarghaya 1b04d06014 Web & UI: resolve system theme preference and default web to system theme 2026-10-12 00:51:23 +05:30
Brandon Thomas fb3737aa03 Merge pull request #19 from justinjohn0306/fix/vba-macro-preservation
Preserve VBA macros + Excel-style macros UX (issue #6)
2026-10-11 15:20:47 -04:00
Brandon ThomasandClaude Opus 5.5 9bf5ecaf04 Merge main into VBA preservation; save macros only into .xlsm (an .xlsx never carries a VBA project); drop the shell round-trip script (review fix-up for #19)
The Rust round-trip test covers what scripts/check-vba-roundtrip.sh checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:20:45 -04:00
vangel76andClaude Opus 5.5 fbabac15d4 Review: Protect Workbook dialog with an Excel-compatible password (#345)
The ribbon button toggled structure protection silently. It now opens a
Protect Structure and Windows dialog with an optional password; when a
password was set, unprotecting asks for it and really verifies it
(SHA-512, spin count 100000, salted). The password hash is read from and
written to XLSX workbookProtection (workbookAlgorithmName/HashValue/
SaltValue/SpinCount or the legacy workbookPassword); an unreadable one
stays locked. File › Info uses the same flow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:12:24 +02:00
vangel76andClaude Opus 5.5 04001fd943 View: restore and save the scroll position (sheetView topLeftCell) (#378)
The model read topLeftCell but the grid always opened at A1 and never wrote
the current scroll back. Sheets now open scrolled to their saved first
visible cell; saves record the current one (and the active cell) without
dirtying the workbook. Frozen panes use the pane's topLeftCell.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:11:23 +02:00
Brandon Thomas 1d3abfa4a7 Merge pull request #203 from gyurix/system-theme-detection
Linux: the display theme asks the desktop, not winit
2026-10-11 15:09:46 -04:00
Brandon ThomasandClaude Opus 5.5 55d41eb13c Desktop theme watcher starts only in the desktop app, not in every SheetApp (tests, embedders) (review fix-up for #203)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:09:43 -04:00
Brandon Thomas 0bea7178a2 Merge branch 'land' into fix-203 2026-10-11 15:04:30 -04:00
Brandon Thomas 177e52a14d Merge pull request #209 from Dejan-Port/print-only
web: print straight to the system print dialog, not just export
2026-10-11 15:04:11 -04:00
Brandon ThomasandClaude Opus 5.5 04fb60ea5d Printing from the UI (Backstage, Ctrl+P, menu) goes through print_now, so the web build opens the browser's print dialog (review fix-up for #209)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 15:04:09 -04:00
vangel76andClaude Opus 5.5 806a39a514 Windows: compile DirectX 12 shaders with FXC, never a stray dxcompiler.dll (#339, #354)
wgpu's default DX12 compiler (Auto) loads the first dxcompiler.dll on the
DLL search path. GridCraft ships none, so another program's copy is used;
without a matching dxil.dll its 'DXIL signing library not found' warning
fails wgpu's internal compute pipelines, the device is lost and the app
exits before the first frame. Pin FXC (part of Windows) unless
WGPU_DX12_COMPILER asks for another compiler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:02:20 +02:00
vangel76andClaude Opus 5.5 3ae319154c Grid: render Shrink to fit (#375)
Cells with shrinkToFit drew at full size: text spilled or was clipped and
numbers showed ####. Too-wide content now gets a smaller font that fits the
cell or merged area, matching the PDF/print path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 21:01:12 +02:00
Brandon Thomas f8edb7c1a4 Merge branch 'land' into fix-209 2026-10-11 15:00:04 -04:00
Brandon ThomasandClaude Opus 5.5 347d2a5bc2 Docs: catalog 274 / 290 after #211 and #193
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:59:45 -04:00
nihilist-narwhal 9d0053f3ad XLOOKUP: return a reference when the result range is one
XLOOKUP returned only values, so it couldn't end a range or feed
functions that need a reference: SUM(XLOOKUP("b",A1:A4,B1:B4):
XLOOKUP("d",A1:A4,B1:B4)) and SUM(B1:XLOOKUP(…)) gave #VALUE!, and so
did CELL("address",XLOOKUP(…)). A match on an empty cell gave 0, so
ISBLANK(XLOOKUP(…)) was FALSE and "x"&XLOOKUP(…) gave "x0" (#374). In
Excel XLOOKUP returns a reference to the matching row (or column) of
its result range. The evaluator now does so, finding the position with
XMATCH; arrays of lookup values, array arguments and errors still go
through the library function.
2026-10-11 13:59:08 -05:00
vangel76andClaude Opus 5.5 7a4aaebab0 Grid: merged ranges draw their right and bottom borders from the edge cells (#376)
Excel stores a merged range's outline on the cells along each edge; the grid
only used the anchor cell's borders, so a boxed merge showed only top and left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 20:58:49 +02:00
Brandon Thomas dc85b2ab07 Merge pull request #193 from zaidshurbaji/feature/table-slicers
Feature/table slicers
2026-10-11 14:58:32 -04:00
Brandon ThomasandClaude Opus 5.5 8aa9cad703 Slicers: the anchor uses #206's checked cell_param and stays on the sheet; drop the personal macOS workflow (review fix-up for #193)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:58:29 -04:00
nihilist-narwhal 686501c7de Data validation: relative formulas, checked with the value being entered
Validation formulas were evaluated as written, at every cell of the
range, and against the cell's old value. A Custom rule =A1>10 on A1:A9
rejected 20 typed into A1 (A1 was still empty) and checked A1, not A5,
when typing into A5; a Whole number rule "<= B1" on C1:C9 compared C2
with B1. As in Excel, the formulas are now relative to the first cell
of the range and see the value being entered.
2026-10-11 13:54:43 -05:00
nihilist-narwhal 683ff6003c Defined names with relative references
A name whose references have no $ was evaluated as if they were
absolute. In Excel such references are relative: defined from B2,
=Sheet1!A2 means "the cell to the left", and the file stores it
relative to A1 (Sheet1!XFD1, wrapping around the sheet's edge).

Name formulas with relative references are now moved by the using
cell's offset from A1, wrapping at the edges, and formulas.defineName
takes relative references as relative to the active cell, as Excel's
Name Manager does, and stores them relative to A1.
2026-10-11 13:53:26 -05:00
nihilist-narwhal 85ca8f6af5 INDEX: arrays of row and column numbers pick a value each
INDEX took one row and one column number, so INDEX(A1:C3,{1;3},{1,3})
gave a single value and SUM(INDEX(A1:C3,{1,2,3},2)) summed one cell.
In Excel, arrays of positions return an array of the values at each
(broadcast) position. A position that picks a whole row or column gives
#CALC! there, as arrays can't nest.
2026-10-11 13:52:23 -05:00
nihilist-narwhal 2ded7bf193 XLSX: write the _xlfn. prefix for GROUPBY, PIVOTBY, ENCODEURL and the REGEX functions
These were missing from the list of functions newer than the original
file format, so they were saved without the prefix, and Excel shows
#NAME? for such formulas.
2026-10-11 13:52:18 -05:00
Brandon Thomas 205981a52a Merge branch 'land' into fix-193
# Conflicts:
#	crates/engine/src/cmd/mod.rs
#	crates/ui-egui/src/chartview.rs
2026-10-11 14:48:14 -04:00
Brandon Thomas ce0483fc17 Merge pull request #211 from Zarvinx/feat/drag-selected-columns
Reorder selected columns by dragging headers
2026-10-11 14:47:43 -04:00
Brandon Thomas 506320b548 Merge branch 'land' into fix-211
# Conflicts:
#	crates/engine/src/tests.rs
#	docs/ui-parity.md
2026-10-11 14:39:47 -04:00
Brandon ThomasandClaude Opus 5.5 743ca809cc Fix-up: Insert Copied Cells target and PivotChart anchor use #206's checked cell_param
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:34:37 -04:00
Brandon Thomas a9f9b09acc Merge pull request #365 from MarekSpodBiedry/issue-359
Ctrl+click on an already selected header or cell deselects it (#359)
2026-10-11 14:34:17 -04:00
Brandon Thomas 57ab1790ad Merge pull request #364 from MarekSpodBiedry/issue-362
Edit date cells as dates, not serial numbers (#362)
2026-10-11 14:34:16 -04:00
Brandon Thomas 1fc7f50104 Merge pull request #360 from ege-arhan/fix/formulas-ribbon-layout
fix(ribbon): Watch Window layout in Formulas ribbon (#342)
2026-10-11 14:34:14 -04:00
Brandon Thomas ff516650da Merge pull request #206 from mikl0s/
Cell references: an invalid reference is an error instead of the active cell
2026-10-11 14:34:10 -04:00
Shirish Veerabattini d0ff4265c7 contributors: add shrshk
Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 13:29:14 -05:00
Shirish Veerabattini 56f784473d engine: refuse formulas with the wrong argument count on entry
A formula calling a built-in function with too few or too many
arguments (=DATEDIF(a,b), =SUM(), =DATE(2024,1)) was stored and showed
#VALUE! with no hint about what was wrong. Entry now refuses it with
the function's signature, e.g. "DATEDIF has too few arguments. Use
DATEDIF(start_date, end_date, unit)", and leaves the cell unchanged.

Only registered functions are checked: special forms the evaluator
handles itself (IF, LET, LAMBDA...), LAMBDA names and unknown functions
are skipped. Paste and Find & Replace keep turning input that fails
entry into text. DATEDIF's description now lists its units.

Fixes #363

Claude-Session: https://claude.ai/code/session_01BGBBGBC2gRpQ7GDuwQ6WPt
2026-10-11 13:29:14 -05:00
Brandon Thomas 76f3a29c79 Merge branch 'land' into fix-206 2026-10-11 14:23:51 -04:00
Brandon ThomasandClaude Opus 5.5 fb8e8ac8f1 Docs: catalog 272 / 290 after #325
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:22:39 -04:00
Brandon ThomasandClaude Opus 5.5 8fcb9b1007 Fix-up: es/de/cs strings for Forecast Sheet (#325)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 14:15:18 -04:00
Brandon Thomas 7a34692a0d Merge pull request #325 from vangel76/feat/forecast-sheet
Data: Forecast Sheet (data.forecastSheet) (#322)

# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/ui-parity.md
2026-10-11 13:52:00 -04:00
Brandon Thomas fda7f5bc14 Merge pull request #333 from vangel76/feat/xlsx-passthrough
XLSX: keep unmodelled parts on save (#330)

# Conflicts:
#	ROADMAP.md
#	crates/model/src/lib.rs
#	crates/model/src/sheet.rs
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-11 13:51:59 -04:00
Brandon Thomas c379da6ac9 Merge pull request #332 from vangel76/feat/xls-read
XLSX/IO: read legacy .xls (BIFF8) workbooks (#121)

# Conflicts:
#	docs/gaps.md
2026-10-11 13:51:48 -04:00
Brandon Thomas 26489863b0 Merge pull request #334 from vangel76/feat/page-layout-view
View: Page Layout view with rulers and in-place headers and footers (#329)
2026-10-11 13:51:31 -04:00
Brandon ThomasandClaude Opus 5.5 4a55aa3e34 Merge main into page-layout-view: pages keep the gliding selection (#266), frozen-pane clipping (#217), right-to-left mirroring and freeze handles (#310, #309); es/de/cs strings for headers and footers
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:39:07 -04:00
Brandon ThomasandClaude Opus 5.5 baffd3c78d Fix-up #325: cap Forecast Sheet history and forecast rows
The default periods (a third of the history, up to ~33k) bypassed
MAX_PERIODS, and each forecast row's three ETS formulas refit over the whole
history, so 100k history rows x 10k periods froze the app. History is now at
most 10,000 rows, periods at most 10,000, and history x periods at most
500,000 (about 3 us per history point per fit: a few seconds of recalc at
the cap). The default is clamped to the cap; explicit periods or an end past
it are refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:30:47 -04:00
Brandon Thomas e800368c91 Merge pull request #266 from arcanii/selection-glide
Glide the selection outline to a new selection; View ▸ Animations turns it off (includes #265)
2026-10-11 13:27:43 -04:00
Brandon ThomasandClaude Opus 5.5 c8b1b941f7 Merge main into selection-glide: the gliding outline and its fill respect frozen panes (#217) and right-to-left sheets (#310); es/de/cs strings for Animations
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:27:27 -04:00
Brandon Thomas cf75981fc2 Merge pull request #261 from AlissonFA/fix/cell-vertical-alignment
M2: fix cell vertical alignment positioning and add keytips (#241)
2026-10-11 13:20:27 -04:00
Brandon ThomasandClaude Opus 5.5 b3908bf81e Key tips HAT/HAM/HAB run Align Top/Middle/Bottom, with a test (review fix-up for #261)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:20:22 -04:00
MarekSpodBiedry 568b754211 Ctrl+click on an already selected header or cell deselects it (#359) 2026-10-11 19:18:39 +02:00
MarekSpodBiedry ea2e2a5bba Edit date cells as dates, not serial numbers (#362) 2026-10-11 19:18:27 +02:00
Brandon Thomas fa33d0b90f Merge pull request #298 from vangel76/fix/symbol-glyph-fallback
UI fonts: symbol fallback faces so interface symbols aren't boxes (#197)
2026-10-11 13:15:43 -04:00
Brandon ThomasandClaude Opus 5.5 27ef18ec2c symbol_glyphs test: compare against a private-use code point no font covers (review fix-up for #298)
U+25FB is a real glyph in DejaVu, so the test could pass while symbols still rendered as boxes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:14:30 -04:00
Brandon Thomas 6cf32cf4eb Merge branch 'land' into fix-298
# Conflicts:
#	ROADMAP.md
2026-10-11 13:13:26 -04:00
Brandon ThomasandClaude Opus 5.5 a0cb8f2ca2 Docs: catalog 271 / 290 after #286 and #288
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:13:01 -04:00
Brandon Thomas 5360a77505 Merge remote-tracking branch 'origin/main' into fix-325
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/mod.rs
#	crates/ui-egui/src/dialogs.rs
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/ui-parity.md
2026-10-11 13:12:41 -04:00
Brandon Thomas 9a978f0461 Merge pull request #288 from vangel76/fix/insert-copied-cells
Clipboard: Insert Copied Cells and Insert Cut Cells (#21)
2026-10-11 13:12:25 -04:00
Brandon ThomasandClaude Opus 5.5 1fb5f3264d Spanish, German and Czech strings for Insert Copied/Cut Cells (review fix-up for #288)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:12:23 -04:00
Brandon ThomasandClaude Opus 5.5 e52fc4aa08 Fix-up #333: escape kept content types and charge kept VML to the kept total
Content types (and extensions) of kept parts come from the input file and
were written into [Content_Types].xml unescaped, so a quote or angle bracket
injected XML; they are now attribute-escaped. Each sheet re-read and kept
its VML drawing (up to 16 MB) outside MAX_KEPT_TOTAL, so many sheets sharing
one highly compressed drawing amplified memory; the drawing is now read
within and charged to the remaining kept-bytes allowance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:05:45 -04:00
Brandon Thomas 9cb6cb2384 Merge branch 'land' into fix-288
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/edit.rs
#	docs/target-app-parity.md
2026-10-11 13:01:23 -04:00
Brandon Thomas 344b5cdb53 Merge pull request #286 from vangel76/feat/review-comment-navigation
Review: Previous/Next Comment, Show Comments, Show All Notes, Convert to Comments (#281)
2026-10-11 13:00:30 -04:00
Brandon ThomasandClaude Opus 5.5 c83f214c9d Spanish, German and Czech strings for comment navigation (review fix-up for #286)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:00:27 -04:00
Brandon Thomas 79fce91359 Merge remote-tracking branch 'origin/main' into fix-333
# Conflicts:
#	ROADMAP.md
#	crates/model/src/lib.rs
#	crates/xlsx/src/sheet_read.rs
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-11 12:56:45 -04:00
Brandon ThomasandClaude Opus 5.5 e78cc6edc9 Fix-up #332: bound .xls formula nesting and share one record budget across sheets
Chained PtgParen/PtgUminus (or operator) tokens built a ~16K-deep Expr whose
printing or drop overflowed the stack; nesting past the formula parser's
MAX_DEPTH (256) is now reported as unsupported. BoundSheet records pointing
into one huge substream each got their own 40M-record allowance; the
allowance is now shared by the whole Workbook stream, and two sheets at the
same offset are refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:55:17 -04:00
Brandon Thomas 141fef26e8 Merge remote-tracking branch 'origin/main' into fix-286
# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/review.rs
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-11 12:52:12 -04:00
Brandon Thomas 30312e7546 Merge remote-tracking branch 'origin/main' into fix-332
# Conflicts:
#	ROADMAP.md
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-11 12:51:12 -04:00
Ege Arhan 64089568c8 fix(ribbon): Watch Window layout in Formulas ribbon (#342) 2026-10-11 16:50:42 +00:00
Brandon Thomas 336deb87de Merge pull request #216 from MarekSpodBiedry/issue-202
Read the browser clock for NOW(), TODAY() and year-less dates on wasm (#202)
2026-10-11 12:46:33 -04:00
Brandon Thomas fa12cb441b Merge pull request #212 from Zarvinx/build/rust-1.95-clippy
Fix Rust 1.95 Clippy warnings

# Conflicts:
#	crates/ui-egui/src/grid.rs
2026-10-11 12:46:32 -04:00
Brandon Thomas 9d3b3a6074 Merge pull request #207 from mikl0s/fix/cell-set-requires-input-v2
Cell: cell.set without an input is an error
2026-10-11 12:46:03 -04:00
Brandon Thomas 05260cf3b8 Merge pull request #268 from ttrudging/fix/worksheet-tab-scrolling
Fix horizontal worksheet tab scrolling
2026-10-11 12:45:34 -04:00
Brandon ThomasandClaude Opus 5.5 4cb4f6586e rustfmt the sheet-tab scroll area (review fix-up for #268)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:42:02 -04:00
Brandon Thomas de8d70cc39 Merge remote-tracking branch 'origin/main' into fix-268 2026-10-11 12:41:54 -04:00
Brandon Thomas 117be4feb1 Merge pull request #335 from Losminek (author's merge with main) 2026-10-11 12:36:55 -04:00
Brandon Thomas a4fc1070c7 Merge pull request #352 (author's merge with main; content already on main) 2026-10-11 12:36:55 -04:00
Brandon Thomas b0c72c92f3 Merge pull request #353 (author's merge with main; content already on main) 2026-10-11 12:36:55 -04:00
Brandon Thomas 18eb274878 Merge pull request #350 (author's merge with main; content already on main) 2026-10-11 12:36:55 -04:00
Brandon Thomas c1a6a9cf3a Merge pull request #355 (author's merge with main; content already on main) 2026-10-11 12:36:55 -04:00
Brandon ThomasandClaude Opus 5.5 cd9662f1d4 Docs: headline counts after wave 3 (513 / 523 functions, 504 working; catalog 266 / 290)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:31:17 -04:00
Brandon ThomasandClaude Opus 5.5 abbd8181b9 Fix-up: theme test picks System from Backstage Options' Display theme combo (#318 after #331)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:31:17 -04:00
Sasha Syrotenko 1a2daefd78 Merge branch 'main' into fix/memory-alloc-on-agg 2026-10-11 19:31:00 +03:00
Brandon ThomasandClaude Opus 5.5 4d2335c8f5 Fix-up: Spanish, German and Czech strings for the features merged alongside them; theme test goes through Backstage Options (#318 after #331)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:21:15 -04:00
lloyd 823dc5a060 Merge branch 'main' of github.com:storytold/gridcraft into fix/copy-multiple-ranges
# Conflicts:
#	crates/engine/src/tests.rs
#	crates/ui-egui/tests/clipboard.rs
2026-10-11 18:19:26 +02:00
lloyd 4e94c2f720 Merge commit '684bc41d0318667295ea8bc4c8887a27f47fb5a7' into fix/multi-select-resize
# Conflicts:
#	crates/engine/src/tests.rs
2026-10-11 18:16:57 +02:00
lloyd 496a631203 Merge commit '684bc41d0318667295ea8bc4c8887a27f47fb5a7' into fix/journal-redact-passwords
# Conflicts:
#	crates/engine/src/tests.rs
2026-10-11 18:16:57 +02:00
LosminekandClaude Sonnet 5.5 b3b2cd3221 i18n (cs): translate "Interface size" and "Auto" (#294)
Two new upstream catalog strings (interface scale control in the View tab).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 18:16:03 +02:00
LosminekandClaude Sonnet 5.5 819dc49c44 Merge origin/main into cs-pr
Upstream added German (de) in the meantime, in the same places where the
Czech language is registered (module list, Language enum and ALL, name,
code, tag parsing, translate, tests, theme font loop, control protocol
list). Both languages kept, German first. contributors/people.toml, the
ROADMAP and docs/localization-parity.md counters: all entries kept.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 18:16:03 +02:00
Brandon ThomasandClaude Opus 5.5 267a2183ac Fix-up: Backstage options read the formula bar from engine prefs (#331 after #295)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:13:09 -04:00
Brandon Thomas 0305d2a666 Merge pull request #335 from Losminek/cs-pr
i18n: Czech interface language (cs)

# Conflicts:
#	ROADMAP.md
#	contributors/people.toml
#	crates/ui-egui/src/control.rs
#	crates/ui-egui/src/i18n.rs
#	crates/ui-egui/src/theme.rs
#	docs/localization-parity.md
2026-10-11 12:10:06 -04:00
Brandon Thomas 29660e8c4d Merge pull request #331 from vangel76/feat/file-backstage
UI: File tab Backstage view (#174)

# Conflicts:
#	ROADMAP.md
#	crates/engine/src/tests.rs
#	crates/ui-egui/src/control.rs
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/ribbon.rs
#	docs/parity-checklist.md
#	docs/ui-parity.md
2026-10-11 12:08:56 -04:00
Brandon Thomas 839072c6dd Merge pull request #327 from vangel76/feat/solver
Data: Solver with Simplex LP, integer branch and bound and a nonlinear method (#326)

# Conflicts:
#	crates/ui-egui/src/dialogs.rs
#	crates/ui-egui/src/i18n.rs
#	crates/ui-egui/src/i18n/ko.rs
#	crates/ui-egui/src/i18n/pt.rs
#	crates/ui-egui/src/i18n/ru.rs
#	crates/ui-egui/src/i18n/zh.rs
#	crates/ui-egui/src/ribbon.rs
#	crates/ui-egui/tests/interaction.rs
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
#	docs/ui-parity.md
2026-10-11 12:07:34 -04:00
Brandon Thomas 1dbad7768d Merge pull request #320 from vangel76/feat/analysis-toolpak
Data: Analysis ToolPak with 13 tools and the Data Analysis dialog (#312)

# Conflicts:
#	crates/ui-egui/src/dialogs.rs
#	docs/gaps.md
#	docs/parity-checklist.md
2026-10-11 12:06:42 -04:00
Brandon Thomas 95660dc132 Merge pull request #319 from vangel76/fix/excel-shortcuts
Keyboard: Excel shortcut audit, add the missing ones (#110)

# Conflicts:
#	docs/ui-parity.md
2026-10-11 12:06:40 -04:00
Brandon Thomas 925ff53122 Merge pull request #303 from vangel76/fix/chart-category-axis
Charts: Select Data edits the category axis labels; blank corner makes column 1 the categories (#287)

# Conflicts:
#	crates/engine/src/tests.rs
#	crates/ui-egui/src/dialogs.rs
#	crates/ui-egui/tests/interaction.rs
#	docs/chart-parity.md
2026-10-11 12:06:39 -04:00
Brandon Thomas fe9e3163f0 Merge pull request #301 from vangel76/fix/recommended-charts
Charts: Recommended Charts opens a dialog of chart types with previews (#215)

# Conflicts:
#	crates/engine/src/tests.rs
#	crates/ui-egui/tests/interaction.rs
#	docs/chart-parity.md
2026-10-11 12:06:37 -04:00
Brandon Thomas 867c5fd1f1 Merge pull request #317 from vangel76/feat/forecast-ets
Functions: FORECAST.ETS, .CONFINT, .SEASONALITY and .STAT (#314)

# Conflicts:
#	README.md
#	ROADMAP.md
#	docs/function-parity.md
#	docs/gaps.md
2026-10-11 12:05:55 -04:00
Brandon Thomas 97bad77ef4 Merge pull request #313 from vangel76/feat/pivot-chart
Charts: PivotCharts (insert.pivotChart) (#311)

# Conflicts:
#	ROADMAP.md
#	crates/engine/src/cmd/pivot.rs
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-11 12:05:54 -04:00
Brandon Thomas 685802ee9f Merge pull request #306 from vangel76/feat/pivot-calculated-field
PivotTables: calculated fields (pivot.calculatedField) (#304)

# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-11 12:05:52 -04:00
Brandon Thomas 2af0984af0 Merge pull request #308 from vangel76/feat/review-allow-edit-ranges
Review: Allow Edit Ranges with Excel-compatible password hashes (#307)

# Conflicts:
#	ROADMAP.md
#	crates/xlsx/src/sheet_write.rs
#	crates/xlsx/src/tests/malformed.rs
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/target-app-parity.md
2026-10-11 12:05:30 -04:00
Brandon Thomas 4dce1181e1 Merge pull request #305 from vangel76/feat/cell-checkbox
Checkboxes: ribbon button, Excel's value and Delete rules, XLSX cell controls (#196)

# Conflicts:
#	ROADMAP.md
2026-10-11 12:05:28 -04:00
Brandon Thomas 1f99931dd3 Merge pull request #302 from vangel76/feat/xlsx-threaded-comments
XLSX: write threaded comments and persons parts, read note visibility (#300)

# Conflicts:
#	ROADMAP.md
#	crates/xlsx/src/tests/roundtrip.rs
2026-10-11 12:05:27 -04:00
Brandon Thomas 1302ec76a4 Merge pull request #310 from vangel76/fix/sheet-right-to-left
Grid: mirror right-to-left sheets (#146)

# Conflicts:
#	crates/ui-egui/src/grid.rs
#	docs/localization-parity.md
2026-10-11 12:05:25 -04:00
Brandon Thomas cf1ba2071f Merge pull request #309 from vangel76/feat/drag-freeze-lines
Grid: freeze panes by dragging the freeze handles (#195)

# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/i18n.rs
#	crates/ui-egui/src/i18n/ko.rs
#	crates/ui-egui/src/i18n/pt.rs
#	crates/ui-egui/src/i18n/ru.rs
#	crates/ui-egui/src/i18n/zh.rs
2026-10-11 12:04:51 -04:00
Brandon Thomas d274eb6dac Merge pull request #318 from vangel76/fix/theme-toggle
UI: title-bar light/dark switch, File › Display theme, system appearance on first run (#194, #239)

# Conflicts:
#	docs/ui-parity.md
2026-10-11 12:04:50 -04:00
Brandon Thomas 2f032392f3 Merge pull request #323 from vangel76/fix/macos-title-bar
macOS: centre the window buttons in the title bar (#170)

# Conflicts:
#	crates/ui-egui/src/ribbon.rs
2026-10-11 12:04:49 -04:00
Brandon Thomas 3657b2bc9b Merge pull request #321 from vangel76/fix/xlsb-ods-open-with
Packaging: offer GridCraft for .xlsb and .ods files (#92)
2026-10-11 12:04:20 -04:00
Brandon Thomas 17c6e46dcd Merge pull request #315 from vangel76/fix/windows-default-renderer
Windows: never load Vulkan by default; OpenGL fallback when DirectX 12 can't start (#120)
2026-10-11 12:04:19 -04:00
Brandon Thomas e5d0074f95 Merge pull request #316 from vangel76/fix/macos-quit-crash
macOS: end the process in on_exit so quitting doesn't crash (#117)
2026-10-11 12:04:18 -04:00
Brandon Thomas 2dbf6d43cf Merge pull request #352 from Fly-Style/fix/memory-alloc-on-agg
Get rid of double range copy for aggregation operations over ranges

# Conflicts:
#	crates/calc/src/tests.rs
2026-10-11 12:04:16 -04:00
Brandon Thomas f8903c9e98 Merge pull request #353 from LloydNicholson/fix/copy-multiple-ranges
Issue #348: copying multiple selections works when the areas line up, and explains when it can't

# Conflicts:
#	crates/engine/src/tests.rs
#	crates/ui-egui/tests/clipboard.rs
2026-10-11 12:04:15 -04:00
Brandon Thomas 9da7acf846 Merge pull request #350 from LloydNicholson/fix/multi-select-resize
Issue #341: resizing Ctrl-selected rows or columns resizes all of them

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-11 12:04:14 -04:00
Brandon Thomas 19b0dc6e97 Merge pull request #351 from LloydNicholson/fix/protect-password-mask
Issue #347: Protect Sheet and Unprotect Sheet mask the password
2026-10-11 12:04:13 -04:00
Brandon Thomas ea3e0ce0c5 Merge pull request #355 from LloydNicholson/fix/journal-redact-passwords
Journal: sheet protection passwords aren't recorded in plain text

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-11 12:04:12 -04:00
Brandon Thomas 684bc41d03 Merge remote-tracking branch 'origin/main' into land 2026-10-11 12:02:56 -04:00
Brandon ThomasandClaude Opus 5.5 5f3e60b48a Docs: headline counts after the community merges (509 / 523 functions, 500 working; catalog 260 / 290)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:02:26 -04:00
Brandon ThomasandClaude Opus 5.5 2f6c2cd486 Fix-up: Spanish and German strings for Interface size (#294 met #242/#271); rustfmt after merges
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:59:24 -04:00
Dylan M. Taylor dfa15c3f25 ci: refactor workflows to use storytold/craft-common-actions (#336)
* ci: refactor workflows to use reusable artcraft-common-actions

* ci: point reusable workflows to storytold/craft-common-actions

* ci: pin storytold/craft-common-actions to commit 27a978f and pass secrets explicitly

* ci: use @main (unpinned) for craft-common-actions with explanation comment
2026-10-11 11:54:22 -04:00
Brandon Thomas 4f7144d753 Merge pull request #295 from vangel76/feat/view-formula-bar-zoom100
View: Formula Bar and Zoom 100% as engine commands (#289)

# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/control.rs
#	crates/ui-egui/src/lib.rs
#	docs/target-app-parity.md
2026-10-11 11:45:32 -04:00
Brandon Thomas 8f3d13a115 Merge pull request #294 from vangel76/fix/interface-scale
View: Interface size preference scales the whole window (#230)

# Conflicts:
#	ROADMAP.md
2026-10-11 11:45:01 -04:00
Brandon Thomas 505d001ad4 Merge pull request #293 from vangel76/fix/name-manager-new
Name Manager: New… and Edit… open the name dialog and return to the manager (#238)

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-11 11:45:00 -04:00
Brandon Thomas fb9266f479 Merge pull request #271 from arekown/german-translation
Add German (de) interface language

# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/i18n.rs
2026-10-11 11:44:58 -04:00
Brandon Thomas ea0e971e27 Merge pull request #228 from webdevtodayjason/fix/200-formula-helpers
Keep formula helpers inside the worksheet when scrolling (#200)

# Conflicts:
#	contributors/people.toml
#	docs/ui-parity.md
2026-10-11 11:44:56 -04:00
Brandon Thomas a1f97c2f06 Merge pull request #218 from MarekSpodBiedry/issue-190
Resize charts from the corner handle and the Size fields, keep typed chart and table names (#190)
2026-10-11 11:44:55 -04:00
Brandon Thomas 0a65ffc31a Merge pull request #219 from Zarvinx/fix-keyboard-chart-delete
Delete selected charts with the keyboard

# Conflicts:
#	ROADMAP.md
2026-10-11 11:44:53 -04:00
Brandon Thomas ad8aeca851 Merge pull request #217 from MarekSpodBiedry/issue-198
Do not draw the selection over the frozen pane when it lies only in the scrolling pane (#198)
2026-10-11 11:44:51 -04:00
Brandon Thomas 90dcc2b329 Merge pull request #297 from vangel76/feat/trimrange
Functions: TRIMRANGE (#296)

# Conflicts:
#	README.md
#	ROADMAP.md
#	crates/xlsx/src/tables.rs
#	docs/function-parity.md
#	docs/gaps.md
#	docs/target-app-parity.md
2026-10-11 11:44:50 -04:00
Brandon Thomas c2c381d55d Merge pull request #292 from vangel76/feat/bahttext
Functions: BAHTTEXT (#291)

# Conflicts:
#	README.md
#	ROADMAP.md
#	docs/function-parity.md
#	docs/gaps.md
#	docs/target-app-parity.md
2026-10-11 11:44:48 -04:00
Brandon Thomas fa4d2e5741 Merge pull request #280 from vangel76/feat/percentof-euroconvert
Functions: PERCENTOF and EUROCONVERT (#279)

# Conflicts:
#	README.md
#	ROADMAP.md
#	crates/functions/src/financial.rs
#	docs/function-parity.md
#	docs/gaps.md
#	docs/target-app-parity.md
2026-10-11 11:44:46 -04:00
LosminekandClaude Opus 5.5 dd8016225d Merge origin/main into cs-pr
The only conflict was contributors/people.toml: other contributors appended
their entries at the end of the file in the meantime. All entries kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 17:44:24 +02:00
Brandon Thomas f91f7bc154 Merge pull request #276 from vangel76/feat/odd-bond-functions
Functions: ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD (#275)

# Conflicts:
#	ROADMAP.md
2026-10-11 11:43:49 -04:00
Brandon Thomas 59deadc4c3 Merge pull request #285 from vangel76/fix/currency-paste
Clipboard: pasted currency cells keep the number from the clipboard HTML (#257)
2026-10-11 11:43:48 -04:00
Brandon Thomas 96703b79d4 Merge pull request #278 from vangel76/fix/fill-handle-ctrl-series
Fill handle: Ctrl+drag swaps copying and extending a series (#264)

# Conflicts:
#	ROADMAP.md
2026-10-11 11:43:47 -04:00
Brandon Thomas 4ea12e967b Merge pull request #242 from diegozpy/i18n/es-interfaz
i18n: Spanish interface translation (the Español option only localized formulas)
2026-10-11 11:42:40 -04:00
Brandon Thomas f6628954fc Merge pull request #263 from alexanderalber/fix/201-filter-header-row
AutoFilter: a selected header row filters the data below it; search box in the filter menu (#201)
2026-10-11 11:42:38 -04:00
Brandon Thomas 3b0da1d760 Merge pull request #254 from nihilist-narwhal/fix-typed-dates-and-times
Typed dates before 1900 stay text; typed times past 24 hours keep their hours
2026-10-11 11:42:37 -04:00
Brandon Thomas 77e6a4a46d Merge pull request #251 from nihilist-narwhal/fix-conditional-format-layers
Conditional formatting: apply every matching rule; Cell Value rules as in Excel
2026-10-11 11:42:36 -04:00
Brandon Thomas 47dcd84e04 Merge pull request #282 from vangel76/fix/name-box-enter
UI: Name Box Enter goes to the typed cell, not the one below (#247)
2026-10-11 11:24:39 -04:00
Brandon Thomas 331a535d3c Merge pull request #277 from vangel76/fix/linux-font-panic
UI: skip system fonts egui can't parse instead of panicking at startup (#226)
2026-10-11 11:24:38 -04:00
Brandon Thomas c97f025459 Merge pull request #248 from MacJedi42/fix/excel-15-digit-display
Accuracy: round an exact tie at the 16th significant digit toward zero
2026-10-11 11:24:37 -04:00
Brandon Thomas 85f0320f5c Merge pull request #267 from alexanderalber/fix/64-write-at-as-single
XLSX: write `@` as `_xlfn.SINGLE` in a dynamic-array formula (#64)

# Conflicts:
#	crates/xlsx/src/tests/roundtrip.rs
2026-10-11 11:24:36 -04:00
Brandon Thomas 1eb7796724 Merge pull request #262 from alexanderalber/fix/235-icon-set-cfvo
XLSX: write one cfvo per icon in icon-set rules (#235)

# Conflicts:
#	contributors/people.toml
2026-10-11 11:24:22 -04:00
Brandon Thomas aa7c97adb9 Merge pull request #255 from nihilist-narwhal/fix-sort-and-duplicates
Sort and Remove Duplicates: compare text the way Excel does
2026-10-11 11:24:00 -04:00
Brandon Thomas d059a5b5a4 Merge pull request #252 from nihilist-narwhal/fix-choose-array-index
CHOOSE: pick element by element when the index is an array
2026-10-11 11:23:59 -04:00
Brandon Thomas 46cd4d7b72 Merge pull request #250 from nihilist-narwhal/fix-criteria-blank-cells
Criteria: text patterns don't match blank cells
2026-10-11 11:23:58 -04:00
Brandon Thomas 711339e2ef Merge pull request #253 from MacJedi42/contributors/add-macjedi42
Add MacJedi42 to the contributor names

# Conflicts:
#	contributors/people.toml
2026-10-11 11:23:52 -04:00
Brandon Thomas 45819abd09 Merge pull request #274 from vangel76/contributors-vangel76
Add vangel76 to the contributor names
2026-10-11 11:23:33 -04:00
Brandon Thomas e1939aac68 Merge pull request #272 from ttrudging/fix/paste-deadlock
Fix Paste button deadlock in ribbon
2026-10-11 11:23:32 -04:00
Brandon Thomas 2559426c60 Merge pull request #222 from Zarvinx/fix/macos-icon-size
macOS: use the correctly padded Dock icon
2026-10-11 11:23:31 -04:00
Brandon Thomas 96af804cb5 Merge pull request #223 from Dejan-Port/fix-web-edit-loss
fix: Save toolbar button and saveChanges dialog discard an in-progress cell edit
2026-10-11 11:23:30 -04:00
Brandon Thomas 1cd3d4af5d Merge pull request #231 from pkibiego/security/quick-xml-0.41
XLSX: bump quick-xml 0.38 -> 0.41 (RUSTSEC-2026-0195 namespace-declaration DoS)
2026-10-11 11:23:29 -04:00
Brandon Thomas f7c40e3d7e Merge pull request #232 from webdevtodayjason/fix/selection-move-overflow
selection.move: clamp extreme dr/dc to the sheet edge instead of overflowing
2026-10-11 11:23:28 -04:00
lloydandClaude Opus 5.5 c1a500c5b9 Journal: leave sheet protection passwords out
Protect Sheet and Unprotect Sheet were journaled with their `password`
param, so the password showed in plain text in the journal dialog and
`engine.journal`, and a recorded script (Automate > Record Actions)
saved it in the workbook's hidden `_sc_scripts` name.

Session::execute now journals the params without secret ones
(`password`, or a name ending in `Password`). A replayed entry runs
without that param: Protect Sheet protects with the same options but no
password, and the matching Unprotect Sheet still succeeds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 17:17:30 +02:00
lloydandClaude Opus 5.5 d665499055 Clipboard: copy lined-up multiple selections; say why others can't be copied (#348)
Copying a multi-area selection always failed in the engine, and the UI
dropped the error, so Ctrl+C did nothing and Ctrl+V had nothing to
paste. Now, as in Excel:

- Areas that cover the same rows (or the same columns) and don't
  overlap are copied as one block, slid together left to right (top to
  bottom). The clipboard keeps a snapshot with the block packed at the
  first area's place; formulas travel as their values, and column
  widths or row heights, comments, pictures and merges come along.
- Other layouts, Cut of several areas and Paste Link of a multi-area
  copy are refused with "This action won't work on multiple
  selections."; Copy and Cut from the keyboard, ribbon and context menus
  now show that message instead of failing silently.
- The marching ants go around each copied area.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 17:02:39 +02:00
lloydandClaude Opus 5.5 a8eb09604d Review: mask the Protect / Unprotect Sheet password (#347)
The password fields in Protect Sheet and Unprotect Sheet were plain
text fields, so the password was readable on screen and in the
accessibility tree. A new Password form field masks it as typed and adds
a "Show password" check box that reveals it on purpose (off each time
the dialog opens).

These are the only password fields in the UI: Protect Workbook runs
without a dialog and encrypted files are refused on open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:55:13 +02:00
Sasha Syrotenko f7f7769460 Fold 'SUM', 'COUNT' and 'AVERAGE' over ranges in place 2026-10-11 17:50:30 +03:00
lloydandClaude Opus 5.5 206d837639 Grid: header drags resize every Ctrl-selected row or column (#341)
Dragging a header boundary inside a selection of whole columns (rows)
sized only the current area, so with B, D and F Ctrl-selected only the
last-selected one changed. The drag now targets every whole-column
(whole-row) area of the selection, as Excel does; lines outside the
selection, and partial-cell areas, keep their size.

home.columnWidth / home.rowHeight accept a comma-separated list of
areas ("B:B,D:F") so the drag stays one command and one undo step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:48:43 +02:00
LosminekandClaude Opus 5.5 a9e743ee6d contributors: add my own people.toml entry
Own entry only, as AGENTS.md describes: credited by the name on my public
GitHub profile (sync_github_name), otherwise by @username.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:47:13 +02:00
LosminekandClaude Opus 5.5 5f346dc3cc i18n (cs): terminology review fixes
An independent review of the table found two meaning errors:
"Enter" is both the status-bar mode and the tooltip of the confirm
button next to the formula bar, so "Zadat" fits both places better
than "Zadavani"; "Convert to Range" uses "oblast" (as "Oblast tisku"
does), not "rozsah".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:47:02 +02:00
LosminekandClaude Opus 5.5 509afaf4cf docs: list Czech (cs) in the localization status
Czech joins Russian under "other shipped languages" in ROADMAP.md and
docs/localization-parity.md: 266 ribbon labels (~12%), menus only,
formulas still en-US. Timestamp lines and revision history updated.
Kept separate from the catalog so it can be dropped if the docs are
refreshed upstream.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:36:55 +02:00
LosminekandClaude Opus 5.5 f44b31e154 i18n: cover Czech in the interface-language tests
- The catalog-completeness test requires a non-empty Czech label for
  every key of the reference (Japanese) table.
- Czech context keys: `Page Layout|Orientation` and `Orientation` get
  different labels; unknown text such as `Sheet1!A1` passes through.
- `cs-CZ` / `cs_CZ.UTF-8` system tags and `parse("cs")` resolve to Czech.
- The ribbon renders after switching to Czech, and the choice persists
  in UiState.
- Czech keeps canonical formula entry (`=SUM(1.5,2.25)`), and `=SUMA(1;2)`
  is not accepted.
- The UI font draws every Czech accented letter, upper and lower case,
  without tofu; Czech shares the default Han font order.

Czech spells "Data" as English does, so the Czech checks probe
"Formulas" -> "Vzorce", where an English fallback would be caught.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:36:33 +02:00
LosminekandClaude Opus 5.5 c8ce333a74 i18n: Czech interface language (cs)
Add a Czech table with all 266 interface labels (the same key set as
Korean, Russian, Simplified Chinese and Brazilian Portuguese) and
register `cs` in Language: name "Čeština", code `cs`, system tags
`cs-*` / `cs_*`, appended to the end of the switcher. The language
command help, its error text and the snapshot example usage list `cs`.

Like the other ribbon tables, it covers the ribbon, sheet tabs and
widgets; dialogs, menus and messages stay English. Formulas stay
canonical English: Czech uses the English formula locale like every
non-Spanish language.

Translated from the meaning of each English label (clean-room, not from
another product's localization), with AI assistance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:35:04 +02:00
vangel76andClaude Opus 5.5 001f025119 View: Page Layout view with rulers and in-place headers and footers (#329)
View › Page Layout (and the status-bar button) now shows the sheet as printed
pages on a desk instead of overlaying page outlines on the grid.

- Model/XLSX: per-sheet view mode (normal / pageLayout / pageBreakPreview),
  saved as <sheetView view="…"> and read back. view.* commands set it per
  sheet ({sheet?}) without an undo step or dirtying a clean workbook.
- Engine: paper::PageGrid paginates the sheet from A1 with the print
  pagination (print::split_bands, shared with PDF export and printing) and
  maps cells to pages and back; header/footer section helpers
  (split/join, &[Page] field names) shared with the PDF header code.
  pageLayout.headerFooter takes {part, section, text} for one section and a
  sheet; header/footer strings are capped at 255 characters.
  view.ruler toggles the rulers.
- UI: Geo carries the page grid, so painting, hit-testing, selection,
  editing, objects and scrolling work through the page transform; frozen
  panes are ignored in this view. Pages with margins and gaps, "Click to add
  data" pages, rulers in inches (English) or centimetres, headers/footers
  drawn on printed pages, click a margin section to edit it in place; a
  click elsewhere commits (one undo step), Escape cancels. Header & Footer
  contextual tab: presets, Page Number, Number of Pages, Current Date/Time,
  File Path, File Name, Sheet Name, Go to Header/Footer. View › Ruler.
- New strings in every catalog; new code-drawn icons; desk colour token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:24:06 +02:00
vangel76andClaude Opus 5.5 ed62390244 XLSX: keep unmodelled parts on save (#330)
Pass-through of package content GridCraft does not model: on read the raw
parts are kept with their content types and relationship graph per owner
(package root, workbook, sheet); on write they get fresh part names where
needed and new relationship ids, and the r:ids in kept XML are rewritten.

Kept: custom document properties, ribbon customisation, add-in task panes,
custom XML, links to external workbooks with <externalReferences> (never
followed), connections, sheet query tables, printer settings with the
<pageSetup r:id> (#324), form and ActiveX controls, OLE objects and sheet
backgrounds with their VML shapes (merged with GridCraft's note shapes).
Content whose graph reaches parts GridCraft rewrites is dropped with a
warning; sheet content goes with its sheet and is not copied by Copy Sheet.

Fixes #324

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:12:56 +02:00
vangel76andClaude Opus 5.5 bd5c5c1d26 XLSX/IO: read legacy .xls (BIFF8) workbooks (#121)
Clean-room import of Excel 97-2003 workbooks from the public [MS-CFB] and
[MS-XLS] specifications: compound-file streams (FAT, mini FAT, directory
tree), the BIFF8 Workbook stream with Continue records, shared strings,
all cell records, formulas decoded from Ptg tokens (shared and array
formulas, 3-D refs, names, add-in/newer functions by name) with cached
results, number formats, the 1904 date system, merges, column widths, row
heights, defined names and print areas/titles. Encrypted (FILEPASS) and
BIFF5 files are refused with a clear message; everything else is skipped
with a warning. .xls opens as a new unsaved workbook (Save As .xlsx).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:09:27 +02:00
vangel76andClaude Opus 5.5 b4d823902a UI: File tab Backstage view (#174)
Clicking the File tab now opens a full-window Backstage view in place of the
ribbon, formula bar, grid and sheet tabs, like Excel's. Esc or the back arrow
return to the sheet. Pages: Home (new + recent), New (blank + samples), Open
(recent + Browse), Info (location, properties, Protect Workbook), Save, Save As,
Print (page preview, scope, fit to page, Page Setup), Export (PDF, CSV, web
page), Close and Options (theme, language, formula bar, AutoSave, calculation).
Every action runs an existing command or dialog.

Adds `file.options` (reports the workbook's calculation settings and asks the
interface for the Options page) and the UI command `ui.backstage {page}`.
Keyboard shortcuts and the macOS native menu are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 13:03:11 +02:00
vangel76andClaude Opus 5.5 dc75b2cf5e Data: Solver with Simplex LP, integer branch and bound and a nonlinear method (#326)
data.solver maximises, minimises or targets a value in an objective cell by
changing variable cells under <=, >=, =, int and bin constraints. Simplex LP
linearises the model through recalculation, checks linearity and solves it
with a two-phase simplex; integers use branch and bound. The GRG Nonlinear
choice runs an augmented-Lagrangian projected-gradient method. The model is
saved as hidden solver_* names; Solver Parameters and Solver Results dialogs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:56:36 +02:00
vangel76andClaude Opus 5.5 c2d2f22e6a Data: Forecast Sheet (data.forecastSheet) (#322)
New sheet before the active one with the sorted history, a FORECAST.ETS
forecast column, FORECAST.ETS.CONFINT lower/upper bounds, an optional
FORECAST.ETS.STAT table, an Excel table over the data and a line or column
chart. Parameters: timeline/values (default: the selection's first two
columns), end or periods, confidence interval, seasonality, missing-point
fill, duplicate aggregation, statistics, chart kind. Data ribbon button
opens a form dialog; programmatic calls never do. gridcraft-functions
exports Timeline to continue a timeline (numeric step or calendar months).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:54:30 +02:00
vangel76andClaude Opus 5.5 46873b2826 macOS: centre the window buttons in the title bar (#170)
AppKit draws the traffic lights centred in its standard 28 pt title-bar
band, but GridCraft's title bar was 38 pt tall, so the lights sat above
its centre line. On macOS the title bar is now 28 pt with 22 pt controls,
and content starts after the lights with the same gap they keep from the
top. Other platforms are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:47:10 +02:00
vangel76andClaude Opus 5.5 d5f007dffb Packaging: offer GridCraft for .xlsb and .ods files (#92)
GridCraft imports XLSB (#101) and ODS (#100) files, but the Linux desktop
entry, shared-mime-info file and AppStream metadata, and the Windows
"Open with" list only named .xlsx, .xlsm, .csv and .tsv. Add the two
import formats there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:45:24 +02:00
vangel76andClaude Opus 5.5 0dfd29efde Data: Analysis ToolPak with 13 tools and the Data Analysis dialog (#312)
data.analysisToolPak runs Descriptive Statistics, Histogram, Correlation,
Covariance, Regression, Moving Average, Exponential Smoothing, Rank and
Percentile, the three t-Tests, F-Test and Anova: Single Factor, writing a
static report to an output range or a new sheet. Non-empty output cells are
refused unless overwrite is set; the dialog asks instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:44:47 +02:00
vangel76andClaude Opus 5.5 76c620fc32 Keyboard: Excel shortcut audit, add the missing ones (#110)
Audited the grid, ribbon and editor key handling against Microsoft's
published Windows and Mac shortcut lists. New keymap.rs binds the ones
whose feature already exists: Ctrl+Shift+~!@#$%^&_ number formats and
borders, Ctrl+2-5, Ctrl+Shift+: time, Ctrl+' / Ctrl+Shift+" from the cell
above, Ctrl+L, Ctrl+Shift+L, Ctrl+P, Ctrl+Alt+V, Alt+=, Alt+Down,
Alt+Page Down/Up, Ctrl+Shift+Home/End, Shift+Home, the F-key family
(Shift+F2/F3/F9/F10/F11, F5, F7, F12, Ctrl+F1/F3/F4, Alt+F1, Ctrl+Alt+F9)
and the Excel for Mac variants (Cmd+L/E alignment, Control+E Flash Fill,
Cmd+Option borders, Cmd+Shift+K/J/H/R). Number-format keys match the
physical key; AltGr text never triggers a Ctrl+Alt shortcut. Fixes the
command catalog's wrong shortcut labels and documents the audit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:43:51 +02:00
vangel76andClaude Opus 5.5 838304accf UI: title-bar light/dark switch, File › Display theme, system appearance on first run (#194, #239)
The theme could only be chosen in the View tab's Display theme box, and
the app always started light. Now:
- a title-bar button switches light/dark in one click (view.darkMode);
  right-click offers System / Light / Dark;
- File › Display theme offers the same three (Excel keeps it under
  File › Account › Office Theme);
- the desktop app follows the system appearance until a theme is chosen
  and saved in ui.json (UiState's default stays light for tests).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:43:47 +02:00
vangel76andClaude Opus 5.5 a1dc03a484 Functions: FORECAST.ETS, .CONFINT, .SEASONALITY and .STAT (#314)
AAA exponential smoothing (Hyndman et al. 2008, ETS(A,A,A)) over an evenly
spaced timeline: documented seasonality, data completion and aggregation
arguments, calendar-month date timelines, autocorrelation seasonality
detection, state-space prediction intervals, statistic types 1-8.
Smoothing parameters minimise the in-sample SSE (grid + clamped
Nelder-Mead). XLSX export treats the family's range arguments as
array-taking (no spurious dynamic-array metadata), FORECAST/FORECAST.LINEAR
included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:42:52 +02:00
vangel76andClaude Opus 5.5 c1d293296c macOS: end the process in on_exit so quitting doesn't crash (#117)
AccessKit's macOS adapter subclasses the window's content view and
restores its class when the window is torn down; AppKit's Touch Bar
support observes that view via KVO, so the next display cycle throws in
-[_NSTouchBarFinderObservation invalidate] and the quit ends in a crash
report. On macOS, on_exit now exits right after saving the preferences,
before eframe drops the window (what eframe itself does without
run_and_return). Same fix as storytold/vectorcraft#670.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:38:19 +02:00
vangel76andClaude Opus 5.5 da99015b11 Windows: never load Vulkan by default; OpenGL fallback when DirectX 12 can't start (#120)
Enumerating Vulkan adapters crashes inside Intel's igvk64.dll on some UHD
Graphics drivers, before any Rust error handling runs. Since #22 the
Windows instance is DirectX 12 only; this keeps Vulkan out of every
default path and adds two fallbacks so DX12-only can't leave a PC without
a window:

- A DirectX 12 probe before eframe starts: no hardware adapter that meets
  eframe's limits -> OpenGL (plus DX12/WARP as last resort when WARP is
  all DX12 offers).
- If run_native fails with a wgpu error before the app was created, start
  once more with the other of DX12/GL (eframe reuses its event loop).

WGPU_BACKEND still overrides everything, and nothing else is tried then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:36:52 +02:00
vangel76andClaude Opus 5.5 1a7c16eb9a Charts: PivotCharts (insert.pivotChart) (#311)
A chart linked to a PivotTable: series are built from the report
(innermost row items x column items/value fields, totals excluded) and
rebuilt on every refresh or layout change; c:pivotSource round trip;
chart series accept union references.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:31:49 +02:00
vangel76andClaude Opus 5.5 2d8c29dad2 Grid: mirror right-to-left sheets (#146)
Sheet Right-to-Left (view.rightToLeft, XLSX rightToLeft) was stored and
round-tripped but never rendered. The grid now lays out in logical
left-to-right coordinates and mirrors on screen: painted shapes are
reflected (text and pictures only moved), floating objects move as a
whole, pointer input is mirrored back for hit-testing, Left/Right arrows
follow the screen, and the cell editor, text box editor, popups and the
vertical scrollbar are placed on the mirrored side. Page Layout gets a
Sheet Right-to-Left button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:30:25 +02:00
vangel76andClaude Opus 5.5 33f10d0e6e Grid: freeze panes by dragging the freeze handles (#195)
Like Excel for the web, a bar in the upper part of the column-header strip
and one in the left part of the row-header strip sit on the frozen panes'
edges (the corner's edges when nothing is frozen). Dragging one previews
the line and, on release, freezes up to the nearest column or row boundary
through view.freezePanes; dragging back to the corner unfreezes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:28:02 +02:00
vangel76andClaude Opus 5.5 3b918ada2c Review: Allow Edit Ranges with Excel-compatible password hashes (#307)
- Model: Sheet.edit_ranges (title, ranges, optional password hash,
  security descriptor) and gridcraft_model::password: the ECMA-376 legacy
  16-bit hash and the salted, iterated SHA-2 hash (SHA-512/384/256; other
  algorithms, damaged hashes and spin counts over 10,000,000 are refused).
  New passwords use SHA-512, spin count 100000. Adds the sha2 crate.
- XLSX: <protectedRanges> read and written; an unreadable password keeps
  the range locked.
- review.allowEditRanges {action: list|add|modify|delete|unlock, ...}: empty
  params list; ranges can't change while the sheet is protected; unlock
  verifies the password for the session. Not journaled (passwords).
- Locked-cell checks (commit guard, cell.set, picture in cell) let edits
  through in open or unlocked ranges; ranges move with structural edits.
- Ribbon button and a form dialog (menu invocation only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:26:14 +02:00
vangel76andClaude Opus 5.5 400ab591cb PivotTables: calculated fields (pivot.calculatedField) (#304)
A value field can be a calculated field whose formula is evaluated on
the sums of the fields it names for each report cell (Excel's documented
semantics). Command to add/change/delete, dialog from the field pane,
XLSX cacheField formula round trip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:24:50 +02:00
vangel76andClaude Opus 5.5 ce411edc91 Checkboxes: ribbon button, Excel's value and Delete rules, XLSX cell controls (#196)
insert.checkbox existed but had no ribbon button, replaced existing values
with FALSE and was written to XLSX as an invalid number format. Now:
Insert > Checkbox (Cell Controls); empty cells start FALSE, other values
stay and display as General; toggling an emptied box checks it and only
checkbox cells toggle; Delete unchecks first, then removes the boxes; XLSX
reads and writes the checkbox as Excel's feature-property-bag cell control
([MS-XLSX] 2.1.22, 2.3.9, 2.4.99).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:24:25 +02:00
vangel76andClaude Opus 5.5 9262fba5ce Charts: Select Data edits the category axis labels; blank corner makes column 1 the categories (#287)
A line chart from numeric X values (years) plotted them as a series and
there was no way to set the axis labels. Now:
- a blank top-left cell over a header row makes the first column the
  category labels even when it holds numbers (the usual convention);
- chart.selectData takes categories (Horizontal (Category) Axis Labels,
  "" clears) and removeSeries, and range is optional;
- Chart Design gets a Select Data button opening a Select Data Source
  dialog: chart data range, legend entries with Remove, axis labels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:20:29 +02:00
vangel76andClaude Opus 5.5 8e5b1ac8e3 XLSX: write threaded comments and persons parts, read note visibility (#300)
- Writer: one xl/threadedComments/threadedCommentN.xml per sheet with
  comments (thread, replies via parentId, done for resolved, dT when known)
  and xl/persons/person.xml (one person per author), with the [MS-XLSX]
  relationship and content types. Each thread keeps its legacy note, linked
  by the tc={id} author and xr:uid; its body is the text plus replies.
  Ids are GUID-shaped and deterministic.
- Reader: keeps dT timestamps (Comment.dates, JSON-compatible), drops
  replies whose thread is missing, and reads note visibility from the VML
  <x:Visible/> (best effort, broken VML skipped silently).
- Invalid dates are never written. Round-trip and hostile-input tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:15:45 +02:00
vangel76andClaude Opus 5.5 f58b1234fb Charts: Recommended Charts opens a dialog of chart types with previews (#215)
The ribbon button inserted a column chart straight away. It now opens an
Insert Chart dialog: a Recommended tab (insert.chartRecommendations, a
heuristic over the data's shape: series, points, labels, negatives) and an
All Charts tab, each with a live preview of the chart for the selection.
OK inserts the chosen type and selects the chart.

insert.recommendedCharts stays dialog-free for programmatic calls: without
a type it inserts the first recommendation; type/subtype pick one.
insert_chart is split into build_chart (also used for previews).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:15:12 +02:00
vangel76andClaude Opus 5.5 022aba41a8 UI fonts: symbol fallback faces so interface symbols aren't boxes (#197)
UI fonts such as Noto Sans, Cantarell and egui's built-in Ubuntu lack some
of the symbols the interface draws as text (▸ ⌃ ✓ ✕ ▲ ▼ arrows), so they
rendered as empty boxes. Two symbol faces now sit at the end of every font
chain: DejaVu Sans (Debian, Fedora and Arch paths; Segoe UI Symbol on
Windows, Apple Symbols on macOS) and Noto Sans Symbols 2. The UI font
candidates also gain Fedora's package folders (#54).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:14:16 +02:00
vangel76andClaude Opus 5.5 52921512c7 Functions: TRIMRANGE (#296)
Evaluator special form returning the range (or array) without its blank
outer rows and columns; trim codes 0-3 as documented; written as
_xlfn.TRIMRANGE. The trim-reference operators are not parsed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:11:25 +02:00
vangel76andClaude Opus 5.5 be028cc6cc View: Formula Bar and Zoom 100% as engine commands (#289)
- view.zoom100 sets the active sheet's zoom to 100% (the ribbon's 100%
  button runs it).
- view.formulaBar {on?} toggles a formulaBar preference (Prefs, saved in
  prefs.json on desktop; an application option, not in the file). The UI
  shows the formula bar from it; the ribbon checkbox, native menu and
  ui.set {formulaBar} go through the command.
- The UI-only interceptions and their entries in engine.commands are gone,
  so the CLI and MCP can run both. Parity checklist regenerated (260 / 290).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:09:30 +02:00
vangel76andClaude Opus 5.5 14ad23044a View: Interface size preference scales the whole window (#230)
UiState gains interfaceScale (percent, 100 = Auto, 75–200), saved in
ui.json and applied as egui's zoom factor on top of the desktop scale.
New UI command view.interfaceScale {percent | "auto"} clamps hostile
values; a malformed saved value reads as 100. View tab gets an
"Interface size" picker. egui's built-in keyboard zoom is turned off so the
preference owns the zoom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:09:29 +02:00
vangel76andClaude Opus 5.5 a11446f2f0 Name Manager: New… and Edit… open the name dialog and return to the manager (#238)
dialogs::show put the Name Manager back into app.dialog after its body
had opened the New Name dialog, so New… did nothing. A dialog opened from
another one now takes over and the opener waits behind it (back), coming
back when the child closes; Go To still hands over to Go To Special.

The Name Manager gets Excel's New…/Edit…/Delete buttons over a selectable
list. formulas.defineName takes oldName/oldScope to edit a name in place;
a renamed name is renamed in cell formulas and other names' definitions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:09:19 +02:00
vangel76andClaude Opus 5.5 35d6c23fd1 Functions: BAHTTEXT (#291)
Thai number words with บาท / สตางค์ / ถ้วน, rounded to satang, ล้าน
repeating per six digits, ลบ for negatives.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:07:41 +02:00
vangel76andClaude Opus 5.5 33afc7d3a5 Clipboard: Insert Copied Cells and Insert Cut Cells (#21)
New command home.insertCopiedCells: makes room at the active cell and
pastes the clipboard there, as one undo step. Whole copied rows or columns
insert whole rows or columns; a copied block shifts the cells down or right
(Insert Paste dialog from the menu). A cut of whole rows or columns moves
them and closes the gap (Insert Cut Cells). The cell and header context
menus show the entry while the clipboard holds a copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:04:52 +02:00
vangel76andClaude Opus 5.5 6f47a8b463 Review: Previous/Next Comment, Show Comments, Show All Notes, Convert to Comments (#281)
- review.previousComment / review.nextComment select the previous/next
  threaded comment in reading order (row by row), across visible sheets in
  tab order, wrapping around; disabled when the workbook has no comments.
- review.showComments {on?} toggles the Comments pane as session state, so
  the CLI, MCP and control channel can drive it; the UI pane follows it.
- review.showAllNotes {on?} displays every note (session display setting,
  not saved in the file).
- review.convertToComments turns every note in the workbook into a threaded
  comment with the same author and text, as one undoable edit.
- Ribbon: Previous/Next and a Show Comments toggle in the Comments group;
  Show All Notes and Convert to Comments in the Notes menu. Strings in all
  catalogs. Parity checklist regenerated (263 / 290).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:04:03 +02:00
vangel76andClaude Opus 5.5 b6618aee8e Clipboard: pasted currency cells keep the number from the clipboard HTML (#257)
Spreadsheets put an HTML table next to the tab-separated text; Excel
(x:num) and LibreOffice Calc (sdval) record each cell's number there.
Paste now reads the HTML flavour (new paste_html host service, arboard on
desktop) and edit.paste takes an optional html param: a field that would
paste as text becomes the recorded number when the HTML cell shows the
same text, with an inferred format ("Rp"#,##0.00) that renders it back
identically.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 12:03:46 +02:00
vangel76andClaude Opus 5.5 5c614fca48 UI: Name Box Enter goes to the typed cell, not the one below (#247)
The Enter that commits the Name Box stayed in the frame's input; the grid,
drawn after the formula bar and focused again, read it as its own Enter
and moved the active cell down. The Name Box now consumes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:57:26 +02:00
vangel76andClaude Opus 5.5 a2894eff83 Functions: PERCENTOF and EUROCONVERT (#279)
PERCENTOF = SUM(subset) / SUM(all), written as _xlfn.PERCENTOF.
EUROCONVERT uses the fixed EU conversion rates for the currencies the
function documents, with currency rounding and triangulation precision.
New Add-in category for EUROCONVERT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:56:18 +02:00
vangel76andClaude Opus 5.5 1b9751ed82 Fill handle: Ctrl+drag swaps copying and extending a series (#264)
A plain drag copies a lone number and extends every other series; Ctrl+drag
(Cmd on macOS) now does the opposite, as in Excel: a lone number counts up
by 1, and numbers, dates, lists and `Item 1`-style text are copied.
edit.autoFill gains mode "alternate" for this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:55:45 +02:00
vangel76andClaude Opus 5.5 573cf92745 UI: skip system fonts egui can't parse instead of panicking at startup (#226)
epaint panics in set_fonts on a face skrifa can't open. Every system font
file is now checked with the same skrifa call (plus a readable cmap)
before it reaches FontDefinitions; a bad candidate is skipped with a
warning and the next one is tried, and a final pass drops any remaining
unparseable face from the definitions and every family.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:55:32 +02:00
vangel76andClaude Opus 5.5 fed3996944 Functions: ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD (#275)
Odd first and last coupon periods via quasi-coupon periods, from the
formulas on Microsoft's public function pages. ODDLYIELD is closed form;
ODDFYIELD bisects ODDFPRICE (bounded). Financial is now 55 / 55.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:51:34 +02:00
vangel76andClaude Opus 5.5 a06de3357a Add vangel76 to the contributor names
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 11:43:50 +02:00
mbi 17211dcb65 Fix Paste button deadlock in ribbon popup 2026-10-11 12:00:07 +03:00
arekown a44cc8540d Add German (de) interface language
New catalog crates/ui-egui/src/i18n/de.rs (266 entries) mirroring the ru.rs
key set exactly; original translations written from the meaning of the
English UI strings, MIT OR Apache-2.0.

- Language::De registered (code de, name Deutsch); de/de-DE/de_AT/de-CH
  resolve via from_tag
- Tests: German coverage in the i18n coverage loop, de/de-AT/de-CH locale
  tags, ribbon round-trip case, default CJK font-order assertion
- Docs: localization-parity.md row, ROADMAP.md languages section

cargo test -p gridcraft-ui-egui i18n: 5 passed; --lib: 21 passed;
interaction + formula_locale: 13 + 8 passed.
2026-10-11 10:57:27 +02:00
Alexander Alber 71c61f7eaa Add alexanderalber to the contributor names
generated with Claude Code
2026-10-11 10:12:00 +02:00
mbi 479185377e Fix worksheet tab scrolling with mouse wheel and touchpad 2026-10-11 11:09:24 +03:00
Alexander Alber 92adfea27c XLSX: write @ as _xlfn.SINGLE in a dynamic-array formula (#64)
The file format has no `@` operator, but formulas with an explicit
implicit intersection were written with a literal `@`
(`<f>@A1:A3*2</f>`). Excel writes `@x` as `_xlfn.SINGLE(x)`, which only
dynamic-array formulas carry. The writer now does the same and marks such
formulas cm="1"; the parser reads `SINGLE(x)` back as `@x`, as it already
does for `ANCHORARRAY` and `#`.

Two cases in the #83 metadata test expected a redundant `@` (`SQRT(@A1:A3)`,
`@A1:A3*2`) to be written as an ordinary formula. Dropping the `@` there is
only lossless if the reader puts it back on legacy formulas, which it
doesn't yet (the read side of #64), so they now expect cm.

generated with Claude Code
2026-10-11 10:04:09 +02:00
Alexander Alber 4e6e0d6c31 AutoFilter: a selected header row filters the data below it; search box in the filter menu (#201)
Turning the filter on with a multi-cell selection used the selection as the
filter range. With only the header row selected, the filter had no data rows:
the dropdown list was empty and filtering hid nothing. A one-row selection
now extends down over the current region below it. An explicit `range`
parameter is still taken as given.

The filter menu gets a search box, as asked for in the issue. It narrows
the value list; Select All then reads "(Select All Search Results)" and
covers only the matches, and Apply keeps only the checked matches. The box
takes focus when the menu opens, so typing no longer lands in the active
cell.

generated with Claude Code
2026-10-11 09:49:46 +02:00
Alexander Alber 32d0a866f9 XLSX: write one cfvo per icon in icon-set rules (#235)
An icon-set rule without stored thresholds (every rule made by
home.conditionalFormat, and the sales sample) was written as an empty
<iconSet>, which CT_IconSet forbids (cfvo minOccurs 2); openpyxl drops it.
The writer now always emits one cfvo per icon: the stored thresholds when
there is one per icon, the lower bound prepended when it is missing, else
Excel's defaults (percent 0/33/67, 0/25/50/75, 0/20/40/60/80).

Evaluation read the thresholds as one fewer than the icons, but files
carry one per icon (the first is the lower bound), so thresholds read from
a file were ignored. Both now share icon_count and default_icon_thresholds
in gridcraft-model; icon_count is clamped to 3..=5 so a set name like
"0Foo" can't underflow k - 1.

generated with Claude Code
2026-10-11 09:26:00 +02:00
Bryan MarkandClaude Opus 5.5 5967b5656f Glide the selection outline to a new selection; View > Animations turns it off
Excel's cell cursor doesn't jump: press an arrow key or click a cell and the
border slides over; extend the selection and it grows. The outline of the
current area now does the same, in 0.12 s with a decelerating curve, from
wherever it is drawn (a held arrow key reads as one motion), with its fill
and fill handle. The timing is an estimate, not yet measured against Excel.

The same cells moving on screen (scrolling, zoom, a resized column), another
sheet or workbook, an outline that wasn't drawn the frame before, and moves
that start or end off screen don't glide. Only painting waits: the
selection, hit testing and the cell editor use the real cells at once.

View > Animations (under Display theme) turns it off; view.animations {on?}
and ui.set {animations?} do the same for agents. Saved with the UI
preferences, on by default; translated in the five catalogs.

Scripted pictures never catch an outline in flight: it stays on its cells
while a ui.screenshot is on its way and when egui's animations are off (the
headless harness, so the offscreen snapshot). The marching ants around a
copied range now advance by the clock instead of once per painted frame,
since a glide repaints every frame and made them lurch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:18:29 +09:00
AlissonFA 9518b041d5 M2: fix cell vertical alignment positioning and add keytips
Closes #241
2026-10-11 04:18:16 -03:00
Bryan MarkandClaude Opus 5.5 a721b087a1 Add arcanii to the contributor names
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:15:57 +09:00
Bryan MarkandClaude Opus 5.5 4517d8be65 Leave the active cell unshaded inside a selected range
The active cell of a selected range was shaded like the rest of the range:
the line meant to clear it painted a fully transparent rectangle, which
changes nothing. The fill now goes around the active cell (the whole merged
cell when it is one) in every area of the selection, so it is plain where
typing goes. A lone active cell among several areas isn't shaded at all,
and neither is a single selected merged cell.

The fill is translucent, so the cell can't be cleared by painting over it:
each area is shaded as up to four rectangles around it that never overlap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-11 16:15:57 +09:00
Sebastian Whincop cf1696aff3 Add MacJedi42 to the contributor names
Adds my own entry to contributors/people.toml, as docs/contributors.md asks: my GitHub
username with `sync_github_name = true`.
2026-10-11 17:36:25 +13:00
nihilist-narwhal 6e31ad9ea8 Typed times of 24 hours or more keep their hours
Typing 25:00 or 36:30:15 gave the right value but the h:mm format, so
the cell showed 1:00 and 12:30:15. Excel formats such entries as
[h]:mm:ss (25:00:00).
2026-10-10 22:52:59 -05:00
nihilist-narwhal ce83871f2b Remove Duplicates: compare the text cells show
Excel decides duplicates by what a cell displays, not the value stored:
the same date shown as 3/8/2006 and as Mar 8, 2006 is two values, while
1.01 and 1.02 both shown as 1.0 are duplicates. Remove Duplicates
compared stored values, so it did the opposite in both cases.
2026-10-10 22:52:59 -05:00
nihilist-narwhal 6fd41d626b Typed dates before 1900 stay text
7/4/1776 was entered as 7/4/3676 and DATEVALUE("12/31/1899") gave
693962: the text parser built dates with DATE()'s rule that adds 1900 to
years below 1900. Excel keeps such entries as text, and DATEVALUE gives
#VALUE!.
2026-10-10 22:52:59 -05:00
nihilist-narwhal 5e22f9b373 Sort: case-sensitive order puts lowercase before uppercase
With Case sensitive checked, Sort compared text by code point, so every
uppercase word came before every lowercase one (A, B, a, b). Excel
compares ignoring case first and only then puts lowercase before
uppercase: a, A, b, B.
2026-10-10 22:52:59 -05:00
nihilist-narwhal a8a4c5dab3 Conditional formatting: accept Excel's operator names, refuse unknown ones
home.conditionalFormat took any operator it didn't know as "greater",
so a Cell Value rule given Excel's own names (lessThan, greaterThan,
lessThanOrEqual, greaterThanOrEqual, as in the file format and VBA)
silently became "greater than". Those names are now accepted, as data
validation already does, and anything else is an error.
2026-10-10 22:52:58 -05:00
nihilist-narwhal 060889afb2 CHOOSE: pick element by element when the index is an array
The evaluator took a single index, so CHOOSE({1,2},"a","b") gave "a"
and VLOOKUP(x,CHOOSE({1,2},B1:B3,A1:A3),2,FALSE) gave #REF!. An array
index now goes through the library CHOOSE, which lifts over its
arguments as Excel does.
2026-10-10 22:52:58 -05:00
nihilist-narwhal d75b6b73b4 Criteria: text patterns don't match blank cells
COUNTIF(range,"*") counted empty cells and COUNTIF(range,"<>*") skipped
them. Excel matches text patterns against text only: an empty string is
text, a blank cell is not.
2026-10-10 22:52:58 -05:00
nihilist-narwhal 4e7379bd68 Conditional formatting: cell value rules on blank and error cells
Excel compares a blank cell as 0 (or empty text) in Cell Value rules,
so "less than 5" or "equal to 0" also formats blank cells, and a
cell holding an error never matches (the comparison is an error).
GridCraft skipped blank cells and matched errors as if they sorted
above every number ("greater than 5" formatted #N/A).

The No Blanks rule also counted a cell holding only spaces as not
blank, while the Blanks rule (like Excel's LEN(TRIM())) counted it as
blank, so such a cell matched both.
2026-10-10 22:52:58 -05:00
nihilist-narwhal 2b1f851d0a Conditional formatting: apply every matching rule's format
Only the first matching rule's format was used, so with a light red
fill for >300 and a red border for >500, 510 showed only the border.
Excel applies every matching rule; where two rules set the same part
(fill, font colour, a border edge…), the rule with the higher priority
wins, and Stop If True still ends the list.
2026-10-10 22:52:58 -05:00
Diego OspinaandClaude Opus 5.5 cbf56f0707 i18n: Spanish interface translation
Language::Es was registered and switches formulas to Spanish (SUMA, decimal comma, semicolon
arguments), but every interface label still fell back to English. This adds es.rs with all 266
labels in Excel's Spanish wording (Combinar y centrar, Inmovilizar paneles, Análisis de
hipótesis, Buscar objetivo, Rastrear precedentes…) and covers Spanish in the i18n tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012JC2QZ1Qc5KQMBswS38GKy
2026-10-10 22:36:49 -05:00
Sebastian Whincop aee898595f Accuracy: round an exact tie at the 16th significant digit toward zero
Excel shows 15 significant digits. When a number is an exact tie at the 16th
(its exact decimal expansion is 15 digits, a 5, then only zeros), Excel
rounds it toward zero: TEXT(1234567890123455,"0") is 1234567890123450.
GridCraft took Rust's `{:.14e}`, which rounds that tie to even, so any tie
with an odd 15th digit came out one unit too high (…460).

decimal_digits now formats 16 digits (correct unless the 16th is a 5),
and only on a 5 checks the exact expansion (a 30-digit screen, then the
full one) and truncates a true tie. Non-ties, including values just above
or below a tie, round as before. One format serves almost every number.

Tests: ties of every 15th-digit parity, negatives, fractional ties, the
neighbours just above and below a tie, the carry after fifteen 9s
(999999999999999.5 shows 999999999999999), and unchanged ordinary cases.

Evidence: Windows Excel 16.0.20430 TEXT() over a 174-row probe and a 24-row
carry probe agree on every row except those under a percent format and
General over negatives (the two bugs named below). The suite's number-format
golden goes from 183,843 to 184,900 of 187,810 passing with no row that
passed before failing now.

	modified:   crates/numfmt/src/decimal.rs
	modified:   crates/numfmt/src/tests.rs
2026-10-11 16:22:36 +13:00
webdevtodayjason fae90c8e4a selection.move: clamp extreme dr/dc to the sheet edge instead of overflowing 2026-10-10 21:05:58 -05:00
pkibiego 2f078962a0 xlsx: bump quick-xml to 0.41 for the namespace-declaration DoS (RUSTSEC-2026-0195)
The ODS and XLSB readers parse untrusted package metadata and content through
`quick_xml::NsReader`. In 0.38.4 that is RUSTSEC-2026-0195 (CVSS 7.5): the namespace
resolver pushes a binding for every `xmlns` / `xmlns:*` declaration on a start tag, with
no cap on how many there are, and `NsReader::read_event` reaches that path - not only
`read_resolved_event`.

None of our caps bound it. MAX_PART (512 MiB), MAX_TOTAL (1 GiB), MAX_ENTRIES,
MAX_CELLS, MAX_TEXT and MAX_DEPTH bound part size, entry count, cells, text and nesting,
never declarations per tag.

Measured with `gridcraft-cli info` on crafted .ods files, before this change:

     754 B, 0 declarations  ->    8.6 MB, exit 0
     24 KB, 1,000,000       ->   52.6 MB, exit 0
    187 KB, 8,000,000       ->  367.8 MB, exit 0
    770 KB, 33,000,000      ->    1.46 GB, exit 0

About 45 bytes of resident memory per declaration, roughly 1,900x the file size, and no
error at all. At MAX_PART a ~1 MB file reaches ~1.9 GB, and every part is held in memory
while the package is read. Both readers share the path, so a downloaded .ods or .xlsb
was enough. Nothing panicked, so `Session::execute` never saw it.

0.41.0 caps declarations per start tag at 256 (DEFAULT_MAX_DECLARATIONS_PER_ELEMENT,
raisable through NamespaceResolver::set_max_declarations_per_element) and returns
`NamespaceError::TooManyDeclarations` beyond it. The same fixtures after:

     754 B ->    8.6 MB, ok         24 KB ->   19 MB, error
    187 KB ->  101.8 MB, error     770 KB ->    397 MB, error

with "start tag declares more than 256 namespace bindings". The residual peak is the
part itself: MAX_PART still lets one part decompress to 256 MiB, the existing intended
bound.

API changes for 0.41 (0.x bumps may break; all four are in the xlsx crate):
- `resolve_element` and `resolve_attribute` moved off `NsReader` on to the resolver:
  `reader.resolver_mut().resolve_element(..)`. `attr` and `tag` in ods.rs take
  `&mut NsReader` for that.
- `Attribute::unescape_value` is deprecated in favour of `normalized_value`, which also
  applies the attribute-value normalization the XML specification requires.
- `BytesText::xml_content` now takes the document's XML version.

This also clears RUSTSEC-2026-0194, the quadratic duplicate-attribute check. xml.rs
already passed `with_checks(false)`, but ods.rs and xlsb.rs used the checked iterator, so
they were on the quadratic path as well.

Regression test: `ods_tests::ods_namespace_declaration_bomb_is_rejected` asserts that a
tag with thousands of declarations is an error and that a document with a handful still
reads. It fails on 0.38.4 (the tag is accepted) and passes on 0.41.0.

Verified: `cargo xtask ci`; the full xlsx suite (80 tests) plus the malformed-input
tests; and the four measurements above, before and after, with no panics either way.
2026-10-11 03:39:32 +03:00
webdevtodayjason a788c41faa #200: keep formula helpers inside the worksheet
Fixes #200
2026-10-10 18:29:25 -05:00
webdevtodayjason 83c7a3c2f5 Contributors: add Jason Brashear display name 2026-10-10 18:29:25 -05:00
Brandon ThomasandClaude Opus 5.5 9f896c1249 Bump version to 0.5.0 for release (#227)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-10 19:10:53 -04:00
Dejan Kocić a0dc1abce1 fix: Save toolbar button and saveChanges dialog discard an in-progress cell edit
Clicking the Save icon in the toolbar, or the Save button in the "save
changes?" dialog, called file.save directly without first committing a
cell edit still in progress (e.g. double-click a cell, type a new value,
then click Save with the mouse instead of pressing Enter). The pending
text in EditState was never flushed into the document, so the saved
file still held the pre-edit value, silently.

The File > Save menu item already guards against this
(app.commit_edit(...) before running the command); this applies the
same guard to the toolbar icon and the saveChanges dialog's Save button.
2026-10-11 00:35:45 +02:00
Zarvinx 706fe7b10c macOS: use the padded app icon in the Dock 2026-10-11 01:20:03 +03:00
Zarvinx ac87c269ff Fix #213: delete selected objects from keyboard 2026-10-11 01:02:18 +03:00
MarekSpodBiedry 36c591883b Resize charts from the corner handle and the Size fields, keep typed chart and table names (#190)
The corner drag now grabs the chart where the press began and the selected object's corner shows a resize cursor. The Format Chart Area Size fields, chart and axis title fields and the Table Name field reloaded their value from the workbook every frame, so typed or dragged edits were thrown away; they now keep a draft until the field loses focus (Escape cancels, like sheet tab rename).
2026-10-10 23:52:49 +02:00
MarekSpodBiedry 5722dc5355 Do not draw the selection over the frozen pane when it lies only in the scrolling pane (#198) 2026-10-10 23:52:14 +02:00
MarekSpodBiedry 27be1753c2 Read the browser clock for NOW(), TODAY() and year-less dates on wasm (#202) 2026-10-10 23:43:32 +02:00
Zarvinx 271119d9e3 Build: satisfy Rust 1.95 clippy 2026-10-11 00:30:51 +03:00
Zarvinx 7a7e23cab7 Grid: reorder selected columns by header drag 2026-10-11 00:30:24 +03:00
Dejan Kocić d27dec0312 web: print straight to the system print dialog, not just export
The web build had no way to actually print — Ctrl+P (Cmd+P, declared on
file.print's shortcut) did nothing at all, and the ribbon's "Print…" menu
item ran file.print and silently discarded the result. file.print already
builds a PDF and returns it as base64 specifically "for the UI to hand to
the system print dialog" per its own doc comment — this wires that up.

- ui-egui: new Services::print hook (web: hand PDF bytes to the browser's
  print flow directly, no download); SheetApp::print_now runs file.print,
  decodes the base64 result, and calls the hook.
- ui-egui: Key::P now dispatches to print_now (was unbound); the ribbon's
  "Print…" menu item calls print_now instead of discarding file.print's
  result.
- gridcraft-web: implements the hook (Blob -> object URL -> hidden iframe
  -> iframe.contentWindow.print() on load).

Desktop builds are unaffected (no Services::print set there; print_now
falls back to the existing alert-on-error behaviour with no UI action on
success, same as before this change).
2026-10-10 22:50:36 +02:00
Mikkel Georgsen c9525ab5fb Cell references: an invalid reference is an error instead of the active cell
cell_param returned None for any cell argument it could not parse, so every
command that falls back to the selection (cell.set, view.freezePanes,
formulas.trace*, insert.* and others) silently used the active cell instead:
set_cell with cell "ZZZZ0" wrote A1 and reported success. It also dropped a
sheet prefix, so "Other!B2" was applied to the active sheet.

cell_param now returns Result<Option<CellRef>>. An absent or null value is still
None, so the selection fallback is unchanged; an unparsable or non-string value
is an error; a sheet prefix naming a sheet other than the one the command works
on is an error.

cell_param_on is for the commands that resolve their own sheet (cell.get, links,
comments, notes, checkboxes, chart placement, paste): they accept a prefix naming
that sheet. cell.set resolves its own target sheet and still writes to another
existing sheet.
2026-10-10 22:41:40 +02:00
Mikkel Georgsen f69861f7e3 Cell: cell.set without an input is an error
cell.set treated a missing input as an empty string, so a call that forgot the
input (or sent it under the wrong key) cleared the cell and reported success.
It now returns an error when neither `input` nor `value` is given. An explicit
empty string still clears the cell.
2026-10-10 22:41:40 +02:00
Brandon ThomasandClaude Opus 5.5 90b3c41eec Fix-up: #83's array-export test expects #156's legacy-array read (cached values refilled on recalc)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:59:42 -04:00
GyuriX e8d935298f Linux: the display theme asks the desktop, not winit
winit reports no system theme on Linux — `ActiveEventLoop::system_theme()` is
`None` there on every desktop — so `System` in the appearance setting never saw
the desktop's choice and fell back to light. A new `desktop_theme` module asks
the XDG Desktop Portal's Settings interface for
`org.gnome.desktop.interface color-scheme` on a thread of its own, so no
D-Bus call is ever made from the frame loop, and the app follows the answer,
including a change made while it runs.

egui resolves `ThemePreference::System` from what winit reports and offers no
way to set that itself, so where a desktop answered, the app hands egui the
concrete theme instead. What is drawn is unchanged on macOS and Windows, where
winit answers and the same resolution happens a step earlier; the saved
preference is still `system`, so a file keeps meaning the same thing.

The colour scheme is asked for under its GNOME schema name first, which GNOME's
portal and XFCE's both answer, then under the older freedesktop one, which KDE
answers. A desktop that answers neither leaves the user's own choice alone.
2026-10-10 21:55:20 +02:00
Brandon ThomasandClaude Opus 5.5 c6392e6380 Fix-up: chartex frames use the (open, close) anchor tags after merging #161 onto the move-only anchor change
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:52:46 -04:00
Brandon Thomas 502c588690 Merge pull request #164 from LloydNicholson/macos-open-documents
macOS: open documents from Finder, the Dock and `open -a` (#69)

# Conflicts:
#	apps/gridcraft/src/main.rs
2026-10-10 15:50:57 -04:00
Brandon Thomas 88d0c772fb Merge pull request #161 from nihilist-narwhal/fix-chart-kinds-roundtrip
Charts: histogram, box & whisker, waterfall, funnel, treemap and sunburst keep their kind through XLSX
2026-10-10 15:50:48 -04:00
Brandon Thomas f23281db8c Merge pull request #144 from harrisonoconnorhover/codex/cross-sheet-cut
Preserve formula references when cutting cells across sheets

# Conflicts:
#	ROADMAP.md
#	crates/formula/src/adjust.rs
#	crates/formula/src/tests.rs
2026-10-10 15:48:08 -04:00
Brandon Thomas 49fbae245a Merge pull request #156 from nihilist-narwhal/fix-legacy-array-formulas
Legacy array formulas: fill the range they were entered in

# Conflicts:
#	crates/engine/src/cmd/edit.rs
#	crates/ui-egui/src/formula_bar.rs
2026-10-10 15:47:56 -04:00
Brandon Thomas de0c715662 Merge pull request #186 from MarekSpodBiedry/issue-126
Write comment and hyperlink maps with A1 keys so JSON save works (#126)

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-10 15:47:35 -04:00
Brandon Thomas b07249de75 Merge pull request #160 from itrycodinganditsbad/fix-month-fill-clamp
fill: clamp month and year date series to the month's last day

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-10 15:47:32 -04:00
Brandon ThomasandClaude Opus 5.5 c15a51c959 Fix-up: move the #179 table-style test module to the end of tables.rs after merging #149
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:47:19 -04:00
Brandon Thomas dd185ff12f Merge pull request #157 from nihilist-narwhal/fix-blocked-spill-dependents
Recalc: formulas over a blocked spill see #SPILL!; no spilling in tables
2026-10-10 15:47:12 -04:00
Brandon Thomas c3cfc92186 Merge pull request #155 from nihilist-narwhal/fix-range-blank-cells
Ranges keep their size past the used range; spilled blanks show 0
2026-10-10 15:47:12 -04:00
Brandon Thomas 9fea6235f7 Merge pull request #148 from nihilist-narwhal/fix-stale-recalc-values
Recalc: stale spills and values after edits (fixes #133, #139)
2026-10-10 15:47:12 -04:00
Brandon Thomas 84a414a705 Merge pull request #158 from nihilist-narwhal/fix-chart-kinds-combo-stock
Charts: combo and stock charts keep their kind in XLSX
2026-10-10 15:47:11 -04:00
Brandon Thomas 1e5edbd43c Merge pull request #154 from nihilist-narwhal/fix-repeated-headers
Repeated headers: number pivot fields and table columns in linear time
2026-10-10 15:47:11 -04:00
Brandon Thomas 5c456df4b7 Merge pull request #152 from nihilist-narwhal/fix-whole-sheet-selection
Whole-sheet selection: Fill and Remove Duplicates no longer run out of memory or time
2026-10-10 15:47:10 -04:00
Brandon Thomas 92fb7cd1b3 Merge pull request #149 from nihilist-narwhal/fix-table-header-edits
Tables: typing in the header row renames the column; Go To a table selects its data

# Conflicts:
#	crates/engine/src/tables.rs
2026-10-10 15:47:10 -04:00
Brandon Thomas 5545e72944 Merge pull request #188 from MarekSpodBiedry/issue-145
Release focus when the sheet tab rename ends (#145)
2026-10-10 15:46:34 -04:00
Brandon Thomas 960c79a328 Merge pull request #187 from MarekSpodBiedry/issue-57
Compare numbers at 15 significant digits like Excel (#57)
2026-10-10 15:46:33 -04:00
Brandon Thomas 645782f5e3 Merge pull request #185 from MarekSpodBiedry/issue-135
Report an error when file commands get no file in MCP and CLI (#135)
2026-10-10 15:46:32 -04:00
Brandon Thomas 87d64f20e1 Merge pull request #184 from MarekSpodBiedry/issue-136
Honor search in the desktop engine.commands handler so connected list_commands filters (#136)
2026-10-10 15:46:32 -04:00
Brandon Thomas d031c8f37e Merge pull request #183 from MarekSpodBiedry/issue-140
Shrink 3-D sheet spans when an end sheet is deleted (#140)
2026-10-10 15:46:31 -04:00
Brandon Thomas cda29c5b73 Merge pull request #182 from MarekSpodBiedry/issue-141
Deliver Export as PDF as a browser download (#141)
2026-10-10 15:46:30 -04:00
Brandon Thomas c21123e375 Merge pull request #181 from MarekSpodBiedry/issue-127
Keep comma when a semicolon or tab is missing from some CSV lines (#127)
2026-10-10 15:46:29 -04:00
Brandon Thomas 75ede09917 Merge pull request #180 from MarekSpodBiedry/issue-129
Keep the untouched part of a data validation range when clearing or replacing part of it (#129)
2026-10-10 15:35:45 -04:00
Brandon Thomas 14402fc5a3 Merge pull request #179 from MarekSpodBiedry/issue-130
Clamp table style number to 1 so zero-numbered styles don't underflow (#130)
2026-10-10 15:35:44 -04:00
Brandon Thomas e9fb005eed Merge pull request #178 from MarekSpodBiedry/issue-134
Rename sheet-qualified defined names with their sheet (#134)
2026-10-10 15:35:44 -04:00
Brandon Thomas 5578c09e55 Merge pull request #159 from itrycodinganditsbad/fix-min-no-args
functions: MIN() accepts zero arguments
2026-10-10 15:35:43 -04:00
Brandon Thomas 00df1908a7 Merge pull request #153 from nihilist-narwhal/fix-jump-without-direction
selection.move: Ctrl+arrow without a direction no longer loops forever
2026-10-10 15:35:42 -04:00
Brandon Thomas c4e4aeb293 Merge pull request #151 from nihilist-narwhal/fix-current-region
Current region: grow past 10,000 rows, in linear time
2026-10-10 15:35:42 -04:00
Brandon Thomas 20aa531d8c Merge pull request #150 from nihilist-narwhal/fix-paste-special-operations
Paste Special operations: keep text, errors and formulas
2026-10-10 15:35:41 -04:00
Brandon ThomasandClaude Opus 5.5 11ef0e6b04 Maintainer fix-up: compare clearly different numbers directly, skipping the 15-digit text round trip on the sort/lookup hot path
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:35:13 -04:00
Brandon ThomasandClaude Opus 5.5 dfd3675324 Maintainer fix-up: drop wall-clock assertions from the repeated-headers test (flaky under load; Instant::now is a disallowed method)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:35:10 -04:00
Brandon ThomasandClaude Opus 5.5 f75ded37e7 Merge pull request #105 from harrisonoconnorhover/codex/cell-pictures
Add static pictures inside cells with XLSX roundtrip

Rebased onto main (conflicts with #83/#98 and main resolved by maintainer); the contributor's branch does not allow maintainer edits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:02:44 -04:00
Brandon ThomasandClaude Opus 5.5 59c8e36d36 Merge pull request #83 from harrisonoconnorhover/codex/nonspilling-array-export
Preserve array evaluation for non-spilling XLSX formulas

Rebased onto main with a maintainer fix-up (LET bindings via split_last/as_chunks for clippy, no slice indexing); the contributor's branch does not allow maintainer edits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 15:02:43 -04:00
Brandon ThomasandClaude Opus 5.5 5b15827ede Maintainer fix-up: leave English formula display untouched, match engine formula detection
English (and languages without a formula table) now shows stored formula
text verbatim instead of re-parsing it every frame; localized entry no longer
trims leading spaces before formula detection (" =1" stays text, as in the
engine). Adds a display round-trip test for string literals containing
separators, decimal commas and the intersection operator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 14:49:52 -04:00
Brandon Thomas 3e40014eb0 Merge pull request #98 from harrisonoconnorhover/codex/spanish-formulas
Support common Spanish formula names and semicolon arguments
2026-10-10 14:49:52 -04:00
Brandon Thomas 82f42713a8 Merge pull request #108 from harrisonoconnorhover/codex/desktop-shortcut
Offer an optional desktop shortcut in the Windows installer

# Conflicts:
#	ROADMAP.md
2026-10-10 14:32:51 -04:00
Zaid ShurbajiandClaude Opus 4.8 b40fdc2470 ci: add macOS universal DMG build workflow
Builds GridCraft.app into a universal .dmg on a GitHub-hosted macOS runner,
ad-hoc signed, uploaded as a workflow artifact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-10-10 21:27:14 +03:00
Zaid ShurbajiandClaude Opus 4.8 fd2243df95 Add table slicers (insert.slicer / table.insertSlicer)
Implements the two slicer commands from the parity catalog as first-class
floating objects that filter a table column.

- model: Slicer struct on Sheet (#[serde(default)]), included in
  Workbook::next_object_id; slicer anchors use AnchorMode::MoveOnly.
- engine: cmd/slicer.rs with insert.slicer, table.insertSlicer, slicer.toggle
  (single + multi), slicer.selectAll, slicer.clear, slicer.delete. Selection is
  written as a FilterCriterion::Values into the sheet AutoFilter and applied via
  the existing apply_filter. object.move / object.delete handle "slicer".
- ui-egui: slicers rendered, hit-tested, selected and dragged like charts; value
  tiles toggle on click (Ctrl/Cmd = multi), funnel button clears. Ribbon buttons
  under Insert > Filters and Table Design > Tools.
- tests: slicer_filters_table; the every_command_survives_empty_params fuzz
  covers the new commands.

Native-only for now; .xlsx slicer-cache round-trip is a follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-10-10 21:27:13 +03:00
Brandon ThomasandClaude Opus 5.5 60aa2dfe07 Progress docs: target-app parity, gaps, alpha gate, readiness by audience (#189)
Progress docs per craftrules standards/progress-docs.md: target-app parity, gaps, roadmap with alpha gate, readiness by audience (full / mainstream / essentials) with Opus 5.5 hours, and feature, format, hardware, UI and localization parity docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 14:09:06 -04:00
Harrison O'Connor-Hoover ada33d1ad5 Fix #45: follow the selected language for formula editing 2026-10-10 13:48:20 -04:00
Brandon Thomas e72e16a0ec Merge pull request #82 from edurbs/feat/i18n-portuguese
i18n: Brazilian Portuguese interface language (#79)
2026-10-10 13:25:35 -04:00
Brandon Thomas 580b14eeb9 Merge pull request #104 from neko233-com/feature/i18n-zh-ko-ru
i18n: add Simplified Chinese, Korean and Russian UI
2026-10-10 13:25:34 -04:00
Brandon Thomas 837bb00f2b Merge pull request #31 from justinjohn0306/feat/i18n-language
i18n: switch the interface language, defaulting to the system language (#20)
2026-10-10 13:25:34 -04:00
Brandon Thomas 4f10e48128 Merge pull request #38 from justinjohn0306/fix/thai-hebrew-font-fallback
Fonts: render Thai and Hebrew (and other non-Latin scripts) instead of tofu (#32)
2026-10-10 13:25:33 -04:00
Brandon Thomas f2ed982fdd Merge pull request #12 from justinjohn0306/fix/anchor-mode-sort
Objects: anchor modes — images/charts/shapes follow cells on sort (#5)

# Conflicts:
#	crates/engine/src/tests.rs
2026-10-10 13:17:30 -04:00
Brandon Thomas eb4174723d Merge pull request #17 from justinjohn0306/fix/encrypted-file-message
File open: report password-protected (encrypted) files clearly (#11)

# Conflicts:
#	crates/engine/src/io.rs
2026-10-10 13:17:21 -04:00
Brandon Thomas bd1be73f2d Merge pull request #62 from justinjohn0306/fix/smooth-line-charts
Line charts: smooth (spline) curves (issue #52)

# Conflicts:
#	crates/xlsx/src/tests/mod.rs
2026-10-10 13:17:07 -04:00
Brandon Thomas 13f8f19248 Merge pull request #116 from nihilist-narwhal/fix-chart-switch-and-scatter
Charts: Switch Row/Column on charts read from a file; scatter with text X values
2026-10-10 13:16:59 -04:00
Brandon Thomas 76f9e2625f Merge updated #104 (latest main) into feat/i18n-portuguese 2026-10-10 13:15:11 -04:00
Brandon Thomas d51d4e51b9 Merge updated #31 (latest main) into feature/i18n-zh-ko-ru 2026-10-10 13:15:11 -04:00
Brandon Thomas 6e935a3c8c Merge origin/main into feat/i18n-language
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/ribbon.rs
2026-10-10 13:15:10 -04:00
MarekSpodBiedry 2cc7dde6c3 Release focus when the sheet tab rename ends (#145) 2026-10-10 19:10:19 +02:00
MarekSpodBiedry 1d33ea81be Write comment and hyperlink maps with A1 keys so JSON save works (#126) 2026-10-10 19:08:53 +02:00
MarekSpodBiedry 0f21244e9e Compare numbers at 15 significant digits like Excel (#57) 2026-10-10 19:08:16 +02:00
MarekSpodBiedry dcda5a52ce Deliver Export as PDF as a browser download (#141) 2026-10-10 19:06:36 +02:00
MarekSpodBiedry 47210cde01 Shrink 3-D sheet spans when an end sheet is deleted (#140) 2026-10-10 19:06:20 +02:00
MarekSpodBiedry fe162f8f23 Report an error when file commands get no file in MCP and CLI (#135) 2026-10-10 19:05:56 +02:00
MarekSpodBiedry c69446aff0 Keep comma when a semicolon or tab is missing from some CSV lines (#127) 2026-10-10 19:05:45 +02:00
MarekSpodBiedry 2faf8ffc78 Honor search in the desktop engine.commands handler so connected list_commands filters (#136) 2026-10-10 19:05:33 +02:00
MarekSpodBiedry 9400dbea2b Keep the untouched part of a data validation range when clearing or replacing part of it (#129) 2026-10-10 19:05:23 +02:00
MarekSpodBiedry b19ffabdaf Rename sheet-qualified defined names with their sheet (#134) 2026-10-10 19:04:13 +02:00
MarekSpodBiedry 82d3c5422f Clamp table style number to 1 so zero-numbered styles don't underflow (#130) 2026-10-10 19:03:55 +02:00
Brandon Thomas 19094e2d62 Merge pull request #36 from harrisonoconnorhover/fix/rich-table-clipboard
Fix copying selected cells as rich HTML tables
2026-10-10 12:58:38 -04:00
Brandon Thomas e20a7b41af Merge pull request #84 from harrisonoconnorhover/codex/text-box-editing
Allow editing and selecting text inside worksheet text boxes
2026-10-10 12:58:37 -04:00
Brandon Thomas cb794080b9 Merge pull request #43 from harrisonoconnorhover/codex/ribbon-keytips
Add initial Alt ribbon keytips and legacy shortcuts (#33)
2026-10-10 12:58:36 -04:00
Brandon ThomasandClaude Opus 5.5 7f2146476e Fix clippy on main: allow the clock read in native-only import tests
#101/#100 added tests that name temp dirs with SystemTime::now(); #125's
disallowed-methods lint (wasm has no clock) landed alongside them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:58:22 -04:00
Brandon ThomasandClaude Opus 5.5 ca4011dc5e Review fix-up: merge fixed #104; Portuguese as an i18n/pt.rs module
Merge the fixed #104 branch (which carries #31 and #38) and restructure
the Brazilian Portuguese language onto its per-language layout:

- The PORTUGUESE table moves, unchanged, to crates/ui-egui/src/i18n/pt.rs
  as pt::translate, like zh/ko/ru. Language::PtBr gets code() "pt"
  (parse also accepts pt-BR/pt_BR via the tag reduction); it is still
  saved as "pt".
- No per-language command: the View combo and the control channel switch
  with app.language.set {"language": "pt"} (app.language.portuguese is
  dropped); error text, engine.commands params and the snapshot example
  list every code.
- pt.rs covers the keys added since (Page Layout|Orientation, the display
  theme combo, and the Sheet Options View/Print checkboxes, Exibir /
  Imprimir); the coverage test checks pt like zh/ko/ru.
- people.toml keeps both new contributor entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:54:33 -04:00
Brandon Thomas b68ae0fe53 Merge pull request #100 from harrisonoconnorhover/codex/ods-import
Import worksheet data and cached values from ODS files
2026-10-10 12:52:43 -04:00
Brandon Thomas 09b1ac8d16 Merge pull request #101 from harrisonoconnorhover/codex/xlsb-import
Import worksheet data and cached results from XLSB workbooks
2026-10-10 12:52:42 -04:00
Brandon ThomasandClaude Opus 5.5 f54c0ca2a6 Review fix-up: merge fixed #31; language-ordered Han faces on #38's fallback
Merge the fixed #31 branch (which carries #38's font fallback) and resolve:

- theme.rs: build on #38's fallback_faces/load_fallback instead of the old
  load_cjk. The interface language only reorders the two Han entries
  (sys-cjk-han-ja / sys-cjk-han-zh; Japanese first for ja, Chinese first
  otherwise); Hangul, Thai and Hebrew keep their place. The region-merged
  Noto Sans CJK .ttc is loaded once, with the leading language's face index.
- Fonts are rebuilt on a language switch only when the Han order changes
  (HanOrder), not on every switch. font_definitions()/setup_context() use
  the default order and never read the host locale.
- Tests stay locale-independent (UiState defaults to English; the desktop
  app applies the system language). The web build follows the browser
  language except CJK, which would render as tofu without system fonts.
- app.language.set error/params list all five codes; engine.commands lists
  it. zh/ko/ru gain the keys #31 added (Page Layout|Orientation, display
  theme). The Page Layout screen checkbox keeps English "View" via a
  "Sheet Options|View" key (was shown as "Screen").
- Coverage test checks zh/ja/ko/Thai/Hebrew/Cyrillic in both the UI and
  cell families by comparing glyphs with the tofu glyph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:52:00 -04:00
Brandon ThomasandClaude Opus 5.5 e8ec40da8b Review fix-up: build test anchors with ..Anchor::default()
Keeps the smooth round-trip test compiling as Anchor gains fields (e.g. #12's anchor mode).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:45:00 -04:00
Brandon ThomasandClaude Opus 5.5 d7c77e94cd Review fix-up: locale-independent defaults, lenient saved language, listed commands
- UiState::default() is English: tests, the kittest harness and the
  snapshot example no longer depend on the host's locale. The desktop app
  alone starts from the system language, when ui.json names no supported
  language (first run, an older file, an unknown value).
- An unknown or malformed saved language reads as English instead of
  failing the whole UiState and resetting every other preference.
- app.language.set takes {"language": "ja"} (with `code` as an alias, the
  name the PR description used); the View combo now uses it via
  Language::code(). The app.language.* commands are listed by
  engine.commands with the other UI commands and documented in
  docs/control-protocol.md.
- Home's text "Orientation" (方向) and Page Layout's print "Orientation"
  (印刷の向き) get separate keys through a `context|label` key form.
- Japanese: Hide Rows → 行を表示しない, Trace Dependents → 参照先のトレース;
  translate the display-theme combo merged in from main.
- system_theme test: the View tab now has two combo boxes; pick the theme one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:44:57 -04:00
Harrison O'Connor-Hoover 9dc3aaf9fa Support static pictures inside cells with XLSX roundtrip (#61) 2026-10-10 12:43:27 -04:00
Brandon ThomasandClaude Opus 5.5 fa9c6798ab Review fix-up: sort moves only objects inside the block; picture default oneCell
Re-anchor loop zips objects with their measured corners instead of indexing; a sort moves
only objects anchored inside the sorted block on the other axis too (a picture at Z3 stays
put when A1:B4 is sorted). insert.picture defaults to Move but don't size (Excel's
editAs="oneCell", which the writer emits for it), and object.setAnchorMode errors on an
unknown or empty kind. Tests for each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:41:17 -04:00
Brandon Thomas b5fe936d83 Merge pull request #66 from LloydNicholson/fix/recalc-range-dependents
Issue #122: Recalc: linear in the number of range formulas
2026-10-10 12:40:00 -04:00
Brandon Thomas c450b545a6 Merge pull request #125 from LloydNicholson/fix/wasm-commit-trap
Issue #118: committing a cell in the web app no longer traps on the clock
2026-10-10 12:39:58 -04:00
Brandon ThomasandClaude Opus 5.5 d2cc499c1d Review fix-up: return copy/cut HTML only when requested
edit.copy and edit.cut build and return the HTML table only with
{"html": true}; the UI asks for it when the host can publish HTML, so
MCP and control-channel responses are not bloated by up to 4 MB. Tests
cover the default, html:false and html:true.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:37:06 -04:00
Harrison O'Connor-Hoover 811cb116fd Release each native MSI preview through its handle (#24) 2026-10-10 12:36:07 -04:00
Brandon Thomas 36723ec310 Merge remote-tracking branch 'origin/main' into pr-12 2026-10-10 12:35:42 -04:00
Brandon ThomasandClaude Opus 5.5 f041904bf8 Review fix-up: only CFB files with an EncryptedPackage are encrypted
Every legacy .xls/.doc is a CFB/OLE2 file, so the signature alone isn't encryption. Walk the
compound file's directory (bounds-checked, bounded loops; raw UTF-16 scan when the structure
is unreadable) and report Encrypted only for an EncryptedPackage/EncryptionInfo stream;
other compound files are LegacyBinary with a "save as .xlsx" message. Tests build CFB bytes
in code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:35:36 -04:00
Brandon Thomas 277f01265b Merge fixed #38 (font fallback) into feat/i18n-language
# Conflicts:
#	crates/ui-egui/src/grid.rs
#	crates/ui-egui/src/ribbon.rs
#	crates/ui-egui/src/widgets.rs
2026-10-10 12:31:57 -04:00
Brandon Thomas c5bf34d5d7 Merge pull request #81 from dylanmtaylor/ci/flatpak-pages
Publish Flatpak repository through GitHub Pages
2026-10-10 12:30:39 -04:00
Brandon Thomas d61a21c922 Merge pull request #90 from dylanmtaylor/feat/riscv-build
ci: Add RISC-V Linux build
2026-10-10 12:30:37 -04:00
Harrison O'Connor-Hoover 784c091ae9 Handle absent installer registry values in Windows smoke checks (#24) 2026-10-10 12:30:29 -04:00
Brandon ThomasandClaude Opus 5.5 efcfd08822 Review fix-up: align the riscv64 job with the other Linux jobs
- Pin actions/checkout and upload-artifact to the SHAs the other jobs use
  (v7.0.1, v7.0.2); add rust-cache; use the same version-override command.
- Run on ubuntu-24.04 (ubuntu-26.04 is not a known hosted label) and take the
  ports suite from /etc/os-release; 22.04's riscv64 ports lag its amd64
  updates and the multiarch install fails there.
- Add linux-riscv64 to the release job's needs so release-linux-riscv64 is
  downloaded before the draft release is built.
- Drop the unused libasound2 dependency, the linker -L flags and the
  qemu-static symlink; package.sh's emulator check is the smoke test
  (QEMU_LD_PREFIX), and quote $EMULATOR there.
- Move the job above the FreeBSD comment; list riscv64 in docs/releasing.md.

Verified: the job's steps in an ubuntu:24.04 container build, package and
run gridcraft-cli --version under qemu-riscv64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:29:33 -04:00
Brandon Thomas cee21c64ec Merge remote-tracking branch 'origin/main' into feat/riscv-build 2026-10-10 12:29:27 -04:00
Harrison O'Connor-Hoover ce1e2d1cee Offer a machine-wide optional Windows desktop shortcut (#24) 2026-10-10 12:29:03 -04:00
Brandon ThomasandClaude Opus 5.5 c67931cff6 Review fix-up: protect and cap text box edits
shape.setText refuses edits on a protected sheet (drawing objects are
locked; there is no edit-objects allowance yet) and text longer than
32,767 characters, like a cell. The editor doesn't open on a protected
sheet and its TextEdit carries the same character limit. Tests for both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:23:51 -04:00
Brandon ThomasandClaude Opus 5.5 20e39fa3cd Review fix-up: clip blank ODS repeats past the sheet edge, struct-update Cell literal
Blank cell and row repeats that run past 16384 columns / 1048576 rows
(padding from writers with larger sheets) are clipped instead of
rejecting the file; any data or merge past the edge is still an error.
convert() builds its Cell with ..Cell::value(value) so new Cell fields
take their defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:22:51 -04:00
c4fd49afc2 Review fix-up: dedupe CJK fallback load, wider Linux/macOS font paths
- Load each fallback font file once: the region-merged Noto Sans CJK .ttc
  found for Han also covers Hangul (and Tahoma covers Thai and Hebrew), so a
  later script whose candidate file is already loaded reuses it instead of
  loading tens of MB again. New test: no two fallback faces share a file.
- Fold in the Linux CJK paths from #103: Fedora google-noto-cjk/, Arch
  noto-cjk/ and wenquanyi/, Debian truetype/wqy/wqy-microhei.ttc, the SC
  .otf builds, /usr/local, plus SimSun on Windows. Document the .ttc face
  indices (JP 0, KR 1, SC 2, TC 3, HK 4); Hangul uses the KR face.
- macOS: Hiragino Sans (ヒラギノ角ゴシック W3) and Hiragino Sans GB come
  before PingFang.ttc, which recent macOS no longer ships in /System.
- Comments promise glyphs instead of tofu, not correct rendering.
- fallback_covers_its_script compared has_glyphs, which is a false negative
  when the owning face also draws the replacement glyph (DejaVu Sans as UI
  font owns Hebrew); compare laid-out glyphs with the tofu glyph instead.

Co-authored-by: eyouhi <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:22:11 -04:00
Brandon Thomas 9365c5a9c6 Merge remote-tracking branch 'origin/main' into pr-17 2026-10-10 12:21:40 -04:00
Brandon ThomasandClaude Opus 5.5 c975b5dc75 Review fix-up: uniform, plot-clamped spline smoothing
smooth_run gives every segment the same number of sub-segments (cap / n, 1..100) so long
series are smoothed end to end within the point cap, and clamps the Catmull-Rom curve to
the plot box. List "smooth" in chart.addElement's params doc, drop the smooth_demo
example, and use the test sheet's own name in series refs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:21:35 -04:00
Brandon ThomasandClaude Opus 5.5 26b3db78db Merge codex/xlsb-import (with origin/main) into codex/ods-import
Resolves the shared integration points for both formats: combined sniff,
file.open spec, file filters, MCP description, docs. open_bytes now lets
sniffed content (ODS or XLSB) win over the extension.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:20:30 -04:00
Harrison O'Connor-Hoover 42854f2fb9 Preserve array-sensitive XLSX formulas (#64) 2026-10-10 12:19:52 -04:00
Brandon ThomasandClaude Opus 5.5 4955382a07 Review fix-up: control-protocol doc typo, tolerant XLSB phonetic-run tail
PhRun is 10 bytes per [MS-XLSB] 2.5.103 (four u16 fields plus a 16-bit
phType/alcH/unused1 word), so the documented size is kept; since the
RichStr ends its record and phonetic data is not imported, bytes after
the documented runs are now ignored instead of rejecting the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:19:33 -04:00
Brandon ThomasandClaude Opus 5.5 86328ec843 Review fix-up: ignore the wall-clock scaling test by default; check its values every run
recalc_with_range_formulas_scales_linearly is flaky under load, so it is #[ignore]d (run with
--ignored in release). A small range_formulas_recalc_and_bulk_edit_correctly test keeps the
helper's value check in every run. The helper reads Instant::now, so it allows
clippy::disallowed_methods (required once #125's clippy.toml lands).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:18:59 -04:00
Brandon Thomas 435a750bba Merge remote-tracking branch 'origin/main' into pr-62 2026-10-10 12:16:17 -04:00
Brandon ThomasandClaude Opus 5.5 ff77dea87f Review fix-up: bound Switch Row/Column on whole-column chart refs
Clip a file chart's series block to the sheet's used range and refuse blocks over the
insert.chart cell cap, so whole-column references can't build ~1M series.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:16:09 -04:00
Brandon ThomasandClaude Opus 5.5 699b95288a Review fix-up: switch to Home only when the legacy keytip prefix changes
ribbon_keys ran ui.ribbonTab every frame while the prefix was E/O/OC,
forcing the Home tab continuously. Run it once on the prefix change and
add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:14:34 -04:00
Dylan M. Taylor d3b8929fde ci: add RISC-V Linux build 2026-10-10 12:14:29 -04:00
Brandon ThomasandClaude Opus 5.5 deecb18f5d Review fix-up: skip pre-releases, prune the Pages repo, read-only pages in build
- Skip the build when the published release is a pre-release, and refuse a
  manual tag with a pre-release suffix or a release GitHub marks as one, so
  rc builds never reach the stable branch.
- flatpak build-update-repo --prune --prune-depth=3 so the re-mirrored
  Pages repository does not grow without bound.
- The build job only needs pages: read for configure-pages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:11:51 -04:00
Brandon Thomas ce2cade393 Merge remote-tracking branch 'origin/main' into pr81 2026-10-10 12:11:24 -04:00
Brandon Thomas 11472b340b Merge remote-tracking branch 'origin/main' into fix66 2026-10-10 12:11:09 -04:00
Brandon ThomasandClaude Opus 5.5 2f9fce88b0 Review fix-up: allow the desktop logger's clock read under the new disallowed-methods lint
The logger (apps/gridcraft/src/logging.rs, merged from main) reads SystemTime::now; the desktop
app never runs on wasm, so allow the lint at that call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 12:10:59 -04:00
Brandon Thomas 7712eb1b0e Merge origin/main into fix/rich-table-clipboard 2026-10-10 12:09:28 -04:00
Brandon Thomas c5a8cf28fe Merge origin/main into codex/text-box-editing
# Conflicts:
#	apps/gridcraft/src/native_menu.rs
#	crates/engine/src/tests.rs
2026-10-10 12:08:36 -04:00
Brandon Thomas c607fe1627 Merge origin/main into fix/thai-hebrew-font-fallback 2026-10-10 12:05:14 -04:00
Brandon Thomas cecbd6cfb3 Merge origin/main into codex/ribbon-keytips 2026-10-10 12:05:04 -04:00
Brandon Thomas ea9d4c6b32 Merge origin/main into codex/xlsb-import 2026-10-10 12:04:33 -04:00
Brandon Thomas 11a921becb Merge remote-tracking branch 'origin/main' into pr-116 2026-10-10 12:04:22 -04:00
Brandon Thomas 15e0f0b6be Merge remote-tracking branch 'origin/main' into pr125 2026-10-10 12:04:21 -04:00
Brandon Thomas 1ded850ee6 Merge pull request #89 from dylanmtaylor/chore/update-actions
chore: bump github actions to fix Node 20 deprecation warnings
2026-10-10 11:57:45 -04:00
Brandon Thomas bd0ccd41b5 Merge pull request #35 from harrisonoconnorhover/fix/ribbon-dropdown-chevron
Fix missing dropdown arrows on large ribbon buttons (#26)
2026-10-10 11:57:44 -04:00
Brandon Thomas 2ad184c2d6 Merge pull request #44 from harrisonoconnorhover/codex/merged-cell-editing
Fix disappearing text when editing merged cells (#40)
2026-10-10 11:57:43 -04:00
Brandon Thomas 886fb0098b Merge pull request #46 from harrisonoconnorhover/codex/header-autofit
Fix header double-click AutoFit for selected columns and rows (#42)
2026-10-10 11:57:42 -04:00
Brandon Thomas 2cb5405b20 Merge pull request #47 from harrisonoconnorhover/codex/popup-dismissal
Fix worksheet popups staying open after outside clicks (#41)
2026-10-10 11:57:42 -04:00
Brandon Thomas 34ed83d13f Merge pull request #8 from switch87/desktop-log-file
Desktop: write log records to standard error and a rotating log file

# Conflicts:
#	apps/gridcraft/src/main.rs
2026-10-10 11:57:41 -04:00
Brandon Thomas 0feb404c68 Merge pull request #22 from DWAA1660/fix/windows-dx12-startup
Default Windows startup to DirectX 12
2026-10-10 11:57:31 -04:00
Brandon Thomas 0796c50816 Merge pull request #75 from DWAA1660/fix/71-snapshot-instructions
Fix the documented offscreen snapshot command (#71)
2026-10-10 11:57:30 -04:00
Brandon Thomas 674d422dc0 Merge pull request #77 from DWAA1660/fix/73-vertical-scrollbar
Add the missing vertical worksheet scrollbar (#73)
2026-10-10 11:57:29 -04:00
Brandon Thomas e165db1ffd Merge pull request #74 from DWAA1660/fix/70-inherit-cell-formatting
Preserve whole-sheet formatting when entering empty cells (#70)
2026-10-10 11:57:28 -04:00
Brandon Thomas f8b98775b8 Merge pull request #96 from harrisonoconnorhover/codex/system-theme
Add System appearance alongside Light and Dark themes
2026-10-10 11:57:27 -04:00
Brandon Thomas 38369a7566 Merge pull request #106 from harrisonoconnorhover/codex/border-previews
Preview border presets and fix shared-edge removal
2026-10-10 11:57:27 -04:00
Brandon Thomas 7f6739e665 Merge pull request #119 from agammann/fix/text-to-columns-escaped-quotes
Preserve doubled text qualifiers in Text to Columns
2026-10-10 11:57:26 -04:00
Brandon Thomas f736286f24 Merge pull request #50 from LloydNicholson/rotated-wrap-text
Issue #48: rotated text with Wrap Text draws upright (grid and print)

# Conflicts:
#	crates/ui-egui/tests/interaction.rs
2026-10-10 11:57:25 -04:00
Brandon Thomas 0aaaf9aeab Merge pull request #53 from LloydNicholson/general-number-fit
Issue #51: General numbers fit by the cell's own font, not 11pt
2026-10-10 11:57:15 -04:00
Brandon Thomas 7f9d77a12a Merge pull request #60 from MarekSpodBiedry/issue-58
ROUND: keep 15 significant digits when asked for 15+ digits, so ROUND(0.1+0.2,15) is 0.3 (#58)
2026-10-10 11:57:14 -04:00
Brandon Thomas 882a19568e Merge pull request #68 from LloydNicholson/fix/date-1900-feb-29
Issue #124: DATE(1900,2,29) is serial 60, as in Excel
2026-10-10 11:57:14 -04:00
Brandon Thomas 453882c6fe Merge pull request #67 from LloydNicholson/fix/sumif-sum-range-resize
Issue #123: SUMIF/AVERAGEIF size the sum range like the criteria range
2026-10-10 11:57:13 -04:00
Brandon Thomas 62d84cbbf5 Merge pull request #65 from MarekSpodBiedry/issue-63
XLSX: write _xlpm. prefix on LET/LAMBDA parameter names, strip it on read (#63)
2026-10-10 11:57:12 -04:00
Brandon Thomas 54df7e1fc5 Merge pull request #115 from nihilist-narwhal/feat-spill-range-operator
Formulas: the spill range operator (A1#)
2026-10-10 11:57:11 -04:00
Brandon Thomas c30a720998 Merge pull request #114 from nihilist-narwhal/fix-defined-name-entry
Names: R1C1-style names, Create from Selection bottom/right, LAMBDA name case
2026-10-10 11:57:10 -04:00
Brandon Thomas 986b6c6ea6 Merge pull request #113 from nihilist-narwhal/fix-defined-name-scopes
Names: keep sheet-level names with their sheet on move, copy and delete
2026-10-10 11:57:09 -04:00
Brandon Thomas 1cdee3ee02 Merge pull request #111 from nihilist-narwhal/fix-protection-commands
Protection: enforce locked cells for every command, keep hidden formulas hidden
2026-10-10 11:57:08 -04:00
Brandon Thomas a678c5d25f Merge pull request #34 from MarekSpodBiedry/issue-21
Fix: inserting or deleting rows, columns or cells cancels copy/cut mode (#21)
2026-10-10 11:57:08 -04:00
Brandon Thomas e92a67bbba Merge pull request #112 from nihilist-narwhal/fix-shifted-cell-references
Insert/Delete Cells: adjust references like Excel
2026-10-10 11:57:07 -04:00
Brandon Thomas 1b20cb873d Merge pull request #85 from nihilist-narwhal/xlsx-spill-cached-errors
XLSX: cache #SPILL! and #CALC! as #VALUE! so Excel can open the file
2026-10-10 11:57:06 -04:00
lloydandClaude Opus 5.5 3509bcfd87 macOS: open documents from Finder, the Dock and open -a (#69)
Double-clicking a workbook, Open With, dropping on the Dock icon and
`open -a GridCraft book.xlsx` send the app a kAEOpenDocuments Apple event
instead of command-line paths. winit 0.30 doesn't handle it, so AppKit
answered "GridCraft cannot open files in the Excel Workbook format".

Register the handler with the audited fmv-macos-events crate that PdfCraft
and PhotoCraft already use: it does the Objective-C interop (unsafe, which
this workspace forbids) behind a safe main-thread API and leaves winit's
delegate alone. Opened paths go through SheetApp::open_path; a quit event
closes the window. The registration lives in main() until the event loop
returns, so the event that launched the app is caught too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 14:17:14 +02:00
Fabio LussiandClaude Opus 5.5 ded67f51d2 fix(fill): clamp month and year date series to the month's last day
Fill Series by month used the previous cell's day as an overflowing DATE()
day, so Jan 31 + 1 month became Mar 3 and February was skipped. The same
overflow affected year steps from Feb 29 and the autofill month pattern.

Each item is now computed from the start date plus n months and the day is
clamped to the target month's length (Jan 31, Feb 28, Mar 31, Apr 30), so
the clamp does not compound. Leap years are handled.

Fixes #132

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 13:28:07 +02:00
Fabio LussiandClaude Opus 5.5 61b264ac21 functions: MIN() accepts zero arguments
Excel documents the first argument of MIN as optional and returns 0
when there are no numbers. MIN was registered with a minimum of one
argument, so =MIN() returned #VALUE!. The aggregate already returns 0
for an empty list, so only the registered arity needed to change.

Fixes #138

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 13:26:36 +02:00
nihilist-narwhal f16fed557e Charts: write and read chartex parts
Histogram, box & whisker, waterfall, funnel, treemap and sunburst charts
were written as clustered columns, and reading skipped such charts in
files made by Excel, which keeps them as cx:chartSpace (chartex) parts.

The writer now writes these kinds as chartEx parts, as Excel lays them
out: the data goes through hidden _xlchart.v1.N workbook names, each
part comes with chart style and colour parts, and the drawing frames it
in mc:AlternateContent with a text-box fallback. Fills are written out
(series in theme accents, waterfall decreases and treemap/sunburst boxes
in their own, a white chart area), so they don't depend on the style
part. The reader reads the parts back (resolving the _xlchart names,
which aren't kept as names) with data, title, axis titles, legend,
labels and colours, and follows mc:AlternateContent in drawings.
2026-10-10 06:25:24 -05:00
nihilist-narwhal e5d34fd63a Recalc: dynamic arrays don't spill in tables
Excel doesn't support spilled arrays in tables: a formula such as
=SEQUENCE(2) entered in a table cell shows #SPILL! ("Spill range in
table"). GridCraft spilled it over the table's cells. An array whose
formula is in a table is now blocked, both when it is computed and when
it is written back.
2026-10-10 05:40:36 -05:00
nihilist-narwhal 8011191824 Go To: a table name selects the table's data
Go To (and the Name Box) with a table's name selected the whole table,
header and totals rows included. In Excel a table's name stands for its
data rows, as in formulas (=SUM(Table1) adds only the data).
2026-10-10 05:30:49 -05:00
nihilist-narwhal 985257b166 Tables: typing in the header row renames the column
Editing a table's header cell changed only the cell: the column kept its
old name, so =SUM(Table1[a]) still worked after the header read "zz",
and saving wrote the old names back into the header row, undoing the
edit on reopening. As in Excel, the column now takes the new header;
an emptied header becomes ColumnN and a repeated one gets a number
("a2"), written back into the cell, and structured references follow
the new name.
2026-10-10 05:30:49 -05:00
Harrison O'Connor-Hoover 8846dadc52 Fix #128: preserve references when cutting cells across sheets 2026-10-10 06:11:29 -04:00
Brandon Thomas c1b1eb6757 Merge pull request #109 from harrisonoconnorhover/codex/fast-drag-selection
Preserve quick selection drags and clarify the fill handle
2026-10-10 06:07:57 -04:00
Brandon Thomas 6f52f1fd3d Merge pull request #94 from harrisonoconnorhover/codex/keyboard-navigation
Fix Enter navigation returning to the last clicked cell
2026-10-10 06:07:56 -04:00
Brandon Thomas 14b59a71f5 Merge pull request #97 from harrisonoconnorhover/codex/file-menu
Add a visible File menu to the shared ribbon
2026-10-10 06:07:56 -04:00
Brandon Thomas 1c6cb3bce9 Merge pull request #95 from harrisonoconnorhover/codex/screenshot-timeout-advice
Recommend supported recovery steps after a screenshot timeout
2026-10-10 06:07:55 -04:00
nihilist-narwhal 97f7dca886 Recalc: INDIRECT and OFFSET see spills laid out in the same pass
A formula whose references are only known while evaluating isn't in the
dependency graph, so when it read a spill area before the array was laid
out in the same pass, nothing evaluated it again. With the full
recalculation now laying every spill out afresh, =INDIRECT("F7") over
a spill moved by an inserted row read 0 after Calculate Now. Such
formulas are evaluated once more when a pass computed any array.
2026-10-10 04:59:27 -05:00
nihilist-narwhal be8e379ca0 Recalc: formulas over a blocked spill see #SPILL!
A dynamic array that couldn't spill was only rejected when results were
written back, after formulas evaluated later in the same pass had read
the array as if it had spilled. With 1s in A1:C3 except B2 =
SEQUENCE(2,2,9) (blocked), =SUM(A1:C3) gave 47 after a full
recalculation (opening a file, Calculate Now) instead of #SPILL!; a
reader through OFFSET kept the wrong value even when entered one cell
at a time. The spill area is now checked as soon as the array is
computed, so the anchor is #SPILL! for everything after it.
2026-10-10 04:45:41 -05:00
nihilist-narwhal 303eabaad1 Recalc: an array that read another array's old spill is evaluated again
When two dynamic arrays were recalculated in the same pass and the
first read the second's spill area before the second was evaluated, it
read the old values. Formulas reading a spill area that changed are
evaluated again, but dynamic arrays were left out of that second round
(only to keep an array from re-queuing itself), so with D11 =
SEQUENCE(1,3,A1) and G5 = UNIQUE(VSTACK(F9:F12,A1)), changing A1 from 1
to 10 left 3 in G6 instead of 12. Only the array itself is left out
now.
2026-10-10 04:42:51 -05:00
nihilist-narwhal 880163d135 Recalc: a spill that goes away unblocks the arrays it blocked
With =SEQUENCE(5) in F8 and =SEQUENCE(1,3) in E10 (blocked by F10),
typing 0 into F9 blocks F8's array, which frees F10, but E10 stayed
#SPILL! until a full recalculation. When a formula stops spilling over
an area, #SPILL! anchors above or to the left of it are evaluated again.
2026-10-10 04:36:06 -05:00
nihilist-narwhal e51c1d98fb Recalc: clearing a distant blocker unblocks the spill
Clearing a cell re-evaluated #SPILL! anchors only within 64 rows and
columns above and to the left of it, so =SEQUENCE(100) in A1 stayed
#SPILL! after the blocker in A90 was cleared. Emptied cells now look
for blocked anchors any distance above or to the left, with one pass
over the formulas per sheet however many cells were cleared.

Fixes #139.
2026-10-10 04:31:28 -05:00
nihilist-narwhal dcc5434bc8 Recalc: structural edits don't leave old spills behind
Inserting or deleting rows and columns moved formula cells but not the
values they had spilled, and the full recalculation that follows
reconciled spills only at the formulas' new positions. =SEQUENCE(3) in
A5 with row 1 deleted showed #SPILL! in A4 (blocked by its own old
values in A6:A7); deleting the anchor's row left 2 and 3 behind. A full
recalculation now drops all spills and lays them out again from the
formulas.

Fixes #133.
2026-10-10 04:27:44 -05:00
nihilist-narwhal fc2f00bd50 Recalc: a range ending in INDEX depends on the cells it spans
=SUM(C3:INDEX(B9:C11,2,2)) adds C3:C10, but only C3 and B9:C11 were
recorded as its precedents, so typing into C5 left the total unchanged
until a full recalculation. A range whose ends are function results now
depends on the box spanned by the references inside it, which contains
any cell those functions can return.
2026-10-10 04:24:42 -05:00
nihilist-narwhal 48910d71d2 Recalc: replacing or clearing a spilling formula removes its spill
Typing a value over a dynamic array formula, or clearing it, left the
values it had spilled: with =SEQUENCE(3) in A1, typing 2 into A1 kept
2 and 3 in A2:A3, and =SUM(A1:A3) gave 7. Only formulas are evaluated
again, so the old spill of a cell that no longer holds a formula was
never written back. It is now removed when the formula goes, and the
formulas reading its area are recalculated.
2026-10-10 04:24:41 -05:00
nihilist-narwhal 5ad3c6eed3 Paste Special operations: keep text, errors and formulas
Add, Subtract, Multiply and Divide replaced every cell that didn't hold
a plain number with the pasted value: multiplying a column by 1 turned
numbers stored as text, headers and #N/A all into 1, and a formula into
a constant. As in Excel, numbers stored as text now take part (the
usual way to turn them into numbers), other text and errors stay, and
a formula is kept and combined with the pasted number: =(B3*2)*1.
2026-10-10 03:51:49 -05:00
nihilist-narwhal 60b60619b2 AutoFill: refuse a source as large as the sheet
The target was capped at 5 million cells but the source wasn't: with the
whole sheet as source and A1 as target, AutoFill read all 17 billion
source cells one column at a time and never finished.
2026-10-10 03:46:15 -05:00
nihilist-narwhal e5af1fcbff Spilled blank cells show 0
A formula's result that is a blank cell shows 0, but blanks inside an
array result spilled as blank cells: =A1:A3, or FILTER or SORT of a
range with blanks, left empty cells that ISBLANK saw as blank and
COUNT skipped. Excel shows 0 in each. GROUPBY and PIVOTBY keep the
blank cells of their own layout.
2026-10-10 03:19:45 -05:00
nihilist-narwhal 62b17379e3 Ranges keep their size past the used range
A multi-cell reference was read only up to the sheet's used range, so
the array it gave depended on what else was on the sheet:
ROWS(A1:A10*1), COUNTBLANK(A1:A10) and SUMPRODUCT(--(A1:A10="")) came
out smaller than in Excel, and changed as cells were entered elsewhere
without the formula recalculating. References of up to 16,384 cells now
keep their size; larger ones (A:A, ranges reserved for data to come
such as $A$2:$A$50000) still stop at the used range, so that formulas
over them stay fast.
2026-10-10 03:19:45 -05:00
nihilist-narwhal 1b0b2009aa Current region: grow past 10,000 rows, in linear time
current_region (Ctrl+A, and the range that sort, filter, AutoSum,
tables and Get Data use when one cell is selected) grew the region one
ring of cells per step and stopped after 10,000 steps, rescanning every
cell of the ring each time. With 20,000 rows of data and one cell
selected, data.sortDescending sorted only the first 10,001 rows and
left the rest as they were; a 100,000-row region took 30 s and was cut
at row 10,001.

It now grows one side at a time while the line next to that side has
data (diagonals included), checking only the cells of that line, with
no step limit.
2026-10-10 03:17:10 -05:00
nihilist-narwhal a059c8e196 Repeated headers: number pivot fields and table columns in linear time
Each header was checked against every name before it, once per suffix
tried, so a source whose headers repeat (a row of thousands of equal
labels, such as check boxes) took cubic time: 4,000 columns took 28 s
in Recommended PivotTables, and a row of 16,384 hung the app, in
PivotTables, in Insert Table and in Get Data from Table/Range. Taken
names and the next suffix of each header are now kept in hash maps, in
the pivot source, in table creation and in the XLSX pivot cache; the
names are the same as before.
2026-10-10 03:05:48 -05:00
nihilist-narwhal 7fece30d49 Remove Duplicates: compare only the part of the range with data
Given whole columns ("range":"D:D"), Remove Duplicates compared a
million blank rows and reported 1,048,573 removed duplicates; given the
whole sheet it ran for minutes, as it also did on a table resized to
the whole sheet. Rows and columns past the used range are blank, so
they are left out: the result is the same and the counts match the
data.
2026-10-10 02:49:31 -05:00
nihilist-narwhal 684567cc9a Whole-sheet selection: Fill and Remove Duplicates stay within the data
With the whole sheet selected (Ctrl+A on an empty sheet), Fill Down,
Right, Up and Left tried to fill all 17 billion cells and ran out of
memory, and Remove Duplicates scanned every row for minutes. Fill Up
and Fill Left also took their source row or column before narrowing the
selection to the data, so they filled up to row 1,048,576 even when the
sheet had data.

Whole rows and columns now narrow to the used range before anything
else (nothing to do on an empty sheet), Remove Duplicates works on the
active cell of an empty sheet, and a fill of more than 5,000,000 cells
is refused, as Auto Fill already does.
2026-10-10 02:33:26 -05:00
nihilist-narwhal 439df2ae3a selection.move: Ctrl+arrow without a direction stays put
jump() searched for the next filled cell by stepping (dr, dc); with
neither set, the step never moved, so selection.move {"jump":true}
from a blank cell of a sheet with content looped forever (found with
an agent call that left out dr and dc). It now returns the cell it
started from.
2026-10-10 02:20:21 -05:00
lloydandClaude Opus 5.5 e893621d76 Web app: committing a cell no longer traps on the clock
Every edit goes through cmd::commit, which read std::time::Instant::now()
up front for GRIDCRAFT_PROFILE timing, whether profiling was on or not.
wasm32-unknown-unknown has no clock: Instant::now panics there, and with
panic=abort the browser reports `RuntimeError: unreachable`. So in the
web app, typing 1 into A1 and pressing Enter trapped (#118). The native
apps and the CLI have a clock and were unaffected.

commit now reads the clock only when GRIDCRAFT_PROFILE is set, and
never on wasm. The other clock reads (NOW(), the current year for typed
dates, the UI's frame timer) already skip wasm.

Native tests can't see this trap, so clippy.toml now disallows
Instant::now and SystemTime::now. A clock read has to be gated off wasm
and allowed at the call, and `cargo clippy -D warnings` fails on the old
commit code. The existing, already-gated reads and the native-only perf
example allow it.

Checked by building the engine for wasm32-unknown-unknown into a small
cdylib that runs cell.set A1=1 on a new workbook, and running it in
Node: before the fix it traps with `RuntimeError: unreachable`, after
it returns normally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-10 09:03:33 +02:00
nihilist-narwhal c650c2828f Legacy array formulas: fill the range they were entered in
A Ctrl+Shift+Enter array formula was evaluated like a dynamic array:

- Read from a file, the cached values in its range were kept as
  constants, so the formula showed #SPILL! (any multi-cell array
  formula saved by Excel or LibreOffice).
- Entered over C2:C4 with a two-value result, C4 stayed blank where
  Excel shows #N/A, and a single-cell array formula spilled.
- On save, the values of its other cells were not cached.

The result is now fitted to the range: a single row or column repeats
across it, cells past the result show #N/A, and a larger result is cut
off. Reading drops the cached values inside the range, entering clears
the range, and saving caches its values. The formula bar shows the
formula in braces, {=B2:B3*2}.
2026-10-10 01:53:55 -05:00
agammann 06cb377c54 Fix escaped quotes in Text to Columns 2026-10-09 22:47:38 -07:00
nihilist-narwhal bf1381253f Charts: scatter and bubble charts with text X values number the points
A scatter or bubble chart whose X values are text (a first column of
labels) drew no points, as none of its X values were numbers. Like
Excel, such X values are now ignored and the points numbered 1..n.
2026-10-09 23:31:26 -05:00
nihilist-narwhal fddd08bec3 Charts: Switch Row/Column on charts read from a file
chart.switchRowColumn did nothing on a chart read from a file: only
charts made by insert.chart keep their source range. Without one, the
command now takes the block the series' names, categories and values
span (when they're all on one sheet), and keeps it.
2026-10-09 23:31:26 -05:00
nihilist-narwhal 925bf22e24 Charts: combo and stock charts keep their kind in XLSX
A combo chart whose series have no kind of their own (as insert.chart
makes them) was written as one column group, and a stock chart as
clustered columns, so both reopened as clustered columns. Combo series
are now written as drawn (the first as columns, the others as lines),
and stock charts as a stockChart group (as lines when they don't have
the 3 or 4 series a stock chart needs).
2026-10-09 23:31:18 -05:00
nihilist-narwhal 9c29ef3fff Formulas: the spill range operator A1#
formula::parse("Sheet1!$D$1#") failed with "unknown error literal".
A # right after a cell reference is now the spill range operator: it
evaluates to the anchor's current spill range, or #REF! when the cell
doesn't spill (or its spill is blocked). Its users depend on the
anchor, so they recalculate when the spill grows or shrinks. Names can
use it.

Files have no # operator: like Excel, the writer stores A1# as
_xlfn.ANCHORARRAY(A1), and the parser reads that back as A1#.
2026-10-09 23:29:35 -05:00
nihilist-narwhal d4d38fd224 Names: calls of LAMBDA names keep the name's case
The parser upper-cases function names, so =Double(4) showed as
=DOUBLE(4). Calls of LAMBDA names are now spelled like the name when
a formula is entered and when a file is read.
2026-10-09 23:27:39 -05:00
nihilist-narwhal b28b4b729f Names: Create from Selection uses bottom and right, keeps existing names
formulas.createFromSelection ignored bottom and right, and replaced any
workbook name with the same label without asking. Bottom-row and
right-column labels now name the cells above and to their left. An
existing name is kept and listed in the result's skipped, unless
replace is set (Excel asks; a command doesn't open dialogs).
2026-10-09 23:27:38 -05:00
nihilist-narwhal 8029433b1c Names: refuse R1C1-style names
valid_name refused R and C but took R1C1, R2, C3 and RC, which Excel
refuses because they read as R1C1 references.
2026-10-09 23:27:38 -05:00
nihilist-narwhal 68fac6d861 Insert/Delete Cells: adjust references like Excel
Delete Cells built the references' edit and then discarded it, so
references into the deleted cells didn't become #REF!, and Insert Cells
treated the shift as a move of everything below, so =SUM(A1:A5) didn't
grow to A1:A6 when A3 was inserted.

Two new structural edits, InsertCells and DeleteCells, adjust a
reference like inserting/deleting rows (columns) when it lies within the
shifted columns (rows), and leave it as it is otherwise, as Excel does.
Formulas, defined names, chart series, conditional-format, validation,
table and print-area ranges, notes, links and sparklines follow.
2026-10-09 23:27:21 -05:00
nihilist-narwhal e294345599 Protection: keep hidden formulas hidden
On a protected sheet a formula formatted Hidden still showed with Show
Formulas on, matched Find in formulas, and showed in the formula bar
when a cell of its spill range was selected.
2026-10-09 23:25:58 -05:00
nihilist-narwhal 2a3d1ffd7f Protection: refuse every edit of a locked cell on a protected sheet
Only cell.set checked protection. The check now runs where every edit
is committed: an edit that changes the value or formula of a locked
cell on a protected sheet is refused with Excel's message, whichever
command made it (clear, paste, fills, setValues, replace, goal seek,
sort, insert/delete cells...).

Inserting and deleting rows and columns follow the protection's
options, and deleted lines must not hold locked cells.
2026-10-09 23:25:58 -05:00
nihilist-narwhal b53a190ea1 Names: keep sheet-level names with their sheet
Moving a sheet left its sheet-level names on whatever sheet took its
index, and copying it shifted nothing and copied no names. Moving now
re-indexes name scopes, and a copy gets copies of the sheet's names,
referring to the copy, as in Excel.

Deleting a sheet left names that referred to it pointing at nothing;
they now become #REF!. formulas.deleteName honours scope, and the Name
Manager's Delete passes it.
2026-10-09 22:52:49 -05:00
Harrison O'Connor-Hoover 198e8ecb05 Issue #28: retain quick selection drag endpoints and clarify fill handle 2026-10-09 23:05:46 -04:00
Harrison O'Connor-Hoover b2386e1c23 Issue 30: preview border presets and clear shared edges 2026-10-09 22:45:41 -04:00
neko233-com 12bfdb0798 i18n: add Chinese, Korean and Russian interface languages 2026-10-10 10:24:09 +08:00
harrisonoconnorhover c51e51fe7b #92: import XLSB worksheet data and saved formula results 2026-10-09 22:19:36 -04:00
harrisonoconnorhover da0bf32d8a #16: import ODS worksheet data without overwriting source files 2026-10-09 22:09:09 -04:00
harrisonoconnorhover daf4591da0 Expose basic file operations in the shared ribbon (#93) 2026-10-09 21:35:53 -04:00
harrisonoconnorhover 922847a1ed Add system-following interface appearance (#72) 2026-10-09 21:35:21 -04:00
harrisonoconnorhover 91d44508b1 Correct screenshot timeout recovery advice (#78) 2026-10-09 21:27:18 -04:00
harrisonoconnorhover 698a2a8009 Keep keyboard navigation separate from pointer clicks (#87) 2026-10-09 21:26:06 -04:00
Dylan M. Taylor 2b1da77e46 chore: bump github actions to fix Node 20 deprecation warnings 2026-10-09 20:08:28 -04:00
nihilist-narwhal 311b1a593f Contributors: add nihilist-narwhal 2026-10-09 17:14:59 -05:00
nihilist-narwhal cd083cfc50 XLSX: cache #SPILL! and #CALC! as #VALUE!
They are not error codes of the file format, and Excel refuses to open a
file whose cached values contain them ("Parameter error"). Any workbook
with a blocked spill could not be opened in Excel. Excel caches these
errors as #VALUE! itself.
2026-10-09 17:14:59 -05:00
harrisonoconnorhover 628732ef58 Enable inline editing of worksheet text boxes (#56) 2026-10-09 17:47:58 -04:00
Eduardo Soares f424d7d56b i18n: Brazilian Portuguese interface language (#79)
Adds PtBr to the interface-language system from #31: a PORTUGUESE table
covering the same 259 chrome strings as JAPANESE (a test keeps the two
tables in step), Excel's pt-BR wording throughout, "pt"/"pt-br" codes
(serde-stored as "pt"), Português (Brasil) in the switcher, the
app.language.portuguese command, and first-run detection of a pt-BR
system locale via the existing tag reduction.
2026-10-09 18:18:57 -03:00
Dylan M. Taylor 4d46b9170b ci: publish Flatpak repository to Pages 2026-10-09 17:14:43 -04:00
DWAA1660andCodex 165e6c8a3b M2: add a vertical worksheet scrollbar (#73)
Reserve a strip beside the virtual grid for a theme-aware vertical
scrollbar. Support paging, dragging and wheel scrolling without changing
the active cell. Keep the scroll extent fixed during thumb dragging.

Co-authored-by: Codex <[email protected]>
2026-10-09 14:46:29 -06:00
DWAA1660andCodex 96b3ab3244 M2: document the supported offscreen snapshot example (#71)
Point both contributor instruction files to the UI crate's snapshot
example and identify it as a command to run from a source checkout.
Verified the documented command produces a readable sales dashboard PNG.

Co-authored-by: Codex <[email protected]>
2026-10-09 14:37:52 -06:00
DWAA1660andCodex d7174f8297 M2: preserve inherited formatting when entering empty cells (#70)
Resolve input styles from the destination cell, row or column before
parsing. Preserve inherited alignment, borders and number formats for
single-cell and bulk entry, including text paste and array formulas.

Co-authored-by: Codex <[email protected]>
2026-10-09 14:33:43 -06:00
MarekSpodBiedry b8b3ba0b0e XLSX: write _xlpm. prefix on LET/LAMBDA parameter names, strip it on read (#63) 2026-10-09 20:57:44 +02:00
lloydandClaude Opus 5.5 631a49ec30 Recalc: linear in the number of range formulas
Opening a workbook with a SUM(E:J) on each of 50,000 rows took 9 s
(1.7 s at 25,000, 0.4 s at 12,500), and editing a cell that 50,000
VLOOKUPs read froze the app for 40 s or more. Two things grew with the
number of ranges:

- Evaluating a range trims it to the sheet's used range, and
  Sheet::used_range walks every stored row. It ran once per range read,
  so a full recalc was rows x range formulas. The pass's host now works
  it out once per sheet (the workbook doesn't change during a pass);
  Host::used_range keeps the old behaviour for other hosts.
- The reverse index kept each column's range precedents in a Vec:
  finding a cell's dependents scanned every range in the column, and
  re-entering a formula ran a retain over each of its columns. Pasting
  a column, filling formulas down or sorting was quadratic. Each column
  (and each sheet's wide ranges) now has an interval index: sorted by
  start, with a segment tree of the largest end, so a lookup costs
  O(log n + matches). Removals mark entries dead and insertions wait in
  a small sorted set; Graph::settle merges them after each batch, so
  edits cost O(log n) amortised. Single-cell dependents are a set, so
  removing one is O(1). dependents_of_range asks each column once
  instead of once per cell.

Semantics are unchanged: whole rows and columns, other sheets, names,
tables, spills and volatile functions go through the same paths.

Release CLI, open + full recalc: 12.5k rows 0.39 s -> 0.06 s, 25k 1.83 s
-> 0.14 s, 50k 9.3 s -> 0.28 s. The 50k x 20 bug-hunt workbook: recalc
on open 87 s -> 1.7 s, editing C2 (100k dependents) 51 s -> 1.3 s;
filling 50k SUMs down 17 s -> 0.18 s, sorting 50k rows 9 s -> 0.14 s.

Tests: the interval index against a linear scan (inserts, removals,
revivals, merges) and its query cost in tree nodes; range, wide,
whole-column, whole-row and cross-sheet dependents after edits; and a
scaling test (open, change a column, re-enter every formula) that
allows 8x the time for 4x the rows. Before the fix it took 16x.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 20:51:15 +02:00
lloydandClaude Opus 5.5 8fe3276cb8 SUMIF/AVERAGEIF size the sum range like the criteria range
Excel adds up the range that starts at sum_range's top-left cell and has
the criteria range's height and width, whatever size sum_range has. With
A1:B3 = a,1 / b,2 / a,3, =SUMIF(A1:A3,"a",B1) is 4; GridCraft gave 1,
because if_numbers only saw sum_range's values (one cell) and read them
at the criteria positions. Its comment promised the resizing, but by then
the argument was a plain value.

The evaluator has the references, so it now does the resizing, as it does
for OFFSET and INDEX: for SUMIF and AVERAGEIF with three arguments, a
single-area sum range reference becomes resized_sum_range(sum, criteria
height, criteria width), cut off at the sheet's edge. It works across
sheets and through names. The dependency graph records the resized
range, so editing a cell inside it recalculates; when the criteria range
isn't a plain reference the formula is recalculated every time instead.
SUMIFS and AVERAGEIFS keep requiring same-size ranges (#VALUE!
otherwise).

Tests: a single-cell, shorter, wider, longer and horizontal sum range,
whole-column criteria, editing a cell of the resized range, the sheet
edge, another sheet and a defined name, and SUMIFS/AVERAGEIFS size
mismatches. They fail before the fix (1 instead of 4).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 20:44:18 +02:00
justinjohn0306 69709bd458 Line charts: smooth (spline) curves (issue #52)
Add support for Excel's "smoothed line" chart style. The smooth flag flows
model -> resolve -> chart render, persists through XLSX (<c:smooth val="1"/>),
and is toggled via the chart.addElement "smooth" element.

Rendering interpolates each gap-free run with a uniform Catmull-Rom spline
(0.5 tangent scale, 100 sub-segments per data segment), so the curve passes
through every data point and rounds the vertices — matching Excel's observed
behaviour. Long runs are still decimated before smoothing.

- model: Series.smooth (#[serde(default)], so old workbooks load unchanged)
- chart: SeriesData.smooth; smooth_run + catmull in render; wired through
  resolve and the sanitize() copy; draw_runs takes the flag (line + scatter)
- engine: chart.addElement element="smooth"
- xlsx: read/write <c:smooth val> instead of hard-coding val="0"
- tests: smooth_line_adds_interpolated_points_and_keeps_endpoints,
  smooth_line_splits_at_gaps, smooth_line_setting_round_trips
- examples/smooth_demo.rs: generates a straight+smooth side-by-side workbook

cargo xtask ci: all 7 steps pass.
2026-10-10 00:09:12 +05:30
lloydandClaude Opus 5.5 ecaead4c12 DATE(1900,2,29) is serial 60, as in Excel
serial_from_ymd worked out the real calendar date and then moved serials
up to 60 down by one. February 1900 has no 29th in the real calendar, so
DATE(1900,2,29) and DATEVALUE("2/29/1900") rolled over to 1 March (61),
and DATE(1900,3,0) gave 28 February (59). Excel's 1900 system keeps the
Lotus leap day: serial 60 is 29 February 1900, and DAY(60) already
said so.

The serial of the first of the month is now taken in Excel's calendar
(one lower up to February 1900), and the day, with any overflow, counts
on from there. So day and month overflow pass through serial 60 both
ways: DATE(1900,1,60), DATE(1900,4,-31) and DATE(1901,-10,29) are 60 too.
Month and day arithmetic is checked, so hostile values return None.

days_in_month_in gives February 1900 29 days in the 1900 system; EDATE
and EOMONTH use it, so EOMONTH(60,0) is 60 rather than the day before,
and the text parser uses it in place of its own special case. The 1904
system is unchanged (1900 is before its epoch).

Tests: serials around the leap day (overflow both ways, every serial
0-366 round-trips through its year, month and day), hostile months and
days, parsing 2/29/1900 and 1900-02-29, DATE/DATEVALUE/EDATE/EOMONTH
in the 1900 system and the 1904 system. The DATE, DATEVALUE and serial
cases fail before the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 20:36:08 +02:00
MarekSpodBiedry 2c2d92ef6b ROUND: keep 15 significant digits when asked for 15+ digits, so ROUND(0.1+0.2,15) is 0.3 (#58) 2026-10-09 19:29:29 +02:00
lloydandClaude Opus 5.5 903bbb096d Issue #51: General numbers fit by the cell's own font, not 11pt
grid.rs measured the digit width once, for an 11pt cell font, and
display_text judged how many General digits fit from that whatever the
cell's size. 9pt marks such as 100 in columns with a stored width of 4
(common in mark sheets) came out as ##. The width is now measured per cell
with its own font and size, as print.rs already does; the shared 11pt
measurement and its paint_quadrant parameter go away.

Test: a 9pt 100 in a 28px column draws in full, while 123456789 next to it
still shows ####. Fails before the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 17:23:15 +02:00
lloydandClaude Opus 5.5 ad6e77f6ef Issue #48: rotated text with Wrap Text draws upright (grid and print)
Narrow columns with tall, upright headers (mark sheets) set both a text
rotation and Wrap Text. The wrap path drew the text flat and returned before
the rotation was applied, so headers came out as 3-4 character fragments.

- Rotated text no longer takes the flat wrap path. Upright (+/-90 deg) text
  wraps to the row height, its lines stacking across the column; other
  angles keep one line, as before.
- Downward text was anchored at the bottom-left and ran out of the cell
  (over the row headers); it now starts at the top, one block-height in.
- Upright text no longer overflows into empty neighbours: its width is its
  line height, and the overflow repainted their gridlines.
- Print/PDF gets the same three fixes.

Tests: ui-egui interaction test (shapes drawn at +/-90 deg, inside a
one-column clip) and a print test (every text block on the page rotated,
a few long lines each). Each failed before the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 17:13:40 +02:00
harrisonoconnorhover 1d2df6126b Dismiss worksheet popups on outside clicks and focus loss (#41) 2026-10-09 10:32:07 -04:00
harrisonoconnorhover 38c11f6fb9 Fix header double-click AutoFit for selected ranges (#42) 2026-10-09 10:23:09 -04:00
harrisonoconnorhover b36f919410 Fix editing and formula bar reads in merged cells (#40) 2026-10-09 09:51:08 -04:00
harrisonoconnorhover 56c32750a2 Add initial ribbon keytips and legacy shortcuts for #33 2026-10-09 09:44:04 -04:00
justinjohn0306 6beb80ed36 Fonts: render Thai and Hebrew (and any non-Latin) instead of tofu (issue #32)
egui bundles only Latin glyphs, and the fallback chain appended just the
Han/Kana and Hangul faces, so Thai and Hebrew text rendered as tofu boxes
even though the text was read correctly.

Generalise the CJK fallback into a per-script fallback: every family now
also carries a Thai face (Leelawadee UI / Tahoma / Thonburi / Noto Sans
Thai) and a Hebrew face (David / Arial Hebrew / Noto Sans Hebrew). epaint
shapes the complex scripts itself via harfrust -- it only needed a face
that has the glyphs. The faces stay at the end of each chain, so Latin
still wins for Latin text.

The tests become script-general: a structural check that every family
ends with the loaded fallback faces, and a per-script render check that
the sample string resolves to a real glyph when the face is present.

Full bidi reordering of mixed LTR/RTL text is a separate epaint limitation
(no Unicode Bidi Algorithm); a pure other-script run is shaped correctly.
2026-10-09 17:06:36 +05:30
harrisonoconnorhover 51f3279135 Fix #23: copy selected cells as HTML tables 2026-10-09 05:56:08 -04:00
harrisonoconnorhover 28113c6c75 Fix #26: paint large ribbon dropdown chevrons 2026-10-09 05:28:48 -04:00
MarekSpodBiedry 4dd49f7b95 Fix: inserting or deleting rows, columns or cells cancels copy/cut mode (#21) 2026-10-09 10:45:50 +02:00
justinjohn0306 e8e010b446 i18n: switch the interface language (issue #20)
Add an interface-language preference. It defaults to the system's
language on first run (sys-locale, native only) and is switched by hand
from the View tab, next to Dark Mode, or with app.language.english /
app.language.japanese over the control channel. It is saved in ui.json.

Follows the filmcraft house convention: a Language enum and a
table of English-to-Japanese strings with English fallback, so coverage
can grow incrementally. Japanese chrome renders without any bundled
font: the CJK fallback faces already appended to every family cover
kana and kanji.

The ribbon chrome all flows through the small_button/big_button/
toggle_button/split_button/icon_button helpers and menu_items, so
translating there localises the whole ribbon in one place; the language
of the frame is read from egui context data (i18n::current). Command
ids, file names and document text are never translated.
2026-10-09 13:14:48 +05:30
justinjohn0306 7e24aa398a CI: satisfy newer clippy lints (toolchain drift, behavior-preserving)
Local clippy 1.96 flags pre-existing patterns the code has always had:
manual range-contains comparisons, a dead `|| true` filter and a
simplifiable boolean. None change behaviour; they only clear the lints
so `cargo xtask ci` passes on a current toolchain.
2026-10-09 13:08:28 +05:30
justinjohn0306 891514892a CJK text renders as tofu: fall back to a system CJK font
A Japanese (or Chinese/Korean) workbook opened fine — the engine reads the
strings correctly — but every kanji and kana drew as a .notdef box, because
egui's bundled fonts carry no CJK coverage and nothing added a CJK face to the
fallback chain.

Append a system CJK face to every font family (UI, cell, serif, mono): a
Japanese face first for correct kana/JIS kanji, a Chinese face for breadth, and
a Hangul face for Korean. epaint picks the first face in a family that has the
glyph, so Latin still renders from the Latin fonts and only Han/Kana/Hangul
reach the CJK fonts. No font bytes are bundled (AGENTS.md): families are loaded
from the OS, and a machine with no CJK font simply keeps the old behaviour.

Tests: the CJK keys end every family chain (Latin stays first); and the
proportional family resolves 「カテゴリ」 to real glyphs, not the replacement
character — verified to fail without the fallback.
2026-10-09 10:13:44 +05:30
DWAA1660andClaude Opus 5.5 881bab8b6a Default Windows startup to DirectX 12
eframe's default wgpu instance enables PRIMARY | GL on Windows. Creating
the OpenGL backend can crash inside AMD's atio6axx.dll before the window
appears, so the app exits silently at launch. When WGPU_BACKEND is not
set, the Windows instance now enables only DirectX 12; an explicit
WGPU_BACKEND is still honoured. macOS, Linux and web are unchanged.

Same fix as storytold/designcraft#168 and storytold/filmcraft#179.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LyVbT6Vv4BwWZ4hY8973qD
2026-10-08 19:40:12 -06:00
justinjohn0306 596b465bb1 Macros UX: Excel-style info bar, Macros dialog, status badge (issue #6)
The engine now preserves a workbook's VBA project, but the UI had no surface
for it and silently dropped every open-time warning. Give preserved macros an
honest, Excel-shaped home without a false "Enable Content":

- Info bar under the ribbon (Excel's message-bar slot) showing the warning a
  `file.open` result carries. A VBA project gets an amber bar reading "This
  workbook contains VBA macros. GridCraft keeps them intact when you save, but
  does not run them." with a "What this means" button; anything else becomes a
  blue informational bar. Dismissable; a clean open clears a stale notice.
- Macros dialog (Automate ▸ Macros, Alt+F8): lists GridCraft's own scripts and
  the preserved VBA project (presence + size, not module names — the blob is
  opaque). Mirrors Excel's Developer ▸ Macros without claiming to run VBA.
- Status-bar badge "Macros preserved (not executed)" whenever the workbook
  carries a VBA project.

New panel `notice_bar` reuses theme tokens (notice_warn_*/notice_info_*), so it
follows light/dark. Two new UI commands, `ui.notice` and `ui.notice.dismiss`,
reach it from the control channel.

Tests: info bar appears for a macro workbook and clears on dismiss; a non-VBA
warning becomes an info bar; clean open clears the notice; the macros dialog
lists the VBA entry; status bar renders with a VBA project; Alt+F8 opens the
dialog. Snapshot-verified in light and dark.
2026-10-09 05:20:04 +05:30
justinjohn0306 9c1d2c3b3a Add scripts/check-vba-roundtrip.sh: verify VBA preservation on a real file
Builds a macro-enabled .xlsm with a fake xl/vbaProject.bin, runs it through
`gridcraft-cli run`, and asserts the blob comes back byte-identical with the
macro-enabled content type and vbaProject relationship intact — the
open → edit → save path a user would exercise by hand.
2026-10-09 01:58:29 +05:30
justinjohn0306 726a31740e Preserve VBA macros on round-trip; never destroy a macro-enabled workbook (#6)
Opening an .xlsm and saving it silently stripped xl/vbaProject.bin, turning a
macro-enabled workbook into a macro-free one — data loss for anyone whose work
depends on macros. GridCraft still does not run VBA, but it now carries the
project through unchanged.

- model: `Workbook.vba_project: Option<Vec<u8>>` (base64 in JSON via a new
  `b64::opt` helper). `None` = no macros.
- xlsx read: capture the `vbaProject` relationship's bytes instead of warning
  and dropping them; warn that macros are kept but not executed.
- xlsx write: when present, emit `xl/vbaProject.bin` byte-identical, add the
  `.../relationships/vbaProject` relationship, switch the main part to the
  macro-enabled content type (`...sheet.macroEnabled.main+xml`) and add the
  `application/vnd.ms-office.vbaProject` override.
- engine: `view.macros` lists the preserved project alongside GridCraft's own
  scripts (`{"kind":"vba","executed":false}`), so callers can see it is there.
- ROADMAP: scope now "preserve, don't execute" (was "out of scope").

Tests: round-trip byte-identical blob + correct content types/relationship;
capture from a foreign-produced .xlsm; a macro-free workbook stays clean.
2026-10-09 00:54:10 +05:30
justinjohn0306 d9fd1b7305 CI: satisfy newer clippy lints (toolchain drift, behavior-preserving)
Local clippy (1.96) flags pre-existing code that an older toolchain accepted;
these lints fire on clean main and block `cargo xtask ci`. All rewrites are
behavior-preserving:

- core/date.rs, numfmt/render.rs, functions/math.rs, functions/stat.rs:
  `!x.is_finite() || x < a || x >= b` -> `!(a..b).contains(&x)` (Range::contains
  is false for NaN/inf, matching the existing is_finite guard).
- functions/util.rs: `!(A && !B)` -> `!A || B`.
- engine/cmd/file.rs: drop a dead `.filter(|| true)`.
- ui-egui/grid.rs: `find(|| true)` was always the first table (use `.first()`);
  `wrap || Justify || (nl && wrap)` -> `wrap || Justify`.
- ui-egui/formula_bar.rs: `tab || (enter && false)` -> `tab`.
- engine/cmd/spelling.rs: split the wasm/non-wasm dictionary init so the
  non-wasm `mut` no longer warns under wasm check.
2026-10-09 00:53:54 +05:30
justinjohn0306 2276eabba8 File open: recognize Excel password-protected (CFB) files, report clearly (#11)
Excel-encrypted workbooks are CFB/OLE2 compound files (magic D0CF11E0),
not zip packages. sniff() now returns Format::Encrypted for them, and
open_bytes reports a clear password-protected message instead of the
cryptic 'not a valid zip package' error.
2026-10-08 21:04:07 +05:30
justinjohn0306 cbc2430f4f Objects: anchor modes — images/charts/shapes follow cells on sort (#5)
Excel anchors a floating object to the grid in one of three ways, stored in the
file as the drawing anchor's `editAs`: "move and size with cells" (twoCellAnchor,
the default), "move but don't size with cells" (oneCellAnchor / editAs="oneCell")
and "don't move or size with cells" (editAs="absolute"). GridCraft had no such
concept: xlsx import dropped `editAs`, export always wrote a plain twoCellAnchor,
and sorting/filtering never moved an object — so pictures stayed put when their
rows were reordered.

Model: add `AnchorMode` on `Anchor` (serde default = MoveAndSize, so existing
documents round-trip unchanged).

xlsx: read the anchor kind and `editAs` into the mode; write it back out
(editAs="oneCell"/"absolute" as Excel does).

Engine: sorting now moves objects anchored inside the sorted body with their
lines, re-fitting "move and size" objects, keeping "move but don't size"
objects' size, and leaving absolute ones pinned. Structural insert/delete
honours the same rule (previously it moved every object's cell unconditionally
and ignored shapes). New `object.setAnchorMode` command sets an object's mode;
`arrange.selectionPane` reports it.

Tests: sort moves images with their rows; absolute objects stay put across a
sort and a row delete; move-only keeps its size; the mode survives an xlsx
round-trip; the drawing fixture parses all three anchor kinds.
2026-10-08 17:58:53 +05:30
Gert Pellin 26f325ec15 Desktop: no eprintln! on the log and panic paths
eprintln! panics when standard error is a broken pipe (a GUI launch on
Windows), and a panic inside the panic hook aborts. The "no log file"
message goes through log::warn! (standard error only by then); the panic
hook's fallback writes to standard error with write_fmt and ignores the
error. Same fix as storytold/vectorcraft#465.
2026-10-08 13:01:16 +02:00
justinjohn0306 f654615640 Fix: list and render installed system fonts (#4)
The font dropdown showed a hardcoded 17-name list and cells always
rendered in the built-in Calibri/role font, so a font installed on the
machine could not be listed or chosen. Both trace to one constraint:
egui panics when asked for a FontFamily::Name that was never bound to
font data, so only the 8 built-in roles were ever bound.

Scan the platform font folders for installed families (a bounded read of
each file's name table via skrifa, already compiled transitively through
epaint), bind the faces a workbook actually uses into egui as
fnt:{family}:{b|n}{i|n} roles chained to the defaults, and offer the
installed families in the font combos after the standard set. cell_family
returns the installed role when it is bound, else the previous bucketing,
so it never names an unbound family. The scan runs in the background and
the first frame that rebinds skips painting, like the existing startup
gate. Native only; wasm keeps the standard list.

Incidental: newer local clippy flagged pre-existing lints in untouched
crates (no toolchain is pinned); fixed behavior-preservingly so the gate
passes.
2026-10-08 16:04:14 +05:30
Gert Pellin 1c8d0b8fe5 Desktop: write log records to standard error and a rotating log file
The desktop app installed no logger, so every log::warn!/log::error! in
the workspace was discarded (a sample that failed to build, wgpu and naga
warnings), and panics a command's guard recovered from only reached
standard error. A launch from a desktop menu has no terminal either, so
there was nothing to attach to a bug report.

apps/gridcraft/src/logging.rs (no new dependency):
- standard error plus logs/gridcraft.log next to ui.json and prefs.json
  (~/.config/gridcraft/logs, or under $XDG_CONFIG_HOME); each launch
  rotates the previous log to gridcraft.1.log and .2.log, so the log of a
  run that crashed survives the next start; the file is capped at 16 MiB
- records logged before the settings directory is known are buffered
  (bounded) and written once the file is attached
- default levels: info for gridcraft*, warn for everything else;
  RUST_LOG replaces them with env_logger-style directives
- never panics: an unusable directory or a failed write leaves standard
  error as the only sink
- runs with GRIDCRAFT_NO_PREFS (agents' test runs) log to standard error
  only, so they don't rotate away the user's own logs

The logger is installed first in main, followed by a panic hook that
reports every panic, caught or not, through log::error! (with a backtrace
when RUST_BACKTRACE is set). The file is opened after argument parsing
(--version leaves no file). The start-up messages in main and the
control channel's go through the logger. Documented in README.md (Logs).
2026-10-08 12:06:39 +02:00
277 changed files with 62984 additions and 2763 deletions
+48
View File
@@ -0,0 +1,48 @@
# The AGENTS.md quality gate (`cargo xtask ci`: fmt, clippy -D warnings, tests, assets, layers,
# wasm, parity --check) on every pull request and every push to main, so a merge burst can't land
# a red tree that only the next agent session discovers.
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
gate:
name: cargo xtask ci
runs-on: ubuntu-24.04
timeout-minutes: 60
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: "0"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Linux build dependencies (winit, wgpu, rfd)
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev \
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
- name: Install Rust (stable + clippy, rustfmt, wasm32)
run: |
rustup toolchain install stable --profile minimal --component clippy,rustfmt \
--target wasm32-unknown-unknown
rustup default stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Quality gate
run: cargo xtask ci
+176
View File
@@ -0,0 +1,176 @@
name: Publish Flatpak repository to Pages
on:
release:
types: [published]
workflow_dispatch:
inputs:
release_tag:
description: "Published GitHub release tag to publish (for example, v1.2.3)"
required: true
type: string
permissions:
contents: read
concurrency:
group: flatpak-pages-${{ github.repository }}
cancel-in-progress: false
jobs:
build:
name: Build Flatpak repository
# Pre-releases (rc builds) never reach the stable branch: a published pre-release is skipped
# here, and the validation step below refuses a manual tag with a pre-release suffix.
if: github.event_name != 'release' || !github.event.release.prerelease
runs-on: ubuntu-24.04
permissions:
contents: read
# configure-pages only reads the Pages configuration (base_url); deploy needs write.
pages: read
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }}
APP_ID: ai.storyteller.gridcraft
steps:
- name: Configure Pages
id: pages
uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
- name: Install Flatpak repository tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends flatpak ostree
- name: Download and validate release bundles
shell: bash
run: |
set -euo pipefail
tag="$RELEASE_TAG"
if ! printf '%s' "$tag" | grep -Eq '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::Release tag '$tag' is not strict SemVer prefixed with v"
exit 1
fi
# A pre-release has a "-" before any "+build" metadata (v1.2.3-rc.1).
case "${tag%%+*}" in
*-*)
echo "::error::$tag is a pre-release; only stable releases are published to the Flatpak repository"
exit 1
;;
esac
published_tag="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$tag" --jq \
'select(.draft == false and .prerelease == false and .published_at != null) | .tag_name')"
if [[ "$published_tag" != "$tag" ]]; then
echo "::error::$tag is not a published stable (non-pre-release) release in $GITHUB_REPOSITORY"
exit 1
fi
version="${tag#v}"
mkdir -p bundles
gh release download "$tag" --repo "$GITHUB_REPOSITORY" \
--pattern SHA256SUMS.txt --dir bundles
for arch in x86_64 aarch64; do
asset="gridcraft-$version-linux-$arch.flatpak"
gh release download "$tag" --repo "$GITHUB_REPOSITORY" \
--pattern "$asset" --dir bundles
test -s "bundles/$asset"
(
cd bundles
awk -v file="$asset" '$2 == file || $2 == "*" file { print; found=1 } END { exit !found }' \
SHA256SUMS.txt | sha256sum --check -
)
done
test "$(find bundles -maxdepth 1 -type f -name '*.flatpak' | wc -l)" -eq 2
for arch in x86_64 aarch64; do
asset="bundles/gridcraft-$version-linux-$arch.flatpak"
validation_repo="$(mktemp -d)"
ostree --repo="$validation_repo" init --mode=archive-z2
flatpak build-import-bundle "$validation_repo" "$asset"
expected_ref="app/$APP_ID/$arch/stable"
ostree --repo="$validation_repo" refs | grep -Fxq "$expected_ref" || {
echo "::error::$(basename "$asset") does not contain $expected_ref"
exit 1
}
rm -rf "$validation_repo"
done
- name: Build repository and site
shell: bash
env:
PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }}
run: |
set -euo pipefail
site="$RUNNER_TEMP/site"
repo_dir="$site/flatpak/repo"
mkdir -p "$repo_dir"
ostree --repo="$repo_dir" init --mode=archive-z2
previous_url="${PAGES_BASE_URL%/}/flatpak/repo"
if curl --fail --silent --show-error --location \
--output /dev/null "$previous_url/summary"; then
ostree --repo="$repo_dir" remote add --no-gpg-verify previous "$previous_url"
ostree --repo="$repo_dir" pull --mirror previous
ostree --repo="$repo_dir" remote delete previous
fi
version="${RELEASE_TAG#v}"
for arch in x86_64 aarch64; do
flatpak build-import-bundle "$repo_dir" \
"bundles/gridcraft-$version-linux-$arch.flatpak"
done
# Prune unreachable objects and keep at most 3 commits per ref, so the Pages repository
# (re-mirrored and re-deployed on every release) does not grow without bound.
flatpak build-update-repo \
--prune --prune-depth=3 \
--title="GridCraft" \
--comment='Official GridCraft releases' \
--description='Official Flatpak repository for GridCraft' \
--homepage="https://github.com/$GITHUB_REPOSITORY" \
--default-branch=stable \
"$repo_dir"
for arch in x86_64 aarch64; do
ostree --repo="$repo_dir" rev-parse "app/$APP_ID/$arch/stable" >/dev/null
done
test -s "$repo_dir/summary"
base_url="${PAGES_BASE_URL%/}"
repo_url="$base_url/flatpak/repo/"
cat >"$site/flatpak/gridcraft.flatpakrepo" <<META
[Flatpak Repo]
Title=GridCraft
Comment=Official GridCraft releases
Description=Official Flatpak repository for GridCraft
Url=$repo_url
Homepage=https://github.com/$GITHUB_REPOSITORY
META
cat >"$site/flatpak/index.html" <<HTML
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>GridCraft Flatpak repository</title></head><body><main><h1>GridCraft Flatpak repository</h1><p>Latest published release: <strong>$RELEASE_TAG</strong></p><p><a href="gridcraft.flatpakrepo">Add the GridCraft repository</a></p><pre>flatpak remote-add --if-not-exists gridcraft $base_url/flatpak/gridcraft.flatpakrepo
flatpak install gridcraft $APP_ID</pre></main></body></html>
HTML
cat >"$site/index.html" <<HTML
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>GridCraft downloads</title></head><body><main><h1>GridCraft downloads</h1><p><a href="flatpak/">Flatpak repository</a></p><p><a href="https://github.com/$GITHUB_REPOSITORY/releases/tag/$RELEASE_TAG">Release assets</a></p></main></body></html>
HTML
touch "$site/.nojekyll"
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
path: ${{ runner.temp }}/site
include-hidden-files: true
deploy:
name: Deploy Pages
needs: build
runs-on: ubuntu-24.04
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
+4 -5
View File
@@ -51,16 +51,15 @@ jobs:
GRIDCRAFT_PACKAGE: ${{ inputs.package && '1' || '' }}
GRIDCRAFT_BUILD_SHA: ${{ github.sha }}
steps:
- uses: actions/checkout@v4
# Optional font input (docs: storytold/craft-fonts docs/integration.md); releases embed it.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Check out craft-fonts
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
path: craft-fonts
- name: Build in a FreeBSD VM
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1.5.9
with:
release: "14.3"
usesh: true
@@ -88,7 +87,7 @@ jobs:
cargo build --workspace --all-targets --locked
CRAFT_FONTS_DIR="$PWD/craft-fonts" cargo test --workspace --locked
fi
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: inputs.package
with:
name: release-freebsd
+4 -47
View File
@@ -1,5 +1,5 @@
# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax,
# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata.
# Quick release-pipeline checks without a Rust build: workflow and packaging-script syntax,
# Linux desktop metadata, and the Windows desktop-shortcut installer lifecycle.
name: Packaging lint
on:
@@ -19,48 +19,5 @@ concurrency:
jobs:
lint:
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@v4
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/gridcraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon.
if grep -oE '<Icon Id="[^"]*"' packaging/windows/gridcraft.wxs | grep -vE '\.(ico|exe)"$'; then
echo "::error::Icon Id must end in .ico or .exe"; exit 1
fi
desktop-file-validate packaging/linux/ai.storyteller.gridcraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.gridcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.gridcraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.gridcraft.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.gridcraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.gridcraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.gridcraft" and m["command"] == "gridcraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
+23 -366
View File
@@ -1,13 +1,3 @@
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "GridCraft v<version>". See docs/releasing.md.
# Copied from DesignCraft (craftrules release/playbook.md); keep the two in step.
#
# The signing jobs (macOS, Windows) and the draft-release job run in the `release` environment
# (restricted to the `release` branch), which holds the signing secrets. Every secret is
# optional: missing ones produce unsigned artifacts and a warning, never a failed build. The
# other jobs sign nothing and get no secrets, so a manual run from another branch is a dry run:
# they build and upload their artifacts, the environment refuses the signing jobs, and the
# draft-release job (which needs them) is skipped.
name: Release
on:
@@ -21,366 +11,33 @@ on:
default: ""
permissions:
contents: read
contents: write
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
GRIDCRAFT_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
jobs:
version:
name: version
runs-on: ubuntu-latest
# No `environment: release`: this job needs no secrets (see the header about dry runs).
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
steps:
- uses: actions/checkout@v4
- id: v
name: Resolve version
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### GridCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
# Optional font input (docs: storytold/craft-fonts docs/integration.md); releases always embed it.
- name: Check out craft-fonts
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@v2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/package.sh --arch universal
- uses: actions/upload-artifact@v4
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
# Optional font input (docs: storytold/craft-fonts docs/integration.md); releases always embed it.
- name: Check out craft-fonts
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build, sign, package
shell: pwsh
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@v4
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@v4
# Optional font input (docs: storytold/craft-fonts docs/integration.md); releases always embed it.
- name: Check out craft-fonts
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
path: craft-fonts
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/gridcraft$|metainfo|applications'
ldd target/release/gridcraft
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.gridcraft.yml')); assert m['id'] == 'ai.storyteller.gridcraft'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/gridcraft-$GRIDCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
web:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@v4
# Optional font input (docs: storytold/craft-fonts docs/integration.md); releases always embed it.
- name: Check out craft-fonts
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: release-web
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
- name: Apply version override
if: inputs.version != ''
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
- name: Build and zip
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/web/package.sh
- uses: actions/upload-artifact@v4
with:
name: release-web
path: dist/release/*
if-no-files-found: error
# FreeBSD has no hosted runners: freebsd.yml builds in a FreeBSD VM and, with package: true,
# uploads the release-freebsd artifact (gridcraft-<v>-freebsd-x86_64.tar.gz). It needs no
# secrets, so the called workflow runs without the release environment (and in dry runs).
freebsd:
name: FreeBSD
needs: version
uses: ./.github/workflows/freebsd.yml
with:
version: ${{ needs.version.outputs.version }}
version_override: ${{ inputs.version != '' }}
package: true
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, flatpak, web, freebsd]
# Belt and braces for branch dry runs: only the release branch drafts a release (the
# environment's branch rule refuses this job and the signing jobs anywhere else, too).
if: github.ref == 'refs/heads/release'
runs-on: ubuntu-latest
environment: release
permissions:
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@v4
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="GridCraft v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
app-name: gridcraft
app-title: GridCraft
craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
+6 -67
View File
@@ -17,71 +17,10 @@ concurrency:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
if: github.ref == 'refs/heads/release'
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@v4
with:
name: gridcraft-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@v4
with:
name: gridcraft-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'GridCraft'
foreach ($exe in 'gridcraft.exe', 'gridcraft-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'gridcraft-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "gridcraft-cli --version exited $LASTEXITCODE" }
Write-Output "ok gridcraft-cli --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'gridcraft.exe')) { throw 'uninstall left gridcraft.exe behind' }
Write-Output 'ok uninstalled'
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: gridcraft
app-dir: GridCraft
+3 -3
View File
@@ -26,7 +26,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
- **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).
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`).
- Crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
## Non-negotiables
@@ -43,14 +43,14 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
## Running and looking at the app
- `cargo run --release -p gridcraft -- --sample sales --control 7979` (sample workbook + control channel).
- Drive it: JSON lines on `127.0.0.1:7979`, 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): `cargo run --release -p gridcraft-cli -- snapshot --sample sales out.png`.
- **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) tracks status, milestones, parity and estimates. Update it whenever a milestone task lands. `cargo xtask parity` regenerates `docs/parity.md` from `crates/engine/src/catalog.rs`.
`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`.
## Contributor credits (About window)
+3 -3
View File
@@ -26,7 +26,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
- **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).
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`).
- Crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
## Non-negotiables
@@ -43,11 +43,11 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
## Running and looking at the app
- `cargo run --release -p gridcraft -- --sample sales --control 7979` (sample workbook + control channel).
- Drive it: JSON lines on `127.0.0.1:7979`, 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): `cargo run --release -p gridcraft-cli -- snapshot --sample sales out.png`.
- **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) tracks status, milestones, parity and estimates. Update it whenever a milestone task lands. `cargo xtask parity` regenerates `docs/parity.md` from `crates/engine/src/catalog.rs`.
`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`.
Generated
+267 -30
View File
@@ -121,6 +121,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aes"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
dependencies = [
"cipher",
"cpubits",
"cpufeatures",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -215,6 +226,7 @@ dependencies = [
"parking_lot",
"percent-encoding",
"windows-sys 0.60.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -446,6 +458,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "block2"
version = "0.5.1"
@@ -598,6 +619,16 @@ dependencies = [
"libc",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -696,6 +727,37 @@ dependencies = [
"libc",
]
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d#d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d"
dependencies = [
"tempfile",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d#d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d"
dependencies = [
"egui",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -745,6 +807,15 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "cursor-icon"
version = "1.2.0"
@@ -775,6 +846,16 @@ dependencies = [
"rayon",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1121,6 +1202,12 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "fixedbitset"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -1132,6 +1219,23 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "fmv-macos-events"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -1289,7 +1393,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a"
dependencies = [
"bytemuck",
"foldhash",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
@@ -1392,15 +1496,19 @@ dependencies = [
[[package]]
name = "gridcraft"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"arboard",
"craft-print",
"eframe",
"egui",
"fmv-macos-events",
"gridcraft-engine",
"gridcraft-ui-egui",
"image",
"log",
"muda",
"pollster 1.0.1",
"rfd",
"serde_json",
"winresource",
@@ -1408,7 +1516,7 @@ dependencies = [
[[package]]
name = "gridcraft-calc"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
@@ -1420,7 +1528,7 @@ dependencies = [
[[package]]
name = "gridcraft-chart"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-calc",
"gridcraft-core",
@@ -1431,18 +1539,21 @@ dependencies = [
[[package]]
name = "gridcraft-cli"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-engine",
"gridcraft-mcp",
"log",
"quick-xml",
"serde_json",
"zip",
]
[[package]]
name = "gridcraft-core"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"js-sys",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1450,7 +1561,7 @@ dependencies = [
[[package]]
name = "gridcraft-engine"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-calc",
"gridcraft-chart",
@@ -1466,11 +1577,12 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip",
]
[[package]]
name = "gridcraft-formula"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-core",
"serde",
@@ -1479,7 +1591,7 @@ dependencies = [
[[package]]
name = "gridcraft-functions"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-core",
"regex",
@@ -1487,7 +1599,7 @@ dependencies = [
[[package]]
name = "gridcraft-mcp"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-engine",
"log",
@@ -1496,44 +1608,52 @@ dependencies = [
[[package]]
name = "gridcraft-model"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
"serde",
"serde_json",
"sha2",
"thiserror 2.0.21",
]
[[package]]
name = "gridcraft-numfmt"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-core",
]
[[package]]
name = "gridcraft-pdf"
version = "0.4.0"
version = "0.6.1"
[[package]]
name = "gridcraft-ui-egui"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"craft-ui",
"egui",
"egui_kittest",
"epaint_default_fonts",
"gridcraft-chart",
"gridcraft-engine",
"gridcraft-xlsx",
"image",
"log",
"serde",
"serde_json",
"skrifa",
"sys-locale",
"toml",
"web-sys",
"zbus",
]
[[package]]
name = "gridcraft-web"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"eframe",
"egui",
@@ -1550,12 +1670,15 @@ dependencies = [
[[package]]
name = "gridcraft-xlsx"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"aes",
"gridcraft-core",
"gridcraft-formula",
"gridcraft-model",
"quick-xml 0.38.4",
"quick-xml",
"sha1",
"sha2",
"thiserror 2.0.21",
"zip",
]
@@ -1593,6 +1716,15 @@ dependencies = [
"smallvec",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -1601,7 +1733,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1610,7 +1742,7 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1625,6 +1757,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "image"
version = "0.25.10"
@@ -1651,6 +1792,15 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "inout"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
dependencies = [
"hybrid-array",
]
[[package]]
name = "is-docker"
version = "0.2.0"
@@ -2038,6 +2188,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2426,6 +2585,16 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "os_pipe"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -2474,6 +2643,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -2671,15 +2851,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quick-xml"
version = "0.38.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.41.0"
@@ -3003,6 +3174,28 @@ dependencies = [
"serde_core",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -3187,6 +3380,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "sys-locale"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
dependencies = [
"libc",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -3355,6 +3557,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "tree_magic_mini"
version = "3.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"petgraph",
]
[[package]]
name = "type-map"
version = "0.5.1"
@@ -3364,6 +3577,12 @@ dependencies = [
"rustc-hash 2.1.3",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
@@ -3637,7 +3856,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml 0.41.0",
"quick-xml",
"quote",
]
@@ -4222,6 +4441,24 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "wl-clipboard-rs"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"
dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
]
[[package]]
name = "x11-dl"
version = "2.21.0"
@@ -4287,7 +4524,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.4.0"
version = "0.6.1"
dependencies = [
"gridcraft-engine",
"serde_json",
+13 -2
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
[workspace.package]
version = "0.4.0"
version = "0.6.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
@@ -32,8 +32,12 @@ serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
rayon = "1"
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
quick-xml = "0.38"
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
sha2 = { version = "0.11", default-features = false }
# Decrypting password-protected workbooks ([MS-OFFCRYPTO]): AES and SHA-1, pure Rust (wasm-safe).
aes = { version = "0.9", default-features = false }
sha1 = { version = "0.11", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# ui
@@ -43,6 +47,13 @@ eframe = { version = "0.36", default-features = false }
egui_kittest = "0.36"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
# The desktop's preferred language, for the first-run interface language (native only).
sys-locale = "0.3"
# Font parser egui's epaint uses; the UI validates system font files with it before handing them
# to egui, which panics on a file it can't parse. Same version as epaint's, so no second copy.
skrifa = { version = "0.44", default-features = false, features = ["std"] }
# Real font bytes for tests (Ubuntu Light, compiled into epaint).
epaint_default_fonts = "0.36"
[workspace.lints.rust]
unsafe_code = "forbid"
+81 -8
View File
@@ -84,6 +84,10 @@
- **Compatible.** XLSX is the native format: styles, themes, formulas (including dynamic arrays),
tables, conditional formats, validation, comments, hyperlinks, charts, pictures, sparklines,
PivotTables and print settings round-trip. CSV and TSV too.
Excel 97-2003 `.xls` workbooks open with their values, formulas and number formats (formatting and objects not yet).
[XLSB worksheet data can be imported](docs/xlsb-import.md), using saved values instead of formulas.
[ODS worksheet data can be imported](docs/ods-import.md), using saved values instead of formulas.
[Static pictures can live inside cells](docs/cell-pictures.md), fitting their size and moving with the data.
- **Capable.** A dependency-graph calculation engine with dynamic arrays and spilling,
500+ worksheet functions plus LET, LAMBDA, MAP, REDUCE, SCAN, BYROW, BYCOL and MAKEARRAY,
structured table references, Excel's full number-format language, sort and AutoFilter,
@@ -105,6 +109,9 @@ cargo run --release -p gridcraft -- --sample sales --control 7979 # + JSON con
cargo xtask ci # fmt, clippy, tests, assets, layering, wasm
```
Choose Español under View → Interface language for [Spanish formula names, decimal commas, and semicolon arguments](docs/formula-input.md).
Workbooks, clipboard exchange, and programmatic APIs retain canonical English syntax.
### Web
```sh
@@ -115,6 +122,42 @@ cd apps/gridcraft-web && trunk serve --release # http://127.0.0.1:8771 (?sa
You need [trunk](https://trunkrs.dev) and the `wasm32-unknown-unknown` target. Open uses the
browser's file picker (dropping files works too) and Save downloads the workbook.
### Ribbon access keys
Press and release **left Alt** on Windows/Linux/BSD, or press **F10** on any platform,
then type a sequence below one key at a time. Keytips appear on the supported Home
controls and menu items. On macOS, use F10 (Fn+F10 if required by your keyboard); Option
remains available for entering accented characters.
| Sequence after Alt/F10 | Action |
|---|---|
| `H A L` / `H A C` / `H A R` | Align left / center / right |
| `H V S` or legacy `E S` | Open Paste Special |
| `H O I` or legacy `O C A` | AutoFit selected columns |
In Paste Special, **T/V/F/C** select formats/values/formulas/comments, and **E** toggles
Transpose. **Enter** applies the selected options; **Escape** cancels the dialog.
These letters also work with Alt held on Windows/Linux/BSD.
Escape backs out one keytip level; Alt/F10 again exits keytips. Clicking, scrolling,
or switching windows cancels navigation. Access keys do not start while editing text
or using another dialog. This is initial support for these Home and legacy paths;
other ribbon commands and full mouse-free navigation remain to be implemented.
Browsers or desktop environments may reserve Alt/F10 for their own menus.
### Logs
The desktop app writes its log to standard error and to `gridcraft.log` in the `logs` folder
next to its settings: `~/.config/gridcraft/logs` on Linux and BSD (`$XDG_CONFIG_HOME/gridcraft/logs`
when set), `~/Library/Application Support/GridCraft/logs` on macOS and
`%APPDATA%\GridCraft\logs` on Windows. Each start moves the previous log to `gridcraft.1.log` and
that one to `gridcraft.2.log`, so the log of a run that crashed survives the next start; attach
them to a bug report. A log file stops growing at 16 MiB. By default GridCraft's own crates log
at `info` and everything else at `warn`; `RUST_LOG` replaces that with env_logger-style
directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a trailing `*`
matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings)
log to standard error only.
## For agents: MCP, CLI and the control channel
```sh
@@ -141,7 +184,7 @@ egui frontend is a separate crate, so the UI can be swapped without touching the
|---|---|
| L0 | `core` (addresses, values, errors, dates, input parsing) · `numfmt` (number format codes) |
| L1 | `formula` (lexer, parser, printer, reference adjustment) · `functions` (worksheet function library) |
| L2 | `model` (workbook, sheets, copy-on-write cells, styles, tables, charts…) · `calc` (dependency graph, evaluator, dynamic arrays) · `xlsx` (XLSX and CSV) |
| L2 | `model` (workbook, sheets, copy-on-write cells, styles, tables, charts…) · `calc` (dependency graph, evaluator, dynamic arrays) · `xlsx` (XLSX, CSV, plus XLSB and ODS data import) |
| L3 | `chart` (toolkit-free chart layout and rendering) |
| L5 | `engine` (session, commands, history, clipboard, fill, sort, filter, file I/O) |
| L6 | `ui-egui` (Excel-style UI, control channel) · `mcp` (MCP server) |
@@ -153,12 +196,13 @@ egui frontend is a separate crate, so the UI can be swapped without touching the
## Roadmap
GridCraft is pre-alpha and moving fast. It covers 89% of Excel's ribbon and menu commands
([`docs/parity.md`](docs/parity.md)) and about 93% of its worksheet functions; weighted by depth,
we estimate about 65% of what Excel power users rely on. We're roughly 80% of the way to a first
alpha. Next up: signed release builds, XLSX fidelity on real-world files, performance on very large
sheets, then slicers, Solver, chart trendlines and a true Page Layout view. The plan and estimates
are in [ROADMAP.md](ROADMAP.md).
GridCraft is in **alpha**: the core workflow works end to end, but depth, fidelity and file
compatibility are still rough. It covers 89% of the Excel ribbon commands in our catalog
([`docs/parity-checklist.md`](docs/parity-checklist.md)) and 513 of Excel's 523 worksheet functions
([`docs/function-parity.md`](docs/function-parity.md)); weighted by what Excel users rely on, we
estimate it is about 50% ready for real work. Next up: XLSX fidelity on real-world files, very large
workbooks and multi-threaded recalc, chart depth, text in every script, and `.xls` import. Stage,
numbers and estimates are in [ROADMAP.md](ROADMAP.md); the ranked work list is [`docs/gaps.md`](docs/gaps.md).
## Downloads
@@ -172,7 +216,36 @@ are in [ROADMAP.md](ROADMAP.md).
| arm64 (Snapdragon and other ARM PCs) | `gridcraft-<ver>-windows-arm64.msi` | `gridcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `gridcraft-<ver>-windows-x86.msi` | `gridcraft-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed.
Installers and executables are code-signed. The MSI installer offers an optional desktop shortcut
(unchecked on a new installation).
**If the app doesn't open on Windows:** the desktop app initializes only DirectX 12 by default.
Letting wgpu also create an OpenGL instance can crash some graphics drivers (AMD's
`atio6axx.dll`) before the window appears, so the app would flash in Task Manager and quit.
`WGPU_BACKEND` overrides the default for troubleshooting (for example `dx12` or `vulkan`). In
PowerShell, from the folder containing the executable:
```powershell
$env:WGPU_BACKEND = "vulkan"
& .\gridcraft.exe
Remove-Item Env:WGPU_BACKEND # restore the default for later launches
```
An explicit `gl` override can bring the driver crash back on affected systems, and `vulkan` can
bring back a crash in some Intel UHD Graphics drivers (`igvk64.dll`, #120). The macOS, Linux and
web backend defaults are unchanged.
**If the app is slow on an older Windows PC, or DirectX 12 can't start:** when DirectX 12 finds no
graphics card with a driver for it, it only offers Microsoft's software renderer, which draws every
frame on the processor. In that case GridCraft uses OpenGL instead, without setting anything; if
the first renderer fails to start, it tries the other one once. The log file records the choice
(lines starting with `graphics:`). `WGPU_BACKEND` still overrides it (and then nothing else is
tried), e.g. `$env:WGPU_BACKEND = "gl"` or `"dx12"`.
DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcompiler.dll` or
`dxil.dll` is needed, and a copy another program put on `PATH` can no longer stop the app at start
("Parent device is lost", #339). `$env:WGPU_DX12_COMPILER = "dxc"` (or `"auto"`) selects wgpu's DXC
handling again for troubleshooting.
### macOS
+186 -124
View File
@@ -1,136 +1,198 @@
# GridCraft roadmap
GridCraft aims at full Microsoft Excel parity — and to be better: faster, open (XLSX is the
native format), fully scriptable by agents (MCP + control channel + CLI), and available on the
web.
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
## Status (2026-10-07)
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (direct desktop printing through craft-print) · **Target:** Microsoft Excel (Microsoft 365)
### Where we are
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
This page is the summary. The detail is in:
| Measure | Value | Notes |
- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative assessment, method and weights
- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list
- [`docs/roadmap.md`](docs/roadmap.md): milestones, current focus, what's next
- [`docs/parity-checklist.md`](docs/parity-checklist.md): generated by `cargo xtask parity` (ribbon commands)
- Area checklists: [functions](docs/function-parity.md) · [charts](docs/chart-parity.md) ·
[file formats](docs/file-format-parity.md) · [UI](docs/ui-parity.md) ·
[hardware](docs/hardware-parity.md) · [localization](docs/localization-parity.md)
- [`docs/architecture.md`](docs/architecture.md): how it is built
## Headline numbers
| Number | Value | Kind |
|---|---|---|
| Ribbon/menu command catalog | **89%** (258 / 290) | `cargo xtask parity` → [`docs/parity.md`](docs/parity.md). Home, Draw, Page Layout, Formulas, Automate, Chart Design and PivotTable Design are at 100%. |
| Worksheet functions | **~93%** of Excel's ~545 | Missing: ODDF*/ODDL*, BAHTTEXT, IMAGE, TRANSLATE, COPILOT/PY, STOCKHISTORY, RTD |
| Feature depth (weighted) | **~65%** | The catalog counts a command once it exists; many are shallower than Excel's (see "What's left") |
| Tests | 332 passing | engine, formula, functions, calc, XLSX (incl. PivotTable round-trip), PDF, MCP, CLI, kittest UI |
| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 274 / 290 (94.5%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) |
| **Ready for real work** | **~50%** | estimated from written weights (51.6); [target-app-parity.md](docs/target-app-parity.md) |
| **Mainstream practitioner** | **~50%** | estimated: typical analyst/finance user, weekly features, × 0.90 interaction × 0.92 stability × 0.88 file exchange; [method](docs/target-app-parity.md#mainstream-practitioner) |
| **Essentials user** | **~63%** | estimated: core features only, × 0.92 launch/stability × 0.95 clarity × 0.90 opening sent files; [method](docs/target-app-parity.md#essentials-user) |
| Remaining to **beta** | **~160–240 Opus 5.5 agent-hours** | estimated; itemized in [roadmap.md](docs/roadmap.md#beta-gates) |
| Remaining to **full parity** | **~700–1,100 Opus 5.5 agent-hours** | estimated; sum of the dimension rows below |
The catalog number is generous: it says "this button does something real", not "it does
everything Excel's does". The weighted depth figure is our honest estimate of how much of what an
Excel power user relies on works as well as in Excel.
| Audience | Ready % | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|---|---|---|---|
| Full target (ready for real work) | ~50% | ~650–1,050 | Get & Transform and the data model, localization (twelve languages), charts depth, file fidelity (`.xls`, corpus, pass-through), PivotTables, collaboration, mobile |
| Mainstream practitioner | ~50% | ~200–310 | File exchange with Excel users (corpus and Excel verification, pass-through, large files, `.xls`, encryption: 63–97 h), common-chart depth (30–45 h), PivotTables (20–30 h), keyboard and interaction (18–28 h), calc correctness and functions (20–33 h) |
| Essentials user | ~63% | ~60–100 | Opening files people send (`.xls` import and saving with a password 24–36 h; macOS Finder open 2–4 h), launch stability (6–10 h), basic chart resize and polish (6–10 h), print and Page Layout (8–12 h), small editing and UI fixes (10–16 h) |
### How close to an alpha?
Each tier is a subset of the one above, so its hours are too. Calibrated as in [Effort and
calibration](docs/target-app-parity.md#effort-and-calibration) (~6–10 h per readiness point for the remaining, verification-heavy
work; single features measured from PRs #66, #100, #101). Parallelism: the full and mainstream
work splits ~65–70% across 4–6 agents by area; the essentials work is mostly small fixes plus one
long `.xls` track, so about half parallelizes (≈30–50 wall-clock hours with three agents).
**About 80% of the way to an alpha. Estimate: ~35 wall-clock hours of Claude Opus 5.5 agent
work** (2–3 days with 2–3 parallel agents), plus a few minutes of human time to set up release
secrets.
Why alpha: all six core workflows in the [alpha gate](docs/roadmap.md#alpha-gate) pass end to end on macOS with save and reopen, and the core workflow works end to end (open an XLSX, enter formulas and data, format, sort
and filter, chart, pivot, print to PDF, save XLSX), but users still hit blocking gaps on real
files: 100 MB workbooks don't open (#175), there's no `.xls` (#121), Arabic and Devanagari text
isn't shaped (Chinese text still reported in #142), charts lose their type and options on round trip, and
nobody has yet confirmed that Excel opens our output without a repair prompt across a real
corpus. Beta needs those closed (see [beta gates](docs/roadmap.md#beta-gates)).
Alpha means: someone can download a signed build, open their real workbooks, edit and save them
without losing data, and not hit a crash in a normal session. The gates:
The 2026-10-07 numbers (catalog 89%, "feature depth ~65%", "~215 h to full parity") were
re-measured. Catalog and function counts held or rose; the depth and hours moved because of new
evidence: 82 issues filed by users and contributors in the repo's first five days, and scope the
old estimate left out (localization, legacy `.xls`, Power Query and the data model,
collaboration, mobile, AI).
| Alpha gate | State | Est. hours |
## By dimension
| Dimension | Ready for real work | Hours to parity | Doc |
|---|---|---|---|
| Features (13 areas, table below) | ~59% (breadth ~75%) | 300–485 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| UI/UX fidelity | ~55% | 50–80 | [ui-parity.md](docs/ui-parity.md) |
| File formats | ~50% | 80–120 | [file-format-parity.md](docs/file-format-parity.md) |
| Performance | ~35% | 35–55 | [target-app-parity.md](docs/target-app-parity.md#performance) |
| Stability | ~60% | 15–25 | [gaps.md](docs/gaps.md) |
| Localization | ~10% (ribbon in 6 languages) | 100–165 | [localization-parity.md](docs/localization-parity.md) |
| Hardware (multi-core calc, GPU, pen, multi-window) | ~40% | 25–40 | [hardware-parity.md](docs/hardware-parity.md) |
| Platforms | ~80% (no iOS/Android; ahead on Linux, BSD, RISC-V) | 30–60 | [target-app-parity.md](docs/target-app-parity.md#platforms) |
| Ecosystem / add-ins | ~10% (VBA out of scope; own scripts, MCP, CLI) | 25–40 | [target-app-parity.md](docs/target-app-parity.md#ecosystem-and-ai) |
| AI features | ~15% (agent control strong; no in-app assistant) | 30–50 | [target-app-parity.md](docs/target-app-parity.md#ecosystem-and-ai) |
| **Total** | **~50%** | **~700–1,100** | |
## Features
| Area | Breadth | Ready | Hours | Doc |
|---|---|---|---|---|
| Formula language and calculation | ~92% | ~72% | 20–30 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Worksheet functions | 96.6% measured | ~82% | 16–26 | [function-parity.md](docs/function-parity.md) |
| Editing, navigation, clipboard, fill | ~90% | ~70% | 15–25 | [ui-parity.md](docs/ui-parity.md) |
| Cell formatting, styles, conditional formatting | ~95% | ~80% | 8–14 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Sort, filter, tables, validation, outline | ~82% | ~70% | 10–16 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| PivotTables | ~65% | ~45% | 25–40 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Charts and sparklines | ~50% | ~30% | 40–60 | [chart-parity.md](docs/chart-parity.md) |
| Page layout, print, PDF | ~80% | ~55% | 12–20 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| What-if and analysis (Goal Seek, Solver, ToolPak, Forecast) | ~50% | ~40% | 22–35 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Get & Transform, external data, data model | ~15% | ~10% | 60–100 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Insert objects (pictures, shapes, ink, SmartArt, equations) | ~55% | ~45% | 25–40 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Review, comments, protection, collaboration | ~55% | ~40% | 35–55 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
| Automation (recorded scripts; no VBA) | ~30% | ~20% | 12–20 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
## Languages
The ribbon is translated into Japanese, Simplified Chinese, Korean, Brazilian Portuguese, Russian
and German (266–268 labels each, ~12% of ~2,200 strings; merged 10-10 in #31, #104, #82, German
added 10-11), the
interface follows the system language, and CJK, Thai and Hebrew text falls back to system fonts
(#38). Dialogs, menus and messages are English; formulas and number formats are en-US only.
Localized German formulas and numbers are in PR #163. Detail: [localization-parity.md](docs/localization-parity.md).
| Language | Code | Status | UI strings |
|---|---|---|---|
| English | en | full (source language) | 100% |
| Simplified Chinese | zh-Hans | menus only | ~12% |
| Spanish | es | none | 0% |
| Hindi | hi | none | 0% |
| Arabic | ar | none (no RTL layout, no shaping) | 0% |
| French | fr | none | 0% |
| Portuguese | pt-BR | menus only | ~12% |
| Indonesian | id | none | 0% |
| Japanese | ja | menus only | ~12% |
| German | de | menus only | ~12% |
| Korean | ko | menus only | ~12% |
| Vietnamese | vi | none | 0% |
Other shipped languages: 2 (Russian and German, menus only, ~12%).
## Upcoming
Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
[docs/roadmap.md](docs/roadmap.md).
1. **Land the open PR queue** (50 open PRs on 2026-10-10, many fixing listed gaps: recalc and spill
correctness, chart kind round-trip, CJK font fallback, macOS Finder open, German and Chinese
UI). Review and merge: 8–15 h.
2. **XLSX fidelity on a real-world corpus**, with Excel opening our output without repair: 25–35 h.
3. **Large workbooks and recalc speed**: 100 MB XLSX, 1M rows, multi-threaded recalc: 40–60 h.
4. **Charts depth**: kinds and options round-trip, axes, trendlines, error bars: 25–35 h.
5. **Text in every script** (CJK, Thai, Arabic, Devanagari) in cells and PDF: 12–20 h.
6. **Legacy `.xls` import and password-protected workbooks**: 20–30 h.
7. **Localization**: extend the catalog past the ribbon, then the twelve languages: 100–165 h.
## Progress log
| Date | What landed |
|---|---|
| 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available |
| 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found |
| 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) |
| 2026-10-11 | Text boxes keep their formatting: run size, bold, italic, typeface, text colour and outline, alignment, vertical anchor and "no outline" (#377) |
| 2026-10-11 | Desktop printing opens the print PDF in the system viewer; Save As offers CSV, web page and PDF; macOS File › Properties opens File › Info (#370, #343) |
| 2026-10-11 | Windows: DirectX 12 shaders compile with FXC, so a missing or stray `dxcompiler.dll` no longer stops the app at start (#339, #354) |
| 2026-10-11 | Merged cells draw their whole outline: right and bottom edges come from the last column's and last row's cells (#376) |
| 2026-10-11 | Shrink to fit draws too-wide text and numbers in a smaller font inside the cell or merged area (#375) |
| 2026-10-11 | Shift+Space and Ctrl+Space select the row / column without starting an edit; Control+Space on Mac (#338) |
| 2026-10-11 | Workbooks reopen at their saved scroll position (`topLeftCell`, also with frozen panes) and save the current one back (#378) |
| 2026-10-11 | Protect Sheet passwords use Excel-compatible hashes and round-trip in XLSX `sheetProtection` (imported passwords verify instead of being dropped) |
| 2026-10-11 | Review › Protect Workbook opens a dialog with an optional password (Excel-compatible hash, kept in XLSX `workbookProtection`); unprotecting verifies it (#345) |
| 2026-10-11 | Formula bar, name box and dialogs fall back to the cell font: Hebrew (and any script cells can show) no longer turns into boxes there (#349) |
| 2026-10-11 | Headers and footers: first-page and odd/even variants are read, kept, printed and edited in Page Layout view; Insert › Header & Footer edits the header in place (#344) |
| 2026-10-11 | Legacy Excel 97-2003 `.xls` (BIFF8) import with formulas, number formats, merges, sizes and names (#121) |
| 2026-10-11 | XLSX pass-through: custom XML, external links, connections, query tables, printer settings, form/ActiveX controls and OLE objects are kept on save (#330, #324) |
| 2026-10-11 | Data › Forecast › Forecast Sheet: a new sheet with the history, FORECAST.ETS forecast, confidence bounds, statistics and a chart (#322) |
| 2026-10-11 | Startup no longer panics on a system font egui can't parse: fonts are validated and skipped (#226) |
| 2026-10-11 | Ctrl+drag on the fill handle swaps copying and extending a series (#264) |
| 2026-10-11 | Odd-period bond functions ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD: Financial 55 / 55 (#275) |
| 2026-10-11 | PERCENTOF and EUROCONVERT worksheet functions (#279) |
| 2026-10-11 | BAHTTEXT: amounts in Thai words with Baht and Satang (#291) |
| 2026-10-11 | TRIMRANGE: ranges and arrays without blank outer rows and columns (#296) |
| 2026-10-11 | Selected charts, pictures and shapes can be deleted from the keyboard (#213) |
| 2026-10-11 | Ribbon translated into German (266 labels; `de`, `de-DE`, `de-AT`, `de-CH` locale tags resolve to German) |
| 2026-10-11 | View › Interface size: a saved 75–200 % scale for the whole window (#230) |
| 2026-10-11 | View › Formula Bar and Zoom 100% reachable from the CLI and MCP (#289) |
| 2026-10-11 | Freeze panes by dragging the freeze handles on the header edges (#195) |
| 2026-10-11 | XLSX: threaded comments (replies, resolved, timestamps) and note visibility survive a save (#300) |
| 2026-10-11 | Cell checkboxes: Insert › Checkbox on the ribbon, Excel's Delete and value rules, XLSX round trip as Excel cell controls (#196) |
| 2026-10-11 | Review › Allow Edit Ranges with Excel-compatible password hashes, kept in XLSX (#307) |
| 2026-10-11 | PivotTable calculated fields (`pivot.calculatedField`), evaluated on sums like Excel, with XLSX round-trip (#304) |
| 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-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 |
| 2026-10-06 | M0–M13 first pass: engine, 478 functions, XLSX/CSV, egui UI, charts, PivotTables with XLSX round-trip, PDF and printing, what-if, spelling, Draw, task panes, MCP, CLI, web build, release packaging |
| 2026-10-05 | Repository created |
## Revision history
| Date | Change | Summary |
|---|---|---|
| Signed release builds on every platform | Workflows and packaging ready; **blocked on the `release` environment and secrets, which need a human** (see [`docs/releasing.md`](docs/releasing.md)). Then a test build per platform | 4 |
| XLSX fidelity on real files | Round-trip tests pass for our own files. Needs a corpus run on real-world workbooks, and confirming Excel opens our output (including PivotTables) with no repair prompt | 10 |
| Performance | Virtualised grid and O(log n) geometry are in. Still need: 100k-cell edit recalc under 100 ms (currently ~0.4 s), faster write-back, 1M-row open | 8 |
| Never-crash soak | Every-command fuzz test exists. Needs a longer randomised UI soak and an autosave/recovery check | 4 |
| Papercuts | Dark-mode row/column headers, a true Page Layout (paper) view, focus edge cases, error messages | 6 |
| Docs and first-run | README, CLI/MCP docs exist; needs a "getting started" page and release notes | 3 |
| **Total** | | **≈ 35** |
### How far to 100% parity?
**Estimate: ~180 wall-clock hours of Claude Opus 5.5 agent work beyond the alpha** (about 1–1.5
weeks running continuously with 3–4 parallel agents), so **≈ 215 hours in total from today**.
Breakdown under "What's left" below.
Scope decisions that affect the count: VBA is out of scope (GridCraft has its own recorded and
editable scripts instead), and features that need Microsoft cloud services (Copilot, live Stocks/
Geography data types, co-authoring through OneDrive, Smart Lookup, Translate) will be replaced
by open equivalents or left out, not cloned.
### What's left
| Area | What's missing | Est. hours |
|---|---|---|
| PivotTables | Slicers and timelines, calculated fields/items, PivotCharts, value/label filters, number grouping | 24 |
| Charts | Trendlines, error bars, full axis options (log scale, units, crossing), element-level Format pane, chart sheets, Recommended Charts dialog, maps | 26 |
| Data | Solver, Analysis ToolPak, Forecast Sheet, Get & Transform beyond CSV/JSON/HTML (Power Query editor lite), relationships / data model | 34 |
| Page layout & print | True Page Layout view, header/footer editor on the page, print preview polish | 12 |
| Insert & Review | Equations, WordArt, SmartArt-lite, signature line, comment navigation, Show Changes, Allow Edit Ranges, notes ↔ comments conversion | 20 |
| XLSX depth | Remaining OOXML parts (form controls, slicer caches, external links, OLE stubs), round-trip of everything we don't model | 16 |
| Functions | The remaining ~35 functions, exact Excel edge-case behaviour across the long tail | 10 |
| Performance | Parallel recalc, 1M-row workbooks everywhere (sort, filter, fill), memory | 14 |
| Fidelity | Side-by-side pixel tuning against Excel, keyboard shortcut completeness, accessibility, localisation | 24 |
| **Total** | | **≈ 180** |
**Working today**
- Engine: A1/R1C1 formula parser with reference adjustment, dependency-graph recalculation with
dynamic arrays (spill + `#SPILL!`), cycle detection, LET/LAMBDA/MAP/REDUCE/SCAN/BYROW/BYCOL/
MAKEARRAY, structured table references, defined names, INDIRECT/OFFSET/INDEX references,
478 worksheet functions (math, statistics and distributions, text and regex, lookup incl.
XLOOKUP/FILTER/SORT/UNIQUE/VSTACK, dates, financial incl. bonds, engineering incl. complex
numbers and Bessel, database, information).
- Number formats: Excel's full format-code language (sections, conditions, colours, dates and
elapsed time, fractions, scientific, accounting fill), General narrowing to column width.
- Files: XLSX read/write (styles, themes, merges, CF, validation, tables, comments, hyperlinks,
charts, pictures, sparklines, print settings, defined names, shared/array/dynamic formulas),
CSV/TSV with encoding and delimiter detection, HTML export, JSON.
- Editing: cell entry with type detection and auto-formats, in-cell and formula-bar editing,
point mode (click/drag/arrow references), reference colouring, F4 anchor cycling, function
autocomplete and argument hints, copy/cut/paste and Paste Special (values, formats, transpose,
operations, link, skip blanks), AutoFill series (numbers, dates, months, weekdays, custom lists,
text+number), Fill Series, Flash Fill, find/replace with wildcards, Go To / Go To Special,
undo/redo with history, format painter.
- Formatting: fonts, fills, all border styles, alignment (wrap, indent, rotation, merge), number
formats, 47 cell styles, 60 table styles, conditional formatting (cell rules, text, dates,
duplicates, top/bottom, averages, data bars, colour scales, icon sets, formulas), automatic
row heights, autofit, hide/unhide, freeze panes.
- Data: sort (multi-level, by colour, custom lists), AutoFilter (values, custom, top 10,
average, colour), tables with totals rows, remove duplicates, text to columns, data validation
with error alerts, grouping/outline, subtotals.
- PivotTables: Insert/Recommended PivotTables, field list pane, compact/outline/tabular layouts,
date grouping, sort, filters, show-values-as, refresh, and XLSX round-trip.
- Page layout & print: Page Break Preview, print settings, PDF export and printing.
- What-if: Goal Seek, scenarios, data tables. Spelling (system word list) and thesaurus.
- Draw: pen, highlighter, eraser, ink strokes and Ink to Shape. Task panes: Comments (threaded
replies, resolve), Watch Window, Selection, Format Chart.
- Charts: column, bar, line, area, pie, doughnut, scatter, bubble, radar, histogram, waterfall,
funnel, treemap, sunburst, box & whisker, stock and combo charts; sparklines.
- UI (egui): Excel-style title bar with Quick Access Toolbar and AutoSave, the full ribbon with
galleries (cell styles, table styles, colour palettes, conditional formatting menus),
contextual Table/Chart Design tabs, formula bar with Name Box, virtualised grid (smooth
scrolling, zoom, frozen panes, text overflow), sheet tabs (rename, reorder, colour, hide),
status bar with Sum/Count/Average and zoom, dialogs (Format Cells, Formula Builder, Find and
Replace, Sort, Name Manager, Data Validation, Paste Special…), command palette, dark mode.
- Agents: every action is an engine command; JSON control channel in the desktop app (pointer,
keyboard, dialogs, screenshots); MCP server (headless or bridged); CLI (`info`, `convert`,
`eval`, `cat`, `run`, `commands`, `functions`, `mcp`, `send`).
- Platforms: macOS, Windows, Linux, FreeBSD; web (WASM via trunk). Release workflows for
signed/notarized macOS universal DMG, signed Windows x64/x86 MSI + zip, Linux AppImage/deb/rpm/
tar.gz + Flatpak manifest, FreeBSD tarball and a web zip.
## Milestones
| # | Milestone | Status |
|---|---|---|
| M0 | Foundation: core, number formats, formula language, functions, model, calc, XLSX/CSV, engine | ✅ done |
| M1 | Excel look: chrome, ribbon, formula bar, grid, tabs, status bar, control channel | ✅ done (polish continues) |
| M2 | Formatting completeness | ✅ done |
| M3 | Editing power (AutoComplete, spelling, drag-move/copy) | ✅ done |
| M4 | Data (advanced filter, consolidate, what-if) | 🟡 most; Solver, ToolPak and Power Query remain |
| M5 | Formulas tab (trace arrows, watch window, evaluate, error checking) | ✅ done |
| M6 | Conditional formatting manager parity | ✅ done |
| M7 | Charts parity | 🟡 partial; Format pane in, trendlines/axes/error bars remain |
| M8 | Insert & Review | 🟡 partial; ink, icons, comments pane in |
| M9 | Page layout & print | 🟡 most; true Page Layout view remains |
| M10 | PivotTables, Solver, Analysis ToolPak | 🟡 PivotTables in; slicers, Solver, ToolPak remain |
| M11 | Automation (record actions, scripts) | ✅ done |
| M12 | Performance, accessibility, i18n | 🟡 partial |
| M13 | Release & polish | 🟡 tooling ready; needs release secrets |
## How to measure
- `cargo xtask parity` — catalog coverage (feature names from Excel's ribbon and menus).
- `cargo test --workspace` — engine, formula, function, XLSX and UI behaviour.
- `cargo run --release -p gridcraft-ui-egui --example snapshot -- --sample sales out.png` — look at the UI offscreen.
| 2026-10-12 | minor | Desktop File > Print now discovers printers and submits PDF jobs through pinned craft-print with printer choice, copies, duplex and grayscale; browser printing and PDF export remain available. Remaining print parity includes page ranges and driver-specific tray/options UI; physical printer fidelity needs hardware validation. |
| 2026-10-11 | minor | Password-encrypted workbooks open (#11); progress log row |
| 2026-10-11 | minor | Forecast Sheet (#322); progress log row |
| 2026-10-11 | minor | Worksheet functions 505 / 523 (ODD* bond functions); progress log row |
| 2026-10-11 | minor | Worksheet functions 503 / 523 (PERCENTOF, EUROCONVERT); progress log row |
| 2026-10-11 | minor | Worksheet functions 502 / 523 (BAHTTEXT); progress log row |
| 2026-10-11 | minor | Worksheet functions 502 / 523 (TRIMRANGE); progress log row |
| 2026-10-11 | minor | Selected objects can be deleted from the keyboard (#213) |
| 2026-10-11 | minor | Catalog 258 → 260 / 290: View › Formula Bar and Zoom 100% (#289) |
| 2026-10-11 | minor | Progress log: XLSX threaded comments round trip (#300) |
| 2026-10-11 | minor | Catalog 258 → 259 / 290: Allow Edit Ranges (#307) |
| 2026-10-11 | minor | Worksheet functions 505 / 523 (FORECAST.ETS family); progress log row |
| 2026-10-11 | minor | Czech (cs) listed under other shipped languages: ribbon only, ~12% |
| 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-07 | major | First estimates: catalog 89%, functions ~93%, depth ~65%, ~35 h to alpha, ~215 h to full parity |
+3
View File
@@ -18,3 +18,6 @@ gridcraft-engine = { workspace = true }
gridcraft-mcp = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
zip = { workspace = true }
quick-xml = { workspace = true }
File diff suppressed because it is too large Load Diff
+15 -2
View File
@@ -5,6 +5,7 @@
//! gridcraft-cli convert <in> <out> [--sheet NAME]
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
@@ -28,6 +29,8 @@ macro_rules! outln {
}};
}
mod check;
use gridcraft_engine::Session;
use serde_json::{Value, json};
@@ -36,6 +39,8 @@ const USAGE: &str = "usage:
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html by extension
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
[--out FILE] [--print RANGE] [--quiet]
gridcraft-cli commands [--json] [--search X]
@@ -71,6 +76,7 @@ fn main() -> ExitCode {
Some("eval") => eval(rest),
Some("cat") => cat(rest),
Some("run") => run(rest),
Some("check") => return check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("mcp") => mcp(rest),
@@ -145,8 +151,15 @@ impl Args {
// ---------------------------------------------------------------- helpers
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
let r = s.execute(id, params).map_err(|e| e.to_string());
s.take_ui_requests();
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
eprintln!("Warning: {warning}");
}
}
r
}
+24
View File
@@ -150,3 +150,27 @@ fn mcp_over_stdio() {
assert_eq!(lines[0]["result"]["serverInfo"]["name"], "gridcraft");
assert!(lines[1]["result"]["content"][0]["text"].as_str().unwrap().contains("42"));
}
#[test]
fn check_exit_codes_and_json() {
let dir = tmpdir("check");
let book = dir.join("calc.xlsx");
let book_s = book.to_str().unwrap();
ok(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"2"}"#, "--cmd", r#"cell.set={"cell":"B1","input":"=A1*3"}"#, "--out", book_s, "--quiet"]);
// GridCraft's own file: its cached values are its own results, and it round-trips.
let o = run(&["check", dir.to_str().unwrap()]);
let out = String::from_utf8_lossy(&o.stdout);
assert_eq!(o.status.code(), Some(0), "{out}");
assert!(out.contains("1 checked: 1 matched, 0 mismatched"), "{out}");
let v: serde_json::Value = serde_json::from_str(&ok(&["check", book_s, "--json"])).unwrap();
assert_eq!(v["schema"], "gridcraft-check/1");
assert_eq!(v["totals"]["matched"], 1);
// A file that can't be opened is reported, not fatal, and fails the check.
let o = run(&["check", book_s, "/no/such/file.xlsx"]);
assert_eq!(o.status.code(), Some(1));
assert!(String::from_utf8_lossy(&o.stdout).contains("1 failed to open"));
// Usage errors exit 2.
assert_eq!(run(&["check"]).status.code(), Some(2));
assert_eq!(run(&["check", book_s, "--tolerance", "x"]).status.code(), Some(2));
assert_eq!(run(&["check", book_s, "--bogus"]).status.code(), Some(2));
}
@@ -0,0 +1,26 @@
use std::process::Command;
#[test]
fn text_to_columns_preserves_doubled_quotes() {
let dir = std::env::temp_dir().join(format!("gridcraft-t2c-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("make temp directory");
let script = dir.join("steps.jsonl");
std::fs::write(
&script,
concat!(
"{\"command\":\"cell.set\",\"params\":{\"cell\":\"A1\",\"input\":\"\\\"a\\\"\\\"b\\\",c\"}}\n",
"{\"command\":\"data.textToColumns\",\"params\":{\"range\":\"A1\",\"delimiters\":[\",\"]}}\n",
),
)
.expect("write commands");
let output = Command::new(env!("CARGO_BIN_EXE_gridcraft-cli"))
.args(["run", "--script"])
.arg(&script)
.args(["--print", "A1:B1", "--csv", "--quiet"])
.output()
.expect("run Gridcraft CLI");
std::fs::remove_file(script).expect("remove script");
std::fs::remove_dir(dir).expect("remove temp directory");
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "\"a\"\"b\",c");
}
+1 -1
View File
@@ -26,4 +26,4 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator"] }
+1
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>GridCraft</title>
<link data-trunk rel="icon" href="../../assets/app-icon/gridcraft.ico" />
<link data-trunk rel="rust" data-bin="gridcraft-web" data-wasm-opt="z" data-weak-refs />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #f3f3f3; }
+239 -8
View File
@@ -3,6 +3,7 @@
use gridcraft_engine::Session;
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
use wasm_bindgen::JsCast as _;
use wasm_bindgen::JsValue;
const CANVAS_ID: &str = "gridcraft_canvas";
const LOADING_ID: &str = "gridcraft_loading";
@@ -37,8 +38,18 @@ pub fn start() {
} else if q.contains("sample") {
let _ = session.execute("file.new", serde_json::json!({"sample": "sales"}));
}
let app = SheetApp::new(session, services(inbox.clone(), cc.egui_ctx.clone()));
SheetApp::setup_context(&cc.egui_ctx, false);
let mut app = SheetApp::new(session, services(inbox.clone(), cc.egui_ctx.clone()));
app.ui.system_theme = true;
// Follow the browser's language, except a CJK one: the web build has no system
// CJK fonts (none are bundled), so that interface would render as tofu.
let browser = gridcraft_ui_egui::i18n::Language::system();
if !matches!(
browser,
gridcraft_ui_egui::i18n::Language::Zh | gridcraft_ui_egui::i18n::Language::Ja | gridcraft_ui_egui::i18n::Language::Ko
) {
app.ui.language = browser;
}
SheetApp::setup_context_for_language(&cc.egui_ctx, false, app.ui.language);
Ok(Box::new(WebShell { app, inbox }))
}),
)
@@ -92,13 +103,17 @@ impl eframe::App for WebShell {
fn services(inbox: Inbox, ctx: egui::Context) -> Services {
let open_inbox = inbox.clone();
let picture_ctx = ctx.clone();
Services {
copy_html: Some(Box::new(copy_html)),
open_async: Some(Box::new(move || {
let inbox = open_inbox.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let Some(file) =
rfd::AsyncFileDialog::new().add_filter("Spreadsheets", &["xlsx", "xlsm", "csv", "tsv", "txt", "json"]).pick_file().await
let Some(file) = rfd::AsyncFileDialog::new()
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"])
.pick_file()
.await
else {
return;
};
@@ -107,11 +122,27 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
ctx.request_repaint();
});
})),
pick_picture_async: Some(Box::new(move |inbox| {
let ctx = picture_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let Some(file) = rfd::AsyncFileDialog::new().add_filter("Pictures (PNG, JPEG)", &["png", "jpg", "jpeg"]).pick_file().await else {
return;
};
let bytes = file.read().await;
inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
download: Some(Box::new(|name: &str, bytes: &[u8]| {
if let Err(e) = download(name, bytes) {
log::error!("download of {name} failed: {e}");
}
})),
print: Some(Box::new(|bytes: &[u8]| {
if let Err(e) = print_pdf(bytes) {
log::error!("print failed: {e}");
}
})),
open_url: Some(Box::new(|url: &str| {
if let Some(w) = web_sys::window() {
let _ = w.open_with_url_and_target(url, "_blank");
@@ -122,17 +153,217 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
}
}
/// Triggers a browser download of `bytes`.
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
/// Start inside the copy gesture; deferring `write` can lose browser user activation.
fn copy_html(html: &str, text: &str) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let clipboard = window.navigator().clipboard();
if clipboard.is_undefined() || clipboard.is_null() {
return Err("browser clipboard is unavailable (a secure context is required)".into());
}
if !js_sys::Reflect::get(&clipboard, &"write".into()).map_err(js)?.is_function() {
return Err("browser does not support rich clipboard writes".into());
}
let data = js_sys::Object::new();
for (mime, value) in [("text/html", html), ("text/plain", text)] {
let opts = web_sys::BlobPropertyBag::new();
opts.set_type(mime);
let parts = js_sys::Array::of1(&wasm_bindgen::JsValue::from_str(value));
let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &opts).map_err(js)?;
js_sys::Reflect::set(&data, &mime.into(), &blob).map_err(js)?;
}
let item = web_sys::ClipboardItem::new_with_record_from_str_to_blob_promise(&data).map_err(js)?;
let promise = clipboard.write(&js_sys::Array::of1(&item));
let text = text.to_owned();
wasm_bindgen_futures::spawn_local(async move {
if let Err(e) = wasm_bindgen_futures::JsFuture::from(promise).await {
log::warn!("Rich clipboard write failed; trying plain text: {e:?}");
if let Err(e) = wasm_bindgen_futures::JsFuture::from(clipboard.write_text(&text)).await {
log::error!("Plain-text clipboard fallback also failed: {e:?}");
}
}
});
Ok(())
}
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
/// `print()` once it has finished loading — the standard way to drive the browser's native print
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
/// them.
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type(if name.ends_with(".csv") { "text/csv" } else { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
opts.set_type("application/pdf");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
iframe.style().set_property("display", "none").map_err(js)?;
document.body().ok_or("no body")?.append_child(&iframe).map_err(js)?;
// `onload` fires once the PDF has actually rendered inside the iframe;
// printing before that would show a blank page. Set the handler BEFORE
// `src` so a fast/cached load can't fire before we're listening.
let iframe_for_load = iframe.clone();
let url_for_cleanup = url.clone();
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
let Some(content_window) = iframe_for_load.content_window() else { return };
let _ = content_window.print();
// `afterprint` fires once the print dialog (or print preview) closes, whether the user
// printed or cancelled — the right moment to release the blob URL and drop the iframe.
let iframe_for_cleanup = iframe_for_load.clone();
let on_after_print = wasm_bindgen::closure::Closure::once_into_js(move || {
web_sys::Url::revoke_object_url(&url_for_cleanup).ok();
iframe_for_cleanup.remove();
});
let _ = content_window.add_event_listener_with_callback("afterprint", on_after_print.unchecked_ref());
});
iframe.set_onload(Some(on_load.unchecked_ref()));
iframe.set_src(&url);
Ok(())
}
fn mime_for(name: &str) -> &'static str {
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
Some("xlsm") => "application/vnd.ms-excel.sheet.macroEnabled.12",
Some("xlsb") => "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
Some("ods") => "application/vnd.oasis.opendocument.spreadsheet",
Some("csv") => "text/csv",
Some("tsv" | "txt") => "text/plain",
Some("pdf") => "application/pdf",
Some("html" | "htm") => "text/html",
Some("json") => "application/json",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
_ => "application/octet-stream",
}
}
/// Trigger a browser save dialog or download of `bytes` named after `name`.
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let show_picker_fn: Option<js_sys::Function> =
js_sys::Reflect::get(&window, &JsValue::from_str("showSaveFilePicker")).ok().and_then(|v| v.dyn_into().ok());
if let Some(picker_fn) = show_picker_fn {
let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("xlsx").to_ascii_lowercase();
let dot_ext = format!(".{ext}");
let mime = mime_for(name);
let accept_obj = js_sys::Object::new();
let exts_arr = js_sys::Array::new();
exts_arr.push(&JsValue::from_str(&dot_ext));
let _ = js_sys::Reflect::set(&accept_obj, &JsValue::from_str(mime), &exts_arr);
let type_desc = match ext.as_str() {
"xlsx" => "Excel Workbook (*.xlsx)",
"xlsm" => "Excel Macro-Enabled Workbook (*.xlsm)",
"xlsb" => "Excel Binary Workbook (*.xlsb)",
"ods" => "OpenDocument Spreadsheet (*.ods)",
"csv" => "CSV (Comma delimited) (*.csv)",
"tsv" => "Tab Delimited Text (*.tsv)",
"txt" => "Plain Text (*.txt)",
"pdf" => "PDF Document (*.pdf)",
"html" | "htm" => "HTML Document (*.html)",
"json" => "JSON Document (*.json)",
"png" => "PNG Image (*.png)",
"jpg" | "jpeg" => "JPEG Image (*.jpeg)",
_ => "Spreadsheet",
};
let type_obj = js_sys::Object::new();
let _ = js_sys::Reflect::set(&type_obj, &JsValue::from_str("description"), &JsValue::from_str(type_desc));
let _ = js_sys::Reflect::set(&type_obj, &JsValue::from_str("accept"), &accept_obj);
let types_arr = js_sys::Array::new();
types_arr.push(&type_obj);
let picker_opts = js_sys::Object::new();
let _ = js_sys::Reflect::set(&picker_opts, &JsValue::from_str("suggestedName"), &JsValue::from_str(name));
let _ = js_sys::Reflect::set(&picker_opts, &JsValue::from_str("types"), &types_arr);
let prom_val = picker_fn.call1(&window, &picker_opts).map_err(js)?;
let prom: js_sys::Promise = prom_val.dyn_into().map_err(|_| "not a promise".to_string())?;
let bytes_vec = bytes.to_vec();
let name_owned = name.to_string();
// Anything but the user cancelling (no user gesture, a denied permission, a failed write)
// falls back to an ordinary download, so a save never fails silently.
let fallback = move |bytes: &[u8]| {
if let Some(w) = web_sys::window()
&& let Err(e) = trigger_anchor_download(&w, &name_owned, bytes)
{
log::error!("download fallback failed: {e}");
}
};
wasm_bindgen_futures::spawn_local(async move {
match wasm_bindgen_futures::JsFuture::from(prom).await {
Ok(handle_val) => {
if let Err(e) = write_file_handle(&handle_val, &bytes_vec).await {
log::error!("failed writing to file handle: {e}");
fallback(&bytes_vec);
} else {
log::info!("Successfully saved file through save file picker");
}
}
Err(e) => {
let err_name = js_sys::Reflect::get(&e, &JsValue::from_str("name")).ok().and_then(|v| v.as_string()).unwrap_or_default();
if err_name == "AbortError" {
log::info!("Save file dialog cancelled by user");
} else {
log::warn!("showSaveFilePicker refused ({err_name}); downloading instead");
fallback(&bytes_vec);
}
}
}
});
return Ok(());
}
// Fallback for browsers without showSaveFilePicker (e.g. Firefox, Safari):
trigger_anchor_download(&window, name, bytes)
}
async fn write_file_handle(handle: &JsValue, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let create_fn: js_sys::Function = js_sys::Reflect::get(handle, &JsValue::from_str("createWritable"))
.map_err(js)?
.dyn_into()
.map_err(|_| "createWritable is not a function".to_string())?;
let stream_prom: js_sys::Promise = create_fn.call0(handle).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
let stream = wasm_bindgen_futures::JsFuture::from(stream_prom).await.map_err(js)?;
let write_fn: js_sys::Function =
js_sys::Reflect::get(&stream, &JsValue::from_str("write")).map_err(js)?.dyn_into().map_err(|_| "write is not a function".to_string())?;
let uint8 = js_sys::Uint8Array::from(bytes);
let write_prom: js_sys::Promise = write_fn.call1(&stream, &uint8).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
wasm_bindgen_futures::JsFuture::from(write_prom).await.map_err(js)?;
let close_fn: js_sys::Function =
js_sys::Reflect::get(&stream, &JsValue::from_str("close")).map_err(js)?.dyn_into().map_err(|_| "close is not a function".to_string())?;
let close_prom: js_sys::Promise = close_fn.call0(&stream).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
wasm_bindgen_futures::JsFuture::from(close_prom).await.map_err(js)?;
Ok(())
}
fn trigger_anchor_download(window: &web_sys::Window, name: &str, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let document = window.document().ok_or("no document")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type(mime_for(name));
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor".to_string())?;
a.set_href(&url);
a.set_download(name);
a.style().set_property("display", "none").map_err(js)?;
+14
View File
@@ -24,7 +24,21 @@ image = { workspace = true }
winresource = "0.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d" }
rfd = { workspace = true }
arboard = { workspace = true }
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
arboard = { workspace = true, features = ["wayland-data-control"] }
[target.'cfg(target_os = "windows")'.dependencies]
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
pollster = "1"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
# Finder double-click, Open With, Dock drops and `open -a GridCraft file.xlsx` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#69). This audited crate (also used
# 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"
+49
View File
@@ -0,0 +1,49 @@
//! macOS open-documents and quit Apple events (#69).
//!
//! Finder double-clicks, Open With, drops on the Dock icon and `open -a GridCraft book.xlsx` don't
//! pass paths on the command line: LaunchServices sends the running (or just-launched) app a
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
//! `NSApplicationDelegate`, so AppKit answered "GridCraft cannot open files in the Excel Workbook
//! format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which this
//! workspace forbids. The audited `fmv-macos-events` crate (also used by PdfCraft and PhotoCraft)
//! wraps exactly that, an `NSAppleEventManager` handler registered before Finder's launch event
//! that leaves winit's delegate alone, behind a safe main-thread API.
use fmv_macos_events::{Event, Inbox, Registration};
use gridcraft_ui_egui::SheetApp;
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
pub struct AppleEvents {
_registration: Registration,
inbox: Inbox,
}
impl AppleEvents {
/// Register the handlers. Call on the main thread before the event loop starts, so the event
/// that launched the app (a Finder double-click) is caught too.
pub fn install() -> Self {
let (registration, inbox) = Registration::install();
Self { _registration: registration, inbox }
}
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
let ctx = ctx.clone();
self.inbox.set_wake(move || ctx.request_repaint());
self.inbox.clone()
}
}
/// Open the documents and act on the quit requests that arrived since the last frame.
pub fn poll(inbox: &Inbox, app: &mut SheetApp, ctx: &egui::Context) {
for e in inbox.drain() {
match e {
Event::Open(paths) => {
for p in paths.iter().filter_map(|p| p.to_str()) {
app.open_path(p);
}
}
Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
}
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ pub fn start(port: u16, ctx: egui::Context) -> std::io::Result<Receiver<ControlR
let _ = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, tx, ctx));
}
})?;
eprintln!("GridCraft control channel listening on 127.0.0.1:{port}");
log::info!("control channel listening on 127.0.0.1:{port}");
Ok(rx)
}
+232
View File
@@ -0,0 +1,232 @@
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
//!
//! 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
//! violation happens in the driver, where no Rust error handling can catch it.
//!
//! DirectX 12 shaders are compiled with FXC (`d3dcompiler_47.dll`, part of Windows), never with
//! whichever `dxcompiler.dll` the DLL search path happens to find (#339, #354): see
//! [`dx12_compiler`].
use eframe::{
NativeOptions,
egui_wgpu::WgpuSetup,
wgpu::{Backends, DeviceType, Dx12Compiler},
};
/// What the start-up probe learned about one DirectX 12 adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Dx12Adapter {
/// `Cpu` is WARP (Microsoft's software rasteriser): it works, but every frame is drawn on the
/// processor, which makes the app lag on older machines.
pub device_type: DeviceType,
/// Whether the adapter offers the limits eframe will ask for when it creates the device.
pub meets_limits: bool,
}
/// The backends to initialize on Windows.
///
/// An explicit `backend_override` (normally `Backends::from_env()`, i.e. `WGPU_BACKEND`) always
/// wins. Otherwise DirectX 12 only, as long as `dx12_adapters` (what a DirectX 12-only probe found)
/// contains a usable hardware GPU. Without one, OpenGL is the way to the GPU: graphics chips whose
/// driver has no DirectX 12 support still have an OpenGL driver, and GL can't reach the AMD driver
/// crash described in [`configure_backends`], because an AMD GPU with a driver shows up as a
/// DirectX 12 adapter and keeps us on DirectX 12. When DirectX 12 offers only WARP, it stays
/// enabled next to GL as a last resort for machines without an OpenGL driver either (virtual
/// machines): wgpu prefers any GPU over a software adapter, so it's only picked when GL has
/// nothing better. Vulkan is never part of the default.
pub fn choose_backends(backend_override: Option<Backends>, dx12_adapters: &[Dx12Adapter]) -> Backends {
if let Some(backends) = backend_override {
return backends;
}
let hardware = |a: &&Dx12Adapter| a.device_type != DeviceType::Cpu;
if dx12_adapters.iter().filter(hardware).any(|a| a.meets_limits) {
Backends::DX12
} else if !dx12_adapters.is_empty() && !dx12_adapters.iter().any(|a| hardware(&a)) {
Backends::DX12 | Backends::GL
} else {
// No DirectX 12 adapter at all, or only GPUs that can't run the app: GL alone, so a
// DirectX 12 GPU that would fail device creation isn't picked over the OpenGL one.
Backends::GL
}
}
/// The backends for a second start when the first one failed with a graphics error before the
/// app was created (no adapter, no device, no surface): the other one of DirectX 12 and OpenGL.
/// `None` when `WGPU_BACKEND` chose the backends (the user asked for exactly those) or the first
/// start already tried both. Never Vulkan (#120).
pub fn fallback_backends(backend_override: Option<Backends>, first: Backends) -> Option<Backends> {
if backend_override.is_some() {
return None;
}
let rest = (Backends::DX12 | Backends::GL).difference(first);
(!rest.is_empty()).then_some(rest)
}
/// The DirectX 12 shader compiler: `env_choice` (normally `Dx12Compiler::from_env()`, i.e.
/// `WGPU_DX12_COMPILER`, for troubleshooting) or else FXC.
///
/// wgpu's default (`Auto`) loads the first `dxcompiler.dll` on the DLL search path. GridCraft ships
/// none, so that is another program's copy (a Windows SDK, an Edge or WebView folder, anything on
/// `PATH`). Without a matching `dxil.dll` beside it, DXC prints "DXIL signing library not found",
/// wgpu treats that warning as a compile error, its internal compute pipelines fail, the device is
/// lost and the app quits before the first frame ("Parent device is lost"). FXC is part of Windows
/// and needs no extra DLL; egui's shaders don't need anything newer.
pub fn dx12_compiler(env_choice: Option<Dx12Compiler>) -> Dx12Compiler {
env_choice.unwrap_or(Dx12Compiler::Fxc)
}
/// Restricts the wgpu instance eframe creates to `backends`, and pins its DirectX 12 shader
/// compiler ([`dx12_compiler`]).
pub fn configure_backends(options: &mut NativeOptions, backends: Backends) {
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.instance_descriptor.backend_options.dx12.shader_compiler = dx12_compiler(Dx12Compiler::from_env());
// eframe's default includes Vulkan and GL. Creating the GL backend can crash inside AMD's
// atio6axx.dll, and enumerating Vulkan adapters inside Intel's igvk64.dll (#120), before
// adapter selection or any Rust error handling runs, so the window never appears.
// Choosing an adapter afterwards is too late: only leaving the backend out of the
// instance avoids it. This matches the verified WGPU_BACKEND=dx12 workaround without
// mutating process environment variables.
create.instance_descriptor.backends = backends;
}
}
/// Chooses the backends ([`choose_backends`]), applies them to `options` and returns them.
/// Without a `backend_override` this first probes DirectX 12 with a short-lived instance of its
/// own, which is dropped before eframe creates the real one.
#[cfg(target_os = "windows")]
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) -> Backends {
let backends = match backend_override {
Some(backends) => {
log::info!("graphics: WGPU_BACKEND override, backends {backends:?}");
backends
}
None => {
let adapters = probe_dx12(options);
let backends = choose_backends(None, &adapters);
log::info!("graphics: {} DirectX 12 adapter(s) {adapters:?}, backends {backends:?}", adapters.len());
backends
}
};
configure_backends(options, backends);
backends
}
/// Lists the DirectX 12 adapters, checking each against the limits eframe's device descriptor
/// will require. Empty when this build has no DirectX 12 backend.
#[cfg(target_os = "windows")]
fn probe_dx12(options: &NativeOptions) -> Vec<Dx12Adapter> {
use eframe::wgpu::{Instance, InstanceDescriptor};
// `Instance::new` panics when the build has no backend for the platform.
if !Instance::enabled_backend_features().contains(Backends::DX12) {
return Vec::new();
}
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
return Vec::new();
};
let instance = Instance::new(InstanceDescriptor { backends: Backends::DX12, ..InstanceDescriptor::new_without_display_handle() });
pollster::block_on(instance.enumerate_adapters(Backends::DX12))
.iter()
.map(|adapter| {
let info = adapter.get_info();
let required = (create.device_descriptor)(adapter).required_limits;
let meets_limits = required.check_limits(&adapter.limits());
log::info!("graphics: DirectX 12 adapter {:?} ({:?}, driver {:?}), limits ok: {meets_limits}", info.name, info.device_type, info.driver);
Dx12Adapter { device_type: info.device_type, meets_limits }
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn configured_backends(backends: Backends) -> Backends {
let mut options = NativeOptions::default();
configure_backends(&mut options, backends);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
create.instance_descriptor.backends
}
const fn adapter(device_type: DeviceType, meets_limits: bool) -> Dx12Adapter {
Dx12Adapter { device_type, meets_limits }
}
#[test]
fn windows_default_never_initializes_vulkan() {
// eframe's own default (PRIMARY | GL) would initialize Vulkan and OpenGL as well.
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
assert!(eframe_default.instance_descriptor.backends.contains(Backends::GL));
let gpu = [adapter(DeviceType::IntegratedGpu, true)];
assert_eq!(configured_backends(choose_backends(None, &gpu)), Backends::DX12);
// #120: whatever the DirectX 12 probe finds, and whatever the retry picks, no Vulkan.
let probes: [&[Dx12Adapter]; 4] = [&[], &gpu, &[adapter(DeviceType::Cpu, true)], &[adapter(DeviceType::IntegratedGpu, false)]];
for adapters in probes {
let first = choose_backends(None, adapters);
assert!(!first.contains(Backends::VULKAN), "{adapters:?}");
if let Some(second) = fallback_backends(None, first) {
assert!(!second.contains(Backends::VULKAN), "{adapters:?}");
}
}
}
#[test]
fn explicit_backend_override_is_preserved() {
let warp_only = [adapter(DeviceType::Cpu, true)];
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
// Whatever the probe would have found, the override wins (the probe doesn't run then),
// and a failed start isn't retried with something the user didn't ask for.
assert_eq!(choose_backends(Some(backends), &[]), backends);
assert_eq!(choose_backends(Some(backends), &warp_only), backends);
assert_eq!(configured_backends(backends), backends);
assert_eq!(fallback_backends(Some(backends), backends), None);
}
}
#[test]
fn gl_when_dx12_has_no_usable_gpu() {
// No DirectX 12 driver, so DirectX 12 offers only WARP (or nothing) and lags.
let warp_only = [adapter(DeviceType::Cpu, true)];
assert_eq!(choose_backends(None, &warp_only), Backends::GL | Backends::DX12);
assert_eq!(choose_backends(None, &[]), Backends::GL);
// A GPU that can't create eframe's device: GL alone, so it isn't picked over the GL one.
let weak_gpu = [adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::Cpu, true)];
assert_eq!(choose_backends(None, &weak_gpu), Backends::GL);
// Any usable GPU keeps DirectX 12 only, next to WARP or a weaker GPU.
let mixed = [adapter(DeviceType::Cpu, true), adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::DiscreteGpu, true)];
assert_eq!(choose_backends(None, &mixed), Backends::DX12);
}
#[test]
fn failed_start_retries_with_the_other_backend() {
assert_eq!(fallback_backends(None, Backends::DX12), Some(Backends::GL));
assert_eq!(fallback_backends(None, Backends::GL), Some(Backends::DX12));
// Both were already tried: nothing left to fall back to.
assert_eq!(fallback_backends(None, Backends::DX12 | Backends::GL), None);
}
#[test]
fn dx12_compiles_shaders_with_fxc_unless_asked() {
// #339, #354: wgpu's `Auto` would load a stray dxcompiler.dll and lose the device.
assert!(matches!(dx12_compiler(None), Dx12Compiler::Fxc));
assert!(matches!(dx12_compiler(Some(Dx12Compiler::Auto)), Dx12Compiler::Auto));
assert!(matches!(dx12_compiler(Some(Dx12Compiler::default_dynamic_dxc())), Dx12Compiler::DynamicDxc { .. }));
// eframe's own default is `Auto`; the configured instance (first start and retry) uses FXC.
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
if Dx12Compiler::from_env().is_none() {
assert!(matches!(eframe_default.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Auto));
let mut options = NativeOptions::default();
configure_backends(&mut options, Backends::DX12);
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
panic!("default native options must create a wgpu instance");
};
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
}
}
}
+580
View File
@@ -0,0 +1,580 @@
//! The desktop app's logger: `log::` records go to standard error and to a log file.
//!
//! Without a logger every `log::warn!`/`log::error!` in the workspace (a sample that failed to
//! build, a graphics adapter warning, a panic a command's guard recovered from) vanished. A launch
//! from a desktop menu has no terminal, so the file is what a bug report can attach:
//! `<settings dir>/logs/gridcraft.log`, next to `ui.json` and `prefs.json` (`config_dir` in
//! `main.rs`). Each start moves the previous log to `gridcraft.1.log` (and that one to `.2`), so
//! the log of a run that crashed survives the next launch. Runs without preferences
//! (`GRIDCRAFT_NO_PREFS`) log to standard error only.
//!
//! Levels: `info` for GridCraft's own crates, `warn` for everything else (wgpu and naga are
//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`,
//! `warn,gridcraft_engine=trace`, `wgpu_core=info`. A directive ending in `*` matches every target
//! that starts with it (`gridcraft*=debug`).
//!
//! Records logged before the settings directory is known are kept (up to [`MAX_PENDING`]) and
//! written once the file is attached. Writing never panics: a file that can't be created or
//! written leaves standard error as the only sink.
//!
//! This is the desktop app's logger only; `gridcraft-cli` and `gridcraft-web` set up their own.
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::SystemTime;
use log::LevelFilter;
/// The current log file's name inside the log directory.
pub const LOG_FILE: &str = "gridcraft.log";
/// How many previous logs are kept (`gridcraft.1.log` … `gridcraft.<KEEP>.log`).
pub const KEEP: usize = 2;
/// The log file stops growing past this size (a runaway warning can't fill the disk).
pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Records kept in memory until the log file is attached.
pub const MAX_PENDING: usize = 512;
/// The built-in filter when `RUST_LOG` is unset or empty.
pub const DEFAULT_FILTER: &str = "warn,gridcraft*=info";
/// Per-target level filter parsed from env_logger-style directives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Filter {
default: LevelFilter,
directives: Vec<(String, LevelFilter)>,
}
impl Filter {
/// Parse `spec`; unknown levels and empty parts are skipped. Without a bare level, targets no
/// directive names log errors only.
pub fn parse(spec: &str) -> Filter {
let mut f = Filter { default: LevelFilter::Error, directives: Vec::new() };
for part in spec.split(',').map(str::trim).filter(|p| !p.is_empty()) {
match part.split_once('=') {
Some((name, level)) => {
let name = name.trim();
if let (false, Some(level)) = (name.is_empty(), parse_level(level)) {
f.directives.push((name.to_owned(), level));
}
}
None => match parse_level(part) {
Some(level) => f.default = level,
// A bare target name: everything from it (env_logger does the same).
None => f.directives.push((part.to_owned(), LevelFilter::Trace)),
},
}
}
f
}
/// The level that applies to `target` (the most specific matching directive wins).
pub fn level_for(&self, target: &str) -> LevelFilter {
self.directives.iter().filter(|(name, _)| matches(name, target)).max_by_key(|(name, _)| name.len()).map_or(self.default, |(_, level)| *level)
}
/// The most verbose level any target can reach (for `log::set_max_level`).
pub fn max(&self) -> LevelFilter {
self.directives.iter().map(|(_, level)| *level).fold(self.default, Ord::max)
}
}
fn parse_level(s: &str) -> Option<LevelFilter> {
s.trim().parse().ok()
}
/// `name` matches `target` itself and its submodules (`a` matches `a` and `a::b`, not `ab`);
/// `name*` matches every target starting with `name`.
fn matches(name: &str, target: &str) -> bool {
match name.strip_suffix('*') {
Some(prefix) => target.starts_with(prefix),
None => target.strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.starts_with("::")),
}
}
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
pub fn timestamp(t: SystemTime) -> String {
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
let secs = since.as_secs();
let (days, rem) = (secs / 86_400, secs % 86_400);
let (y, m, d) = civil_from_days(days);
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
}
/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch). Saturating, so no clock
/// value can overflow it.
fn civil_from_days(days: u64) -> (u64, u64, u64) {
let z = days.saturating_add(719_468);
let era = z / 146_097;
let doe = z % 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = era.saturating_mul(400).saturating_add(yoe).saturating_add(u64::from(m <= 2));
(y, m, d)
}
fn numbered(dir: &Path, n: usize) -> PathBuf {
if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("gridcraft.{n}.log")) }
}
/// Shift the previous logs up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest dropped)
/// and create a fresh, empty log file in `dir` (created if missing).
pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
std::fs::create_dir_all(dir)?;
for n in (1..=KEEP).rev() {
match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
}
let path = numbered(dir, 0);
let file = File::create(&path)?;
Ok((path, file))
}
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
/// then appended to it until it reaches its size cap.
pub struct Sink {
file: Option<File>,
pending: Vec<String>,
dropped: usize,
written: u64,
max_bytes: u64,
capped: bool,
}
impl Sink {
pub fn new(max_bytes: u64) -> Sink {
Sink { file: None, pending: Vec::new(), dropped: 0, written: 0, max_bytes, capped: false }
}
/// Append `line` to the file, or keep it until [`Sink::attach`].
pub fn write(&mut self, line: &str) {
if self.file.is_none() {
if self.capped {
// No file is coming ([`Sink::no_file`]): standard error had the line.
} else if self.pending.len() < MAX_PENDING {
self.pending.push(line.to_owned());
} else {
self.dropped = self.dropped.saturating_add(1);
}
return;
}
self.append(line);
}
/// Start writing to `file` (a fresh one: the size cap starts over), first the lines kept so far.
pub fn attach(&mut self, file: File) {
self.file = Some(file);
self.written = 0;
self.capped = false;
for line in std::mem::take(&mut self.pending) {
self.append(&line);
}
if self.dropped > 0 {
let note = format!("{} earlier log lines were dropped before the log file was opened\n", self.dropped);
self.dropped = 0;
self.append(&note);
}
}
/// There will be no log file: forget the lines kept for it and keep no more.
pub fn no_file(&mut self) {
self.pending = Vec::new();
self.dropped = 0;
self.capped = true;
}
fn append(&mut self, line: &str) {
if self.capped {
return;
}
let Some(file) = self.file.as_mut() else { return };
let len = u64::try_from(line.len()).unwrap_or(u64::MAX);
let text = if self.written.saturating_add(len) > self.max_bytes {
self.capped = true;
format!("log file reached {} bytes; later records go to standard error only\n", self.max_bytes)
} else {
self.written = self.written.saturating_add(len);
line.to_owned()
};
// A full disk or a vanished file must not take the app down: drop the file sink.
if file.write_all(text.as_bytes()).is_err() {
self.file = None;
self.capped = true;
}
}
}
/// The installed logger: a [`Filter`], standard error and a [`Sink`].
pub struct AppLogger {
filter: Filter,
stderr: bool,
sink: Mutex<Sink>,
}
impl AppLogger {
pub fn new(filter: Filter, stderr: bool) -> AppLogger {
AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) }
}
/// Rotate the logs in `dir` and send records to the fresh file; returns its path. On an error
/// standard error stays the only sink.
pub fn attach_dir(&self, dir: &Path) -> Result<PathBuf, String> {
// A thread that panicked while logging leaves the sink usable: take it back.
let mut sink = self.sink.lock().unwrap_or_else(PoisonError::into_inner);
match rotate(dir) {
Ok((path, file)) => {
sink.attach(file);
Ok(path)
}
Err(e) => {
sink.no_file();
Err(format!("{}: {e}", dir.display()))
}
}
}
/// No log file for this run (runs without preferences): log to standard error only.
pub fn no_file(&self) {
self.sink.lock().unwrap_or_else(PoisonError::into_inner).no_file();
}
}
impl log::Log for AppLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.level() <= self.filter.level_for(metadata.target())
}
fn log(&self, record: &log::Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
// Formatted before the sink is locked, so a message that logs while it is formatted can't deadlock.
let thread = std::thread::current();
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
let line =
format_line(&timestamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string());
if self.stderr {
// No terminal (a Windows GUI build, a closed pipe) is not an error worth reporting.
let _ = std::io::stderr().write_all(line.as_bytes());
}
self.sink.lock().unwrap_or_else(PoisonError::into_inner).write(&line);
}
fn flush(&self) {}
}
/// Install the logger (filter from `RUST_LOG`, else [`DEFAULT_FILTER`]); `None` when another
/// logger was installed first. Call [`AppLogger::attach_dir`] once the settings directory is known.
pub fn install() -> Option<&'static AppLogger> {
static LOGGER: OnceLock<AppLogger> = OnceLock::new();
let spec = std::env::var("RUST_LOG").ok().filter(|s| !s.trim().is_empty());
let filter = Filter::parse(spec.as_deref().unwrap_or(DEFAULT_FILTER));
let max = filter.max();
let logger = LOGGER.get_or_init(|| AppLogger::new(filter, true));
log::set_logger(logger).ok()?;
log::set_max_level(max);
Some(logger)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, UNIX_EPOCH};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("gridcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
d
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).expect("read log")
}
fn record(logger: &AppLogger, level: log::Level, target: &str, msg: &str) {
use log::Log;
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
}
#[test]
fn the_default_filter_shows_gridcraft_info_and_other_crates_warnings() {
let f = Filter::parse(DEFAULT_FILTER);
assert_eq!(f.level_for("gridcraft"), LevelFilter::Info);
assert_eq!(f.level_for("gridcraft::control_server"), LevelFilter::Info);
assert_eq!(f.level_for("gridcraft_engine::sample"), LevelFilter::Info);
assert_eq!(f.level_for("gridcraft_ui_egui::control"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
assert_eq!(f.max(), LevelFilter::Info);
}
#[test]
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
let f = Filter::parse("info,wgpu_core=error,gridcraft_calc=trace,gridcraft_calc::recalc=off");
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
assert_eq!(f.level_for("gridcraft_calc::graph"), LevelFilter::Trace);
assert_eq!(f.level_for("gridcraft_calc::recalc"), LevelFilter::Off);
assert_eq!(f.max(), LevelFilter::Trace);
// A module name is matched at `::` boundaries, not as a bare prefix.
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
// A trailing `*` is a prefix.
assert_eq!(Filter::parse("gridcraft*=debug").level_for("gridcraft_xlsx::read"), LevelFilter::Debug);
assert_eq!(Filter::parse("gridcraft*=debug").level_for("eframe"), LevelFilter::Error);
// A bare target name sets that target to the most verbose level, as env_logger does.
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
// Levels are case-insensitive and surrounding blanks are ignored.
assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("gridcraft"), LevelFilter::Debug);
assert_eq!(Filter::parse(" WARN , gridcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
}
#[test]
fn hostile_specs_never_panic_and_fall_back_sensibly() {
let long = "x".repeat(100_000);
let many = "a=info,".repeat(10_000);
for spec in [
"",
",,,",
"=",
"==",
"=debug",
"gridcraft=",
"nonsense=loud",
"🦀=info",
"*",
"*=",
"=*",
"a=b=c",
"warn,,gridcraft=DEBUG",
"\0",
"é::ü=trace",
&long,
&many,
] {
let f = Filter::parse(spec);
for target in ["", "gridcraft", "🦀", "a::b", "*"] {
let _ = f.level_for(target);
}
let _ = f.max();
}
assert_eq!(Filter::parse("warn,,gridcraft=DEBUG").level_for("gridcraft"), LevelFilter::Debug);
// An unknown level is skipped: that target keeps the default.
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
assert_eq!(Filter::parse("gridcraft=").level_for("gridcraft"), LevelFilter::Error);
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
}
#[test]
fn timestamps_are_utc_with_milliseconds() {
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
// Leap day, and the day after it.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
// 2000 is a leap year (divisible by 400), 2100 is not.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
}
#[test]
fn a_line_carries_time_level_thread_target_and_message() {
assert_eq!(
format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "gridcraft", "book.xlsx: file not found"),
"2026-10-08T07:59:17.728Z WARN [main] gridcraft: book.xlsx: file not found\n"
);
// A multi-line message keeps its lines; the record still ends in one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
}
#[test]
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
let dir = temp_dir("rotate");
for run in 1..=4 {
let (path, _file) = rotate(&dir).expect("rotate");
assert_eq!(path, dir.join(LOG_FILE));
assert_eq!(read(&path), "");
std::fs::write(&path, format!("run {run}")).expect("write");
}
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
assert_eq!(read(&dir.join("gridcraft.1.log")), "run 3");
assert_eq!(read(&dir.join("gridcraft.2.log")), "run 2");
assert!(!dir.join("gridcraft.3.log").exists(), "only {KEEP} old logs are kept");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
let dir = temp_dir("blocked");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "a file where the directory should be").expect("block");
assert!(rotate(&dir).is_err());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
let dir = temp_dir("pending");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early 1\n");
sink.write("early 2\n");
sink.attach(file);
sink.write("late\n");
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
let dir = temp_dir("bounded");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING + 5 {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn exactly_a_full_pending_buffer_drops_nothing() {
let dir = temp_dir("full");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().count(), MAX_PENDING);
assert!(!text.contains("dropped"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_a_file_nothing_is_kept_in_memory() {
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early\n");
sink.no_file();
sink.write("late\n");
assert!(sink.pending.is_empty() && sink.dropped == 0);
}
#[test]
fn the_file_stops_at_its_size_cap_with_one_note() {
let dir = temp_dir("cap");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(100);
sink.attach(file);
for i in 0..50 {
sink.write(&format!("line {i:02} with some padding\n"));
}
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
use log::Log;
let dir = temp_dir("logger");
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
record(&logger, log::Level::Info, "gridcraft", "before the settings directory");
record(&logger, log::Level::Info, "wgpu_core::device", "too chatty");
let path = logger.attach_dir(&dir).expect("attach");
assert_eq!(path, dir.join(LOG_FILE));
record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
record(&logger, log::Level::Error, "gridcraft", "internal error: boom");
record(&logger, log::Level::Debug, "gridcraft", "below info");
let text = read(&path);
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 3, "{text}");
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("gridcraft: before the settings directory"), "{text}");
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("gridcraft: internal error: boom"), "{text}");
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("gridcraft_ui_egui").build()));
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
// Attaching again rotates: the first log becomes `.1`.
logger.attach_dir(&dir).expect("attach again");
assert_eq!(read(&dir.join("gridcraft.1.log")), text);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn records_from_many_threads_are_whole_lines() {
let dir = temp_dir("threads");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let path = logger.attach_dir(&dir).expect("attach");
let workers: Vec<_> = (0..8)
.map(|t| {
let l = std::sync::Arc::clone(&logger);
std::thread::spawn(move || {
for i in 0..100 {
record(&l, log::Level::Info, "gridcraft", &format!("thread {t} record {i}"));
}
})
})
.collect();
for w in workers {
w.join().expect("worker");
}
let text = read(&path);
assert_eq!(text.lines().count(), 800);
assert!(text.lines().all(|l| l.contains(" gridcraft: thread ")), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
let dir = temp_dir("unusable");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "not a directory").expect("block");
let logger = AppLogger::new(Filter::parse("info"), false);
assert!(logger.attach_dir(&dir).is_err());
record(&logger, log::Level::Error, "x", "still fine");
// Nothing waits in memory for a file that won't come.
assert!(logger.sink.lock().expect("sink").pending.is_empty());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn a_poisoned_sink_still_logs() {
let dir = temp_dir("poison");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let l = std::sync::Arc::clone(&logger);
let _ = std::thread::spawn(move || {
let _guard = l.sink.lock().expect("lock");
panic!("poison the sink");
})
.join();
assert!(logger.sink.is_poisoned());
let path = logger.attach_dir(&dir).expect("attach");
record(&logger, log::Level::Warn, "gridcraft", "after the poison");
assert!(read(&path).contains("gridcraft: after the poison"));
let _ = std::fs::remove_dir_all(&dir);
}
}
+207 -44
View File
@@ -8,15 +8,24 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_os = "macos")]
mod apple_events;
mod control_server;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod print;
use std::cell::RefCell;
use std::rc::Rc;
use gridcraft_engine::Session;
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
struct App(SheetApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App(SheetApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
@@ -28,8 +37,13 @@ impl eframe::App for App {
if let Some(m) = &self.1 {
m.poll(&mut self.0, ctx);
}
apple_events::poll(&self.2, &mut self.0, ctx);
}
self.0.logic(ctx);
self.0.poll_printing(ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(raw);
@@ -44,7 +58,18 @@ impl eframe::App for App {
self.0.ui(ui);
}
fn on_exit(&mut self) {
print::finish_pending_jobs();
save_prefs(&self.0);
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
// macOS adapter subclasses the window's content view and restores its class on teardown;
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
// `-[_NSTouchBarFinderObservation invalidate]` throws "not registered" and the quit ends
// in a crash report. eframe calls `on_exit` on every way of quitting (Quit/⌘Q, the Dock,
// the close button, `app.quit`), and nothing after it is needed: the preferences are
// saved and the log file is unbuffered. eframe does the same when it doesn't
// run-and-return. `on_exit` only runs once the app exists, never on a failed start.
#[cfg(target_os = "macos")]
std::process::exit(0);
}
}
@@ -61,15 +86,33 @@ fn config_dir() -> Option<std::path::PathBuf> {
}
}
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
/// them, and keep no log file.
fn prefs_enabled() -> bool {
std::env::var_os("GRIDCRAFT_NO_PREFS").is_none()
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
fn log_dir() -> Option<std::path::PathBuf> {
Some(config_dir()?.join("logs"))
}
fn load_prefs(app: &mut SheetApp) {
if std::env::var_os("GRIDCRAFT_NO_PREFS").is_some() {
if !prefs_enabled() {
return;
}
// First run (or a ui.json without a usable language): follow the desktop's language.
app.ui.language = gridcraft_ui_egui::i18n::Language::system();
// ...and its light or dark appearance (#239), until a theme is chosen and saved in ui.json.
app.ui.system_theme = true;
let Some(dir) = config_dir() else { return };
if let Ok(b) = std::fs::read(dir.join("ui.json"))
&& let Ok(ui) = serde_json::from_slice(&b)
&& let Ok(ui) = serde_json::from_slice::<gridcraft_ui_egui::UiState>(&b)
{
let saved = serde_json::from_slice(&b).ok().and_then(|v| gridcraft_ui_egui::i18n::saved_language(&v));
let language = saved.unwrap_or(app.ui.language);
app.ui = ui;
app.ui.language = language;
}
if let Ok(b) = std::fs::read(dir.join("prefs.json"))
&& let Ok(p) = serde_json::from_slice(&b)
@@ -79,7 +122,7 @@ fn load_prefs(app: &mut SheetApp) {
}
fn save_prefs(app: &SheetApp) {
if std::env::var_os("GRIDCRAFT_NO_PREFS").is_some() {
if !prefs_enabled() {
return;
}
let Some(dir) = config_dir() else { return };
@@ -93,46 +136,106 @@ fn save_prefs(app: &SheetApp) {
}
fn services() -> Services {
// Keep the owner alive: X11/Wayland serve clipboard data from this handle.
let clipboard: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();
let paste_clipboard = clipboard.clone();
Services {
copy_html: Some(Box::new(move |html, text| {
let mut clipboard = clipboard.borrow_mut();
if clipboard.is_none() {
*clipboard = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?);
}
clipboard.as_mut().ok_or("clipboard unavailable")?.set_html(html, Some(text)).map_err(|e| e.to_string())
})),
paste_html: Some(Box::new(move || {
let mut clipboard = paste_clipboard.try_borrow_mut().ok()?;
if clipboard.is_none() {
*clipboard = arboard::Clipboard::new().ok();
}
clipboard.as_mut()?.get().html().ok()
})),
pick_open: Some(Box::new(|| {
rfd::FileDialog::new()
.add_filter("Spreadsheets", &["xlsx", "xlsm", "csv", "tsv", "txt", "json"])
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"])
.add_filter("Excel Workbook", &["xlsx", "xlsm"])
.add_filter("Excel 97-2003 Workbook (import)", &["xls"])
.add_filter("Excel Binary Workbook (data import)", &["xlsb"])
.add_filter("OpenDocument Spreadsheet (data import)", &["ods"])
.add_filter("CSV", &["csv"])
.pick_file()
.and_then(|p| p.to_str().map(str::to_string))
})),
pick_save: Some(Box::new(|suggested: &str| {
let stem = std::path::Path::new(suggested).file_stem().and_then(|s| s.to_str()).unwrap_or("Book1").to_string();
pick_picture: Some(Box::new(|| {
rfd::FileDialog::new()
.set_file_name(format!("{stem}.xlsx"))
.add_filter("Excel Workbook (.xlsx)", &["xlsx"])
.add_filter("CSV UTF-8 (.csv)", &["csv"])
.add_filter("Web Page (.html)", &["html"])
.save_file()
.add_filter("Pictures (PNG, JPEG)", &["png", "jpg", "jpeg"])
.pick_file()
.and_then(|p| p.to_str().map(str::to_string))
})),
open_url: Some(Box::new(|url: &str| {
let cmd = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
let _ = std::process::Command::new(cmd).arg(url).spawn();
pick_save: Some(Box::new(|suggested: &str| {
let path = std::path::Path::new(suggested);
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Book1").to_string();
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
const TYPES: [(&str, &str); 4] =
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
for (label, x) in TYPES.iter().filter(|(_, x)| *x == ext).chain(TYPES.iter().filter(|(_, x)| *x != ext)) {
dialog = dialog.add_filter(*label, &[*x]);
}
dialog.save_file().and_then(|p| p.to_str().map(str::to_string))
})),
open_url: Some(Box::new(|url: &str| open_with_system(url))),
printers: Some(print::discover()),
print_native: Some(print::submit()),
..Default::default()
}
}
/// Opens a URL or file with the system's default application.
fn open_with_system(target: &str) {
let cmd = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() {
log::warn!("{cmd} {target}: {e}");
}
}
fn icon() -> Option<egui::IconData> {
#[cfg(target_os = "macos")]
let bytes = include_bytes!("../../../assets/app-icon/gridcraft-macos-512.png");
#[cfg(not(target_os = "macos"))]
let bytes = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png");
let img = image::load_from_memory(bytes).ok()?.to_rgba8();
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
}
fn main() -> eframe::Result<()> {
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
// Commands catch their panics (`Session::execute`), but the default hook only prints to
// standard error; this one sends every panic, caught or not, to the log file too, with a
// backtrace when RUST_BACKTRACE is set.
std::panic::set_hook(Box::new(|info| {
let trace = std::backtrace::Backtrace::capture();
let report = if trace.status() == std::backtrace::BacktraceStatus::Captured {
format!("internal error: {info}\n{trace}")
} else {
format!("internal error: {info}")
};
// Standard error and the log file; standard error alone when RUST_LOG turned errors off.
if log::log_enabled!(log::Level::Error) {
log::error!("{report}");
} else {
// `eprintln!` panics on a broken stderr pipe, and a panic inside the panic hook aborts.
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n"));
}
}));
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", env!("CARGO_PKG_VERSION"));
@@ -157,23 +260,40 @@ fn main() -> eframe::Result<()> {
}
i += 1;
}
// The log file lives in the settings folder, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
// don't rotate away the user's own logs.
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
None => logger.no_file(),
}
}
let mut session = Session::new();
if let Some(s) = &sample
&& let Err(e) = session.execute("file.new", json!({"sample": s}))
{
eprintln!("sample: {e}");
}
for f in &files {
if let Err(e) = session.execute("file.open", json!({"path": f})) {
eprintln!("{f}: {e}");
}
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.after_engine(); // Show warnings from the sample.
let control_port = control_port;
load_prefs(&mut app);
// 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.
for f in &files {
app.open_path(f);
}
let mut viewport = egui::ViewportBuilder::default()
.with_title("GridCraft")
.with_inner_size([1440.0, 900.0])
@@ -187,22 +307,65 @@ fn main() -> eframe::Result<()> {
viewport = viewport.with_icon(i);
}
let options = eframe::NativeOptions { viewport, ..Default::default() };
eframe::run_native(
"GridCraft",
options,
Box::new(move |cc| {
SheetApp::setup_context(&cc.egui_ctx, app.ui.dark);
if let Some(port) = control_port {
match control_server::start(port, cc.egui_ctx.clone()) {
Ok(rx) => app.control_rx = Some(rx),
Err(e) => eprintln!("control channel on port {port}: {e}"),
// Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when
// DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs).
#[cfg(target_os = "windows")]
let backend_override = eframe::wgpu::Backends::from_env();
#[cfg(target_os = "windows")]
let (options, first_backends) = {
let mut options = options;
let backends = graphics::configure(&mut options, backend_override);
(options, backends)
};
#[cfg(target_os = "windows")]
let retry_options = options.clone();
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
// The app waits here until a start gets as far as creating it; a start that fails before
// (no graphics adapter, device or surface) leaves it here for the next attempt.
let pending = std::cell::Cell::new(Some(app));
let run = |options: eframe::NativeOptions| {
eframe::run_native(
"GridCraft",
options,
Box::new(|cc| {
let Some(mut app) = pending.take() else {
return Err("the app was already created".into());
};
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
if let Some(port) = control_port {
match control_server::start(port, cc.egui_ctx.clone()) {
Ok(rx) => app.control_rx = Some(rx),
Err(e) => log::error!("control channel on port {port}: {e}"),
}
}
}
Ok(Box::new(App(
app,
#[cfg(target_os = "macos")]
None,
)))
}),
)
Ok(Box::new(App(
app,
#[cfg(target_os = "macos")]
None,
#[cfg(target_os = "macos")]
apple_events.connect(&cc.egui_ctx),
)))
}),
)
};
let result = run(options);
// A graphics error before the app existed: start once more with the other backend (eframe
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
#[cfg(target_os = "windows")]
if let Err(eframe::Error::Wgpu(e)) = &result
&& let Some(app) = pending.take()
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
{
log::error!("graphics: the renderer didn't start on {first_backends:?} ({e}); trying {backends:?}");
pending.set(Some(app));
let mut options = retry_options;
graphics::configure_backends(&mut options, backends);
return run(options);
}
result
}
+82 -9
View File
@@ -6,7 +6,7 @@ use std::sync::mpsc::{Receiver, channel};
use gridcraft_ui_egui::SheetApp;
use muda::accelerator::Accelerator;
use muda::{Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use serde_json::{Value, json};
type Entry = (&'static str, &'static str, Option<&'static str>);
@@ -30,7 +30,7 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
("Page Setup…", "dialog:pageSetup", None),
("Print…", "file.print", Some("CMD+P")),
("-", "", None),
("Properties…", "file.properties", None),
("Properties…", "dialog:backstage:info", None),
],
),
(
@@ -78,7 +78,7 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
("Freeze Top Row", "view.freezeTopRow", None),
("Unfreeze Panes", "view.unfreezePanes", None),
("-", "", None),
("Dark Mode", "view.darkMode", None),
("Display Theme", "view.theme", None),
("Collapse Ribbon", "view.collapseRibbon", Some("CMD+ALT+R")),
],
),
@@ -160,6 +160,8 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
("-", "", None),
("Group", "data.group", None),
("Ungroup", "data.ungroup", None),
("Show Detail", "data.showDetail", None),
("Hide Detail", "data.hideDetail", None),
("Subtotal…", "dialog:subtotal", None),
("-", "", None),
("Calculate Now", "formulas.calculateNow", None),
@@ -181,6 +183,18 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
pub struct NativeMenu {
_menu: Menu,
events: Receiver<MenuEvent>,
theme_items: Vec<(&'static str, CheckMenuItem)>,
}
fn select_theme(app: &mut SheetApp, id: &str) -> bool {
let mode = match id {
"theme:system" => "system",
"theme:light" => "light",
"theme:dark" => "dark",
_ => return false,
};
app.run_or_alert("view.theme", json!({"mode": mode}));
true
}
impl NativeMenu {
@@ -200,6 +214,7 @@ impl NativeMenu {
&PredefinedMenuItem::quit(None),
]);
let _ = menu.append(&app_menu);
let mut theme_items = Vec::new();
for (title, entries) in tree() {
let sub = Submenu::new(title, true);
for (label, id, acc) in entries {
@@ -207,6 +222,16 @@ impl NativeMenu {
let _ = sub.append(&PredefinedMenuItem::separator());
continue;
}
if id == "view.theme" {
let themes = Submenu::new(label, true);
for (mode, label) in [("system", "System"), ("light", "Light"), ("dark", "Dark")] {
let item = CheckMenuItem::with_id(format!("theme:{mode}"), label, true, false, None);
let _ = themes.append(&item);
theme_items.push((mode, item));
}
let _ = sub.append(&themes);
continue;
}
let accel = acc.and_then(|a| Accelerator::from_str(a).ok());
let item = MenuItem::with_id(id, label, true, accel);
let _ = sub.append(&item);
@@ -220,12 +245,40 @@ impl NativeMenu {
let _ = tx.send(e);
ctx.request_repaint();
}));
NativeMenu { _menu: menu, events: rx }
NativeMenu { _menu: menu, events: rx, theme_items }
}
pub fn poll(&self, app: &mut SheetApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
let id = ev.id.as_ref().to_string();
// Text selection belongs to the inline editor, not the worksheet clipboard/undo.
if app.text_box_editor.is_some() {
let clipboard = match id.as_str() {
"edit.copy" => Some(egui::ViewportCommand::RequestCopy),
"edit.cut" => Some(egui::ViewportCommand::RequestCut),
"edit.paste" => Some(egui::ViewportCommand::RequestPaste),
_ => None,
};
if let Some(command) = clipboard {
ctx.send_viewport_cmd(command);
continue;
}
if id == "edit.undo" || id == "edit.redo" {
ctx.input_mut(|i| {
i.events.push(egui::Event::Key {
key: egui::Key::Z,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers { command: true, mac_cmd: true, shift: id == "edit.redo", ..Default::default() },
});
});
continue;
}
}
if select_theme(app, &id) {
continue;
}
if let Some(url) = id.strip_prefix("url:") {
if let Some(open) = &app.services.open_url {
open(url);
@@ -238,19 +291,39 @@ impl NativeMenu {
("note", _) => json!({"threaded": false}),
("comment", _) => json!({"threaded": true}),
("about", tab) => json!({"tab": tab}),
("backstage", page) => json!({"page": page}),
_ => json!({}),
};
let name = if name == "note" { "comment" } else { name };
app.open_dialog(name, params);
} else if id == "edit.copy" || id == "edit.cut" {
if let Ok(r) = app.run(&id, json!({}))
&& let Some(t) = r.get("text").and_then(Value::as_str)
{
ctx.copy_text(t.to_string());
}
app.copy_to_clipboard(ctx, &id);
} else {
app.run_or_alert(&id, json!({}));
}
}
for (mode, item) in &self.theme_items {
let checked = app.ui.theme_mode() == *mode;
if item.is_checked() != checked {
item.set_checked(checked);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn theme_choices_use_the_shared_preference_command() {
let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default());
for mode in ["dark", "system", "light"] {
assert!(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_eq!(app.ui.theme_mode(), "light");
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
pub fn discover() -> Discover {
Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
let printers = craft_print::printers().into_iter().map(|printer| Printer { name: printer.name, default: printer.default }).collect();
let _ = sender.send(printers);
});
receiver
})
}
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
// let process exit kill PowerShell/CUPS before it hands the job to the spooler.
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
pub fn finish_pending_jobs() {
let workers = std::mem::take(&mut *JOBS.lock().unwrap_or_else(|poison| poison.into_inner()));
for worker in workers {
if worker.join().is_err() {
log::error!("the print worker stopped unexpectedly during shutdown");
}
}
}
pub fn submit() -> Submit {
Box::new(|bytes, settings: Settings| {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
printer: Some(settings.printer),
copies: settings.copies.clamp(1, 999),
duplex: settings.duplex.map(|value| match value {
Duplex::LongEdge => craft_print::Duplex::LongEdge,
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
Duplex::Off => craft_print::Duplex::Off,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
title: "GridCraft document".into(),
..Default::default()
};
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
});
if let Ok(worker) = worker {
let mut jobs = JOBS.lock().unwrap_or_else(|poison| poison.into_inner());
jobs.retain(|job| !job.is_finished());
jobs.push(worker);
}
receiver
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shutdown_waits_for_pending_submission_workers() {
let (release, wait) = std::sync::mpsc::channel();
let (completed, completion) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
wait.recv().unwrap();
completed.send(()).unwrap();
});
JOBS.lock().unwrap().push(worker);
let shutdown = std::thread::spawn(finish_pending_jobs);
assert!(completion.try_recv().is_err(), "the print worker is still pending");
release.send(()).unwrap();
shutdown.join().unwrap();
completion.recv().unwrap();
assert!(JOBS.lock().unwrap().is_empty(), "workers were joined before shutdown returned");
}
}
+8
View File
@@ -2,3 +2,11 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
# The web app (wasm32-unknown-unknown) has no clock: these trap (`RuntimeError: unreachable`)
# instead of returning. Read the clock only off wasm (`cfg(not(target_arch = "wasm32"))` or
# `cfg!`) and allow the lint at that call.
disallowed-methods = [
{ path = "std::time::Instant::now", reason = "traps on wasm; read the clock only off wasm" },
{ path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" },
]
+189 -11
View File
@@ -2,23 +2,36 @@
"schema": 1,
"repo": "storytold/gridcraft",
"branch": "main",
"head": "51b531be3e8b3f5a19d2b7714a4780a79569ca92",
"head_date": "2026-10-08T13:12:32Z",
"commits": 24,
"head": "90b3c41eec691797129303603d4073269aebab73",
"head_date": "2026-10-10T19:59:42Z",
"commits": 148,
"unattributed_commits": 0,
"contributors": [
{
"login": "echelon",
"people_entry": true,
"github_name": null,
"prs": 4,
"commits": 21,
"lines_added": 79088,
"lines_deleted": 3997,
"prs": 5,
"commits": 46,
"lines_added": 81717,
"lines_deleted": 4837,
"binary_added": 35,
"binary_deleted": 12,
"first_commit": "2026-10-06T02:09:42Z",
"last_commit": "2026-10-08T13:50:17Z"
"last_commit": "2026-10-10T19:59:42Z"
},
{
"login": "switch87",
"people_entry": false,
"github_name": null,
"prs": 1,
"commits": 2,
"lines_added": 646,
"lines_deleted": 8,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-08T10:06:39Z",
"last_commit": "2026-10-08T11:01:16Z"
},
{
"login": "h-a-n-a-s-h-i",
@@ -33,6 +46,19 @@
"first_commit": "2026-10-08T12:13:30Z",
"last_commit": "2026-10-08T14:02:29Z"
},
{
"login": "justinjohn0306",
"people_entry": false,
"github_name": null,
"prs": 6,
"commits": 7,
"lines_added": 1408,
"lines_deleted": 116,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-08T12:28:53Z",
"last_commit": "2026-10-09T18:39:12Z"
},
{
"login": "XusBadia",
"people_entry": false,
@@ -45,6 +71,149 @@
"binary_deleted": 0,
"first_commit": "2026-10-08T13:12:32Z",
"last_commit": "2026-10-08T13:12:32Z"
},
{
"login": "DWAA1660",
"people_entry": false,
"github_name": null,
"prs": 4,
"commits": 4,
"lines_added": 244,
"lines_deleted": 24,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T01:40:12Z",
"last_commit": "2026-10-09T20:46:29Z"
},
{
"login": "MarekSpodBiedry",
"people_entry": false,
"github_name": null,
"prs": 14,
"commits": 14,
"lines_added": 586,
"lines_deleted": 52,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T08:45:50Z",
"last_commit": "2026-10-10T17:06:52Z"
},
{
"login": "harrisonoconnorhover",
"people_entry": false,
"github_name": null,
"prs": 20,
"commits": 22,
"lines_added": 9266,
"lines_deleted": 371,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T09:28:48Z",
"last_commit": "2026-10-10T17:48:20Z"
},
{
"login": "LloydNicholson",
"people_entry": false,
"github_name": null,
"prs": 7,
"commits": 2,
"lines_added": 130,
"lines_deleted": 25,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T15:13:40Z",
"last_commit": "2026-10-09T15:23:15Z"
},
{
"login": "lloyd-nich",
"people_entry": false,
"github_name": null,
"prs": 0,
"commits": 5,
"lines_added": 854,
"lines_deleted": 88,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T18:36:08Z",
"last_commit": "2026-10-10T12:17:14Z"
},
{
"login": "dylanmtaylor",
"people_entry": false,
"github_name": null,
"prs": 3,
"commits": 3,
"lines_added": 281,
"lines_deleted": 45,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T21:14:43Z",
"last_commit": "2026-10-10T03:14:29Z"
},
{
"login": "edurbs",
"people_entry": true,
"github_name": "Eduardo Soares",
"prs": 1,
"commits": 1,
"lines_added": 311,
"lines_deleted": 11,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T21:18:57Z",
"last_commit": "2026-10-09T21:18:57Z"
},
{
"login": "nihilist-narwhal",
"people_entry": true,
"github_name": null,
"prs": 19,
"commits": 35,
"lines_added": 2261,
"lines_deleted": 145,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-09T22:14:59Z",
"last_commit": "2026-10-10T10:40:00Z"
},
{
"login": "neko233-com",
"people_entry": false,
"github_name": null,
"prs": 1,
"commits": 1,
"lines_added": 1004,
"lines_deleted": 81,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-10T02:20:59Z",
"last_commit": "2026-10-10T02:20:59Z"
},
{
"login": "agammann",
"people_entry": false,
"github_name": null,
"prs": 1,
"commits": 1,
"lines_added": 34,
"lines_deleted": 2,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-10T05:47:38Z",
"last_commit": "2026-10-10T05:47:38Z"
},
{
"login": "itrycodinganditsbad",
"people_entry": false,
"github_name": null,
"prs": 2,
"commits": 2,
"lines_added": 68,
"lines_deleted": 7,
"binary_added": 0,
"binary_deleted": 0,
"first_commit": "2026-10-10T11:25:38Z",
"last_commit": "2026-10-10T11:28:07Z"
}
],
"models": [
@@ -53,9 +222,18 @@
"company": "Anthropic",
"model": "Claude Opus",
"version": "5.5",
"commits": 23,
"lines_added": 79359,
"lines_deleted": 4032
"commits": 58,
"lines_added": 83111,
"lines_deleted": 4992
},
{
"id": "openai/codex",
"company": "OpenAI",
"model": "Codex",
"version": "",
"commits": 3,
"lines_added": 173,
"lines_deleted": 24
}
]
}
+40
View File
@@ -21,3 +21,43 @@
real_name = "Brandon Thomas"
display_name = "Brandon Thomas"
sync_github_name = false
[people.nihilist-narwhal]
display_name = "nihilist-narwhal"
sync_github_name = false
[people.edurbs]
sync_github_name = true
[people.arcanii]
real_name = "Bryan Mark"
display_name = "Arcanii"
sync_github_name = false
[people.vangel76]
real_name = "Valentin Klein"
sync_github_name = true
[people.MacJedi42]
sync_github_name = true
[people.alexanderalber]
real_name = "Alexander Alber"
[people.webdevtodayjason]
display_name = "Jason Brashear"
sync_github_name = false
[people.Losminek]
sync_github_name = true
[people.GhostMitra]
sync_github_name = true
[people.shrshk]
real_name = "Shirish Veerabattini"
sync_github_name = true
[people.jsymes21-byte]
real_name = "James Symes"
sync_github_name = true
+379 -35
View File
@@ -13,6 +13,10 @@ use gridcraft_model::Workbook;
/// Largest array a reference may expand to.
pub const MAX_CELLS: u64 = 16_000_000;
/// References up to this many cells are read at their full size; larger ones (`A:A`, ranges
/// reserved for data to come such as `$A$2:$A$50000`) stop at the sheet's used range, so that
/// formulas over them stay fast.
const FULL_SIZE_CELLS: u64 = 16_384;
const MAX_DEPTH: usize = 400;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -54,10 +58,24 @@ pub trait Host {
fn random(&mut self) -> f64;
/// Called when a volatile or dynamic-reference function is used.
fn note_volatile(&mut self) {}
/// The spill range of the dynamic array anchored at `anchor` (`None`: it doesn't spill).
fn spill_range(&mut self, sheet: usize, anchor: CellRef) -> Option<RangeRef> {
self.workbook().sheet(sheet)?.spill_ranges.get(&anchor).copied()
}
/// Values of a block, row-major. Hosts can override with a sparse fast path.
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
range.iter().map(|c| self.cell_value(sheet, c)).collect()
}
/// The sheet's used range (`Sheet::used_range`, which walks every stored row). Hosts that
/// keep the workbook unchanged while evaluating can remember it.
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
self.workbook().sheet(sheet).and_then(|s| s.used_range())
}
/// Calls `f` on each stored value of a block, row-major (formula cells evaluated first),
/// until `f` returns false. `false` when this host can't (callers use `range_values`).
fn visit_range(&mut self, _sheet: usize, _range: RangeRef, _f: &mut dyn FnMut(&Value) -> bool) -> bool {
false
}
}
pub struct Evaluator<'h> {
@@ -129,7 +147,10 @@ impl<'h> Evaluator<'h> {
if a.range.is_single() {
return self.host.cell_value(a.sheet, a.range.start);
}
let range = self.trim(a);
// A reference keeps its size, so the array has its shape and its blanks count
// (`=A1:A10`, `SUMPRODUCT(--(A1:A10=""))`).
let cells = u64::from(a.range.height()) * u64::from(a.range.width());
let range = if cells > FULL_SIZE_CELLS { self.trim(a) } else { a.range };
let (h, w) = (range.height() as usize, range.width() as usize);
if (h as u64) * (w as u64) > MAX_CELLS {
return Value::Error(CellError::Num);
@@ -140,9 +161,11 @@ impl<'h> Evaluator<'h> {
/// Trims the bottom/right of an area to the sheet's used range (keeps the top-left so
/// positions stay right).
pub fn trim(&self, a: &Area) -> RangeRef {
let Some(sheet) = self.host.workbook().sheet(a.sheet) else { return a.range };
let used = sheet.used_range();
pub fn trim(&mut self, a: &Area) -> RangeRef {
if self.host.workbook().sheet(a.sheet).is_none() {
return a.range;
}
let used = self.host.used_range(a.sheet);
let (mut r1, mut c1) = (a.range.end.row, a.range.end.col);
match used {
Some(u) => {
@@ -226,6 +249,13 @@ impl<'h> Evaluator<'h> {
let scope = def.scope.unwrap_or(self.sheet);
return match gridcraft_formula::parse(&text) {
Ok(expr) => {
// Relative references in a name are relative to A1: used here, they move by
// this cell's offset from it.
let expr = if gridcraft_formula::adjust::has_relative_refs(&expr) {
gridcraft_formula::adjust::shift_relative_wrapping(expr, self.at.row as i64, self.at.col as i64)
} else {
expr
};
let saved = self.sheet;
// Unqualified references in a name refer to the scope sheet.
self.sheet = scope;
@@ -322,6 +352,22 @@ impl<'h> Evaluator<'h> {
}
fn unary(&mut self, op: UnOp, x: &Expr) -> Ev {
if let UnOp::Trim(mode) = op {
return self.trim_ref(mode, x);
}
if op == UnOp::Spill {
return match self.eval(x) {
Ev::R(areas) => match areas.as_slice() {
[a] if a.range.is_single() => match self.host.spill_range(a.sheet, a.range.start) {
Some(range) => Ev::R(vec![Area { sheet: a.sheet, range }]),
None => err(CellError::Ref),
},
_ => err(CellError::Ref),
},
Ev::V(Value::Error(e)) => err(e),
_ => err(CellError::Ref),
};
}
if op == UnOp::At {
let ev = self.eval(x);
return match ev {
@@ -343,7 +389,7 @@ impl<'h> Evaluator<'h> {
UnOp::Neg => Value::number(-n),
UnOp::Plus => Value::number(n),
UnOp::Percent => Value::number(n / 100.0),
UnOp::At => Value::number(n),
UnOp::At | UnOp::Spill | UnOp::Trim(_) => Value::number(n),
},
op == UnOp::Plus,
))
@@ -523,7 +569,20 @@ impl<'h> Evaluator<'h> {
if args.len() < 2 {
return err(CellError::Value);
}
let i = match self.arg_num(args, 0, 0.0) {
let index = self.value(&args[0]);
if let Value::Array(_) = index {
// An array of indexes picks element by element: `CHOOSE({1,2},A1:A3,B1:B3)`
// is a two-column array. The library CHOOSE lifts over its arguments.
let Some(spec) = gridcraft_functions::lookup(name) else { return err(CellError::Name) };
let mut evaluated = vec![Arg { value: index, from_ref: false }];
for a in &args[1..] {
let value = self.value(a);
evaluated.push(Arg { value, from_ref: false });
}
let mut ctx = FnCtx { ev: self };
return gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V);
}
let i = match index.to_number() {
Ok(n) => n.trunc() as i64,
Err(e) => return err(e),
};
@@ -632,7 +691,9 @@ impl<'h> Evaluator<'h> {
"OFFSET" => self.offset(args),
"INDIRECT" => self.indirect(args),
"INDEX" => self.index(args),
"XLOOKUP" => self.xlookup(args),
"CELL" => self.cell_info(args),
"TRIMRANGE" => self.trimrange(args),
"SUBTOTAL" | "AGGREGATE" => self.subtotal(name, args),
"TEXT" => {
if args.len() != 2 {
@@ -695,9 +756,24 @@ impl<'h> Evaluator<'h> {
if args.len() < spec.min_args || args.len() > spec.max_args {
return err(CellError::Value);
}
if let Some(kind) = Agg::of(spec.name) {
return self.aggregate(kind, args);
}
let mut evaluated = Vec::with_capacity(args.len());
for a in args {
let ev = self.eval(a);
// SUMIF/AVERAGEIF: the size of the criteria range (argument 1), which the sum range takes.
let mut criteria_shape = None;
for (i, a) in args.iter().enumerate() {
let mut ev = self.eval(a);
if resizes_sum_range(name, args.len()) {
if i == 0 {
criteria_shape = ev_shape(&ev);
} else if i == 2
&& let (Some((h, w)), Ev::R(areas)) = (criteria_shape, &ev)
&& let [area] = areas.as_slice()
{
ev = Ev::R(vec![Area { sheet: area.sheet, range: resized_sum_range(area.range, h, w) }]);
}
}
let from_ref = matches!(ev, Ev::R(_));
let value = match ev {
Ev::R(areas) if areas.len() > 1 => {
@@ -719,6 +795,70 @@ impl<'h> Evaluator<'h> {
gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V)
}
/// Performs aggregation operations without copying its ranges: blocks are folded over the stored
/// cells, so no array is built and there is no `MAX_CELLS` limit. Arguments are evaluated and read one
/// after another, as the array path does, so volatile formulas (like `RAND`) see the same order.
/// Only `SUM`, `COUNT` and `AVG` are supported currently.
fn aggregate(&mut self, kind: Agg, args: &[Expr]) -> Ev {
let mut acc = Acc::default();
let mut first_error = None;
for a in args {
let ev = self.eval(a);
let steps = match ev {
Ev::R(areas) => areas.iter().map(|area| self.aggregate_area(kind, area, &mut acc)).collect(),
ev => {
let value = self.deref(ev);
vec![self.aggregate_value(kind, value, false, &mut acc)]
}
};
if first_error.is_none() {
first_error = steps.into_iter().find_map(Result::err);
}
}
first_error.unwrap_or_else(|| Ev::V(acc.finish(kind)))
}
/// Adds one area to `acc`; `Err` is the result the function ends with.
fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> {
if !a.range.is_single() {
let mut error = None;
let walked = self.host.visit_range(a.sheet, a.range, &mut |v| match acc.add_cell(kind, v) {
Ok(()) => true,
Err(e) => {
error = Some(e);
false
}
});
if walked {
return error.map_or(Ok(()), |e| Err(err(e)));
}
}
let value = self.area_value(a);
self.aggregate_value(kind, value, true, acc)
}
/// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules
/// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`).
fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> {
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else {
return Err(err(CellError::Name));
};
let args = [Arg { value, from_ref }];
if kind != Agg::Count {
match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self }) {
Value::Number(n) => acc.sum += n,
other => return Err(Ev::V(other)),
}
}
if kind != Agg::Sum {
match gridcraft_functions::call(count, &args, &mut FnCtx { ev: self }) {
Value::Number(n) => acc.count = acc.count.saturating_add(n as u64),
other => return Err(Ev::V(other)),
}
}
Ok(())
}
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
if args.len() > l.params.len() {
return err(CellError::Value);
@@ -881,7 +1021,7 @@ impl<'h> Evaluator<'h> {
}
/// Whole rows/columns trimmed for ROW()/COLUMN() arrays.
fn trim_lines(&self, a: &Area) -> RangeRef {
fn trim_lines(&mut self, a: &Area) -> RangeRef {
if a.range.is_full_cols() || a.range.is_full_rows() { self.trim(a) } else { a.range }
}
@@ -956,18 +1096,57 @@ impl<'h> Evaluator<'h> {
return err(CellError::Value);
}
let src = self.eval(&args[0]);
let row = match self.arg_num(args, 1, 0.0) {
Ok(n) => n.trunc() as i64,
Err(e) => return err(e),
};
let col = match self.arg_num(args, 2, 0.0) {
Ok(n) => n.trunc() as i64,
Err(e) => return err(e),
let mut arg = |i: usize| match args.get(i) {
None | Some(Expr::Missing) => None,
Some(e) => Some(self.value(e)),
};
let (rows, cols) = (arg(1), arg(2));
let area_n = match self.arg_num(args, 3, 1.0) {
Ok(n) => n.trunc() as i64,
Err(e) => return err(e),
};
let two = args.len() == 2;
let num = |v: &Option<Value>| v.as_ref().map_or(Ok(0.0), |v| v.to_number()).map(|n| n.trunc() as i64);
// Arrays of positions pick a value for each: INDEX(A1:C10,{1;2},{1,3}) is 2×2.
if let (Some(Value::Array(_)), _) | (_, Some(Value::Array(_))) = (&rows, &cols) {
let as_array = |v: &Option<Value>| match v {
Some(Value::Array(a)) => Arc::clone(a),
Some(v) => Arc::new(Array::scalar(v.clone())),
None => Arc::new(Array::scalar(Value::Number(0.0))),
};
let (ra, ca) = (as_array(&rows), as_array(&cols));
let (h, w) = (ra.rows.max(ca.rows), ra.cols.max(ca.cols));
if (h as u64).saturating_mul(w as u64) > MAX_CELLS {
return err(CellError::Num);
}
let mut out = Vec::with_capacity(h * w);
for r in 0..h {
for c in 0..w {
let pos = (num(&Some(ra.get_broadcast(r, c))), num(&Some(ca.get_broadcast(r, c))));
let v = match pos {
(Ok(row), Ok(col)) => {
let one = self.index_one(src.clone(), row, col, area_n, two);
match self.deref(one) {
Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc),
v => v.scalar(),
}
}
(Err(e), _) | (_, Err(e)) => Value::Error(e),
};
out.push(v);
}
}
return Ev::V(Array::new(h, w, out).map(Value::from).unwrap_or(Value::Error(CellError::Value)));
}
let (row, col) = match (num(&rows), num(&cols)) {
(Ok(r), Ok(c)) => (r, c),
(Err(e), _) | (_, Err(e)) => return err(e),
};
self.index_one(src, row, col, area_n, two)
}
/// INDEX for one row and column position (0 = the whole column or row).
fn index_one(&mut self, src: Ev, row: i64, col: i64, area_n: i64, two_args: bool) -> Ev {
if row < 0 || col < 0 {
return err(CellError::Value);
}
@@ -976,7 +1155,7 @@ impl<'h> Evaluator<'h> {
let Some(a) = areas.get((area_n - 1).max(0) as usize).copied() else { return err(CellError::Ref) };
let r = a.range;
// A single row or column with one index picks along it.
let (row, col) = if args.len() == 2 && r.height() == 1 { (1, row) } else { (row, col) };
let (row, col) = if two_args && r.height() == 1 { (1, row) } else { (row, col) };
if row as u64 > r.height() as u64 || col as u64 > r.width() as u64 {
return err(CellError::Ref);
}
@@ -985,7 +1164,7 @@ impl<'h> Evaluator<'h> {
Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) }])
}
Ev::V(Value::Array(arr)) => {
let (row, col) = if args.len() == 2 && arr.rows == 1 { (1, row) } else { (row, col) };
let (row, col) = if two_args && arr.rows == 1 { (1, row) } else { (row, col) };
if row as usize > arr.rows || col as usize > arr.cols {
return err(CellError::Ref);
}
@@ -1008,6 +1187,66 @@ impl<'h> Evaluator<'h> {
}
}
/// XLOOKUP whose result range is a reference returns a reference, as in Excel, so that it can
/// end a range (`SUM(XLOOKUP(a,…):XLOOKUP(b,…))`) or feed CELL. Everything else (arrays of
/// lookup values, array arguments, errors) goes to the library function.
fn xlookup(&mut self, args: &[Expr]) -> Ev {
if (3..=6).contains(&args.len())
&& let (Ev::R(look), Ev::R(ret)) = (self.eval(&args[1]), self.eval(&args[2]))
&& let ([l], [r]) = (look.as_slice(), ret.as_slice())
&& let Some(spec) = gridcraft_functions::lookup("XMATCH")
{
let key = self.value(&args[0]);
let (l, r) = (*l, *r);
let vertical = l.range.width() == 1 && l.range.height() > 1;
let horizontal = l.range.height() == 1 && l.range.width() > 1;
let same_len = if vertical { r.range.height() == l.range.height() } else { r.range.width() == l.range.width() };
if !matches!(key, Value::Array(_)) && (vertical || horizontal) && same_len {
let mut xargs = vec![Arg { value: key, from_ref: false }, Arg { value: self.area_value(&l), from_ref: true }];
// An empty match_mode before a given search_mode is the default (0), not the end.
let given = |i: usize| args.get(i).is_some_and(|e| !matches!(e, Expr::Missing));
let last = if given(5) {
5
} else if given(4) {
4
} else {
3
};
for i in 4..=last {
match args.get(i) {
Some(Expr::Missing) | None => xargs.push(Arg { value: Value::Number(0.0), from_ref: false }),
Some(e) => {
let value = self.value(e);
xargs.push(Arg { value, from_ref: false });
}
}
}
let mut ctx = FnCtx { ev: self };
return match gridcraft_functions::call(spec, &xargs, &mut ctx) {
Value::Number(p) if p >= 1.0 => {
let k = p as u32 - 1;
let range = if vertical {
RangeRef::new(
CellRef::new(r.range.start.row + k, r.range.start.col),
CellRef::new(r.range.start.row + k, r.range.end.col),
)
} else {
RangeRef::new(
CellRef::new(r.range.start.row, r.range.start.col + k),
CellRef::new(r.range.end.row, r.range.start.col + k),
)
};
Ev::R(vec![Area { sheet: r.sheet, range }])
}
Value::Error(CellError::NA) if args.get(3).is_some_and(|e| !matches!(e, Expr::Missing)) => self.eval(&args[3]),
Value::Error(e) => err(e),
_ => err(CellError::Value),
};
}
}
self.builtin("XLOOKUP", args)
}
fn cell_info(&mut self, args: &[Expr]) -> Ev {
let kind = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) {
Some(Ok(t)) => t.to_ascii_lowercase(),
@@ -1072,6 +1311,9 @@ impl<'h> Evaluator<'h> {
return err(CellError::Value);
}
let skip_hidden = matches!(options, 1 | 3 | 5 | 7);
// SUBTOTAL leaves out rows a filter hides whatever the function number (Microsoft's
// SUBTOTAL documentation); 101-111 also leave out rows hidden by hand.
let skip_filtered = name == "SUBTOTAL";
let skip_errors = matches!(options, 2 | 3 | 6 | 7);
let skip_nested = options <= 3;
let mut values = Vec::new();
@@ -1089,7 +1331,8 @@ impl<'h> Evaluator<'h> {
let (hidden, nested) = {
let wb = self.host.workbook();
let s = wb.sheet(a.sheet);
let hidden = skip_hidden && s.is_some_and(|s| s.is_row_hidden(c.row));
let hidden =
s.is_some_and(|s| if skip_hidden { s.is_row_hidden(c.row) } else { skip_filtered && s.is_row_filtered(c.row) });
let nested = skip_nested
&& s.and_then(|s| s.cell(c)).and_then(|cell| cell.formula.as_ref()).is_some_and(|f| {
let u = f.text.to_ascii_uppercase();
@@ -1196,6 +1439,57 @@ pub fn r1c1_to_a1(s: &str, at: CellRef) -> Option<String> {
Some(format!("{sheet}{out}"))
}
/// The aggregates that can fold a reference without building an array.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Agg {
Sum,
Count,
Average,
}
impl Agg {
fn of(name: &str) -> Option<Agg> {
match name {
"SUM" => Some(Agg::Sum),
"COUNT" => Some(Agg::Count),
"AVERAGE" => Some(Agg::Average),
_ => None,
}
}
}
/// What a folded aggregate carries from one value to the next.
#[derive(Default)]
struct Acc {
sum: f64,
count: u64,
}
impl Acc {
/// Takes a value found inside a reference: only numbers count. `Err` is an error value that
/// ends `SUM` and `AVERAGE`; `COUNT` skips errors.
fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> {
match v {
Value::Number(n) => {
self.sum += n;
self.count = self.count.saturating_add(1);
Ok(())
}
Value::Error(e) if kind != Agg::Count => Err(*e),
_ => Ok(()),
}
}
fn finish(&self, kind: Agg) -> Value {
match kind {
Agg::Sum => Value::number(self.sum),
Agg::Count => Value::number(self.count as f64),
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
Agg::Average => Value::number(self.sum / self.count as f64),
}
}
}
// ---------------------------------------------------------------- operators
fn map_unary(v: &Value, f: &dyn Fn(f64) -> Value, plus: bool) -> Value {
@@ -1306,30 +1600,64 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value) -> Value {
}
}
/// SUMIF and AVERAGEIF with a sum range: Excel sizes the sum range like the criteria range.
fn resizes_sum_range(name: &str, args: usize) -> bool {
args == 3 && matches!(name, "SUMIF" | "AVERAGEIF")
}
/// Height and width of a single-area reference or an array argument.
fn ev_shape(ev: &Ev) -> Option<(u32, u32)> {
match ev {
Ev::R(areas) => match areas.as_slice() {
[a] => Some((a.range.height(), a.range.width())),
_ => None,
},
Ev::V(Value::Array(a)) => Some((u32::try_from(a.rows).unwrap_or(u32::MAX), u32::try_from(a.cols).unwrap_or(u32::MAX))),
Ev::V(_) => Some((1, 1)),
Ev::L(_) => None,
}
}
/// The range SUMIF/AVERAGEIF add up: from the sum range's top-left cell, as many rows and columns
/// as the criteria range (`height` × `width`), cut off at the sheet's edge.
pub fn resized_sum_range(sum: RangeRef, height: u32, width: u32) -> RangeRef {
let row = sum.start.row.saturating_add(height.saturating_sub(1)).min(MAX_ROWS - 1);
let col = sum.start.col.saturating_add(width.saturating_sub(1)).min(MAX_COLS - 1);
RangeRef::new(sum.start, CellRef::new(row, col))
}
/// Collects the static references of an expression with their sheets resolved; `dynamic` is
/// set when the formula uses INDIRECT/OFFSET/names/tables whose targets can change.
pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec<Area>, bool) {
let mut out = Vec::new();
let mut dynamic = false;
e.walk(&mut |x| match x {
Expr::Ref(r) => {
let range = r.range();
match &r.sheet {
SheetSel::Current => out.push(Area { sheet, range }),
SheetSel::Named(n) => {
if let Some(i) = wb.sheet_index(n) {
out.push(Area { sheet: i, range });
}
}
SheetSel::Span(a, b) => {
if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) {
for s in i.min(j)..=i.max(j) {
out.push(Area { sheet: s, range });
}
}
let push = |out: &mut Vec<Area>, r: &Reference, range: RangeRef| match &r.sheet {
SheetSel::Current => out.push(Area { sheet, range }),
SheetSel::Named(n) => {
if let Some(i) = wb.sheet_index(n) {
out.push(Area { sheet: i, range });
}
}
SheetSel::Span(a, b) => {
if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) {
for s in i.min(j)..=i.max(j) {
out.push(Area { sheet: s, range });
}
}
}
};
e.walk(&mut |x| match x {
Expr::Ref(r) => push(&mut out, r, r.range()),
// The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when
// the criteria range's size isn't known statically, recalculate the formula every time.
Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) {
(Some(Expr::Ref(c)), Some(Expr::Ref(s))) => {
let (crit, sum) = (c.range(), s.range());
push(&mut out, s, resized_sum_range(sum, crit.height(), crit.width()));
}
(_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {}
_ => dynamic = true,
},
Expr::Call(n, _)
if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") =>
{
@@ -1337,6 +1665,20 @@ pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec<Area>, bool) {
}
Expr::Name(_) | Expr::Struct(_) => dynamic = true,
Expr::Call(n, _) if gridcraft_functions::lookup(n).is_none() && !is_special(n) => dynamic = true,
// A range ending in a function's result (`A1:INDEX(B1:B9,n)`) covers the cells between
// the references inside it, not only those references.
Expr::Binary(BinOp::Range, a, b) if !matches!((&**a, &**b), (Expr::Ref(_), Expr::Ref(_))) => {
let mut inner = precedents(wb, sheet, a).0;
inner.extend(precedents(wb, sheet, b).0);
let mut boxes: Vec<Area> = Vec::new();
for area in inner {
match boxes.iter_mut().find(|x| x.sheet == area.sheet) {
Some(x) => x.range = x.range.union(&area.range),
None => boxes.push(area),
}
}
out.extend(boxes);
}
_ => {}
});
(out, dynamic)
@@ -1364,6 +1706,7 @@ fn is_special(n: &str) -> bool {
| "INDIRECT"
| "INDEX"
| "CELL"
| "TRIMRANGE"
| "SUBTOTAL"
| "AGGREGATE"
| "TEXT"
@@ -1401,6 +1744,7 @@ pub const SPECIAL_FUNCTIONS: &[&str] = &[
"INDIRECT",
"INDEX",
"CELL",
"TRIMRANGE",
"SUBTOTAL",
"AGGREGATE",
"TEXT",
+1
View File
@@ -5,6 +5,7 @@
pub mod eval;
pub mod recalc;
mod trimrange;
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
pub use recalc::{Calc, Key, evaluate, now_serial};
+827 -83
View File
File diff suppressed because it is too large Load Diff
+753
View File
@@ -33,6 +33,40 @@ impl T {
}
}
#[test]
fn spill_range_operator() {
let mut t = T::new();
t.set("A1", "3");
t.set("B1", "=SEQUENCE(A1)");
t.set("C1", "=SUM(B1#)");
t.set("C2", "=ROWS(B1#)");
assert_eq!((t.num("C1"), t.num("C2")), (6.0, 3.0));
// Growing and shrinking the spill recalculates its users.
t.set("A1", "5");
assert_eq!((t.num("C1"), t.num("C2")), (15.0, 5.0));
t.set("A1", "2");
assert_eq!((t.num("C1"), t.num("C2")), (3.0, 2.0));
// A blocked spill, or a cell that doesn't spill, gives #REF!.
t.set("B2", "x");
assert_eq!(t.get("C1"), Value::Error(CellError::Ref));
t.set("B2", "");
assert_eq!(t.num("C1"), 3.0);
t.set("D1", "=SUM(A1#)");
assert_eq!(t.get("D1"), Value::Error(CellError::Ref));
// Through a defined name.
t.wb.names.push(gridcraft_model::DefinedName {
name: "Seq".into(),
scope: None,
formula: "Sheet1!$B$1#".into(),
comment: String::new(),
hidden: false,
});
t.set("E1", "=SUM(Seq)*10");
assert_eq!(t.num("E1"), 30.0);
t.set("A1", "4");
assert_eq!(t.num("E1"), 100.0);
}
#[test]
fn arithmetic_and_dependencies() {
let mut t = T::new();
@@ -60,6 +94,39 @@ fn chains_out_of_order() {
assert_eq!(t.num("A5"), 5.0);
}
#[test]
fn xlookup_returns_a_reference() {
let mut t = T::new();
for (i, (k, v)) in [("a", 1), ("b", 2), ("c", 3), ("d", 4)].iter().enumerate() {
t.set(&format!("A{}", i + 1), k);
t.set(&format!("B{}", i + 1), &v.to_string());
}
t.set("D1", "=SUM(XLOOKUP(\"b\",A1:A4,B1:B4):XLOOKUP(\"d\",A1:A4,B1:B4))");
assert_eq!(t.num("D1"), 9.0);
t.set("D2", "=SUM(B1:XLOOKUP(\"c\",A1:A4,B1:B4))");
assert_eq!(t.num("D2"), 6.0);
t.set("D3", "=CELL(\"address\",XLOOKUP(\"c\",A1:A4,B1:B4))");
assert_eq!(t.get("D3"), Value::from("$B$3"));
// Not found: if_not_found, else #N/A, as before.
t.set("D4", "=XLOOKUP(\"z\",A1:A4,B1:B4,\"none\")");
assert_eq!(t.get("D4"), Value::from("none"));
t.set("D5", "=XLOOKUP(\"z\",A1:A4,B1:B4)");
assert_eq!(t.get("D5"), Value::Error(CellError::NA));
// A match on an empty cell is a blank reference: ISBLANK is TRUE and & adds nothing (#374).
t.set("A5", "e");
t.set("D6", "=ISBLANK(XLOOKUP(\"e\",A1:A5,B1:B5))");
assert_eq!(t.get("D6"), Value::Bool(true));
t.set("D7", "=\"x\"&XLOOKUP(\"e\",A1:A5,B1:B5)&\"y\"");
assert_eq!(t.get("D7"), Value::from("xy"));
// An empty match_mode keeps the search_mode after it: search last to first.
t.set("A6", "b");
t.set("B6", "20");
t.set("D8", "=XLOOKUP(\"b\",A1:A6,B1:B6,,,-1)");
assert_eq!(t.num("D8"), 20.0);
t.set("D9", "=XLOOKUP(\"b\",A1:A6,B1:B6)");
assert_eq!(t.num("D9"), 2.0);
}
#[test]
fn long_chain() {
let mut t = T::new();
@@ -72,6 +139,24 @@ fn long_chain() {
assert_eq!(t.num("A3000"), 3009.0);
}
#[test]
fn index_with_arrays_of_positions() {
let mut t = T::new();
for (i, row) in [[1, 2, 3], [4, 5, 6], [7, 8, 9]].iter().enumerate() {
for (j, v) in row.iter().enumerate() {
t.set(&format!("{}{}", ["A", "B", "C"][j], i + 1), &v.to_string());
}
}
t.set("E1", "=INDEX(A1:C3,{1;3},{1,3})");
assert_eq!([t.num("E1"), t.num("F1"), t.num("E2"), t.num("F2")], [1.0, 3.0, 7.0, 9.0]);
t.set("E4", "=SUM(INDEX(A1:C3,{1,2,3},2))");
assert_eq!(t.num("E4"), 15.0);
t.set("E5", "=INDEX({10,20,30},{3,1})");
assert_eq!([t.num("E5"), t.num("F5")], [30.0, 10.0]);
t.set("E7", "=INDEX(A1:C3,2,3)");
assert_eq!(t.num("E7"), 6.0);
}
#[test]
fn errors_and_cycles() {
let mut t = T::new();
@@ -86,6 +171,105 @@ fn errors_and_cycles() {
assert_eq!(t.get("C2"), Value::Error(CellError::Name));
}
impl T {
fn iterative(max_iterations: u32, max_change: f64) -> T {
let mut t = T::new();
t.wb.calc.iterative = true;
t.wb.calc.set_max_iterations(max_iterations);
t.wb.calc.set_max_change(max_change);
t
}
}
#[test]
fn iterative_calculation_stops_at_maximum_iterations() {
// A1 =A1+1 never settles: every recalculation adds Maximum Iterations.
let mut t = T::iterative(100, 0.001);
t.set("A1", "=A1+1");
assert_eq!(t.num("A1"), 100.0);
assert!(t.calc.circular.is_empty());
// An edit outside the loop doesn't recalculate it.
t.set("B1", "7");
assert_eq!(t.num("A1"), 100.0);
// Each recalculation starts from the value the cell shows.
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("A1"), 200.0);
t.wb.calc.set_max_iterations(5);
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("A1"), 205.0);
// Through a range that holds the formula itself.
t.set("C1", "1");
t.set("C2", "2");
t.set("C3", "=SUM(C1:C3)");
assert_eq!(t.num("C3"), 15.0);
// Excel's largest Maximum Iterations.
let mut t = T::iterative(32767, 0.001);
t.set("A1", "=A1+1");
assert_eq!(t.num("A1"), 32767.0);
}
#[test]
fn iterative_calculation_converges_within_maximum_change() {
let mut t = T::iterative(100, 0.001);
t.set("A1", "=(A2+10)/2");
t.set("A2", "=A1");
assert!((t.num("A1") - 10.0).abs() < 0.002, "{}", t.num("A1"));
assert!((t.num("A2") - 10.0).abs() < 0.002, "{}", t.num("A2"));
assert!(t.calc.circular.is_empty());
// A loop fed by a constant, and a formula that reads the loop, follow a change.
t.set("D1", "10");
t.set("A1", "=(A2+D1)/2");
t.set("E1", "=A1*2");
t.set("D1", "30");
assert!((t.num("A1") - 30.0).abs() < 0.002, "{}", t.num("A1"));
assert!((t.num("E1") - 60.0).abs() < 0.004, "{}", t.num("E1"));
// Already settled: recalculating changes it by less than Maximum Change.
let a1 = t.num("A1");
t.calc.recalc_all(&mut t.wb);
assert!((t.num("A1") - a1).abs() < 0.001);
}
#[test]
fn iterative_calculation_stops_once_changes_are_below_maximum_change() {
// A1 halves its distance to 10 each pass, from 5: 7.5, 8.75, 9.375, 9.6875, and A2 trails
// one pass behind. Maximum Change 1 stops once neither moved by 1 or more.
let mut t = T::iterative(100, 1.0);
t.set("A1", "=(A2+10)/2");
assert_eq!(t.num("A1"), 5.0);
t.set("A2", "=A1");
assert_eq!((t.num("A1"), t.num("A2")), (9.6875, 9.375));
// Maximum Iterations 2 stops first.
let mut t = T::iterative(2, 1.0);
t.set("A1", "=(A2+10)/2");
t.set("A2", "=A1");
assert_eq!((t.num("A1"), t.num("A2")), (8.75, 7.5));
}
#[test]
fn iterative_calculation_of_text_and_errors() {
let mut t = T::iterative(100, 0.001);
t.set("A1", "=IF(ISTEXT(A1),A1&\"\",\"go\")");
assert_eq!(t.get("A1"), Value::from("go"));
t.set("B1", "=B1+1/0");
assert_eq!(t.get("B1"), Value::Error(CellError::Div0));
}
#[test]
fn circular_references_without_iterative_calculation() {
let mut t = T::new();
t.set("A1", "=A1+1");
assert_eq!(t.get("A1"), Value::Error(CellError::Circ));
assert_eq!(t.calc.circular, vec![(0, c("A1"))]);
// Switched on, the loop is calculated from 0 rather than from the error.
t.wb.calc.iterative = true;
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("A1"), 100.0);
assert!(t.calc.circular.is_empty());
t.wb.calc.iterative = false;
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.get("A1"), Value::Error(CellError::Circ));
}
#[test]
fn operators() {
let mut t = T::new();
@@ -105,6 +289,73 @@ fn operators() {
assert_eq!(t.num("A7"), 0.0);
}
#[test]
fn blocked_spill_reads_as_spill_error() {
// Calculated in the same pass, a formula over a blocked spill read the array that couldn't
// spill.
let mut t = T::new();
let s = t.wb.sheet_mut(0).unwrap();
for a in ["A1", "B1", "C1", "A2", "C2", "A3", "B3", "C3"] {
s.cells.set(c(a), Cell::value(Value::Number(1.0)));
}
s.cells.set(c("B2"), Cell::formula(Formula::new("=SEQUENCE(2,2,9)")));
s.cells.set(c("E1"), Cell::formula(Formula::new("=SUM(A1:C3)")));
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.get("B2"), Value::Error(CellError::Spill));
assert_eq!(t.get("E1"), Value::Error(CellError::Spill));
assert_eq!(t.num("C3"), 1.0);
}
#[test]
fn blocked_spill_read_through_offset() {
// The reader's reference is only known while evaluating, so it isn't in the dependency graph.
let mut t = T::new();
t.set("E4", "5");
t.set("E8", "=SUM(OFFSET(E2,0,0,2,2))");
t.set("E3", "=SEQUENCE(2,2,3)");
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.get("E3"), Value::Error(CellError::Spill));
assert_eq!(t.get("E8"), Value::Error(CellError::Spill));
}
#[test]
fn spill_into_the_old_area_of_a_blocked_neighbour() {
// C7's array becomes blocked by C8, whose array then takes over C7's old area.
let mut t = T::new();
t.set("C7", "=SEQUENCE(2,2)");
t.set("C8", "=SEQUENCE(2,2)");
assert_eq!(t.get("C7"), Value::Error(CellError::Spill));
assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]);
}
#[test]
fn arrays_do_not_spill_in_tables() {
// Excel: spilled array formulas aren't supported in tables.
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(gridcraft_model::Table {
id: 1,
name: "Table1".into(),
range: gridcraft_core::RangeRef::parse("B3:C6").unwrap(),
header_row: true,
totals_row: false,
columns: vec![],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: false,
filter: vec![],
});
t.set("C4", "=SEQUENCE(2)");
t.set("E1", "=SEQUENCE(4)");
t.set("H1", "=SUM(C4:C5)");
assert_eq!(t.get("C4"), Value::Error(CellError::Spill));
assert_eq!(t.get("C5"), Value::Empty);
assert_eq!(t.get("H1"), Value::Error(CellError::Spill));
assert_eq!(t.num("E4"), 4.0);
}
#[test]
fn ifs_and_lazy() {
let mut t = T::new();
@@ -119,6 +370,25 @@ fn ifs_and_lazy() {
assert_eq!(t.get("B4"), Value::from("five"));
}
#[test]
fn choose_with_an_array_index() {
let mut t = T::new();
for (i, (k, v)) in [(1, 10), (2, 20), (3, 30)].iter().enumerate() {
t.set(&format!("A{}", i + 1), &k.to_string());
t.set(&format!("B{}", i + 1), &v.to_string());
}
t.set("D1", "=CHOOSE({1,2},\"a\",\"b\")");
assert_eq!(t.get("D1"), Value::from("a"));
assert_eq!(t.get("E1"), Value::from("b"));
// The usual "look left" idiom: a two-column array from two ranges.
t.set("D3", "=VLOOKUP(20,CHOOSE({1,2},B1:B3,A1:A3),2,FALSE)");
assert_eq!(t.num("D3"), 2.0);
t.set("D4", "=SUM(CHOOSE({1,2},A1:A3,B1:B3))");
assert_eq!(t.num("D4"), 66.0);
t.set("D5", "=CHOOSE(2,A1:A3,B1:B3)");
assert_eq!(t.num("D7"), 30.0);
}
#[test]
fn references_functions() {
let mut t = T::new();
@@ -142,6 +412,32 @@ fn references_functions() {
assert_eq!(t.num("B6"), 105.0);
}
#[test]
fn relative_names() {
let mut t = T::new();
// As files store them: relative to A1. `Left` is the cell to the left, `Above3` the three
// cells above, `Mixed` column A of the same row.
for (name, formula) in [("Left", "Sheet1!XFD1"), ("Above3", "Sheet1!A1048574:A1048576"), ("Mixed", "Sheet1!$A1")] {
t.wb.names.push(gridcraft_model::DefinedName {
name: name.into(),
scope: None,
formula: formula.into(),
comment: String::new(),
hidden: false,
});
}
t.calc.rebuild(&t.wb);
for r in 1..=5 {
t.set(&format!("A{r}"), &(r * 10).to_string());
}
t.set("B2", "=Left");
assert_eq!(t.num("B2"), 20.0);
t.set("B4", "=Left+Mixed");
assert_eq!(t.num("B4"), 80.0);
t.set("A6", "=SUM(Above3)");
assert_eq!(t.num("A6"), 120.0);
}
#[test]
fn spills() {
let mut t = T::new();
@@ -158,6 +454,40 @@ fn spills() {
assert_eq!(t.num("D2"), 40.0);
}
#[test]
fn references_keep_their_size_past_the_used_range() {
let mut t = T::new();
t.set("A1", "5");
t.set("A2", "6");
t.set("C1", "=ROWS(A1:A10*1)");
t.set("C2", "=SUMPRODUCT(--(A1:A10=\"\"))");
t.set("C3", "=COUNTBLANK(A1:A10)");
t.set("C4", "=COUNTIF(A1:A10,\"\")");
t.set("C5", "=COLUMNS(TRANSPOSE(A1:A10))");
for (at, want) in [("C1", 10.0), ("C2", 8.0), ("C3", 8.0), ("C4", 8.0), ("C5", 10.0)] {
assert_eq!(t.num(at), want, "{at}");
}
// Whole columns are still read up to the used range.
t.set("D1", "=ROWS(FILTER(A:A,A:A<>\"\"))");
assert_eq!(t.num("D1"), 2.0);
}
#[test]
fn spilled_blank_cells_show_zero() {
let mut t = T::new();
t.set("A1", "5");
t.set("A3", "7");
t.set("C1", "=A1:A4");
assert_eq!(t.get("C2"), Value::Number(0.0));
assert_eq!(t.get("C4"), Value::Number(0.0));
t.set("D1", "=COUNT(C1:C4)");
assert_eq!(t.num("D1"), 4.0);
t.set("E1", "=A2:A3");
assert_eq!(t.get("E1"), Value::Number(0.0));
t.set("F1", "=SORT(A1:A3)");
assert_eq!(t.get("F3"), Value::Number(0.0));
}
#[test]
fn let_lambda() {
let mut t = T::new();
@@ -185,6 +515,33 @@ fn names_and_sheets() {
assert_eq!(t.num("A1"), 5.0);
}
#[test]
fn legacy_array_formulas_fill_their_range() {
let mut t = T::new();
t.set("A1", "1");
t.set("A2", "2");
let cse = |t: &mut T, at: &str, formula: &str, range: &str| {
let mut f = Formula::new(formula);
f.array = gridcraft_core::RangeRef::parse(range);
t.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::formula(f));
t.calc.cells_changed(&mut t.wb, &[(0, c(at))]);
};
// Past the result: #N/A. A single column repeats across the range.
cse(&mut t, "C1", "=A1:A2*2", "C1:D3");
cse(&mut t, "F1", "=A1:A2*2", "F1");
cse(&mut t, "G1", "=5", "G1:G2");
assert_eq!(t.num("C2"), 4.0);
assert_eq!(t.num("D2"), 4.0);
assert_eq!(t.get("C3"), Value::Error(CellError::NA));
// A smaller range shows only part of the result and never spills.
assert_eq!(t.num("F1"), 2.0);
assert_eq!(t.get("F2"), Value::Empty);
assert_eq!(t.num("G2"), 5.0);
// A range too large to fill is an error, not an allocation of every cell.
cse(&mut t, "H1", "=1", "H1:XFD1048576");
assert_eq!(t.get("H1"), Value::Error(CellError::Num));
}
#[test]
fn text_function() {
let mut t = T::new();
@@ -205,6 +562,52 @@ fn subtotal_skips_hidden() {
assert_eq!(t.num("B2"), 6.0);
}
/// SUBTOTAL leaves out rows a filter hides for every function number, while 1-11 keep rows
/// hidden by hand (as in ConditionalFormattingSamples.xlsx, where `SUBTOTAL(9,Table69[Sales])`
/// under a filtered table adds only the visible rows).
#[test]
fn subtotal_skips_filtered_rows() {
use gridcraft_model::{AutoFilter, FilterCriterion, LineInfo};
let mut t = T::new();
for (i, v) in [1, 2, 4, 8, 16, 32].iter().enumerate() {
t.set(&format!("A{}", i + 2), &v.to_string());
t.set(&format!("C{}", i + 2), &v.to_string());
}
let crit = || vec![(0, FilterCriterion::Custom { a: (">".into(), "1".into()), b: None, and: false })];
let sh = t.wb.sheet_mut(0).unwrap();
sh.tables.push(gridcraft_model::Table {
id: 1,
name: "Sales".into(),
range: gridcraft_core::RangeRef::parse("A1:A7").unwrap(),
header_row: true,
totals_row: false,
columns: vec![gridcraft_model::TableColumn { name: "Amount".into(), totals: Default::default(), totals_label: None, formula: None }],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: true,
filter: crit(),
});
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
for row in [2, 4, 8] {
sh.rows.insert(row, LineInfo { hidden: true, ..Default::default() });
}
t.set("A9", "64");
t.set("E1", "=SUBTOTAL(9,Sales[Amount])");
t.set("E2", "=SUBTOTAL(109,Sales[Amount])");
t.set("E3", "=SUBTOTAL(9,C2:C7)");
t.set("E4", "=SUBTOTAL(9,A2:A9)");
t.set("E5", "=SUBTOTAL(109,A2:A9)");
t.set("E6", "=SUBTOTAL(2,A2:A7)");
t.set("E7", "=AGGREGATE(9,4,A2:A7)");
for (at, want) in [("E1", 53.0), ("E2", 53.0), ("E3", 53.0), ("E4", 117.0), ("E5", 53.0), ("E6", 4.0), ("E7", 63.0)] {
assert_eq!(t.num(at), want, "{at}");
}
}
#[test]
fn recalc_all_after_load() {
let mut t = T::new();
@@ -215,3 +618,353 @@ fn recalc_all_after_load() {
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("A3"), 12.0);
}
#[test]
fn sumif_sum_range_takes_the_criteria_size() {
// Excel adds up the range that starts at sum_range's top-left cell with the criteria range's
// height and width, whatever size sum_range has.
let mut t = T::new();
for (r, (k, v)) in [("a", 1), ("b", 2), ("a", 3)].iter().enumerate() {
t.set(&format!("A{}", r + 1), k);
t.set(&format!("B{}", r + 1), &v.to_string());
}
t.set("D1", "=SUMIF(A1:A3,\"a\",B1)");
assert_eq!(t.num("D1"), 4.0);
t.set("D2", "=AVERAGEIF(A1:A3,\"a\",B1)");
assert_eq!(t.num("D2"), 2.0);
t.set("D3", "=SUMIF(A1:A3,\"a\",B1:B2)");
assert_eq!(t.num("D3"), 4.0);
t.set("D4", "=SUMIF(A1:A3,\"a\",B1:F1)");
assert_eq!(t.num("D4"), 4.0);
t.set("D5", "=SUMIF(A1:A3,\"a\",B1:B99)");
assert_eq!(t.num("D5"), 4.0);
t.set("D6", "=SUMIF(A:A,\"a\",B1)");
assert_eq!(t.num("D6"), 4.0);
t.set("D7", "=SUMIF(A1:A3,\"a\",$B$2)");
assert_eq!(t.num("D7"), 2.0); // B2:B4: rows 1 and 3 match → B2 + B4 (empty)
t.set("D8", "=SUMIF(A1:A3,\"a\")");
assert_eq!(t.num("D8"), 0.0);
// A horizontal criteria range resizes across.
t.set("H1", "1");
t.set("I1", "0");
t.set("J1", "1");
t.set("H2", "10");
t.set("I2", "20");
t.set("J2", "30");
t.set("D9", "=SUMIF(H1:J1,1,H2)");
assert_eq!(t.num("D9"), 40.0);
// The resized cells are precedents: editing one recalculates.
t.set("B3", "5");
assert_eq!(t.num("D1"), 6.0);
assert_eq!(t.num("D2"), 3.0);
assert_eq!(t.num("D3"), 6.0);
assert_eq!(t.num("D4"), 6.0);
assert_eq!(t.num("D6"), 6.0);
// SUMIFS and AVERAGEIFS don't resize: different sizes are #VALUE!.
t.set("D11", "=SUMIFS(B1,A1:A3,\"a\")");
assert_eq!(t.get("D11"), Value::Error(CellError::Value));
t.set("D12", "=AVERAGEIFS(B1:B2,A1:A3,\"a\")");
assert_eq!(t.get("D12"), Value::Error(CellError::Value));
t.set("D13", "=SUMIFS(B1:B3,A1:A3,\"a\")");
assert_eq!(t.num("D13"), 6.0);
}
#[test]
fn sumif_resized_sum_range_stops_at_the_sheet_edge() {
let mut t = T::new();
t.set("A1", "a");
t.set("A2", "a");
t.set("B1048575", "5");
t.set("B1048576", "7");
t.set("C1", "=SUMIF(A1:A2,\"a\",B1048576)");
assert_eq!(t.num("C1"), 7.0);
t.set("C2", "=SUMIF(A1:A2,\"a\",B1048575)");
assert_eq!(t.num("C2"), 12.0);
t.set("C3", "=SUMIF(A1:B1,\"a\",XFD1)");
assert_eq!(t.num("C3"), 0.0);
}
#[test]
fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() {
let mut t = T::new();
t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Data")));
t.wb.names.push(gridcraft_model::DefinedName {
name: "Amounts".into(),
scope: None,
formula: "Data!$B$1".into(),
comment: String::new(),
hidden: false,
});
for (r, k) in ["a", "b", "a"].iter().enumerate() {
t.set(&format!("A{}", r + 1), k);
t.wb.sheet_mut(1).unwrap().set_value(CellRef::new(r as u32, 1), Value::Number((r + 1) as f64));
}
t.calc.rebuild(&t.wb);
t.set("C1", "=SUMIF(A1:A3,\"a\",Data!B1)");
assert_eq!(t.num("C1"), 4.0);
t.set("C2", "=AVERAGEIF(A1:A3,\"a\",Amounts)");
assert_eq!(t.num("C2"), 2.0);
t.wb.sheet_mut(1).unwrap().set_value(c("B3"), Value::Number(9.0));
t.calc.cells_changed(&mut t.wb, &[(1, c("B3"))]);
assert_eq!(t.num("C1"), 10.0);
assert_eq!(t.num("C2"), 5.0);
}
#[test]
fn trimrange() {
let mut t = T::new();
t.set("C3", "1");
t.set("D5", "2");
let cases = [
("J1", "=ROWS(TRIMRANGE(A1:F10))", 3.0),
("J2", "=COLUMNS(TRIMRANGE(A1:F10))", 2.0),
("J3", "=ROWS(TRIMRANGE(A1:F10,2))", 5.0),
("J4", "=ROWS(TRIMRANGE(A1:F10,1,0))", 8.0),
("J5", "=COLUMNS(TRIMRANGE(A1:F10,1,0))", 6.0),
("J6", "=ROWS(TRIMRANGE(A1:F10,0,0))", 10.0),
("J7", "=SUM(TRIMRANGE(C:C))", 1.0),
("J8", "=ROWS(TRIMRANGE(C:C))", 1.0),
("J9", "=ROWS(TRIMRANGE(C:C,2))", 3.0),
("J10", "=MIN(ROW(TRIMRANGE(A1:F10)))", 3.0),
("J11", "=COLUMNS(TRIMRANGE({1,2;3,4}))", 2.0),
];
for (at, f, _) in cases {
t.set(at, f);
}
for (at, f, want) in cases {
assert_eq!(t.num(at), want, "{f}");
}
// The result spills as the trimmed block and follows edits.
t.set("L1", "=TRIMRANGE(A1:F10)");
assert_eq!((t.num("L1"), t.num("M3")), (1.0, 2.0));
t.set("E6", "3");
assert_eq!((t.num("J1"), t.num("J2")), (4.0, 3.0));
// Errors: a bad trim code, nothing but blanks, several areas.
t.set("K1", "=TRIMRANGE(A1:F10,4)");
assert_eq!(t.get("K1"), Value::Error(CellError::Value));
t.set("K2", "=TRIMRANGE(Q1:Q9)");
assert_eq!(t.get("K2"), Value::Error(CellError::Calc));
t.set("K3", "=TRIMRANGE((A1:B2,C3:D4))");
assert_eq!(t.get("K3"), Value::Error(CellError::Value));
}
/// `formula` in AB1 over a small mixed sheet. The ranges in the cases below are cut from it:
///
/// ```text
/// A B C E
/// 1 1.5 10 =A1*4 (C1 is a formula cell inside the ranges)
/// 2 2 TRUE #DIV/0! (E2 only when `error` is set)
/// 3 text 3
/// 4 -0.25
/// ```
fn aggregate_of(error: bool, formula: &str) -> Value {
let mut t = T::new();
for (at, v) in [("A1", "1.5"), ("A2", "2"), ("A3", "skipped"), ("A4", "-0.25"), ("B1", "10"), ("B2", "TRUE"), ("B3", "3"), ("C1", "=A1*4")] {
t.set(at, v);
}
if error {
t.set("E2", "#DIV/0!");
}
// AB1 is outside every range used, so the formula can't read itself.
t.set("AB1", formula);
t.get("AB1")
}
#[test]
fn sum_count_average_over_ranges() {
// Text, booleans, blanks and a formula cell inside ranges; direct arguments; unions; whole
// columns; blocks holding an error or nothing numeric. The expected values are what the
// array path (the ranges copied into an array) gave before the ranges were folded in place,
// so any difference is a change of behavior.
let n = Value::Number;
let e = Value::Error;
// (formula written with SUM, error in E2?, [SUM, COUNT, AVERAGE] of that formula)
#[rustfmt::skip]
let cases: &[(&str, bool, [Value; 3])] = &[
("=SUM(A1:A1,B3)", false, [n(4.5), n(2.0), n(2.25)]),
("=SUM(A1:A1,B3)", true, [n(4.5), n(2.0), n(2.25)]),
("=SUM((A1:A2,B1:B3))", false, [n(16.5), n(4.0), n(4.125)]),
("=SUM((A1:A2,B1:B3))", true, [n(16.5), n(4.0), n(4.125)]),
("=SUM(A1:A4,B1:B3)", false, [n(16.25), n(5.0), n(3.25)]),
("=SUM(A1:A4,B1:B3)", true, [n(16.25), n(5.0), n(3.25)]),
("=SUM(A1:A4,\"x\")", false, [e(CellError::Value), n(3.0), e(CellError::Value)]),
("=SUM(A1:A4,\"x\")", true, [e(CellError::Value), n(3.0), e(CellError::Value)]),
("=SUM(A1:B4,5,\"7\",TRUE)", false, [n(29.25), n(8.0), n(3.65625)]),
("=SUM(A1:B4,5,\"7\",TRUE)", true, [n(29.25), n(8.0), n(3.65625)]),
("=SUM(A1:C4)+SUM(B1:B3)", false, [n(35.25), n(8.0), n(10.208333333333334)]),
("=SUM(A1:C4)+SUM(B1:B3)", true, [n(35.25), n(8.0), n(10.208333333333334)]),
("=SUM(A1:C4)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
("=SUM(A1:C4)", true, [n(22.25), n(6.0), n(3.7083333333333335)]),
("=SUM(A1:E4)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
("=SUM(A1:E4)", true, [e(CellError::Div0), n(6.0), e(CellError::Div0)]),
("=SUM(A1)", false, [n(1.5), n(1.0), n(1.5)]),
("=SUM(A1)", true, [n(1.5), n(1.0), n(1.5)]),
("=SUM(A3,B2)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
("=SUM(A3,B2)", true, [n(0.0), n(0.0), e(CellError::Div0)]),
("=SUM(A:C)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
("=SUM(A:C)", true, [n(22.25), n(6.0), n(3.7083333333333335)]),
("=SUM(E1:E3)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
("=SUM(E1:E3)", true, [e(CellError::Div0), n(0.0), e(CellError::Div0)]),
("=SUM(Z1:Z9)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
("=SUM(Z1:Z9)", true, [n(0.0), n(0.0), e(CellError::Div0)]),
];
for (formula, error, want) in cases {
for (func, want) in ["SUM", "COUNT", "AVERAGE"].into_iter().zip(want) {
// The same formula for each function: `SUM(` becomes `COUNT(` or `AVERAGE(`.
let f = formula.replace("SUM", func);
assert_eq!(&aggregate_of(*error, &f), want, "{f} (error in E2: {error})");
}
}
}
#[test]
fn sum_count_average_have_no_size_limit() {
// One stored cell far down stretches the used range to 27 million cells (27 columns by a
// million rows), past the 16M-cell limit of ranges copied into an array. Only two cells are
// stored, so the sheet itself is tiny.
for (func, want) in [("SUM", Value::Number(2.5)), ("COUNT", Value::Number(2.0)), ("AVERAGE", Value::Number(1.25))] {
for range in ["A1:AA1000000", "A:AA"] {
let mut t = T::new();
t.set("A1", "1.5");
t.set("Z1000000", "1");
t.set("AB1", &format!("={func}({range})"));
assert_eq!(t.get("AB1"), want, "{func}({range})");
}
}
}
#[test]
fn sum_count_average_over_spilled_values() {
// A1 spills over A1:A3, so the block holds values that exist only as a spill (they have no
// stored cell of their own). The host must not fold such a block in place: it falls back
// to the array path, which sees the spill. Expected: 1 + 2 + 3 + 10.
let mut t = T::new();
t.set("A1", "=SEQUENCE(3)");
t.set("A4", "10");
for (f, want) in [("SUM", 16.0), ("COUNT", 4.0), ("AVERAGE", 4.0)] {
t.set("C1", &format!("={f}(A1:A5)"));
assert_eq!(t.num("C1"), want, "{f}");
}
}
#[test]
fn aggregate_arguments_are_read_in_order() {
// Volatile cells draw a random number each time they are calculated, so the order in which
// the arguments are read decides which draw each one gets. `B1:B2` comes first, so B2 must
// draw before the `RAND()` argument does. (Reading the plain `RAND()` first once gave
// 7.9043 here.) The expected values are what the array path gave; they depend on the random
// generator and its seed, and must be updated if either changes.
let mut t = T::new();
t.set("B1", "1");
t.set("B2", "=RAND()*10");
t.set("A1", "=SUM(B1:B2,RAND())");
assert_eq!((t.num("A1"), t.num("B2")), (4.968520165759784, 3.3112028100185356));
}
#[test]
fn sum_count_average_follow_edits_inside_the_range() {
// A range read in place must still count as a precedent of the formula: if it didn't, an
// edit inside it would leave the formula showing a stale value. Each step below changes one
// cell inside the range and checks all three functions; the last one changes a cell outside.
for range in ["A1:A5", "A:A"] {
let mut t = T::new();
t.set("A1", "1");
t.set("A3", "3");
t.set("C1", &format!("=SUM({range})"));
t.set("C2", &format!("=COUNT({range})"));
t.set("C3", &format!("=AVERAGE({range})"));
let all = |t: &T| (t.num("C1"), t.num("C2"), t.num("C3"));
assert_eq!(all(&t), (4.0, 2.0, 2.0), "{range}");
t.set("A1", "5");
assert_eq!(all(&t), (8.0, 2.0, 4.0), "{range}: edit");
t.set("A2", "10");
assert_eq!(all(&t), (18.0, 3.0, 6.0), "{range}: fill a blank");
t.set("A3", "text");
assert_eq!(all(&t), (15.0, 2.0, 7.5), "{range}: number to text");
t.set("A2", "");
assert_eq!(all(&t), (5.0, 1.0, 5.0), "{range}: clear");
t.set("A5", "=A1*2");
assert_eq!(all(&t), (15.0, 2.0, 7.5), "{range}: formula in the range");
t.set("A1", "1");
assert_eq!(all(&t), (3.0, 2.0, 1.5), "{range}: its precedent changes");
// A7 is inside the whole column A:A but outside A1:A5.
t.set("A7", "100");
let outside = if range == "A:A" { (103.0, 3.0, 103.0 / 3.0) } else { (3.0, 2.0, 1.5) };
assert_eq!(all(&t), outside, "{range}: a cell outside the range");
}
}
#[test]
fn visit_range_declines_when_a_formula_in_the_block_spills_into_it() {
// The sheet: D1 = SEQUENCE(3) and D4 = 10, and D1 has not been calculated yet when the
// block D1:D5 is read.
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
sh.cells.set(c("D1"), Cell::formula(Formula::new("=SEQUENCE(3)")));
sh.cells.set(c("D4"), Cell::value(Value::Number(10.0)));
let block = gridcraft_core::RangeRef::parse("D1:D5").unwrap();
// Reading the block calculates D1, which spills over D2:D3. A walk over the stored cells
// would never see 2 and 3, so the host must decline and leave the block to `range_values`.
// (`Calc` recalculates a pass that produced new spills, so final results are right either
// way; only this direct call shows the host's contract.)
let walked = crate::recalc::tests::probe_visit_range(&wb, &[("D1", "=SEQUENCE(3)")], block);
assert_eq!(walked, None, "walked a block holding a spill it can't see");
}
/// Trim references evaluate as `TRIMRANGE(range, code, code)`.
#[test]
fn trim_references() {
let mut t = T::new();
t.set("C3", "1");
t.set("D5", "2");
t.set("A20", "5");
t.set("A21", "6");
let cases = [
("J1", "=ROWS(A1.:.F10)", "=ROWS(TRIMRANGE(A1:F10,3,3))", 3.0),
("J2", "=COLUMNS(A1.:.F10)", "=COLUMNS(TRIMRANGE(A1:F10,3,3))", 2.0),
("J3", "=ROWS(A1:.F10)", "=ROWS(TRIMRANGE(A1:F10,2,2))", 5.0),
("J4", "=COLUMNS(A1:.F10)", "=COLUMNS(TRIMRANGE(A1:F10,2,2))", 4.0),
("J5", "=ROWS(A1.:F10)", "=ROWS(TRIMRANGE(A1:F10,1,1))", 8.0),
("J6", "=MIN(ROW(A1.:F10))", "=MIN(ROW(TRIMRANGE(A1:F10,1,1)))", 3.0),
("J7", "=SUM(A:.A)", "=SUM(TRIMRANGE(A:A,2,2))", 11.0),
("J8", "=ROWS(A:.A)", "=ROWS(TRIMRANGE(A:A,2,2))", 21.0),
("J9", "=ROWS(A.:.A)", "=ROWS(TRIMRANGE(A:A,3,3))", 2.0),
("J10", "=ROWS(20.:.30)", "=ROWS(TRIMRANGE(20:30,3,3))", 2.0),
];
for (at, f, _, _) in cases {
t.set(at, f);
}
for (i, (at, f, same, want)) in cases.iter().enumerate() {
assert_eq!(t.num(at), *want, "{f}");
let k = format!("K{}", i + 1);
t.set(&k, same);
assert_eq!(t.num(&k), *want, "{same}");
}
// The trimmed block spills and follows edits to the full range.
t.set("L1", "=C1.:.F10");
assert_eq!((t.num("L1"), t.num("M3")), (1.0, 2.0));
t.set("A22", "4");
assert_eq!((t.num("J7"), t.num("J8")), (15.0, 22.0));
// Nothing but blanks.
t.set("K20", "=SUM(Q1:.Q9)");
assert_eq!(t.get("K20"), Value::Error(CellError::Calc));
}
+127
View File
@@ -0,0 +1,127 @@
//! TRIMRANGE: a range or array without its blank outer rows and columns (Microsoft's
//! documented semantics: trim_rows / trim_cols 0 none, 1 leading, 2 trailing, 3 both).
use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value};
use gridcraft_formula::{Expr, TrimMode};
use crate::eval::{Area, Ev, Evaluator, MAX_CELLS};
/// (leading, trailing) for a trim_rows / trim_cols code.
fn mode(code: f64) -> Result<(bool, bool), CellError> {
match code.trunc() {
0.0 => Ok((false, false)),
1.0 => Ok((true, false)),
2.0 => Ok((false, true)),
3.0 => Ok((true, true)),
_ => Err(CellError::Value),
}
}
/// Rows and columns (first, last) holding a non-blank value in a row-major grid.
fn bounds(values: &[Value], width: usize) -> Option<((usize, usize), (usize, usize))> {
let mut b: Option<((usize, usize), (usize, usize))> = None;
for (i, v) in values.iter().enumerate() {
if matches!(v, Value::Empty) {
continue;
}
let (r, c) = (i / width.max(1), i % width.max(1));
b = Some(match b {
None => ((r, r), (c, c)),
Some(((r0, r1), (c0, c1))) => ((r0.min(r), r1.max(r)), (c0.min(c), c1.max(c))),
});
}
b
}
/// The kept span of `0..len` given the non-blank span and the trim flags.
fn keep(len: usize, nonblank: (usize, usize), (lead, trail): (bool, bool)) -> (usize, usize) {
(if lead { nonblank.0 } else { 0 }, if trail { nonblank.1 } else { len.saturating_sub(1) })
}
impl Evaluator<'_> {
pub(crate) fn trimrange(&mut self, args: &[Expr]) -> Ev {
match self.trimrange_inner(args) {
Ok(ev) => ev,
Err(e) => Ev::V(Value::Error(e)),
}
}
/// A trim reference `A1.:E10` / `A1:.E10` / `A1.:.E10`: `TRIMRANGE(range, code, code)`.
pub(crate) fn trim_ref(&mut self, mode: TrimMode, x: &Expr) -> Ev {
let flags = match mode {
TrimMode::Leading => (true, false),
TrimMode::Trailing => (false, true),
TrimMode::All => (true, true),
};
let ev = self.eval(x);
match self.trim_ev(ev, flags, flags) {
Ok(ev) => ev,
Err(e) => Ev::V(Value::Error(e)),
}
}
fn trim_mode(&mut self, args: &[Expr], i: usize) -> Result<(bool, bool), CellError> {
match args.get(i) {
None | Some(Expr::Missing) => Ok((true, true)),
Some(e) => match self.value(e).scalar() {
Value::Error(e) => Err(e),
v => mode(v.to_number()?),
},
}
}
fn trimrange_inner(&mut self, args: &[Expr]) -> Result<Ev, CellError> {
let first = match args {
[first] | [first, _] | [first, _, _] => first,
_ => return Err(CellError::Value),
};
let rows = self.trim_mode(args, 1)?;
let cols = self.trim_mode(args, 2)?;
let ev = self.eval(first);
self.trim_ev(ev, rows, cols)
}
fn trim_ev(&mut self, ev: Ev, rows: (bool, bool), cols: (bool, bool)) -> Result<Ev, CellError> {
let none = rows == (false, false) && cols == (false, false);
match ev {
Ev::R(areas) => {
let [a] = areas.as_slice() else { return Err(CellError::Value) };
if none {
return Ok(Ev::R(vec![*a]));
}
// Cells past the used range are blank: only the used part is read.
let part = self.trim(a);
let (h, w) = (part.height() as usize, part.width() as usize);
if (h as u64) * (w as u64) > MAX_CELLS {
return Err(CellError::Num);
}
let values = self.host.range_values(a.sheet, part);
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
let at = |r: usize, c: usize| CellRef::new(a.range.start.row.saturating_add(r as u32), a.range.start.col.saturating_add(c as u32));
Ok(Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(at(kr0, kc0), at(kr1, kc1)) }]))
}
Ev::V(Value::Array(arr)) => {
if none {
return Ok(Ev::V(Value::Array(arr)));
}
let ((r0, r1), (c0, c1)) = bounds(&arr.data, arr.cols).ok_or(CellError::Calc)?;
let (kr0, kr1) = keep(arr.rows, (r0, r1), rows);
let (kc0, kc1) = keep(arr.cols, (c0, c1), cols);
let mut data = Vec::with_capacity((kr1 + 1 - kr0) * (kc1 + 1 - kc0));
for r in kr0..=kr1 {
for c in kc0..=kc1 {
data.push(arr.get(r, c).cloned().unwrap_or(Value::Empty));
}
}
Array::new(kr1 + 1 - kr0, kc1 + 1 - kc0, data).map(|a| Ev::V(Value::from(a))).ok_or(CellError::Value)
}
Ev::V(Value::Error(e)) => Err(e),
Ev::V(Value::Empty) if !none => Err(CellError::Calc),
Ev::V(v) => Ok(Ev::V(v)),
Ev::L(_) => Err(CellError::Value),
}
}
}
+17 -3
View File
@@ -15,17 +15,18 @@ mod raster;
mod render;
mod resolve;
mod sparkline;
mod trend;
#[cfg(test)]
mod tests;
pub use gridcraft_model::{Chart, ChartKind, LegendPos, SparklineKind};
pub use gridcraft_model::{Chart, ChartKind, LegendPos, SparklineKind, Trendline, TrendlineKind};
use serde::{Deserialize, Serialize};
pub use axis::{Scale, format_number, nice_scale};
pub use raster::rasterize;
pub use render::{Swatch, legend_entries, render};
pub use resolve::{default_palette, resolve, series_color};
pub use render::{Swatch, legend_entries, render, supports_trendline};
pub use resolve::{default_palette, resolve, series_color, series_plot_kind};
pub use sparkline::render_sparkline;
/// Straight (non-premultiplied) RGBA colour.
@@ -138,10 +139,21 @@ pub struct SeriesData {
pub kind: ChartKind,
/// Plotted against the secondary (right) value axis.
pub secondary: bool,
/// Draw line segments as a smoothed (spline) curve.
pub smooth: bool,
/// Trendlines to fit and draw over this series.
pub trendlines: Vec<TrendlineData>,
/// Number format code of the source values ("General" by default).
pub number_format: String,
}
/// A trendline to draw: the model settings with the line colour resolved against the theme.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrendlineData {
pub spec: Trendline,
pub color: Rgba,
}
impl Default for SeriesData {
fn default() -> Self {
SeriesData {
@@ -152,6 +164,8 @@ impl Default for SeriesData {
color: [0x15, 0x60, 0x82, 0xFF],
kind: ChartKind::ColumnClustered,
secondary: false,
smooth: false,
trendlines: vec![],
number_format: "General".into(),
}
}
+307 -23
View File
@@ -3,10 +3,11 @@
use std::collections::HashSet;
use std::f32::consts::{PI, TAU};
use gridcraft_model::{Chart, ChartKind, LegendPos, Theme};
use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, Theme, TrendlineKind};
use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale};
use crate::resolve::{MAX_POINTS, MAX_SERIES, series_color};
use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color};
use crate::trend::{auto_name, fit_trendline, moving_average};
use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign};
pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF];
@@ -158,20 +159,28 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
let total = data.series.first().map(|s| s.color).unwrap_or(TEXT);
vec![("Increase".into(), UP, Swatch::Box), ("Decrease".into(), DOWN, Swatch::Box), ("Total".into(), total, Swatch::Box)]
}
_ => data
.series
.iter()
.take(MAX_SERIES)
.map(|s| {
let sw = match plot_kind(chart, s) {
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
_ => Swatch::Box,
};
(s.name.clone(), s.color, sw)
})
.collect(),
_ => {
let series = data.series.iter().take(MAX_SERIES);
let mut out: Vec<(String, Rgba, Swatch)> = series
.clone()
.map(|s| {
let sw = match plot_kind(chart, s) {
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
_ => Swatch::Box,
};
(s.name.clone(), s.color, sw)
})
.collect();
// Trendlines follow the series, named "Linear (Sales)" unless given a name.
for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) {
for t in s.trendlines.iter().take(MAX_TRENDLINES) {
out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line));
}
}
out
}
}
}
@@ -194,6 +203,8 @@ fn sanitize(d: &ChartData) -> ChartData {
color: s.color,
kind: s.kind,
secondary: s.secondary,
smooth: s.smooth,
trendlines: s.trendlines.iter().take(MAX_TRENDLINES).cloned().collect(),
number_format: s.number_format.clone(),
})
.collect(),
@@ -545,8 +556,9 @@ fn decimate(pts: Vec<[f32; 2]>, max: usize) -> Vec<[f32; 2]> {
out
}
/// Draws a polyline split at gaps (`None`), decimated when long.
fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32) {
/// Draws a polyline split at gaps (`None`), decimated when long. With `smooth` (the plot box),
/// each run is interpolated with a Catmull-Rom spline so the line curves through the data points.
fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32, smooth: Option<Bx>) {
let mut run: Vec<[f32; 2]> = Vec::new();
for p in pts.iter().chain(std::iter::once(&None)) {
match p {
@@ -554,6 +566,10 @@ fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32) {
None => {
if run.len() >= 2 {
let r = decimate(std::mem::take(&mut run), MAX_LINE_PTS);
let r = match smooth {
Some(plot) => smooth_run(r, plot),
None => r,
};
ctx.line(r, color, width);
} else {
run.clear();
@@ -563,6 +579,48 @@ fn draw_runs(ctx: &mut Ctx, pts: &[Option<[f32; 2]>], color: Rgba, width: f32) {
}
}
/// Catmull-Rom spline through `pts`: every segment gets the same number of sub-segments (up to
/// 100), chosen so the whole curve stays within `MAX_LINE_PTS * 2` points. Endpoints are
/// duplicated so the curve passes through the first and last points, and the curve is clamped
/// to the `plot` box (a spline overshoots its data near sharp turns).
fn smooth_run(pts: Vec<[f32; 2]>, plot: Bx) -> Vec<[f32; 2]> {
let n = pts.len();
if n < 3 {
return pts;
}
let cap = MAX_LINE_PTS * 2;
let steps = (cap / n).clamp(1, 100);
let mut out: Vec<[f32; 2]> = Vec::with_capacity(n.saturating_mul(steps).min(cap) + 1);
let at = |i: isize| -> [f32; 2] {
let j = i.clamp(0, n as isize - 1) as usize;
pts.get(j).copied().unwrap_or([0.0, 0.0])
};
let (x0, x1) = (plot.x.min(plot.right()), plot.x.max(plot.right()));
let (y0, y1) = (plot.y.min(plot.bottom()), plot.y.max(plot.bottom()));
let clip = |p: [f32; 2]| [p[0].clamp(x0, x1), p[1].clamp(y0, y1)];
for i in 0..n.saturating_sub(1) {
let (p0, p1, p2, p3) = (at(i as isize - 1), at(i as isize), at(i as isize + 1), at(i as isize + 2));
for s in 0..steps {
let t = s as f32 / steps as f32;
out.push(clip(catmull(p0, p1, p2, p3, t)));
}
}
out.push(clip(at(n as isize - 1)));
out
}
/// One Catmull-Rom point between `p1` and `p2` (uniform parameterisation), tangent-scaled by 0.5.
fn catmull(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] {
let t2 = t * t;
let t3 = t2 * t;
let mut o = [0.0f32; 2];
for k in 0..2 {
let (a0, a1, a2, a3) = (p0[k], p1[k], p2[k], p3[k]);
o[k] = 0.5 * ((2.0 * a1) + (-a0 + a2) * t + (2.0 * a0 - 5.0 * a1 + 4.0 * a2 - a3) * t2 + (-a0 + 3.0 * a1 - 3.0 * a2 + a3) * t3);
}
o
}
fn draw_markers(ctx: &mut Ctx, pts: impl Iterator<Item = [f32; 2]>, r: f32, color: Rgba) {
let mut seen = HashSet::new();
for p in pts {
@@ -582,6 +640,160 @@ fn value_range(it: impl Iterator<Item = f64>) -> Option<(f64, f64)> {
})
}
// ---------------------------------------------------------------- trendlines
/// Samples along a regression trendline.
const TREND_STEPS: usize = 200;
/// Whether series drawn as `k` show trendlines (Excel offers them on 2-D unstacked column,
/// bar, line, area, scatter and bubble charts).
pub fn supports_trendline(k: ChartKind) -> bool {
use ChartKind::*;
matches!(k, ColumnClustered | BarClustered | Line | LineMarkers | Area | Scatter | ScatterLines | Bubble)
}
/// A forecast distance as drawn: finite, non-negative and bounded.
fn forecast(v: f64) -> f64 {
if v.is_finite() && v > 0.0 { v.min(1e9) } else { 0.0 }
}
/// Longest forward forecast among `s`'s regression trendlines.
fn max_forward(s: &SeriesData) -> f64 {
s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.forward)).fold(0.0, f64::max)
}
/// Longest backward forecast among `s`'s regression trendlines.
fn max_backward(s: &SeriesData) -> f64 {
s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.backward)).fold(0.0, f64::max)
}
/// Liang–Barsky: the part of segment `a`–`b` inside the unit square, with whether the start and
/// end were cut.
#[allow(clippy::type_complexity)]
fn clip_segment(a: (f64, f64), b: (f64, f64)) -> Option<((f64, f64), (f64, f64), bool, bool)> {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let (mut t0, mut t1) = (0.0f64, 1.0f64);
for (p, q) in [(-dx, a.0), (dx, 1.0 - a.0), (-dy, a.1), (dy, 1.0 - a.1)] {
if p == 0.0 {
if q < 0.0 {
return None;
}
} else {
let r = q / p;
if p < 0.0 {
if r > t1 {
return None;
}
t0 = t0.max(r);
} else {
if r < t0 {
return None;
}
t1 = t1.min(r);
}
}
}
Some(((a.0 + t0 * dx, a.1 + t0 * dy), (a.0 + t1 * dx, a.1 + t1 * dy), t0 > 0.0, t1 < 1.0))
}
/// Clips a sampled polyline in plot fractions (`None` = gap) to the plot box (the unit
/// square), returning the visible runs.
fn clip_unit(pts: &[Option<(f64, f64)>]) -> Vec<Vec<(f64, f64)>> {
const LIM: f64 = 1e9;
let ok = |p: &(f64, f64)| p.0.is_finite() && p.1.is_finite();
let cl = |p: (f64, f64)| (p.0.clamp(-LIM, LIM), p.1.clamp(-LIM, LIM));
let mut runs: Vec<Vec<(f64, f64)>> = Vec::new();
let mut run: Vec<(f64, f64)> = Vec::new();
for w in pts.windows(2) {
let seg = match w {
[Some(a), Some(b)] if ok(a) && ok(b) => clip_segment(cl(*a), cl(*b)),
_ => None,
};
match seg {
Some((p, q, cut_start, cut_end)) => {
if cut_start || run.is_empty() {
if run.len() >= 2 {
runs.push(std::mem::take(&mut run));
}
run.clear();
run.push(p);
}
run.push(q);
if cut_end {
runs.push(std::mem::take(&mut run));
}
}
None => {
if run.len() >= 2 {
runs.push(std::mem::take(&mut run));
}
run.clear();
}
}
}
if run.len() >= 2 {
runs.push(run);
}
runs
}
/// Draws `s`'s trendlines fitted to its plotted points `pts` (data x, y). `frac` maps data to
/// fractions of the plot box (0..1 inside, along the x and y axes), `px` fractions to pixels.
/// Equation and R² label lines are appended to `labels`. Degenerate fits draw nothing.
fn draw_trendlines(
ctx: &mut Ctx,
s: &SeriesData,
pts: &[(f64, f64)],
frac: &dyn Fn(f64, f64) -> (f64, f64),
px: &dyn Fn((f64, f64)) -> [f32; 2],
labels: &mut Vec<String>,
) {
let Some((xlo, xhi)) = value_range(pts.iter().map(|p| p.0)) else { return };
for t in s.trendlines.iter().take(MAX_TRENDLINES) {
let spec = &t.spec;
let samples: Vec<Option<(f64, f64)>> = match spec.kind {
TrendlineKind::MovingAverage(p) => moving_average(pts, p).into_iter().map(|(x, y)| Some(frac(x, y))).collect(),
_ => {
let Some(fit) = fit_trendline(spec, pts) else { continue };
let (lo, hi) = (xlo - forecast(spec.backward), xhi + forecast(spec.forward));
if spec.display_equation {
labels.push(fit.equation());
}
if spec.display_r_squared {
labels.push(fit.r_squared());
}
(0..=TREND_STEPS)
.map(|i| {
let x = lo + (hi - lo) * i as f64 / TREND_STEPS as f64;
fit.eval(x).map(|y| frac(x, y))
})
.collect()
}
};
let width = spec.width.filter(|w| w.is_finite()).unwrap_or(1.5).clamp(0.25, 12.0);
let dash = spec.dash != Some(LineDash::Solid);
for run in clip_unit(&samples) {
let line = decimate(run.into_iter().map(px).collect(), MAX_LINE_PTS);
if line.len() >= 2 {
ctx.out.push(Prim::Line { pts: line, color: t.color, width, dash });
}
}
}
}
/// Trendline equation / R² labels, stacked in the plot's top-right corner.
fn draw_trend_labels(ctx: &mut Ctx, plot: Bx, labels: &[String]) {
let lh = LABEL_SIZE * 1.3;
for (i, t) in labels.iter().enumerate() {
let y = plot.y + 4.0 + i as f32 * lh;
if y + lh > plot.bottom() {
break;
}
let t = ctx.fit(t, LABEL_SIZE, plot.w - 8.0);
ctx.text(plot.right() - 4.0, y, &t, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Top);
}
}
// ---------------------------------------------------------------- cartesian (column/bar/line/area/combo)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -715,14 +927,23 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
let Some((s1, f1)) = axes.first() else { return };
let y1 = ValAxis { scale: *s1, fmt: f1 };
let y2 = axes.get(1).map(|(s, f)| ValAxis { scale: *s, fmt: f });
let labels: Vec<String> = (0..ncat).map(|j| cat_label(data, j)).collect();
// A forward forecast on a category axis adds empty category slots after the data.
let fwd = data
.series
.iter()
.enumerate()
.filter(|(i, _)| kinds.get(*i).is_some_and(|k| supports_trendline(*k)))
.map(|(_, s)| max_forward(s))
.fold(0.0, f64::max);
let ncat_slots = ncat.saturating_add(fwd.ceil() as usize).min(MAX_CATS.max(ncat));
let labels: Vec<String> = (0..ncat_slots).map(|j| if j < ncat { cat_label(data, j) } else { String::new() }).collect();
let plot = frame(ctx, area, CatAxis::Labels(&labels), &y1, y2.as_ref(), horizontal, chart.gridlines);
if !plot.ok() {
return;
}
let scale_of = |i: usize| -> Scale { if sec.get(i).copied().unwrap_or(false) { y2.as_ref().map(|a| a.scale).unwrap_or(*s1) } else { *s1 } };
let cat_len = if horizontal { plot.h } else { plot.w };
let cw = cat_len / ncat as f32;
let cw = cat_len / ncat_slots as f32;
let center = |j: usize| if horizontal { plot.bottom() - (j as f32 + 0.5) * cw } else { plot.x + (j as f32 + 0.5) * cw };
let vpos = |v: f64, sc: &Scale| if horizontal { plot.x + sc.frac(v) * plot.w } else { plot.bottom() - sc.frac(v) * plot.h };
@@ -836,7 +1057,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
}
_ => {
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25);
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if k == ChartKind::LineMarkers && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
@@ -852,6 +1073,25 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
}
}
}
// Trendlines on top: x is the category number 1..n.
let mut trend_labels = Vec::new();
for (i, s) in data.series.iter().enumerate() {
if s.trendlines.is_empty() || !kinds.get(i).is_some_and(|k| supports_trendline(*k)) {
continue;
}
let sc = scale_of(i);
let pts: Vec<(f64, f64)> = s.values.iter().take(ncat).enumerate().filter_map(|(j, v)| v.map(|v| ((j + 1) as f64, v))).collect();
let frac = |x: f64, y: f64| ((x - 0.5) / ncat_slots as f64, (y - sc.min) / (sc.max - sc.min));
let px = |(fx, fy): (f64, f64)| {
if horizontal {
[plot.x + fy as f32 * plot.w, plot.bottom() - fx as f32 * plot.h]
} else {
[plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h]
}
};
draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels);
}
draw_trend_labels(ctx, plot, &trend_labels);
}
// ---------------------------------------------------------------- scatter & bubble
@@ -874,7 +1114,14 @@ fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
.collect()
};
let all: Vec<Vec<Option<(f64, f64)>>> = data.series.iter().map(pts_of).collect();
let Some((xlo, xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return };
let Some((mut xlo, mut xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return };
// Forecasts extend the x axis to the trendline's ends.
for (s, pts) in data.series.iter().zip(&all) {
if let Some((lo, hi)) = value_range(pts.iter().flatten().map(|p| p.0)).filter(|_| !s.trendlines.is_empty()) {
xlo = xlo.min(lo - max_backward(s));
xhi = xhi.max(hi + max_forward(s));
}
}
let Some((ylo, yhi)) = value_range(all.iter().flatten().flatten().map(|p| p.1)) else { return };
let xs = nice_scale(xlo, xhi, false);
let ys = nice_scale(ylo, yhi, false);
@@ -914,7 +1161,7 @@ fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
} else {
let lines = chart.kind == ChartKind::ScatterLines || s.kind == ChartKind::ScatterLines;
if lines {
draw_runs(ctx, &px, s.color, 2.0);
draw_runs(ctx, &px, s.color, 2.0, s.smooth.then_some(plot));
}
if !lines || px.len() <= 500 {
draw_markers(ctx, px.iter().flatten().copied(), 3.5, s.color);
@@ -928,6 +1175,17 @@ fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
}
}
}
let mut trend_labels = Vec::new();
for (s, pts) in data.series.iter().zip(&all) {
if s.trendlines.is_empty() {
continue;
}
let pts: Vec<(f64, f64)> = pts.iter().flatten().copied().collect();
let frac = |x: f64, y: f64| ((x - xs.min) / (xs.max - xs.min), (y - ys.min) / (ys.max - ys.min));
let px = |(fx, fy): (f64, f64)| [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h];
draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels);
}
draw_trend_labels(ctx, plot, &trend_labels);
}
// ---------------------------------------------------------------- histogram
@@ -1468,3 +1726,29 @@ pub(crate) fn finalize(prims: Vec<Prim>, w: f32, h: f32) -> Vec<Prim> {
})
.collect()
}
#[cfg(test)]
mod smooth_tests {
use super::*;
#[test]
fn long_runs_are_smoothed_uniformly_within_the_cap() {
let plot = Bx { x: 0.0, y: 0.0, w: 3000.0, h: 100.0 };
let pts: Vec<[f32; 2]> = (0..1500).map(|i| [i as f32 * 2.0, if i % 2 == 0 { 20.0 } else { 80.0 }]).collect();
let out = smooth_run(pts, plot);
assert!(out.len() <= MAX_LINE_PTS * 2 + 1, "{}", out.len());
// Two sub-segments per segment all the way to the end, not 100 each and then a straight tail.
assert_eq!(out.len(), 1499 * 2 + 1);
assert_eq!(out.last().copied(), Some([2998.0, 80.0]));
}
#[test]
fn spline_overshoot_is_clamped_to_the_plot() {
let plot = Bx { x: 0.0, y: 10.0, w: 300.0, h: 100.0 };
// A step right at the plot edges: Catmull-Rom overshoots past both.
let pts = vec![[0.0, 110.0], [100.0, 110.0], [110.0, 10.0], [200.0, 10.0], [300.0, 10.0]];
let out = smooth_run(pts, plot);
assert!(out.len() > 5);
assert!(out.iter().all(|p| (0.0..=300.0).contains(&p[0]) && (10.0..=110.0).contains(&p[1])));
}
}
+74 -4
View File
@@ -5,12 +5,14 @@ use gridcraft_core::{CellRef, RangeRef, Value, number_to_text};
use gridcraft_model::{Chart, ChartKind, Theme, Workbook, style::apply_tint};
use gridcraft_numfmt::{NumberFormat, format_value};
use crate::{ChartData, Rgba, SeriesData};
use crate::{ChartData, Rgba, SeriesData, TrendlineData};
/// Cap on points per series (keeps whole-column references from exploding).
pub(crate) const MAX_POINTS: usize = 100_000;
/// Cap on series per chart.
pub(crate) const MAX_SERIES: usize = 255;
/// Cap on trendlines drawn per series.
pub(crate) const MAX_TRENDLINES: usize = 16;
/// Tints used for series beyond the six theme accents: lighter, darker, lighter still…
const CYCLE_TINTS: [f64; 6] = [0.0, 0.4, -0.25, 0.6, -0.5, 0.2];
@@ -46,12 +48,54 @@ fn parse_ref(wb: &Workbook, sheet: usize, formula: &str) -> Option<(usize, Range
Some((sh, r))
}
/// Evaluates a series formula to a flat list of values (row-major), capped.
/// The parts of a union reference `(Sheet1!$A$1:$A$3,Sheet1!$A$5)`, or `None`.
fn union_parts(f: &str) -> Option<Vec<&str>> {
let inner = f.strip_prefix('(')?.strip_suffix(')')?;
let mut parts = Vec::new();
let (mut depth, mut quoted, mut start) = (0i32, false, 0usize);
for (i, c) in inner.char_indices() {
match c {
'\'' => quoted = !quoted,
'(' if !quoted => depth += 1,
')' if !quoted => depth -= 1,
',' if !quoted && depth == 0 => {
parts.push(inner.get(start..i)?);
start = i + 1;
}
_ => {}
}
if depth < 0 {
return None;
}
}
parts.push(inner.get(start..)?);
(parts.len() > 1).then_some(parts)
}
/// Evaluates a series formula to a flat list of values (row-major), capped. A union of
/// references (`(A1:A3,A5)`, as PivotCharts use) is read part by part.
fn eval_list(wb: &Workbook, sheet: usize, formula: &str) -> Vec<Value> {
eval_list_in(wb, sheet, formula, 0)
}
fn eval_list_in(wb: &Workbook, sheet: usize, formula: &str, depth: u32) -> Vec<Value> {
let f = formula.trim();
if f.is_empty() {
return vec![];
}
if depth < 4
&& let Some(parts) = union_parts(f)
{
let mut out = Vec::new();
for p in parts {
if out.len() >= MAX_POINTS {
break;
}
let rest = MAX_POINTS - out.len();
out.extend(eval_list_in(wb, sheet, p, depth + 1).into_iter().take(rest));
}
return out;
}
match evaluate(wb, sheet, CellRef::default(), f) {
Value::Array(a) => a.iter().take(MAX_POINTS).cloned().collect(),
v => vec![v],
@@ -139,6 +183,11 @@ fn effective_kind(chart_kind: ChartKind, series_kind: Option<ChartKind>, i: usiz
}
}
/// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's.
pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind {
if chart.kind == ChartKind::Combo { effective_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } else { chart.kind }
}
/// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X
/// values (scatter/bubble), bubble sizes, number formats and colours (explicit, else the
/// default palette derived from the workbook theme accents).
@@ -153,7 +202,8 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
let kind = effective_kind(chart.kind, s.kind, i);
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
(Some(f), true) => Some(nums(wb, sheet, f)),
// X values with text in them (labels) are ignored: the points are numbered 1..n.
(Some(f), true) => Some(eval_list(wb, sheet, f)).filter(|xs| !xs.iter().any(Value::is_text)).map(|xs| xs.iter().map(to_num).collect()),
_ => None,
};
if categories.is_none()
@@ -165,7 +215,27 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
}
}
let sizes = s.bubble_sizes.as_deref().map(|f| nums(wb, sheet, f));
series.push(SeriesData { name, values, x, sizes, color, kind, secondary: s.secondary, number_format: ref_format(wb, sheet, &s.values) });
let trendlines = s
.trendlines
.iter()
.take(MAX_TRENDLINES)
.map(|t| TrendlineData {
spec: t.clone(),
color: t.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or(color),
})
.collect();
series.push(SeriesData {
name,
values,
x,
sizes,
color,
kind,
secondary: s.secondary,
smooth: s.smooth,
trendlines,
number_format: ref_format(wb, sheet, &s.values),
});
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
+337 -2
View File
@@ -48,6 +48,7 @@ fn chart(kind: ChartKind) -> Chart {
y_title: Some("Revenue".into()),
source: None,
by_rows: false,
pivot: None,
}
}
@@ -60,6 +61,8 @@ fn series(name: &str, values: &[f64], color: Rgba, kind: ChartKind) -> SeriesDat
color,
kind,
secondary: false,
smooth: false,
trendlines: Vec::new(),
number_format: "$#,##0".into(),
}
}
@@ -223,6 +226,8 @@ fn resolve_from_workbook() {
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
},
Series {
name: None,
@@ -232,6 +237,8 @@ fn resolve_from_workbook() {
color: Some(Color::rgb(1, 2, 3)),
secondary: true,
kind: None,
smooth: false,
trendlines: Vec::new(),
},
Series {
name: Some("Literal".into()),
@@ -241,6 +248,8 @@ fn resolve_from_workbook() {
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
},
];
let d = resolve(&wb, 0, &c);
@@ -269,8 +278,28 @@ fn resolve_from_workbook() {
// Combo kinds and scatter X values.
let mut c = chart(ChartKind::Combo);
c.series = vec![
Series { name: None, categories: None, values: "Sales!B2:B4".into(), bubble_sizes: None, color: None, secondary: false, kind: None },
Series { name: None, categories: None, values: "Sales!B2:B4".into(), bubble_sizes: None, color: None, secondary: true, kind: None },
Series {
name: None,
categories: None,
values: "Sales!B2:B4".into(),
bubble_sizes: None,
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
},
Series {
name: None,
categories: None,
values: "Sales!B2:B4".into(),
bubble_sizes: None,
color: None,
secondary: true,
kind: None,
smooth: false,
trendlines: Vec::new(),
},
];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].kind, ChartKind::ColumnClustered);
@@ -284,6 +313,8 @@ fn resolve_from_workbook() {
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
@@ -299,6 +330,8 @@ fn resolve_from_workbook() {
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
}];
let d = resolve(&wb, 7, &c);
assert_eq!(d.series.len(), 1);
@@ -314,6 +347,29 @@ fn palette_beyond_six_series() {
assert_ne!(p[6], p[12]);
}
#[test]
fn scatter_with_text_x_values_numbers_the_points() {
let mut wb = Workbook::new();
let s = wb.sheet_mut(0).unwrap();
for (i, (label, v)) in [("North", 3.0), ("South", 5.0), ("East", 4.0)].iter().enumerate() {
s.set_value(CellRef::new(i as u32, 0), Value::from(*label));
s.set_value(CellRef::new(i as u32, 1), Value::Number(*v));
s.set_value(CellRef::new(i as u32, 2), Value::Number(i as f64 * 10.0));
}
for kind in [ChartKind::Scatter, ChartKind::ScatterLines, ChartKind::Bubble] {
let mut c = chart(kind);
c.series = vec![Series { categories: Some("Sheet1!$A$1:$A$3".into()), values: "Sheet1!$B$1:$B$3".into(), ..Default::default() }];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].x, None, "{kind:?}");
let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure);
let empty = render(&c, &ChartData { categories: vec![], series: vec![] }, 400.0, 300.0, &ApproxMeasure);
assert!(prims.len() > empty.len() + 2, "{kind:?} draws its points");
// Numeric X values are kept.
c.series[0].categories = Some("Sheet1!$C$1:$C$3".into());
assert_eq!(resolve(&wb, 0, &c).series[0].x, Some(vec![Some(0.0), Some(10.0), Some(20.0)]));
}
}
fn pixel(img: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * w + x) * 4) as usize;
[img[i], img[i + 1], img[i + 2], img[i + 3]]
@@ -450,8 +506,51 @@ fn thousands_of_points_are_decimated() {
}
}
#[test]
fn smooth_line_adds_interpolated_points_and_keeps_endpoints() {
let m = ApproxMeasure;
let cats = ["a", "b", "c", "d"].map(String::from).to_vec();
let line_pts = |smooth: bool, m: &ApproxMeasure| -> usize {
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
s.smooth = smooth;
let d = ChartData { categories: cats.clone(), series: vec![s] };
render(&chart(ChartKind::Line), &d, 600.0, 400.0, m)
.iter()
.filter_map(|p| match p {
Prim::Line { pts, .. } => Some(pts.len()),
_ => None,
})
.max()
.unwrap_or(0)
};
let straight = line_pts(false, &m);
let curved = line_pts(true, &m);
assert_eq!(straight, 4, "straight polyline keeps one point per datum");
assert!(curved > straight, "smooth line interpolates extra points: {curved} vs {straight}");
// Rendering either way must stay finite and inside the canvas.
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
s.smooth = true;
let d = ChartData { categories: cats, series: vec![s] };
assert_sane(&render(&chart(ChartKind::Line), &d, 600.0, 400.0, &m), 600.0, 400.0);
}
#[test]
fn smooth_line_splits_at_gaps() {
let m = ApproxMeasure;
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
s.smooth = true;
s.values[1] = None; // gap between two data points
let d = ChartData { categories: vec!["a".into(), "b".into(), "c".into(), "d".into()], series: vec![s] };
let prims = render(&chart(ChartKind::Line), &d, 600.0, 400.0, &m);
// Two separate runs (before/after the gap) → at least two line primitives.
let lines = prims.iter().filter(|p| matches!(p, Prim::Line { .. })).count();
assert!(lines >= 2, "a gap must split the smoothed line into runs, got {lines}");
assert_sane(&prims, 600.0, 400.0);
}
/// Small deterministic PRNG (xorshift) for the fuzz test.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
@@ -491,6 +590,29 @@ fn fuzz_random_data_and_sizes() {
color: [(r.next() % 256) as u8, 100, 50, 255],
kind: ALL_KINDS[(r.next() % ALL_KINDS.len() as u64) as usize],
secondary: r.next().is_multiple_of(3),
smooth: r.next().is_multiple_of(4),
trendlines: (0..r.next() % 3)
.map(|_| TrendlineData {
spec: Trendline {
kind: [
TrendlineKind::Linear,
TrendlineKind::Exponential,
TrendlineKind::Logarithmic,
TrendlineKind::Polynomial((r.next() % 8) as u8),
TrendlineKind::Power,
TrendlineKind::MovingAverage((r.next() % 6) as u32),
][(r.next() % 6) as usize],
forward: [0.0, 1.5, -2.0, f64::NAN, 1e300][(r.next() % 5) as usize],
backward: [0.0, 0.5, f64::INFINITY][(r.next() % 3) as usize],
intercept: [None, Some(0.0), Some(-5.0), Some(f64::NAN)][(r.next() % 4) as usize],
display_equation: r.next().is_multiple_of(2),
display_r_squared: r.next().is_multiple_of(2),
width: [None, Some(0.0), Some(f32::NAN), Some(3.0)][(r.next() % 4) as usize],
..Trendline::default()
},
color: [0, 0, 0, 255],
})
.collect(),
number_format: ["General", "$#,##0", "0.00%", "yyyy-mm-dd", "#,##0.0;[Red]-#,##0.0", "@"][(r.next() % 6) as usize].into(),
})
.collect();
@@ -539,6 +661,193 @@ fn sparklines() {
assert!(render_sparkline(SparklineKind::Line, &[], [0; 4], false, 10.0, 10.0).is_empty());
}
// ---------------------------------------------------------------- trendlines
fn close(a: f64, b: f64) -> bool {
(a - b).abs() <= 1e-9 * (1.0 + b.abs())
}
fn fit(kind: TrendlineKind, pts: &[(f64, f64)]) -> crate::trend::TrendFit {
crate::trend::fit_trendline(&Trendline { kind, ..Trendline::default() }, pts).expect("fits")
}
#[test]
fn linear_trendline_matches_least_squares() {
// Slope 0.6, intercept 2.2, R² = 1 - 2.4 / 6.
let f = fit(TrendlineKind::Linear, &[(1.0, 2.0), (2.0, 4.0), (3.0, 5.0), (4.0, 4.0), (5.0, 5.0)]);
assert!(close(f.coef[0], 2.2) && close(f.coef[1], 0.6), "{:?}", f.coef);
assert!(close(f.r2.unwrap(), 0.6));
assert_eq!(f.equation(), "y = 0.6x + 2.2");
assert_eq!(f.r_squared(), "R² = 0.6");
assert!(close(f.eval(10.0).unwrap(), 8.2));
let down = fit(TrendlineKind::Linear, &[(0.0, 1.0), (1.0, -1.0), (2.0, -3.0)]);
assert_eq!(down.equation(), "y = -2x + 1");
}
#[test]
fn set_intercept_fits_through_it() {
// Through the origin: slope Σxy / Σx² = 30 / 14; R² against the uncentred total.
let pts = [(1.0, 2.0), (2.0, 5.0), (3.0, 6.0)];
let f = crate::trend::fit_trendline(&Trendline { intercept: Some(0.0), ..Trendline::default() }, &pts).unwrap();
assert!(close(f.coef[0], 0.0) && close(f.coef[1], 15.0 / 7.0), "{:?}", f.coef);
let ss_res: f64 = pts.iter().map(|(x, y)| (y - 15.0 / 7.0 * x).powi(2)).sum();
assert!(close(f.r2.unwrap(), 1.0 - ss_res / 65.0));
let q = crate::trend::fit_trendline(
&Trendline { kind: TrendlineKind::Polynomial(2), intercept: Some(2.0), ..Trendline::default() },
&[(1.0, 0.0), (2.0, 0.0), (3.0, 2.0), (4.0, 6.0)],
)
.unwrap();
assert!(close(q.coef[0], 2.0) && close(q.coef[1], -3.0) && close(q.coef[2], 1.0), "{:?}", q.coef);
}
#[test]
fn transformed_trendlines_recover_their_curves() {
let xs: [f64; 6] = [0.5, 1.0, 2.0, 3.0, 4.5, 6.0];
let e = fit(TrendlineKind::Exponential, &xs.map(|x| (x, 3.0 * (0.5 * x).exp())));
assert!(close(e.coef[0].exp(), 3.0) && close(e.coef[1], 0.5));
assert_eq!(e.equation(), "y = 3e^(0.5x)");
let l = fit(TrendlineKind::Logarithmic, &xs.map(|x| (x, 2.0 * x.ln() + 1.0)));
assert!(close(l.coef[1], 2.0) && close(l.coef[0], 1.0));
assert_eq!(l.equation(), "y = 2ln(x) + 1");
let p = fit(TrendlineKind::Power, &xs.map(|x| (x, 4.0 * x.powf(1.5))));
assert!(close(p.coef[0].exp(), 4.0) && close(p.coef[1], 1.5));
assert_eq!(p.equation(), "y = 4x^1.5");
assert!(close(p.r2.unwrap(), 1.0));
assert_eq!(p.eval(-1.0), None, "power is undefined left of zero");
// Points the transform can't take are skipped, as Excel documents.
let skip = fit(TrendlineKind::Exponential, &[(1.0, 2.0f64.exp()), (2.0, 0.0), (3.0, -4.0), (4.0, 8.0f64.exp())]);
assert!(close(skip.coef[1], 2.0) && close(skip.coef[0], 0.0), "{:?}", skip.coef);
assert!(
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::Power, ..Trendline::default() }, &[(-1.0, 1.0), (0.0, 2.0), (3.0, 3.0)])
.is_none()
);
}
#[test]
fn polynomial_trendlines_are_stable() {
let q = fit(TrendlineKind::Polynomial(2), &[0.0, 1.0, 2.0, 3.0, 4.0].map(|x| (x, x * x - 3.0 * x + 2.0)));
assert!(close(q.coef[0], 2.0) && close(q.coef[1], -3.0) && close(q.coef[2], 1.0), "{:?}", q.coef);
assert_eq!(q.equation(), "y = x² - 3x + 2");
// Year-valued x would make the raw normal equations hopelessly ill-conditioned.
let curve = |x: f64| {
let t = x - 2000.0;
0.001 * t.powi(6) - 0.02 * t.powi(5) + 0.1 * t.powi(3) - t + 7.0
};
let years: Vec<(f64, f64)> = (2001..=2012).map(|x| (f64::from(x), curve(f64::from(x)))).collect();
let six = fit(TrendlineKind::Polynomial(6), &years);
for x in [2001.0, 2006.5, 2012.0, 2014.0] {
let (got, want) = (six.eval(x).unwrap(), curve(x));
assert!((got - want).abs() <= 1e-6 * (1.0 + want.abs()), "{x}: {got} vs {want}");
}
assert!(six.r2.unwrap() > 0.999_999);
}
#[test]
fn degenerate_trendlines_fit_nothing() {
let lin = |pts: &[(f64, f64)]| crate::trend::fit_trendline(&Trendline::default(), pts);
assert!(lin(&[]).is_none());
assert!(lin(&[(1.0, 1.0)]).is_none());
assert!(lin(&[(2.0, 1.0), (2.0, 5.0), (2.0, 3.0)]).is_none(), "all x equal is singular");
assert!(lin(&[(f64::NAN, 1.0), (1.0, f64::INFINITY), (2.0, 3.0)]).is_none());
assert!(
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::Polynomial(3), ..Trendline::default() }, &[(1.0, 1.0), (2.0, 4.0), (3.0, 9.0)])
.is_none()
);
assert!(
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::MovingAverage(2), ..Trendline::default() }, &[(1.0, 1.0), (2.0, 2.0)])
.is_none()
);
let flat = lin(&[(1.0, 4.0), (2.0, 4.0), (3.0, 4.0)]).unwrap();
assert_eq!((flat.equation(), flat.r2), ("y = 4".to_string(), None));
assert!(lin(&[(0.0, 1e300), (1.0, -1e300), (2.0, 1e300)]).is_none_or(|f| f.coef.iter().all(|c| c.is_finite())));
}
#[test]
fn moving_average_and_labels() {
let pts = [(1.0, 1.0), (2.0, 2.0), (3.0, 6.0), (4.0, f64::NAN), (5.0, 4.0)];
assert_eq!(crate::trend::moving_average(&pts, 2), vec![(2.0, 1.5), (3.0, 4.0), (5.0, 5.0)]);
assert_eq!(crate::trend::moving_average(&pts, 3), vec![(3.0, 3.0), (5.0, 4.0)]);
assert!(crate::trend::moving_average(&pts, 9).is_empty());
assert_eq!(crate::trend::num_text(0.000012345), "1.2345E-05");
assert_eq!(crate::trend::num_text(-0.00001), "-1E-05");
assert_eq!(crate::trend::num_text(1234.56789), "1234.5679");
assert_eq!(crate::trend::auto_name(TrendlineKind::MovingAverage(3), "Sales"), "3 per. Mov. Avg. (Sales)");
assert_eq!(crate::trend::auto_name(TrendlineKind::Exponential, "Sales"), "Expon. (Sales)");
}
fn lines_of(prims: &[Prim], color: Rgba) -> Vec<&Vec<[f32; 2]>> {
prims
.iter()
.filter_map(|p| match p {
Prim::Line { pts, color: c, .. } if *c == color => Some(pts),
_ => None,
})
.collect()
}
#[test]
fn line_chart_draws_trendline_forecast_and_labels() {
let m = ApproxMeasure;
let tc: Rgba = [1, 2, 3, 255];
let mut s = series("Sales", &[9.0, 7.0, 5.0, 3.0], [10, 20, 30, 255], ChartKind::Line);
s.trendlines =
vec![TrendlineData { spec: Trendline { forward: 1.0, display_equation: true, display_r_squared: true, ..Trendline::default() }, color: tc }];
let d = ChartData { categories: ["a", "b", "c", "d"].map(String::from).to_vec(), series: vec![s.clone()] };
let mut c = chart(ChartKind::Line);
c.legend = LegendPos::None; // keeps legend swatches out of the line counts
let prims = render(&c, &d, 600.0, 400.0, &m);
assert_sane(&prims, 600.0, 400.0);
let data = lines_of(&prims, [10, 20, 30, 255]);
let trend = lines_of(&prims, tc);
assert_eq!((data.len(), trend.len()), (1, 1));
let (d0, dn) = (data[0][0], data[0][3]);
let (t0, tn) = (trend[0][0], *trend[0].last().unwrap());
// Exact data: the trendline starts on the first point and runs through the last,
// then on one more category (the forecast slot).
assert!((t0[0] - d0[0]).abs() < 0.01 && (t0[1] - d0[1]).abs() < 0.01, "{t0:?} vs {d0:?}");
let step = (dn[0] - d0[0]) / 3.0;
assert!((tn[0] - (dn[0] + step)).abs() < 0.01, "forecast end {tn:?}, last point {dn:?}");
assert!(tn[1] > dn[1], "keeps falling past the data");
let t = texts(&prims);
assert!(t.contains(&"y = -2x + 11") && t.contains(&"R² = 1"), "{t:?}");
assert!(legend_entries(&chart(ChartKind::Line), &d).iter().any(|(n, col, sw)| n == "Linear (Sales)" && *col == tc && *sw == Swatch::Line));
// Not on chart kinds Excel doesn't offer trendlines on.
let pie = render(&chart(ChartKind::Pie), &d, 600.0, 400.0, &m);
assert!(lines_of(&pie, tc).is_empty());
// One point: nothing to fit, nothing drawn.
s.values.truncate(1);
let one = ChartData { categories: vec!["a".into()], series: vec![s] };
assert!(lines_of(&render(&c, &one, 600.0, 400.0, &m), tc).is_empty());
}
#[test]
fn scatter_trendlines_use_x_values_and_stay_in_the_plot() {
let m = ApproxMeasure;
let xs = [1.0, 2.0, 4.0, 8.0];
let mut s = series("P", &xs.map(|x| 4.0 * x * x), [10, 20, 30, 255], ChartKind::Scatter);
s.x = Some(xs.iter().map(|x| Some(*x)).collect());
let colors: [Rgba; 3] = [[1, 0, 0, 255], [2, 0, 0, 255], [3, 0, 0, 255]];
s.trendlines = vec![
TrendlineData {
spec: Trendline { kind: TrendlineKind::Power, backward: 0.5, display_equation: true, ..Trendline::default() },
color: colors[0],
},
// A steep exponential leaves the plot box and is clipped to it.
TrendlineData { spec: Trendline { kind: TrendlineKind::Exponential, forward: 30.0, ..Trendline::default() }, color: colors[1] },
TrendlineData { spec: Trendline { kind: TrendlineKind::MovingAverage(2), ..Trendline::default() }, color: colors[2] },
];
let d = ChartData { categories: vec![], series: vec![s] };
let mut c = chart(ChartKind::Scatter);
c.legend = LegendPos::None;
let prims = render(&c, &d, 600.0, 400.0, &m);
assert_sane(&prims, 600.0, 400.0);
for c in colors {
assert!(!lines_of(&prims, c).is_empty(), "{c:?} not drawn");
}
assert_eq!(lines_of(&prims, colors[2])[0].len(), 3, "moving average: one point per full window");
assert!(texts(&prims).contains(&"y = 4x^2"));
}
#[test]
fn treemap_and_histogram_shapes() {
let d = ChartData {
@@ -567,3 +876,29 @@ fn treemap_and_histogram_shapes() {
let bins = prims.iter().filter(|p| matches!(p, Prim::Rect { fill: Some([10, 20, 30, 255]), .. })).count();
assert_eq!(bins, 10);
}
#[test]
fn union_series_references() {
let mut wb = Workbook::new();
{
let s = wb.sheet_mut(0).unwrap();
for (r, (l, v)) in [("a", 1.0), ("b", 2.0), ("Total", 3.0), ("d", 4.0)].iter().enumerate() {
s.set_value(CellRef::new(r as u32, 0), Value::from(*l));
s.set_value(CellRef::new(r as u32, 1), Value::Number(*v));
}
}
let mut c = chart(ChartKind::ColumnClustered);
c.series = vec![Series {
name: Some("\"Sum of X\"".into()),
categories: Some("(Sheet1!$A$1:$A$2,Sheet1!$A$4)".into()),
values: "(Sheet1!$B$1:$B$2,Sheet1!$B$4)".into(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].values, vec![Some(1.0), Some(2.0), Some(4.0)]);
assert_eq!(d.series[0].name, "Sum of X");
assert_eq!(d.categories, vec!["a", "b", "d"]);
// Deeply nested parentheses from a file are bounded, not a crash.
c.series[0].values = format!("{}Sheet1!$B$1,Sheet1!$B$2{}", "(".repeat(5000), ")".repeat(5000));
let _ = resolve(&wb, 0, &c);
}
+278
View File
@@ -0,0 +1,278 @@
//! Trendline maths: least-squares fits behind chart trendlines and moving averages.
//!
//! Exponential, logarithmic and power trendlines are linear fits of transformed data
//! (`ln y` against `x`, `y` against `ln x`, `ln y` against `ln x`), the way Excel documents them;
//! points where the transform is undefined (non-positive values) are skipped and R² is reported
//! for the transformed fit. Polynomials solve the normal equations on centred, scaled x.
use gridcraft_model::{Trendline, TrendlineKind};
/// A fitted regression trendline.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TrendFit {
kind: TrendlineKind,
/// Coefficients `c0..=cd` of `Y = Σ cₖ·Xᵏ` in the transformed variables, for the equation.
pub coef: Vec<f64>,
/// The same polynomial in `u = (X - center) / scale`, for stable evaluation.
center: f64,
scale: f64,
a: Vec<f64>,
/// Coefficient of determination; `None` when undefined (all Y equal).
pub r2: Option<f64>,
}
/// Polynomial degree in the transformed variable; `None` for moving averages.
fn degree(k: TrendlineKind) -> Option<usize> {
match k {
TrendlineKind::Linear | TrendlineKind::Exponential | TrendlineKind::Logarithmic | TrendlineKind::Power => Some(1),
TrendlineKind::Polynomial(o) => Some(usize::from(o.clamp(2, 6))),
TrendlineKind::MovingAverage(_) => None,
}
}
fn log_x(k: TrendlineKind) -> bool {
matches!(k, TrendlineKind::Logarithmic | TrendlineKind::Power)
}
fn log_y(k: TrendlineKind) -> bool {
matches!(k, TrendlineKind::Exponential | TrendlineKind::Power)
}
/// Fits `t` to the points `(x, y)`. `None` for moving averages and degenerate data (too few
/// usable points, all x equal, a singular system, non-finite results).
pub(crate) fn fit_trendline(t: &Trendline, pts: &[(f64, f64)]) -> Option<TrendFit> {
let kind = t.kind;
let d = degree(kind)?;
let data: Vec<(f64, f64)> = pts
.iter()
.filter(|(x, y)| x.is_finite() && y.is_finite() && (!log_x(kind) || *x > 0.0) && (!log_y(kind) || *y > 0.0))
.map(|&(x, y)| (if log_x(kind) { x.ln() } else { x }, if log_y(kind) { y.ln() } else { y }))
.collect();
if data.len() < 2 || data.len() <= d {
return None;
}
// Set Intercept applies to linear, exponential and polynomial trendlines; it fixes Y at x = 0.
let fixed = match kind {
TrendlineKind::Linear | TrendlineKind::Polynomial(_) => t.intercept,
TrendlineKind::Exponential => t.intercept.filter(|b| *b > 0.0).map(f64::ln),
_ => None,
}
.filter(|b| b.is_finite());
let n = data.len() as f64;
let center = if fixed.is_some() { 0.0 } else { data.iter().map(|p| p.0).sum::<f64>() / n };
let scale = data.iter().map(|p| (p.0 - center).abs()).fold(0.0f64, f64::max);
if !(scale.is_finite() && scale > 0.0) {
return None;
}
let first = usize::from(fixed.is_some());
let b0 = fixed.unwrap_or(0.0);
// Normal equations over the unknown powers `first..=d` of u.
let m = d + 1 - first;
let mut ata = vec![vec![0.0f64; m]; m];
let mut aty = vec![0.0f64; m];
for &(x, y) in &data {
let u = (x - center) / scale;
let pows: Vec<f64> = (first..=d).map(|k| u.powi(k as i32)).collect();
for (i, pi) in pows.iter().enumerate() {
if let Some(v) = aty.get_mut(i) {
*v += pi * (y - b0);
}
for (j, pj) in pows.iter().enumerate() {
if let Some(v) = ata.get_mut(i).and_then(|r| r.get_mut(j)) {
*v += pi * pj;
}
}
}
}
let sol = solve(ata, aty)?;
let mut a = vec![b0; d + 1];
for (k, v) in sol.into_iter().enumerate() {
if let Some(slot) = a.get_mut(k + first) {
*slot = v;
}
}
let coef = expand(&a, center, scale)?;
let fit = TrendFit { kind, coef, center, scale, a, r2: None };
let mean = data.iter().map(|p| p.1).sum::<f64>() / n;
let (mut ss_res, mut ss_tot) = (0.0f64, 0.0f64);
for &(x, y) in &data {
ss_res += (y - fit.poly(x)).powi(2);
// A set intercept is LINEST(y - b, x, FALSE): the total sum of squares is not centred.
ss_tot += if fixed.is_some() { (y - b0).powi(2) } else { (y - mean).powi(2) };
}
let r2 = (ss_tot > 0.0 && ss_tot.is_finite() && ss_res.is_finite()).then(|| 1.0 - ss_res / ss_tot);
Some(TrendFit { r2, ..fit })
}
/// Gaussian elimination with partial pivoting; `None` when (nearly) singular.
fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
let n = b.len();
let big = a.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs()));
if !(big.is_finite() && big > 0.0) {
return None;
}
for col in 0..n {
let piv = (col..n).max_by(|&i, &j| {
let vi = a.get(i).and_then(|r| r.get(col)).map_or(0.0, |v| v.abs());
let vj = a.get(j).and_then(|r| r.get(col)).map_or(0.0, |v| v.abs());
vi.total_cmp(&vj)
})?;
a.swap(col, piv);
b.swap(col, piv);
let p = *a.get(col)?.get(col)?;
if !p.is_finite() || p.abs() <= big * 1e-13 {
return None;
}
let prow = a.get(col)?.clone();
let pb = *b.get(col)?;
for r in col + 1..n {
let row = a.get_mut(r)?;
let f = *row.get(col)? / p;
for (v, pv) in row.iter_mut().zip(&prow).skip(col) {
*v -= f * pv;
}
*b.get_mut(r)? -= f * pb;
}
}
let mut x = vec![0.0f64; n];
for r in (0..n).rev() {
let row = a.get(r)?;
let s: f64 = (r + 1..n).map(|c| row.get(c).copied().unwrap_or(0.0) * x.get(c).copied().unwrap_or(0.0)).sum();
let v = (b.get(r)? - s) / row.get(r)?;
*x.get_mut(r)? = v;
}
x.iter().all(|v| v.is_finite()).then_some(x)
}
/// Coefficients in X of `Σ aₖ·((X - c) / s)ᵏ` (binomial expansion).
fn expand(a: &[f64], c: f64, s: f64) -> Option<Vec<f64>> {
let mut out = vec![0.0f64; a.len()];
for (k, ak) in a.iter().enumerate() {
let lead = ak / s.powi(k as i32);
let mut binom = 1.0f64;
for j in 0..=k {
// C(k, j) · (-c)^(k-j) · X^j
if let Some(o) = out.get_mut(j) {
*o += lead * binom * (-c).powi((k - j) as i32);
}
binom = binom * (k - j) as f64 / (j + 1) as f64;
}
}
out.iter().all(|v| v.is_finite()).then_some(out)
}
impl TrendFit {
/// The fitted polynomial at transformed `x` (Horner in u).
fn poly(&self, x: f64) -> f64 {
let u = (x - self.center) / self.scale;
self.a.iter().rev().fold(0.0, |acc, c| acc * u + c)
}
/// The trendline's y at `x`; `None` outside its domain (x ≤ 0 for log/power) or when not finite.
pub(crate) fn eval(&self, x: f64) -> Option<f64> {
let xx = if log_x(self.kind) { if x > 0.0 { x.ln() } else { return None } } else { x };
let p = self.poly(xx);
let y = if log_y(self.kind) { p.exp() } else { p };
y.is_finite().then_some(y)
}
/// Equation label text, e.g. `y = 2x + 1`, `y = 0.5x² - 2x + 1`, `y = 3e^(0.2x)`.
pub(crate) fn equation(&self) -> String {
let c0 = self.coef.first().copied().unwrap_or(0.0);
let c1 = self.coef.get(1).copied().unwrap_or(0.0);
match self.kind {
TrendlineKind::Exponential => format!("y = {}e^({}x)", num_text(c0.exp()), num_text(c1)),
TrendlineKind::Power => format!("y = {}x^{}", num_text(c0.exp()), num_text(c1)),
TrendlineKind::Logarithmic => terms(&[(c1, "ln(x)"), (c0, "")]),
_ => {
let parts: Vec<(f64, &str)> = self.coef.iter().enumerate().rev().map(|(k, c)| (*c, POWERS.get(k).copied().unwrap_or("x"))).collect();
terms(&parts)
}
}
}
/// R² label text, e.g. `R² = 0.9963`.
pub(crate) fn r_squared(&self) -> String {
match self.r2 {
Some(r) => format!("R² = {}", num_text(r)),
None => "R² = #N/A".into(),
}
}
}
const POWERS: [&str; 7] = ["", "x", "x²", "x³", "x⁴", "x⁵", "x⁶"];
/// `y = a·t1 ± b·t2 …`, skipping terms whose coefficient shows as 0.
fn terms(parts: &[(f64, &str)]) -> String {
let mut s = String::from("y = ");
let mut first = true;
for (c, t) in parts {
let txt = num_text(c.abs());
if txt == "0" {
continue;
}
let neg = *c < 0.0;
if first {
if neg {
s.push('-');
}
} else {
s.push_str(if neg { " - " } else { " + " });
}
// A unit coefficient on a power of x is left out: `y = x² - x + 1`.
if txt != "1" || t.is_empty() {
s.push_str(&txt);
}
s.push_str(t);
first = false;
}
if first {
s.push('0');
}
s
}
/// A coefficient as trendline labels show it: up to four decimals, scientific when tiny or huge.
pub(crate) fn num_text(v: f64) -> String {
if !v.is_finite() {
return "#NUM!".into();
}
let a = v.abs();
if a == 0.0 {
return "0".into();
}
if !(1e-4..1e11).contains(&a) {
let s = format!("{v:.4E}");
let (mant, exp) = s.split_once('E').unwrap_or((s.as_str(), "0"));
let mant = trim_zeros(mant);
let e: i32 = exp.parse().unwrap_or(0);
return format!("{mant}E{}{:02}", if e < 0 { '-' } else { '+' }, e.unsigned_abs());
}
let s = trim_zeros(&format!("{v:.4}"));
if s == "-0" { "0".into() } else { s }
}
fn trim_zeros(s: &str) -> String {
if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s.to_string() }
}
/// Moving average of `period` consecutive points in plotted order: point `i` (from
/// `period - 1`) is `(xᵢ, mean(yᵢ₋ₚ₊₁..=yᵢ))`. Empty when there are fewer points than `period`.
pub(crate) fn moving_average(pts: &[(f64, f64)], period: u32) -> Vec<(f64, f64)> {
let p = period.clamp(2, 255) as usize;
let pts: Vec<(f64, f64)> = pts.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
pts.windows(p).filter_map(|w| w.last().map(|(x, _)| (*x, w.iter().map(|q| q.1).sum::<f64>() / p as f64))).collect()
}
/// Excel's automatic trendline name for the legend, e.g. `Linear (Sales)`.
pub(crate) fn auto_name(kind: TrendlineKind, series: &str) -> String {
let k = match kind {
TrendlineKind::Linear => "Linear".to_string(),
TrendlineKind::Exponential => "Expon.".into(),
TrendlineKind::Logarithmic => "Log.".into(),
TrendlineKind::Polynomial(_) => "Poly.".into(),
TrendlineKind::Power => "Power".into(),
TrendlineKind::MovingAverage(p) => format!("{} per. Mov. Avg.", p.clamp(2, 255)),
};
format!("{k} ({series})")
}
+3
View File
@@ -12,5 +12,8 @@ workspace = true
serde = { workspace = true }
thiserror = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3"
[dev-dependencies]
serde_json = { workspace = true }
+19 -4
View File
@@ -30,14 +30,14 @@ impl CellRef {
}
/// Moved by `(dr, dc)`, `None` when the result leaves the sheet.
pub fn offset(&self, dr: i64, dc: i64) -> Option<CellRef> {
let r = self.row as i64 + dr;
let c = self.col as i64 + dc;
let r = (self.row as i64).checked_add(dr)?;
let c = (self.col as i64).checked_add(dc)?;
if (0..MAX_ROWS as i64).contains(&r) && (0..MAX_COLS as i64).contains(&c) { Some(CellRef::new(r as u32, c as u32)) } else { None }
}
/// Moved by `(dr, dc)` and clamped to the sheet.
pub fn offset_clamped(&self, dr: i64, dc: i64) -> CellRef {
let r = (self.row as i64 + dr).clamp(0, MAX_ROWS as i64 - 1);
let c = (self.col as i64 + dc).clamp(0, MAX_COLS as i64 - 1);
let r = (self.row as i64).saturating_add(dr).clamp(0, MAX_ROWS as i64 - 1);
let c = (self.col as i64).saturating_add(dc).clamp(0, MAX_COLS as i64 - 1);
CellRef::new(r as u32, c as u32)
}
/// Parses `A1`, `$A$1`, `xfd1048576` (case-insensitive). `None` if malformed or out of range.
@@ -272,6 +272,21 @@ mod tests {
assert_eq!(a.iter().count(), 9);
}
#[test]
fn extreme_offsets() {
let cell = CellRef::new(1, 1);
for delta in [i64::MIN, i64::MAX] {
assert_eq!(cell.offset(delta, 0), None);
assert_eq!(cell.offset(0, delta), None);
assert_eq!(cell.offset(delta, delta), None);
}
assert_eq!(cell.offset_clamped(i64::MAX, i64::MAX), CellRef::new(MAX_ROWS - 1, MAX_COLS - 1));
assert_eq!(cell.offset_clamped(i64::MIN, i64::MIN), CellRef::new(0, 0));
assert_eq!(cell.offset_clamped(i64::MAX, i64::MIN), CellRef::new(MAX_ROWS - 1, 0));
assert_eq!(cell.offset_clamped(i64::MIN, i64::MAX), CellRef::new(0, MAX_COLS - 1));
assert_eq!(cell.offset(2, -1), Some(CellRef::new(3, 0)));
}
#[test]
fn offsets() {
assert_eq!(CellRef::new(0, 0).offset(-1, 0), None);
+98 -14
View File
@@ -39,6 +39,26 @@ pub fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
era * 146097 + doe - 719468
}
/// Milliseconds since the Unix epoch (UTC) from the system clock; `None` when the clock is unavailable.
/// On wasm32 `std::time::SystemTime::now` traps, so the browser clock is read through `Date.now()`.
#[allow(clippy::disallowed_methods)] // the std clock is read only off wasm
pub fn unix_now_ms() -> Option<f64> {
#[cfg(not(target_arch = "wasm32"))]
{
let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?;
Some(d.as_secs_f64() * 1000.0)
}
#[cfg(target_arch = "wasm32")]
{
Some(js_sys::Date::now())
}
}
/// Date serial (1900 system, with fraction) for a Unix time in milliseconds.
pub fn serial_from_unix_ms(ms: f64) -> f64 {
25569.0 + ms / 86_400_000.0
}
pub fn civil_from_days(z: i64) -> (i32, u32, u32) {
let z = z + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
@@ -69,26 +89,34 @@ pub fn days_in_month(y: i32, m: u32) -> u32 {
}
}
/// Days in a month of a date system's calendar: like [`days_in_month`], except that February
/// 1900 has 29 days in the 1900 system (serial 60 is the fictitious 1900-02-29).
pub fn days_in_month_in(sys: DateSystem, y: i32, m: u32) -> u32 {
if sys == DateSystem::D1900 && y == 1900 && m == 2 { 29 } else { days_in_month(y, m) }
}
/// Serial for a date. Month and day overflow roll over like `DATE()` (month 13 = January next
/// year, day 0 = last day of the previous month). `None` before the epoch or after 9999-12-31.
/// year, day 0 = last day of the previous month), in the date system's own calendar: in the 1900
/// system February 1900 has 29 days, so `(1900, 2, 29)` and `(1900, 3, 0)` are serial 60.
/// `None` before the epoch or after 9999-12-31.
pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
// DATE(): years 0–1899 are added to 1900.
let mut y = if (0..1900).contains(&year) { year + 1900 } else { year };
let m0 = month - 1;
y += m0.div_euclid(12);
let y = if (0..1900).contains(&year) { year + 1900 } else { year };
let m0 = month.checked_sub(1)?;
let y = y.checked_add(m0.div_euclid(12))?;
let m = m0.rem_euclid(12) + 1;
if !(1900..=9999).contains(&y) && sys == DateSystem::D1900 || !(1904..=9999).contains(&y) && sys == DateSystem::D1904 {
return None;
}
let base = days_from_civil(y as i32, m as u32, 1) + day - 1;
let serial = match sys {
DateSystem::D1900 => {
let s = base - UNIX_1899_12_30;
// Before the fictitious 1900-02-29 serials are one lower than the day count from 1899-12-30.
if s <= 60 { s - 1 } else { s }
}
DateSystem::D1904 => base - UNIX_1904_01_01,
let first = days_from_civil(y as i32, m as u32, 1);
// Serial of the first of the month; the day (and any overflow) counts on from there.
let first = match sys {
// Up to February 1900 the serial is one lower than the day count from 1899-12-30: the
// fictitious 1900-02-29 (serial 60) comes before 1 March.
DateSystem::D1900 => first - UNIX_1899_12_30 - i64::from(y == 1900 && m <= 2),
DateSystem::D1904 => first - UNIX_1904_01_01,
};
let serial = first.checked_add(day)?.checked_sub(1)?;
if !(0..=2_958_465).contains(&serial) {
return None;
}
@@ -97,7 +125,7 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
/// Date/time from a serial. `None` for negative or too-large serials.
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
if !serial.is_finite() || serial < 0.0 || serial >= 2_958_466.0 {
if !serial.is_finite() || !(0.0..2_958_466.0).contains(&serial) {
return None;
}
let mut day = serial.floor() as i64;
@@ -152,6 +180,14 @@ pub const WEEKDAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Th
mod tests {
use super::*;
#[test]
fn serial_from_unix_time() {
assert_eq!(serial_from_unix_ms(0.0), 25569.0);
// 2026-10-10T12:00:00Z
assert_eq!(serial_from_unix_ms(1_791_633_600_000.0), 46305.5);
assert!(unix_now_ms().is_some_and(|ms| serial_from_unix_ms(ms) > 46305.0));
}
#[test]
fn known_serials() {
let s = DateSystem::D1900;
@@ -168,10 +204,58 @@ mod tests {
assert_eq!(serial_from_ymd(DateSystem::D1904, 2000, 1, 1), Some(35064.0));
}
#[test]
fn fictitious_1900_02_29() {
// Excel's 1900 calendar has a 29 February 1900 (serial 60); day and month overflow count
// through it.
let s = DateSystem::D1900;
assert_eq!(serial_from_ymd(s, 1900, 2, 29), Some(60.0));
assert_eq!(serial_from_ymd(s, 1900, 3, 0), Some(60.0));
assert_eq!(serial_from_ymd(s, 1900, 2, 30), Some(61.0));
assert_eq!(serial_from_ymd(s, 1900, 1, 60), Some(60.0));
assert_eq!(serial_from_ymd(s, 1900, 1, 61), Some(61.0));
assert_eq!(serial_from_ymd(s, 1900, 1, 400), Some(400.0));
assert_eq!(serial_from_ymd(s, 1900, 4, -30), Some(61.0));
assert_eq!(serial_from_ymd(s, 1900, 4, -31), Some(60.0));
assert_eq!(serial_from_ymd(s, 1900, 3, -1), Some(59.0));
assert_eq!(serial_from_ymd(s, 1901, -10, 29), Some(60.0));
assert_eq!(serial_from_ymd(s, 1900, 1, 0), Some(0.0));
assert_eq!(serial_from_ymd(s, 1900, 1, -1), None);
assert_eq!(serial_from_ymd(s, 1900, 0, 1), None);
// Later years keep the real calendar.
assert_eq!(serial_from_ymd(s, 1901, 2, 29), serial_from_ymd(s, 1901, 3, 1));
assert_eq!(serial_from_ymd(s, 1904, 2, 29), Some(1521.0));
// Every serial up to 1900-12-31 comes back from its own year, month and day.
for serial in 0..=366 {
let d = datetime_from_serial(s, serial as f64).unwrap();
assert_eq!(serial_from_ymd(s, d.year as i64, d.month as i64, d.day as i64), Some(serial as f64), "{d:?}");
}
assert_eq!(days_in_month_in(s, 1900, 2), 29);
assert_eq!(days_in_month_in(s, 1901, 2), 28);
assert_eq!(days_in_month_in(DateSystem::D1904, 1900, 2), 28);
// The 1904 system has no fictitious day: 1904 is a real leap year.
let s = DateSystem::D1904;
assert_eq!(serial_from_ymd(s, 1904, 2, 29), Some(59.0));
assert_eq!(serial_from_ymd(s, 1904, 3, 0), Some(59.0));
assert_eq!(serial_from_ymd(s, 1904, 3, 1), Some(60.0));
assert_eq!(serial_from_ymd(s, 1904, 1, 0), None);
assert_eq!(serial_from_ymd(s, 1900, 2, 29), None);
}
#[test]
fn hostile_month_and_day() {
let s = DateSystem::D1900;
assert_eq!(serial_from_ymd(s, 2000, i64::MIN, 1), None);
assert_eq!(serial_from_ymd(s, 2000, i64::MAX, 1), None);
assert_eq!(serial_from_ymd(s, 2000, 1, i64::MAX), None);
assert_eq!(serial_from_ymd(s, 2000, 1, i64::MIN), None);
assert_eq!(serial_from_ymd(s, i64::MAX, 1, 1), None);
}
#[test]
fn roundtrip() {
let s = DateSystem::D1900;
for serial in [1.0, 59.0, 61.0, 36526.0, 46302.0, 2958465.0] {
for serial in [1.0, 59.0, 60.0, 61.0, 36526.0, 46302.0, 2958465.0] {
let d = datetime_from_serial(s, serial).unwrap();
assert_eq!(serial_from_ymd(s, d.year as i64, d.month as i64, d.day as i64), Some(serial));
}
+1 -1
View File
@@ -10,4 +10,4 @@ pub mod value;
pub use addr::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, col_to_letters, letters_to_col};
pub use date::DateSystem;
pub use value::{Array, CellError, Value, compare, compare_text, number_to_text, sort_compare};
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
+32 -10
View File
@@ -263,25 +263,23 @@ fn parse_date(t: &str, sys: DateSystem) -> Option<(f64, &'static str)> {
}
fn valid_ymd(sys: DateSystem, y: i64, m: i64, d: i64) -> Option<f64> {
if !(1..=12).contains(&m) || d < 1 {
// Dates before 1900 stay text (`DATE()` would add 1900 to such a year).
if !(1..=12).contains(&m) || d < 1 || y < 1900 {
return None;
}
let max = if y == 1900 && m == 2 { 29 } else { crate::date::days_in_month(y as i32, m as u32) as i64 };
let max = crate::date::days_in_month_in(sys, y as i32, m as u32) as i64;
if d > max {
return None;
}
serial_from_ymd(sys, y, m, d)
}
/// The year used for dates typed without one. Fixed per process from the system clock when
/// available (wasm without clock falls back to 2026).
/// The year used for dates typed without one, from the system clock (browser clock on wasm).
/// Falls back to 2026 only when no clock is available.
pub fn current_year() -> i64 {
#[cfg(not(target_arch = "wasm32"))]
{
if let Ok(d) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
let days = (d.as_secs() / 86400) as i64;
return crate::date::civil_from_days(days).0 as i64;
}
if let Some(ms) = crate::date::unix_now_ms() {
let days = (ms / 86_400_000.0).floor() as i64;
return crate::date::civil_from_days(days).0 as i64;
}
2026
}
@@ -289,6 +287,8 @@ pub fn current_year() -> i64 {
fn parse_datetime(t: &str, sys: DateSystem) -> Option<(f64, Option<&'static str>)> {
if let Some((tf, secs, ampm)) = parse_time(t) {
let f = match (secs, ampm) {
// 24 hours or more: elapsed hours, so 25:00 shows as 25:00:00, not 1:00.
_ if tf >= 1.0 => "[h]:mm:ss",
(false, false) => "h:mm",
(true, false) => "h:mm:ss",
(false, true) => "h:mm AM/PM",
@@ -351,10 +351,32 @@ mod tests {
assert_eq!(p("7-Oct-2026").value, Value::Number(46302.0));
assert_eq!(p("Oct 7, 2026").value, Value::Number(46302.0));
assert_eq!(p("2/30/2026").value, Value::text("2/30/2026"));
assert_eq!(p("7/4/1776").value, Value::text("7/4/1776"));
assert_eq!(p("1776-07-04").value, Value::text("1776-07-04"));
assert_eq!(p("4-Jul-1776").value, Value::text("4-Jul-1776"));
assert_eq!(p("12/31/1899").value, Value::text("12/31/1899"));
assert_eq!(p("1/1/1900").value, Value::Number(1.0));
assert_eq!(p("12:00").value, Value::Number(0.5));
assert_eq!(p("6:00 PM").value, Value::Number(0.75));
assert_eq!(p("12:00 AM").value, Value::Number(0.0));
assert_eq!(p("10/7/2026 18:00").value, Value::Number(46302.75));
assert_eq!(p("25:00").value, Value::Number(25.0 / 24.0));
assert_eq!(p("25:00").format, Some("[h]:mm:ss"));
assert_eq!(p("23:59").format, Some("h:mm"));
}
#[test]
fn fictitious_1900_02_29() {
// Excel accepts 29 February 1900 (serial 60) and keeps 1 March 1900 at 61.
assert_eq!(p("2/29/1900").value, Value::Number(60.0));
assert_eq!(p("1900-02-29").value, Value::Number(60.0));
assert_eq!(p("29-Feb-1900").value, Value::Number(60.0));
assert_eq!(p("2/28/1900").value, Value::Number(59.0));
assert_eq!(p("3/1/1900").value, Value::Number(61.0));
assert_eq!(p("2/29/1901").value, Value::text("2/29/1901"));
assert_eq!(p("2/30/1900").value, Value::text("2/30/1900"));
// The 1904 system starts after it.
assert_eq!(parse_input("2/29/1900", DateSystem::D1904).value, Value::text("2/29/1900"));
assert_eq!(parse_input("2/29/1904", DateSystem::D1904).value, Value::Number(59.0));
}
}
+31 -3
View File
@@ -288,13 +288,13 @@ impl Value {
pub fn compare(a: &Value, b: &Value) -> Ordering {
match (a, b) {
(Value::Empty, Value::Empty) => Ordering::Equal,
(Value::Empty, Value::Number(n)) => 0.0f64.partial_cmp(n).unwrap_or(Ordering::Equal),
(Value::Number(n), Value::Empty) => n.partial_cmp(&0.0).unwrap_or(Ordering::Equal),
(Value::Empty, Value::Number(n)) => compare_numbers(0.0, *n),
(Value::Number(n), Value::Empty) => compare_numbers(*n, 0.0),
(Value::Empty, Value::Text(t)) => "".cmp(&t.to_lowercase() as &str),
(Value::Text(t), Value::Empty) => (t.to_lowercase() as String).as_str().cmp(""),
(Value::Empty, Value::Bool(b)) => false.cmp(b),
(Value::Bool(b), Value::Empty) => b.cmp(&false),
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
(Value::Number(x), Value::Number(y)) => compare_numbers(*x, *y),
(Value::Text(x), Value::Text(y)) => compare_text(x, y),
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
(Value::Error(x), Value::Error(y)) => x.code().cmp(&y.code()),
@@ -302,6 +302,23 @@ pub fn compare(a: &Value, b: &Value) -> Ordering {
}
}
/// Compares numbers the way Excel does: both are rounded to 15 significant digits first, so binary
/// noise such as `0.1+0.2` versus `0.3` counts as equal.
pub fn compare_numbers(a: f64, b: f64) -> Ordering {
fn round15(x: f64) -> f64 {
if !x.is_finite() || x == 0.0 { x } else { format!("{x:.14e}").parse().unwrap_or(x) }
}
if a == b {
return Ordering::Equal;
}
// Numbers further apart than the 15th digit can't round together, and rounding keeps their
// order: skip the text round trip (this is on the sort and lookup hot path).
if (a - b).abs() > a.abs().max(b.abs()) * 1e-13 {
return a.partial_cmp(&b).unwrap_or(Ordering::Equal);
}
round15(a).partial_cmp(&round15(b)).unwrap_or(Ordering::Equal)
}
/// Case-insensitive text order (Unicode lowercase).
pub fn compare_text(a: &str, b: &str) -> Ordering {
let mut ai = a.chars().flat_map(char::to_lowercase);
@@ -410,6 +427,17 @@ mod tests {
assert_eq!(CellError::parse("#div/0!"), Some(CellError::Div0));
}
#[test]
fn numbers_compare_at_15_significant_digits() {
let num = Value::Number;
assert_eq!(compare(&num(0.1 + 0.2), &num(0.3)), Ordering::Equal);
assert_eq!(compare(&num(1.1 * 3.0), &num(3.3)), Ordering::Equal);
assert_eq!(compare(&num(1.0), &num(1.0 + 1e-16)), Ordering::Equal);
assert_ne!(compare(&num(0.1 + 0.2), &num(0.3)), Ordering::Greater);
assert_eq!(compare(&num(1.0), &num(1.00000000000001)), Ordering::Less);
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
}
#[test]
fn arrays() {
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).unwrap();
+4
View File
@@ -23,3 +23,7 @@ gridcraft-xlsx = { workspace = true }
gridcraft-chart = { workspace = true }
gridcraft-pdf = { workspace = true }
image = { workspace = true }
[dev-dependencies]
gridcraft-xlsx = { workspace = true, features = ["test-support"] }
zip = { workspace = true }
+2
View File
@@ -1,6 +1,8 @@
//! Performance scenarios on large workbooks (release build):
//! `cargo run --release -p gridcraft-engine --example perf -- [rows]`
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
use std::time::Instant;
use gridcraft_engine::Session;
+1 -1
View File
@@ -1,6 +1,6 @@
//! Excel's ribbon and menu tree (feature names only), used as the parity metric: a catalog
//! entry counts as done when a command with its id is registered. `cargo xtask parity` writes
//! `docs/parity.md` from this list.
//! `docs/parity-checklist.md` from this list.
/// (id, tab, group, label)
pub const CATALOG: &[(&str, &str, &str, &str)] = &[
+119 -14
View File
@@ -90,10 +90,7 @@ fn lerp(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] {
]
}
/// Number of icons in a set name like `3TrafficLights1`, `5Quarters`.
pub fn icon_count(set: &str) -> usize {
set.chars().next().and_then(|c| c.to_digit(10)).unwrap_or(3) as usize
}
pub use gridcraft_model::icon_count;
impl CfCache {
pub fn new() -> Self {
@@ -144,7 +141,8 @@ impl CfCache {
CfOperator::GreaterOrEqual => compare(&v, &av) != std::cmp::Ordering::Less,
CfOperator::LessOrEqual => compare(&v, &av) != std::cmp::Ordering::Greater,
};
(ok && !v.is_empty()).then_some(style.as_ref())
// As in Excel, a blank cell compares as 0 (or ""), and an error never matches.
(ok && !v.is_error()).then_some(style.as_ref())
}
CfRule::Expression { formula, style } => {
gridcraft_calc::evaluate(wb, sheet, c, &relative(formula, first, c)).to_bool().unwrap_or(false).then_some(style.as_ref())
@@ -154,7 +152,7 @@ impl CfCache {
CfRule::BeginsWith { text: t, style } => text.to_lowercase().starts_with(&t.to_lowercase()).then_some(style.as_ref()),
CfRule::EndsWith { text: t, style } => text.to_lowercase().ends_with(&t.to_lowercase()).then_some(style.as_ref()),
CfRule::Blanks { style } => (v.is_empty() || text.trim().is_empty()).then_some(style.as_ref()),
CfRule::NoBlanks { style } => (!v.is_empty()).then_some(style.as_ref()),
CfRule::NoBlanks { style } => (!v.is_empty() && !text.trim().is_empty()).then_some(style.as_ref()),
CfRule::Errors { style } => v.is_error().then_some(style.as_ref()),
CfRule::NoErrors { style } => (!v.is_error()).then_some(style.as_ref()),
CfRule::Duplicate { style } => {
@@ -261,11 +259,18 @@ impl CfCache {
CfRule::IconSet { set, thresholds, reverse, show_value } => {
if let Some(n) = v.as_f64() {
let k = icon_count(set);
let cuts: Vec<f64> = if thresholds.len() + 1 == k {
thresholds.iter().map(|t| threshold(wb, sheet, c, &st, t)).collect()
} else {
(1..k).map(|i| percentile(&st.sorted, i as f64 * 100.0 / k as f64)).collect()
// One threshold per icon, the first being the lower bound (as in the file);
// also accept the lower bound left out, else Excel's defaults.
let defaults;
let lower = match thresholds.len() {
n if n == k => thresholds.get(1..).unwrap_or_default(),
n if n + 1 == k => thresholds.as_slice(),
_ => {
defaults = default_icon_thresholds(set);
defaults.get(1..).unwrap_or_default()
}
};
let cuts: Vec<f64> = lower.iter().map(|t| threshold(wb, sheet, c, &st, t)).collect();
let mut idx = cuts.iter().filter(|cut| n >= **cut).count();
if *reverse {
idx = k - 1 - idx.min(k - 1);
@@ -281,10 +286,12 @@ impl CfCache {
};
if let Some(st) = matched_style {
any = true;
out.style = Some(match out.style.take() {
None => st.clone(),
Some(prev) => prev,
});
// Every matching rule applies; where two set the same part, the rule with the
// higher priority (seen first) wins.
match &mut out.style {
None => out.style = Some(st.clone()),
Some(prev) => layer_under(prev, st),
}
if cf.stop_if_true {
break;
}
@@ -294,6 +301,39 @@ impl CfCache {
}
}
/// Adds the parts `lower` sets that `style` leaves unset (differential styles: default parts
/// are unset).
fn layer_under(style: &mut Style, lower: &Style) {
if style.fill.pattern == PatternType::None {
style.fill = lower.fill;
}
if style.font.color == Color::Auto {
style.font.color = lower.font.color;
}
style.font.bold |= lower.font.bold;
style.font.italic |= lower.font.italic;
style.font.strike |= lower.font.strike;
if style.font.underline == Underline::None {
style.font.underline = lower.font.underline;
}
let b = &mut style.borders;
for (dst, src) in [
(&mut b.left, lower.borders.left),
(&mut b.right, lower.borders.right),
(&mut b.top, lower.borders.top),
(&mut b.bottom, lower.borders.bottom),
(&mut b.diag_down, lower.borders.diag_down),
(&mut b.diag_up, lower.borders.diag_up),
] {
if dst.is_none() {
*dst = src;
}
}
if style.num_fmt.as_str() == "General" {
style.num_fmt = lower.num_fmt.clone();
}
}
/// Shifts a rule formula written for the top-left cell of the range to `c`.
fn relative(f: &str, first: CellRef, c: CellRef) -> String {
if first == c {
@@ -306,3 +346,68 @@ fn relative(f: &str, first: CellRef, c: CellRef) -> String {
Err(_) => f.to_string(),
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn every_matching_rule_applies() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[200], [400], [510]]})).unwrap();
let rule = |op: &str, value: &str, preset: &str| json!({"range": "A1:A3", "rule": {"type": "cellIs", "operator": op, "value": value, "preset": preset}});
s.execute("home.conditionalFormat", rule("greaterThan", "300", "lightRedFill")).unwrap();
s.execute("home.conditionalFormat", rule("greaterThan", "500", "redBorder")).unwrap();
let d = s.doc().unwrap();
let mut cache = CfCache::new();
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style);
assert!(look("A1").is_none());
let only_fill = look("A2").unwrap();
assert_eq!(only_fill.fill.pattern, PatternType::Solid);
assert!(only_fill.borders.top.is_none());
let both = look("A3").unwrap();
assert_eq!(both.fill, only_fill.fill);
assert!(!both.borders.top.is_none());
}
#[test]
fn cell_value_rules_on_blanks_and_errors() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[3, "=NA()"], [null, 7], ["=NA()", null], [" ", null], [7, null]]})).unwrap();
let rule = |range: &str, r: serde_json::Value| json!({"range": range, "rule": r});
s.execute("home.conditionalFormat", rule("A1:A5", json!({"type": "cellIs", "operator": "less", "value": "5", "preset": "lightRedFill"})))
.unwrap();
s.execute("home.conditionalFormat", rule("A1:A5", json!({"type": "noBlanks", "preset": "redBorder"}))).unwrap();
s.execute("home.conditionalFormat", rule("B1:B2", json!({"type": "cellIs", "operator": "greater", "value": "5", "preset": "lightRedFill"})))
.unwrap();
let d = s.doc().unwrap();
let mut cache = CfCache::new();
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style);
let fill = |st: Option<Style>| st.is_some_and(|st| st.fill.pattern == PatternType::Solid);
let border = |st: Option<Style>| st.is_some_and(|st| !st.borders.top.is_none());
// Less than 5: 3 and the blank cell (as 0), not #N/A.
assert_eq!([look("A1"), look("A2"), look("A3"), look("A5")].map(fill), [true, true, false, false]);
// Greater than 5: 7, not #N/A.
assert_eq!([look("B1"), look("B2")].map(fill), [false, true]);
// No blanks: neither the empty cell nor the one holding a space.
assert_eq!([look("A1"), look("A2"), look("A4")].map(border), [true, false, false]);
}
#[test]
fn cell_value_operator_names() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[3], [7]]})).unwrap();
let rule = |op: &str| json!({"range": "A1:A2", "rule": {"type": "cellIs", "operator": op, "value": "5", "preset": "lightRedFill"}});
s.execute("home.conditionalFormat", rule("lessThan")).unwrap();
assert!(s.execute("home.conditionalFormat", rule("smaller")).is_err());
let d = s.doc().unwrap();
let mut cache = CfCache::new();
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style).is_some();
assert_eq!([look("A1"), look("A2")], [true, false]);
}
}
+323
View File
@@ -0,0 +1,323 @@
//! Reading the HTML flavour of the system clipboard on paste.
//!
//! Spreadsheets put an HTML table on the clipboard next to the tab-separated text. The text holds
//! what each cell *shows* ("Rp10,000.00"), which en-US input parsing can't always turn back into a
//! number. The HTML of the common sources also carries the underlying number as a cell attribute:
//! `x:num="10000"` (Excel, Excel for the web) and `sdval="10000"` (LibreOffice Calc). Paste uses
//! it to keep such cells numeric (#257). Only the table structure, the cell text and these two
//! attributes are read; everything else in the markup is ignored.
/// Largest clipboard HTML we look at; past this the paste uses the plain text alone.
const MAX_HTML: usize = 16 * 1024 * 1024;
/// Widest `colspan` honoured (the sheet's column count).
const MAX_SPAN: usize = gridcraft_core::MAX_COLS as usize;
/// One table cell: its visible text and the number the source recorded for it, if any.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct HtmlCell {
pub text: String,
pub num: Option<f64>,
}
/// The cells of the first table in `html`, row by row; a cell spanning columns is followed by
/// empty cells so positions line up with the tab-separated text. Empty when there is no table.
pub(crate) fn table_cells(html: &str) -> Vec<Vec<HtmlCell>> {
let mut rows: Vec<Vec<HtmlCell>> = Vec::new();
if html.len() > MAX_HTML {
return rows;
}
let mut cell: Option<(HtmlCell, usize)> = None;
let mut in_table = false;
let mut rest = html;
while !rest.is_empty() {
let Some(lt) = rest.find('<') else {
if let Some((c, _)) = cell.as_mut() {
c.text.push_str(rest);
}
break;
};
if let Some((c, _)) = cell.as_mut() {
c.text.push_str(rest.get(..lt).unwrap_or_default());
}
rest = rest.get(lt..).unwrap_or_default();
if let Some(after) = rest.strip_prefix("<!--") {
rest = after.find("-->").and_then(|e| after.get(e + 3..)).unwrap_or_default();
continue;
}
let Some(gt) = tag_end(rest) else { break };
let tag = rest.get(1..gt).unwrap_or_default();
rest = rest.get(gt + 1..).unwrap_or_default();
let closing = tag.starts_with('/');
let body = tag.trim_start_matches('/');
let name_end = body.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(body.len());
let name = body.get(..name_end).unwrap_or_default().to_ascii_lowercase();
let attrs = body.get(name_end..).unwrap_or_default();
match (name.as_str(), closing) {
("style" | "script", false) => {
// Raw text: skip to the closing tag.
let end = format!("</{name}");
rest = find_ci(rest, &end).and_then(|i| rest.get(i..)).unwrap_or_default();
}
("table", false) => {
if in_table {
break; // a nested table: the outer one is the clipboard grid, stop here
}
in_table = true;
}
("table", true) => {
finish(&mut rows, &mut cell);
if !rows.is_empty() {
break;
}
in_table = false;
}
("tr", false) if in_table => {
finish(&mut rows, &mut cell);
rows.push(Vec::new());
}
("td" | "th", false) if in_table => {
finish(&mut rows, &mut cell);
if rows.is_empty() {
rows.push(Vec::new());
}
let num = attr(attrs, "x:num").or_else(|| attr(attrs, "sdval")).and_then(|v| v.trim().parse::<f64>().ok()).filter(|n| n.is_finite());
let span = attr(attrs, "colspan").and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1).clamp(1, MAX_SPAN);
cell = Some((HtmlCell { text: String::new(), num }, span));
}
("td" | "th", true) | ("tr", true) => finish(&mut rows, &mut cell),
("br", _) => {
if let Some((c, _)) = cell.as_mut() {
c.text.push(' ');
}
}
_ => {}
}
}
finish(&mut rows, &mut cell);
rows
}
/// Closes the open cell (if any) into the last row, decoding its text.
fn finish(rows: &mut Vec<Vec<HtmlCell>>, cell: &mut Option<(HtmlCell, usize)>) {
let Some((mut c, span)) = cell.take() else { return };
c.text = decode(&c.text);
if rows.is_empty() {
rows.push(Vec::new());
}
if let Some(row) = rows.last_mut() {
row.push(c);
let room = MAX_SPAN.saturating_sub(row.len());
row.extend(std::iter::repeat_n(HtmlCell::default(), span.saturating_sub(1).min(room)));
}
}
/// Byte index of the `>` that closes the tag `rest` starts with; a `>` inside a quoted attribute
/// value (an inline `mso-number-format` condition such as `[>=1000]`) doesn't end it.
fn tag_end(rest: &str) -> Option<usize> {
let mut quote: Option<char> = None;
for (i, c) in rest.char_indices() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '"' | '\'') => quote = Some(c),
(None, '>') => return Some(i),
_ => {}
}
}
None
}
/// Case-insensitive ASCII search.
fn find_ci(hay: &str, needle: &str) -> Option<usize> {
let (h, n) = (hay.as_bytes(), needle.as_bytes());
if n.is_empty() || h.len() < n.len() {
return None;
}
(0..=h.len() - n.len()).find(|&i| h.get(i..i + n.len()).is_some_and(|w| w.eq_ignore_ascii_case(n)))
}
/// The value of attribute `name` in a tag's attribute text (quoted or bare). A bare attribute
/// without `=` has no value.
fn attr<'a>(attrs: &'a str, name: &str) -> Option<&'a str> {
let mut s = attrs;
loop {
s = s.trim_start_matches(|c: char| c.is_whitespace() || c == '/');
if s.is_empty() {
return None;
}
let key_end = s.find(|c: char| c.is_whitespace() || c == '=' || c == '/').unwrap_or(s.len());
let key = s.get(..key_end).unwrap_or_default();
s = s.get(key_end..).unwrap_or_default().trim_start();
let mut value = None;
if let Some(after) = s.strip_prefix('=') {
let after = after.trim_start();
let (v, next) = match after.chars().next() {
Some(q @ ('"' | '\'')) => {
let inner = after.get(1..).unwrap_or_default();
let end = inner.find(q).unwrap_or(inner.len());
(inner.get(..end).unwrap_or_default(), inner.get(end + 1..).unwrap_or_default())
}
_ => {
let end = after.find(char::is_whitespace).unwrap_or(after.len());
(after.get(..end).unwrap_or_default(), after.get(end..).unwrap_or_default())
}
};
value = Some(v);
s = next;
}
if key.eq_ignore_ascii_case(name) {
return value;
}
if key.is_empty() && value.is_none() {
// Stray character (e.g. a lone '='): skip it so the loop always advances.
let mut chars = s.chars();
chars.next();
s = chars.as_str();
}
}
}
/// HTML text to plain text: entities decoded, whitespace runs (and `<br>`) collapsed to one
/// space, trimmed. The text only serves to match a cell with the tab-separated text.
fn decode(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut rest = raw;
while let Some(amp) = rest.find('&') {
out.push_str(rest.get(..amp).unwrap_or_default());
rest = rest.get(amp..).unwrap_or_default();
let semi = rest.get(..12).unwrap_or(rest).find(';');
let entity = semi.and_then(|e| rest.get(1..e));
let ch = entity.and_then(|e| match e {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some('\u{a0}'),
_ => {
let n = e
.strip_prefix("#x")
.or_else(|| e.strip_prefix("#X"))
.map(|h| u32::from_str_radix(h, 16))
.or_else(|| e.strip_prefix('#').map(str::parse::<u32>));
n.and_then(Result::ok).and_then(char::from_u32)
}
});
match (ch, semi) {
(Some(c), Some(e)) => {
out.push(c);
rest = rest.get(e + 1..).unwrap_or_default();
}
_ => {
out.push('&');
rest = rest.get(1..).unwrap_or_default();
}
}
}
out.push_str(rest);
let mut text = String::with_capacity(out.len());
let mut space = false;
for c in out.chars() {
if c.is_whitespace() && c != '\u{a0}' {
space = true;
continue;
}
if space && !text.is_empty() {
text.push(' ');
}
space = false;
text.push(c);
}
text
}
/// Same-looking text: non-breaking spaces as spaces, whitespace runs collapsed, trimmed.
pub(crate) fn normalized(s: &str) -> String {
s.replace('\u{a0}', " ").split_whitespace().collect::<Vec<_>>().join(" ")
}
/// A number format that shows `n` exactly as `shown` ("Rp10,000.00" for 10000 →
/// `"Rp"#,##0.00`), inferred from the text around the digits. `None` unless the format renders
/// `shown` back character for character.
pub(crate) fn format_for(shown: &str, n: f64) -> Option<String> {
let shown = normalized(shown);
let start = shown.find(|c: char| c.is_ascii_digit())?;
let end = shown.rfind(|c: char| c.is_ascii_digit()).map(|i| i + 1)?;
let core = shown.get(start..end)?;
let mut prefix = shown.get(..start)?.to_string();
let suffix = shown.get(end..)?;
if core.chars().any(|c| !(c.is_ascii_digit() || c == ',' || c == '.')) {
return None;
}
if n < 0.0 {
// A one-section format shows the minus sign itself, in front of everything.
prefix = prefix.strip_prefix('-')?.to_string();
}
let decimals = core.split_once('.').map_or(0, |(_, f)| f.len());
let mut code = String::new();
let quote = |s: &str| if s.is_empty() { String::new() } else { format!("\"{}\"", s.replace('"', "")) };
code.push_str(&quote(&prefix));
code.push_str(if core.contains(',') { "#,##0" } else { "0" });
if decimals > 0 {
code.push('.');
code.push_str(&"0".repeat(decimals.min(30)));
}
code.push_str(&quote(suffix));
let rendered = gridcraft_numfmt::text_function(&gridcraft_core::Value::number(n), &code, gridcraft_core::date::DateSystem::D1900).ok()?;
(normalized(&rendered) == shown).then_some(code)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_excel_and_libreoffice_cell_values() {
let excel = r#"<html><head><style>td{mso-number-format:General}</style></head><body><table>
<!--StartFragment--><tr height=20><td class=xl65 x:num="10000">Rp10,000.00</td><td x:str>Name</td></tr>
<tr><td colspan=2 x:num="2.5">2.50 &amp; up</td><td>x</td></tr><!--EndFragment--></table></body></html>"#;
let rows = table_cells(excel);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0][0], HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) });
assert_eq!(rows[0][1], HtmlCell { text: "Name".into(), num: None });
assert_eq!(rows[1].len(), 3, "colspan keeps the next cell in its column");
assert_eq!(rows[1][0].text, "2.50 & up");
assert_eq!(rows[1][2].text, "x");
let calc = r#"<table cellspacing="0" border="0"><colgroup width="85"></colgroup><tr>
<td height="17" align="right" sdval="10000" sdnum="1033;0;[$Rp-421]#,##0.00"><font face="Liberation Sans">Rp10,000.00</font></td></tr></table>"#;
assert_eq!(table_cells(calc), vec![vec![HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) }]]);
let quoted_gt = r#"<table><tr><td style='mso-number-format:"\[>=1000\]0"' x:num="1500">1500</td></tr></table>"#;
assert_eq!(table_cells(quoted_gt), vec![vec![HtmlCell { text: "1500".into(), num: Some(1500.0) }]]);
}
#[test]
fn hostile_markup_does_not_panic() {
for html in [
"",
"<",
"<td",
"<table><td x:num=>",
"<table><tr><td colspan=999999999>a",
"&#xFFFFFFFF;&",
"<table><td x:num='1e999'>1</td>",
"<!--",
"<style>",
"<table><table><td>",
] {
let _ = table_cells(html);
}
assert_eq!(table_cells("<table><td x:num='1e999'>1</td></table>")[0][0].num, None);
assert!(table_cells("<table><tr><td colspan=999999999>a</td></tr></table>")[0].len() <= MAX_SPAN);
}
#[test]
fn infers_a_format_that_shows_the_same_text() {
assert_eq!(format_for("Rp10,000.00", 10000.0).as_deref(), Some("\"Rp\"#,##0.00"));
assert_eq!(format_for("1 234 kr", 1234.0), None, "space grouping is not reproduced");
assert_eq!(format_for("10.000,00 €", 10000.0), None, "comma decimals don't render back in en-US");
assert_eq!(format_for("-Rp5", -5.0).as_deref(), Some("\"Rp\"0"));
assert_eq!(format_for("12 EUR", 12.0).as_deref(), Some("0\" EUR\""));
}
}
File diff suppressed because it is too large Load Diff
+418 -49
View File
@@ -8,6 +8,7 @@ use gridcraft_model::*;
use serde_json::{Value as Json, json};
use super::*;
use crate::outline;
use crate::selection::current_region;
pub fn specs() -> Vec<CommandSpec> {
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"data.filter",
"Filter",
["Data", "Sort & Filter"],
Some("Cmd+Shift+F"),
Some("Ctrl+Shift+L"),
"{range?} toggles AutoFilter on the current region",
has_doc,
toggle_filter
@@ -74,10 +75,37 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd),
cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → invalid cells", has_doc, circle_invalid),
cmd!("data.group", "Group", ["Data", "Outline"], Some("Cmd+Shift+K"), "{rows?: \"2:5\" | cols?: \"B:C\"}", has_doc, |s, p| group(s, p, true)),
cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Cmd+Shift+J"), "{rows? | cols?}", has_doc, |s, p| group(s, p, false)),
cmd!("data.hideDetail", "Hide Detail", ["Data", "Outline"], None, "{rows? | cols?}", has_doc, |s, p| detail(s, p, true)),
cmd!("data.showDetail", "Show Detail", ["Data", "Outline"], None, "{rows? | cols?}", has_doc, |s, p| detail(s, p, false)),
cmd!(
"data.group",
"Group",
["Data", "Outline"],
Some("Alt+Shift+Right"),
"{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default)}",
has_doc,
|s, p| group(s, p, true)
),
cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Alt+Shift+Left"), "{rows? | cols? | by?: rows|cols}", has_doc, |s, p| group(
s, p, false
)),
cmd!(
"data.hideDetail",
"Hide Detail",
["Data", "Outline"],
None,
"{rows? | cols? | by?, level?: 1-7} (the innermost group, or the one at `level`, holding the lines or summarised by them)",
has_doc,
|s, p| detail(s, p, true)
),
cmd!("data.showDetail", "Show Detail", ["Data", "Outline"], None, "{rows? | cols? | by?, level?: 1-7}", has_doc, |s, p| detail(s, p, false)),
cmd!(
"data.showLevels",
"Show Outline Levels",
[],
None,
"{rows?: 1-8, cols?: 1-8} (1 shows only the top-level summaries, as the outline's level buttons)",
has_doc,
show_levels
),
cmd!(
"data.subtotal",
"Subtotal",
@@ -112,7 +140,8 @@ fn data_range(s: &Session, p: &Json) -> Result<RangeRef> {
}
let sel = d.selection.current();
if !sel.is_single() {
let used = sh.used_range().unwrap_or(sel);
// An empty sheet has no data to work on: just the active cell.
let Some(used) = sh.used_range() else { return Ok(RangeRef::cell(d.selection.active)) };
return Ok(sel.intersection(&used).unwrap_or(sel));
}
Ok(current_region(sh, d.selection.active))
@@ -247,7 +276,7 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
let pos = |v: &Value| v.as_text().and_then(|t| list.iter().position(|x| x.eq_ignore_ascii_case(t))).unwrap_or(usize::MAX);
pos(va).cmp(&pos(vb))
} else if case && va.is_text() && vb.is_text() {
va.as_text().unwrap_or("").cmp(vb.as_text().unwrap_or(""))
sort_compare(va, vb).then_with(|| case_order(va.as_text().unwrap_or(""), vb.as_text().unwrap_or("")))
} else {
sort_compare(va, vb)
};
@@ -265,6 +294,7 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
// Move whole lines (cells with formulas adjusted for relative references).
let lanes: Vec<u32> = if by_cols { (body.start.row..=body.end.row).collect() } else { (body.start.col..=body.end.col).collect() };
let mut moved: Vec<(CellRef, Option<Cell>)> = Vec::with_capacity(body.count() as usize);
let mut pictures = Vec::new();
for (dst_i, &src_i) in order.iter().enumerate() {
for &k in &lanes {
let src = line(src_i, k);
@@ -277,21 +307,52 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
let shifted = gridcraft_formula::adjust::shift_relative(e, dst.row as i64 - src.row as i64, dst.col as i64 - src.col as i64);
c.formula = Some(Arc::new(Formula::from_expr(shifted)));
}
if let Some(picture) = sh.cell_pictures.get(&src) {
pictures.push((dst, picture.clone()));
}
moved.push((dst, cell));
}
}
// Row heights travel with rows.
let heights: Vec<Option<LineInfo>> =
if by_cols { vec![] } else { order.iter().map(|&i| sh.rows.get(&(body.start.row + i)).copied()).collect() };
// Floating objects anchored inside the sorted body travel with their lines, unless they
// are pinned absolutely ("Don't move or size with cells", `editAs="absolute"`). Reordering
// is the inverse of `order`: `dst_of[src] = dst`.
let dst_of: Vec<u32> = {
let mut v = vec![0u32; order.len()];
for (dst_i, &src_i) in order.iter().enumerate() {
if let Some(slot) = v.get_mut(src_i as usize) {
*slot = dst_i as u32;
}
}
v
};
// The object's own geometry (its top-left anchor cell, offset and size) is read from the
// pre-sort `sh`; a two-cell object's bottom-right cell is derived from its size here so it
// can be re-fitted to the lines it spans after the sort.
let objs: Vec<Anchor> =
sh.images.iter().map(|o| o.anchor).chain(sh.charts.iter().map(|o| o.anchor)).chain(sh.shapes.iter().map(|o| o.anchor)).collect();
let descs: Vec<(u32, u32, f32, f32)> = objs
.iter()
.map(|a| {
let x2 = sh.col_left(a.cell.col) + a.dx as f64 + a.width.max(0.0) as f64;
let y2 = sh.row_top(a.cell.row) + a.dy as f64 + a.height.max(0.0) as f64;
let tc = sh.col_at(x2);
let tr = sh.row_at(y2);
(tc, tr, (x2 - sh.col_left(tc)) as f32, (y2 - sh.row_top(tr)) as f32)
})
.collect();
let shm = cx.sheet_mut(sheet)?;
for (c, cell) in &moved {
match cell {
Some(x) => shm.cells.set(*c, x.clone()),
Some(x) => shm.set_cell(*c, x.clone()),
None => {
shm.cells.remove(*c);
shm.remove_cell(*c);
}
}
}
shm.cell_pictures.extend(pictures);
for (i, h) in heights.into_iter().enumerate() {
let row = body.start.row + i as u32;
match h {
@@ -305,6 +366,34 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
}
}
}
// Re-anchor floating objects now that the row heights are final. `objs` was collected as
// images ++ charts ++ shapes, so the same index maps straight onto each vec.
// Only objects anchored inside the sorted block move: within its lines on the sort axis
// and within its span on the other axis (a picture beside the block stays put).
let (b0, b1) = if by_cols { (body.start.col, body.end.col) } else { (body.start.row, body.end.row) };
let (o0, o1) = if by_cols { (body.start.row, body.end.row) } else { (body.start.col, body.end.col) };
let ni = shm.images.len();
let nch = shm.charts.len();
for (i, (a, desc)) in objs.into_iter().zip(descs).enumerate() {
let other = if by_cols { a.cell.row } else { a.cell.col };
if other < o0 || other > o1 {
continue;
}
let na = sorted_anchor(shm, a, desc, by_cols, b0, b1, &dst_of);
if na != a {
if i < ni {
if let Some(o) = shm.images.get_mut(i) {
o.anchor = na;
}
} else if i < ni + nch {
if let Some(o) = shm.charts.get_mut(i - ni) {
o.anchor = na;
}
} else if let Some(o) = shm.shapes.get_mut(i - ni - nch) {
o.anchor = na;
}
}
}
for (c, _) in moved {
cx.changed.push((sheet, c));
}
@@ -314,6 +403,35 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
Ok(json!({"sorted": body.a1()}))
}
/// Re-anchor one floating object for a sort. `bottom` is the object's bottom-right line and the
/// offset of that corner inside it, measured before the sort. `map` (via `dst_of`) translates a
/// line index on the moving axis and is the identity outside `b0..=b1`. `sh` is the post-sort
/// grid (row heights already reordered), so re-fitting uses the heights the object lands on.
/// Objects pinned absolutely ("Don't move or size with cells") never move; "move but don't size"
/// keeps its size; "move and size" is re-fitted when its whole extent stays inside the body.
fn sorted_anchor(sh: &Sheet, a: Anchor, bottom: (u32, u32, f32, f32), by_cols: bool, b0: u32, b1: u32, dst_of: &[u32]) -> Anchor {
if a.mode == AnchorMode::Absolute {
return a;
}
let (tc, tr, tdx, tdy) = bottom;
let map = |v: u32| -> u32 { if v >= b0 && v <= b1 { dst_of.get((v - b0) as usize).map_or(v, |&d| b0 + d) } else { v } };
let (axis_start, axis_end) = if by_cols { (a.cell.col, tc) } else { (a.cell.row, tr) };
if axis_start < b0 || axis_start > b1 {
return a;
}
let (nr, nc) = if by_cols { (a.cell.row, map(a.cell.col)) } else { (map(a.cell.row), a.cell.col) };
if a.mode == AnchorMode::MoveAndSize && axis_end >= b0 && axis_end <= b1 {
let (nbr, nbc) = if by_cols { (tr, map(tc)) } else { (map(tr), tc) };
let x1 = sh.col_left(nc) + a.dx as f64;
let y1 = sh.row_top(nr) + a.dy as f64;
let x2 = sh.col_left(nbc) + tdx as f64;
let y2 = sh.row_top(nbr) + tdy as f64;
Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode: a.mode }
} else {
Anchor { cell: CellRef::new(nr, nc), ..a }
}
}
// ---------------------------------------------------------------- filter
fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
@@ -326,6 +444,9 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
let sh = cx.sheet_mut(sheet)?;
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
t.filter_button = !t.filter_button;
if !t.filter_button {
t.filter.clear();
}
}
Ok(Json::Null)
});
@@ -341,7 +462,16 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
Ok(json!({"filter": false}))
});
}
let r = data_range(s, p)?;
let mut r = data_range(s, p)?;
// A selected header row filters the data below it (#201).
if p.get("range").is_none() && r.height() == 1 {
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let below = current_region(sh, r.start).end.row;
if below > r.end.row {
r = RangeRef::new(r.start, CellRef::new(below, r.end.col));
}
}
edit(s, |cx| {
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
Ok(json!({"filter": true, "range": r.a1()}))
@@ -497,6 +627,8 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
},
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
// Icons are not evaluated here: the row keeps its current visibility.
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
};
if !ok {
visible = false;
@@ -563,6 +695,12 @@ pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool
seen.into_iter().map(|((_, t), on)| (t, on)).collect()
}
/// Case-sensitive tie-break for text that is equal ignoring case: as in Excel, lowercase sorts
/// before uppercase at the first letter that differs in case.
fn case_order(a: &str, b: &str) -> Ordering {
a.chars().zip(b.chars()).find(|(x, y)| x != y).map_or(Ordering::Equal, |(x, y)| y.is_lowercase().cmp(&x.is_lowercase()))
}
fn sort_key(v: &Value) -> (u8, i64, String) {
match v {
Value::Number(n) => (0, (n * 1e6) as i64, String::new()),
@@ -579,6 +717,9 @@ fn remove_duplicates(s: &mut Session, p: &Json) -> Result<Json> {
let r = data_range(s, p)?;
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
// Rows and columns past the data are blank: only the part with data is compared (whole
// columns compared a million blank rows and reported them as removed duplicates).
let r = sh.used_range().and_then(|u| r.intersection(&u)).unwrap_or(RangeRef::cell(r.start));
let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r));
let cols: Vec<u32> = p
.get("columns")
@@ -592,29 +733,41 @@ fn remove_duplicates(s: &mut Session, p: &Json) -> Result<Json> {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
let mut seen = std::collections::HashSet::new();
let mut keep: Vec<u32> = Vec::new();
// Cells are compared by the text they show, as in Excel: the same date in two formats
// isn't a duplicate, while 1.01 and 1.02 shown as 1.0 are.
let shown = |c: CellRef| crate::display::format(&sh.value(c), cx.wb.styles.get(sh.style_id(c)).num_fmt.as_str(), &cx.wb).text;
for row in start..=r.end.row {
let key: Vec<String> = cols.iter().map(|c| sh.value(CellRef::new(row, *c)).display().to_lowercase()).collect();
let key: Vec<String> = cols.iter().map(|c| shown(CellRef::new(row, *c)).to_lowercase()).collect();
if seen.insert(key) {
keep.push(row);
} else {
removed += 1;
}
}
let pictures: Vec<_> = keep
.iter()
.enumerate()
.flat_map(|(i, row)| {
(r.start.col..=r.end.col)
.filter_map(move |col| sh.cell_pictures.get(&CellRef::new(*row, col)).map(|p| (CellRef::new(start + i as u32, col), p.clone())))
})
.collect();
let rows: Vec<Vec<Option<Cell>>> =
keep.iter().map(|row| (r.start.col..=r.end.col).map(|c| sh.cell(CellRef::new(*row, c)).cloned()).collect()).collect();
let shm = cx.sheet_mut(sheet)?;
for row in start..=r.end.row {
for c in r.start.col..=r.end.col {
shm.cells.remove(CellRef::new(row, c));
shm.remove_cell(CellRef::new(row, c));
}
}
for (i, cells) in rows.into_iter().enumerate() {
for (j, cell) in cells.into_iter().enumerate() {
if let Some(cell) = cell {
shm.cells.set(CellRef::new(start + i as u32, r.start.col + j as u32), cell);
shm.set_cell(CellRef::new(start + i as u32, r.start.col + j as u32), cell);
}
}
}
shm.cell_pictures.extend(pictures);
for c in RangeRef::new(CellRef::new(start, r.start.col), r.end).iter() {
cx.changed.push((sheet, c));
}
@@ -639,7 +792,7 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result<Json> {
p.get("fixedWidths").and_then(Json::as_array).map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as usize)).collect());
let consecutive = bool_param(p, "treatConsecutive").unwrap_or(false);
let quote = str_param(p, "textQualifier").and_then(|q| q.chars().next()).unwrap_or('"');
let dest = cell_param(p, "destination").unwrap_or(r.start);
let dest = cell_param_on(s, p, "destination", sheet)?.unwrap_or(r.start);
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
let mut out: Vec<(CellRef, String)> = Vec::new();
@@ -662,13 +815,12 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result<Json> {
}
}
for (c, t) in out {
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(c)).cloned();
let cell = super::edit::input_to_cell(&t, old.as_ref(), &mut cx.wb).unwrap_or(None);
let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None);
let shm = cx.sheet_mut(sheet)?;
match cell {
Some(x) => shm.cells.set(c, x),
Some(x) => shm.set_cell(c, x),
None => {
shm.cells.remove(c);
shm.remove_cell(c);
}
}
cx.changed.push((sheet, c));
@@ -683,9 +835,15 @@ fn split_delimited(text: &str, delims: &[char], consecutive: bool, quote: char)
let mut cur = String::new();
let mut in_q = false;
let mut last_delim = false;
for c in text.chars() {
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == quote {
in_q = !in_q;
if in_q && chars.peek() == Some(&quote) {
cur.push(quote);
chars.next();
} else {
in_q = !in_q;
}
continue;
}
if !in_q && delims.contains(&c) {
@@ -718,16 +876,42 @@ fn op_param(s: Option<&str>) -> CfOperator {
}
}
/// `r` minus `cut`, as up to four non-overlapping rectangles.
fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec<RangeRef> {
let Some(i) = r.intersection(cut) else { return vec![r] };
let mut out = Vec::new();
if i.start.row > r.start.row {
out.push(RangeRef::new(r.start, CellRef::new(i.start.row - 1, r.end.col)));
}
if i.end.row < r.end.row {
out.push(RangeRef::new(CellRef::new(i.end.row + 1, r.start.col), r.end));
}
if i.start.col > r.start.col {
out.push(RangeRef::new(CellRef::new(i.start.row, r.start.col), CellRef::new(i.end.row, i.start.col - 1)));
}
if i.end.col < r.end.col {
out.push(RangeRef::new(CellRef::new(i.start.row, i.end.col + 1), CellRef::new(i.end.row, r.end.col)));
}
out
}
/// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges.
fn remove_validation_cells(validations: &mut Vec<Validation>, cuts: &[RangeRef]) {
for dv in validations.iter_mut() {
for cut in cuts {
dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect();
}
}
validations.retain(|d| !d.ranges.is_empty());
}
fn validation(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
if bool_param(p, "clear").unwrap_or(false) {
return edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
for dv in sh.validations.iter_mut() {
dv.ranges.retain(|r| !ranges.iter().any(|x| x.contains_range(r)));
}
sh.validations.retain(|d| !d.ranges.is_empty());
remove_validation_cells(&mut sh.validations, &ranges);
Ok(Json::Null)
});
}
@@ -767,10 +951,7 @@ fn validation(s: &mut Session, p: &Json) -> Result<Json> {
};
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
for v in sh.validations.iter_mut() {
v.ranges.retain(|r| !ranges.iter().any(|x| x.contains_range(r)));
}
sh.validations.retain(|d| !d.ranges.is_empty());
remove_validation_cells(&mut sh.validations, &ranges);
sh.validations.push(dv.clone());
Ok(Json::Null)
})
@@ -804,10 +985,26 @@ pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -
return None;
}
let v = gridcraft_core::parse::parse_input(input, wb.date_system).value;
let num = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, f).to_number().ok();
// The formulas are written for the first cell of the range and see the value being entered,
// as in Excel (a custom `=A1>10` on A1:A9 checks A5's new value at A5).
let first = dv.ranges.first().map(|r| r.start).unwrap_or(at);
let entered;
let wb = if sh.value(at) == v {
wb
} else {
let mut w = wb.clone();
if let Some(sh) = w.sheet_mut(sheet) {
let style = sh.style_id(at);
sh.cells.set(at, Cell { value: v.clone(), style, ..Default::default() });
}
entered = w;
&entered
};
let eval = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, &formula_at(f, first, at));
let num = |f: &str| eval(f).to_number().ok();
let ok = match dv.kind {
ValidationKind::List => list_items(wb, sheet, dv).iter().any(|x| x.eq_ignore_ascii_case(input)),
ValidationKind::Custom => gridcraft_calc::evaluate(wb, sheet, at, &dv.f1).to_bool().unwrap_or(false),
ValidationKind::Custom => eval(&dv.f1).to_bool().unwrap_or(false),
ValidationKind::TextLength => {
let n = input.chars().count() as f64;
compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num))
@@ -834,6 +1031,21 @@ pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -
Some((dv.clone(), msg))
}
/// A formula written for `first`, as seen from `at` (relative references shifted).
fn formula_at(f: &str, first: CellRef, at: CellRef) -> String {
if first == at {
return f.to_string();
}
match gridcraft_formula::parse(f.trim_start_matches('=')) {
Ok(e) => gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative(
e,
at.row as i64 - first.row as i64,
at.col as i64 - first.col as i64,
)),
Err(_) => f.to_string(),
}
}
fn compare_op(op: CfOperator, n: f64, a: Option<f64>, b: Option<f64>) -> bool {
let Some(a) = a else { return false };
match op {
@@ -850,7 +1062,7 @@ fn compare_op(op: CfOperator, n: f64, a: Option<f64>, b: Option<f64>) -> bool {
fn validate_cmd(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let input = str_param(p, "input").unwrap_or("");
match check_validation(&d.wb, d.wb.active_sheet, at, input) {
None => Ok(json!({"ok": true})),
@@ -868,7 +1080,7 @@ fn circle_invalid(s: &mut Session, _: &Json) -> Result<Json> {
let r = sh.used_range().and_then(|u| r.intersection(&u));
let Some(r) = r else { continue };
for c in r.iter().take(100_000) {
let text = sh.cell(c).map(|x| x.input_text()).unwrap_or_default();
let text = sh.input_text(c);
if !text.is_empty() && check_validation(&d.wb, sheet, c, &text).is_some() {
bad_cells.push(c.a1());
}
@@ -888,7 +1100,12 @@ fn outline_lines(s: &Session, p: &Json) -> Result<(bool, u32, u32)> {
return Ok((false, r.start.col, r.end.col));
}
let r = s.doc()?.selection.current();
if r.is_full_cols() && !r.is_full_rows() { Ok((false, r.start.col, r.end.col)) } else { Ok((true, r.start.row, r.end.row)) }
match str_param(p, "by") {
Some("rows") => Ok((true, r.start.row, r.end.row)),
Some("cols" | "columns") => Ok((false, r.start.col, r.end.col)),
_ if r.is_full_cols() && !r.is_full_rows() => Ok((false, r.start.col, r.end.col)),
_ => Ok((true, r.start.row, r.end.row)),
}
}
fn group(s: &mut Session, p: &Json, on: bool) -> Result<Json> {
@@ -897,39 +1114,94 @@ fn group(s: &mut Session, p: &Json, on: bool) -> Result<Json> {
let si = cx.sheet_index();
let sh = cx.sheet_mut(si)?;
let map = if rows { &mut sh.rows } else { &mut sh.cols };
for i in a..=b.min(a + 1_048_575) {
let b = b.min(a.saturating_add(1_048_575));
for i in a..=b {
let e = map.entry(i).or_default();
e.outline = if on { (e.outline + 1).min(7) } else { e.outline.saturating_sub(1) };
e.outline = if on { (e.outline + 1).min(outline::MAX_LEVEL) } else { e.outline.saturating_sub(1) };
if !on && e.outline == 0 {
e.hidden = false;
}
}
// A summary line whose group is gone has nothing left to collapse.
if !on
&& !outline::groups(map).iter().any(|g| g.end == b)
&& let Some(e) = map.get_mut(&b.saturating_add(1))
{
e.collapsed = false;
}
Ok(Json::Null)
})
}
/// Hide Detail / Show Detail: the innermost group (or the one at `level`) that holds the lines, or
/// failing that the one they are the summary of. Hiding marks the summary line collapsed (the
/// + button, saved to XLSX); showing keeps inner groups that were collapsed on their own collapsed.
fn detail(s: &mut Session, p: &Json, hide: bool) -> Result<Json> {
let (rows, a, b) = outline_lines(s, p)?;
let want = p.get("level").and_then(Json::as_u64).map(|l| l.min(outline::MAX_LEVEL as u64) as u8);
edit(s, |cx| {
let si = cx.sheet_index();
let sh = cx.sheet_mut(si)?;
let map = if rows { &mut sh.rows } else { &mut sh.cols };
// Expand to the whole group around the selection.
let level = (a..=b).filter_map(|i| map.get(&i).map(|e| e.outline)).max().unwrap_or(0);
if level == 0 {
return Ok(Json::Null);
let all = outline::groups(map);
let level_ok = |g: &outline::OutlineGroup| want.is_none_or(|l| g.level == l);
let pick = |hit: &dyn Fn(&outline::OutlineGroup) -> bool| -> Vec<outline::OutlineGroup> {
let hits: Vec<_> = all.iter().filter(|g| level_ok(g) && hit(g)).copied().collect();
let deepest = hits.iter().map(|g| g.level).max().unwrap_or(0);
hits.into_iter().filter(|g| g.level == deepest).collect()
};
let mut chosen = pick(&|g| g.start <= b && g.end >= a);
if chosen.is_empty() {
chosen = pick(&|g| g.summary() >= a && g.summary() <= b);
}
let mut lo = a;
while lo > 0 && map.get(&(lo - 1)).is_some_and(|e| e.outline >= level) {
lo -= 1;
for g in chosen {
// Inner groups collapsed on their own (their summary marked), before this one changes.
let inner: Vec<outline::OutlineGroup> = all
.iter()
.filter(|o| o.level > g.level && o.start >= g.start && o.end <= g.end && o.summary() != g.summary())
.filter(|o| map.get(&o.summary()).is_some_and(|e| e.collapsed))
.copied()
.collect();
for i in g.start..=g.end {
if let Some(e) = map.get_mut(&i) {
e.hidden = hide || inner.iter().any(|o| o.contains(i));
}
}
if hide {
map.entry(g.summary()).or_default().collapsed = true;
} else if let Some(e) = map.get_mut(&g.summary()) {
e.collapsed = false;
}
}
let mut hi = b;
while map.get(&(hi + 1)).is_some_and(|e| e.outline >= level) {
hi += 1;
}
for i in lo..=hi {
if let Some(e) = map.get_mut(&i) {
e.hidden = hide;
cx.structural = true;
Ok(Json::Null)
})
}
/// The outline's level buttons: show rows / columns down to outline level `n` (1 = only the
/// top-level summaries); deeper detail is hidden and its summary lines marked collapsed.
fn show_levels(s: &mut Session, p: &Json) -> Result<Json> {
let level = |k: &str| p.get(k).and_then(Json::as_u64).map(|n| n.clamp(1, outline::MAX_LEVEL as u64 + 1) as u8);
let (rows, cols) = (level("rows"), level("cols"));
if rows.is_none() && cols.is_none() {
return Err(EngineError::BadParams {
cmd: "data.showLevels".into(),
msg: "give `rows` or `cols`: the outline level to show (1 = top-level summaries only)".into(),
});
}
edit(s, |cx| {
let si = cx.sheet_index();
let sh = cx.sheet_mut(si)?;
for (map, n) in [(&mut sh.rows, rows), (&mut sh.cols, cols)] {
let Some(n) = n else { continue };
let groups = outline::groups(map);
for e in map.values_mut().filter(|e| e.outline > 0) {
e.hidden = e.outline >= n;
}
// Inner groups come first, so a summary line shared with the group around it ends up
// as that outer group says.
for g in groups {
map.entry(g.summary()).or_default().collapsed = g.level >= n;
}
}
cx.structural = true;
@@ -1006,6 +1278,103 @@ fn subtotal(s: &mut Session, p: &Json) -> Result<Json> {
mod tests {
use super::*;
#[test]
fn partial_validation_edits_keep_the_rest_of_the_old_rule() {
let mut s = Session::new();
s.new_workbook();
let rule = |range: &str, lo: &str, hi: &str| json!({"range": range, "type": "whole", "operator": "between", "formula1": lo, "formula2": hi});
let ok = |s: &mut Session, cell: &str, input: &str| {
s.execute("data.validate", json!({"cell": cell, "input": input})).unwrap()["ok"] == json!(true)
};
s.execute("data.validation", rule("B1:B3", "1", "10")).unwrap();
s.execute("data.validation", json!({"range": "B2", "clear": true})).unwrap();
assert!(ok(&mut s, "B2", "999"));
assert!(!ok(&mut s, "B1", "999"));
assert!(!ok(&mut s, "B3", "999"));
s.execute("data.validation", rule("B2:B4", "100", "200")).unwrap();
for cell in ["B2", "B3", "B4"] {
assert!(ok(&mut s, cell, "150"), "{cell}");
assert!(!ok(&mut s, cell, "5"), "{cell}");
}
assert!(ok(&mut s, "B1", "5"));
assert!(!ok(&mut s, "B1", "150"));
}
/// Rows 5:8 grouped, with 6:7 grouped again inside (0-based 4..=7 and 5..=6).
fn nested_rows() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("data.group", json!({"rows": "5:8"})).unwrap();
s.execute("data.group", json!({"rows": "6:7"})).unwrap();
s
}
/// (hidden, collapsed) of 0-based rows.
fn row_state(s: &Session, rows: std::ops::RangeInclusive<u32>) -> Vec<(bool, bool)> {
let sh = s.doc().unwrap().wb.active().unwrap();
rows.map(|r| sh.rows.get(&r).map(|l| (l.hidden, l.collapsed)).unwrap_or_default()).collect()
}
#[test]
fn hide_detail_marks_the_summary_collapsed_and_show_detail_keeps_inner_groups_collapsed() {
let mut s = nested_rows();
s.execute("data.hideDetail", json!({"rows": "6:7", "level": 2})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]);
s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
s.execute("data.showDetail", json!({"rows": "6:7", "level": 2})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(false, false); 5]);
// Each step is one undoable command.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(row_state(&s, 5..=7), [(true, false), (true, false), (false, true)]);
}
#[test]
fn hide_detail_on_the_summary_row_collapses_the_group_above_it() {
let mut s = nested_rows();
s.execute("data.hideDetail", json!({"rows": "9:9"})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, false), (false, true)]);
}
#[test]
fn show_levels_collapses_and_expands_to_a_level() {
let mut s = nested_rows();
s.execute("data.showLevels", json!({"rows": 1})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]);
s.execute("data.showLevels", json!({"rows": 2})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
s.execute("data.showLevels", json!({"rows": 3})).unwrap();
assert_eq!(row_state(&s, 4..=8), [(false, false); 5]);
// Columns are separate; no level at all is an error rather than a guess.
s.execute("data.group", json!({"cols": "C:E"})).unwrap();
s.execute("data.showLevels", json!({"cols": 1})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!((2..=4).all(|c| sh.cols.get(&c).is_some_and(|l| l.hidden)));
assert!(sh.cols.get(&5).is_some_and(|l| l.collapsed));
assert_eq!(row_state(&s, 4..=4), [(false, false)]);
assert!(s.execute("data.showLevels", json!({})).is_err());
}
#[test]
fn group_by_columns_for_a_block_of_cells() {
let mut s = Session::new();
s.new_workbook();
s.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
s.execute("data.group", json!({"by": "cols"})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!((1..=2).all(|c| sh.cols.get(&c).is_some_and(|l| l.outline == 1)));
assert!(sh.rows.values().all(|l| l.outline == 0));
}
#[test]
fn group_shortcuts_are_the_windows_ones() {
let sc = |id: &str| specs().into_iter().find(|c| c.id == id).and_then(|c| c.shortcut);
assert_eq!(sc("data.group"), Some("Alt+Shift+Right"));
assert_eq!(sc("data.ungroup"), Some("Alt+Shift+Left"));
}
#[test]
fn split() {
assert_eq!(split_delimited("a,b,,c", &[','], false, '"'), ["a", "b", "", "c"]);
+10 -1
View File
@@ -82,10 +82,19 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
let shape = Shape {
id,
kind: ShapeKind::Ink,
anchor: Anchor { cell, dx, dy, width: (maxx - minx).max(1.0) as f32, height: (maxy - miny).max(1.0) as f32 },
anchor: Anchor {
cell,
dx,
dy,
width: (maxx - minx).max(1.0) as f32,
height: (maxy - miny).max(1.0) as f32,
// Ink is a freehand mark: pinned where it was drawn, it does not follow cells.
mode: gridcraft_model::AnchorMode::Absolute,
},
fill: Color::from_hex(&format!("#{:02X}0000", width.round().clamp(0.0, 255.0) as u8)).unwrap_or_default(),
line: Color::from_hex(&color).unwrap_or(Color::rgb(0x1F, 0x5F, 0xC9)),
text,
format: Default::default(),
};
edit(s, |cx| {
cx.sheet_mut(si)?.shapes.push(shape);
+412 -85
View File
@@ -1,6 +1,6 @@
//! Cell entry, selection, undo/redo, clipboard, clear, fill, find & replace.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
use gridcraft_core::{CellRef, MAX_ROWS, RangeRef, Value};
use gridcraft_model::{Cell, Formula, StyleId};
use serde_json::{Value as Json, json};
@@ -40,14 +40,14 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "edit.goToSpecial", "Go To Special…", ["Home", "Editing", "Find & Select"], None, "{kind: blanks|constants|formulas|comments|lastCell|currentRegion|visible|conditionalFormats|dataValidation|errors|numbers|text}", has_doc, go_to_special),
cmd!(noundo "edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{steps?: 1}", can_undo, undo),
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Y"), "{steps?: 1}", can_redo, redo),
cmd!(noundo "edit.copy", "Copy", ["Home", "Clipboard"], Some("Cmd+C"), "{range?}", has_doc, copy),
cmd!(noundo "edit.cut", "Cut", ["Home", "Clipboard"], Some("Cmd+X"), "{range?}", has_doc, cut),
cmd!(noundo "edit.copy", "Copy", ["Home", "Clipboard"], Some("Cmd+C"), "{range?, html?: bool} → {range, text, html?} (html: a styled HTML table, only when requested and small enough)", has_doc, copy),
cmd!(noundo "edit.cut", "Cut", ["Home", "Clipboard"], Some("Cmd+X"), "{range?, html?: bool} → {range, text, html?} (html: a styled HTML table, only when requested and small enough)", has_doc, cut),
cmd!(
"edit.paste",
"Paste",
["Home", "Clipboard"],
Some("Cmd+V"),
"{at?: \"C3\", text?: \"tab-separated text from the system clipboard\"}",
"{at?: \"C3\", text?: \"tab-separated text from the system clipboard\", html?: \"the clipboard's HTML flavour; cells the source recorded as numbers (x:num, sdval) stay numbers\"}",
has_doc,
paste
),
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"AutoFill",
[],
None,
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|copy|formats|values}: the fill-handle drag",
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies)",
has_doc,
auto_fill
),
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
fill_series
),
cmd!("edit.flashFill", "Flash Fill", ["Home", "Editing", "Fill"], Some("Cmd+E"), "{range?}", has_doc, flash_fill),
cmd!("edit.flashFill", "Flash Fill", ["Home", "Editing", "Fill"], Some("Ctrl+E"), "{range?}", has_doc, flash_fill),
cmd!(noundo "edit.find", "Find…", ["Home", "Editing", "Find & Select"], Some("Cmd+F"), "{what, matchCase?, wholeCell?, lookIn?: formulas|values, byColumns?, all?: bool, within?: sheet|workbook}", has_doc, find),
cmd!(
"edit.replace",
@@ -119,9 +119,10 @@ pub fn specs() -> Vec<CommandSpec> {
// ---------------------------------------------------------------- entry
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
/// format). Errors when the formula can't be parsed.
pub(crate) fn input_to_cell(input: &str, old: Option<&Cell>, wb: &mut gridcraft_model::Workbook) -> Result<Option<Cell>> {
let style = old.map(|c| c.style).unwrap_or_default();
/// format). Inherits the destination's cell, row or column style, including its number
/// format, before parsing. Errors when the formula can't be parsed.
pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result<Option<Cell>> {
let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default();
if input.is_empty() {
let c = Cell { value: Value::Empty, formula: None, style };
return Ok(if c.is_blank() { None } else { Some(c) });
@@ -148,6 +149,8 @@ pub(crate) fn input_to_cell(input: &str, old: Option<&Cell>, wb: &mut gridcraft_
parsed = gridcraft_formula::parse(&text);
}
let expr = parsed.map_err(|e| EngineError::Other(format!("There's a problem with this formula: {e}")))?;
let expr = wb.name_call_case(expr);
check_arg_counts(&expr)?;
let mut cell = Cell::formula(Formula::from_expr(expr));
cell.style = style;
// Formulas whose result is a date/time get a format from functions like TODAY().
@@ -188,41 +191,81 @@ pub(crate) fn input_to_cell(input: &str, old: Option<&Cell>, wb: &mut gridcraft_
Ok(Some(Cell { value: parsed.value, formula: None, style }))
}
/// Like Excel, a formula that calls a built-in function with too few or too many arguments is
/// refused when it's entered, rather than stored to show `#VALUE!`. Functions the registry doesn't
/// hold (special forms like LET, LAMBDA, OFFSET, INDIRECT, SUBTOTAL), defined LAMBDA names and
/// unknown functions are skipped.
fn check_arg_counts(expr: &gridcraft_formula::Expr) -> Result<()> {
let mut bad = None;
expr.walk(&mut |e| {
if bad.is_none()
&& let gridcraft_formula::Expr::Call(name, args) = e
&& let Some(spec) = gridcraft_functions::lookup(name)
&& !spec.accepts(args.len())
{
let few = args.len() < spec.min_args;
bad = Some(format!("{} has too {} arguments. Use {}", spec.name, if few { "few" } else { "many" }, spec.signature));
}
});
match bad {
Some(msg) => Err(EngineError::Other(msg)),
None => Ok(()),
}
}
fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = match cell_param(p, "cell") {
let at = match cell_param_on(s, p, "cell", sheet)? {
Some(c) => c,
None => s.doc()?.selection.active,
};
let input =
str_param(p, "input").or_else(|| str_param(p, "value")).map(str::to_string).or_else(|| p.get("value").map(json_to_input)).unwrap_or_default();
let input = str_param(p, "input")
.or_else(|| str_param(p, "value"))
.map(str::to_string)
.or_else(|| p.get("value").map(json_to_input))
.ok_or_else(|| bad("cell.set", "missing `input` (or `value`)"))?;
let array = bool_param(p, "array").unwrap_or(false);
let protected =
s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.is_protected() && s.doc().is_ok_and(|d| d.wb.styles.get(sh.style_id(at)).protection.locked));
if protected {
return Err(EngineError::Other("The cell or chart you're trying to change is on a protected sheet.".into()));
let d = s.doc()?;
if let Some(sh) = d.wb.sheet(sheet)
&& sh.is_protected()
&& d.wb.styles.get(sh.style_id(at)).protection.locked
&& let Some(m) = locked_cell_error(sh, at, &d.unlocked_ranges)
{
return Err(EngineError::Other(m));
}
let active_sheet = s.doc()?.wb.active_sheet;
edit(s, |cx| {
if array {
// Legacy Ctrl+Shift+Enter array formula over the selection.
let range = cx.sel.current();
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(range.start)).cloned();
let mut cell = input_to_cell(&input, old.as_ref(), &mut cx.wb)?.unwrap_or_default();
// Legacy Ctrl+Shift+Enter array formula over the selection, when the selection holds
// the cell; a cell elsewhere (or on another sheet) gets a one-cell array.
let selected = cx.sel.current();
let range = if sheet == active_sheet && selected.contains(at) { selected } else { RangeRef::cell(at) };
// A table header can't hold an array's value, and a table resizes under it.
if !range.is_single() && cx.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&range))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
if let Some(f) = cell.formula.as_mut() {
std::sync::Arc::make_mut(f).array = Some(range);
}
let sh = cx.sheet_mut(sheet)?;
sh.cells.set(range.start, cell);
// The array takes the whole range: other cells in it lose their contents.
for c in range.iter().skip(1).take(1_000_000) {
if let Some(old) = sh.cells.get(c).filter(|x| !x.value.is_empty() || x.formula.is_some()) {
let style = old.style;
sh.set_cell(c, Cell { style, ..Cell::default() });
}
}
sh.set_cell(range.start, cell);
cx.touch(sheet, range.start);
return Ok(Json::Null);
}
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(at)).cloned();
let cell = input_to_cell(&input, old.as_ref(), &mut cx.wb)?;
let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?;
let sh = cx.sheet_mut(sheet)?;
match cell {
Some(c) => sh.cells.set(at, c),
Some(c) => sh.set_cell(at, c),
None => {
sh.cells.remove(at);
sh.remove_cell(at);
}
}
cx.touch(sheet, at);
@@ -265,21 +308,22 @@ fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
for (ci, v) in cols.iter().enumerate() {
let Some(at) = start.offset(ri as i64, ci as i64) else { continue };
let input = json_to_input(v);
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(at)).cloned();
let cell = match v {
Json::Number(n) => Some(Cell {
value: Value::number(n.as_f64().unwrap_or(0.0)),
formula: None,
style: old.as_ref().map(|c| c.style).unwrap_or_default(),
style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(),
}),
Json::Bool(b) => Some(Cell { value: Value::Bool(*b), formula: None, style: old.as_ref().map(|c| c.style).unwrap_or_default() }),
_ => input_to_cell(&input, old.as_ref(), &mut cx.wb)?,
Json::Bool(b) => {
Some(Cell { value: Value::Bool(*b), formula: None, style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default() })
}
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
};
let sh = cx.sheet_mut(sheet)?;
match cell {
Some(c) => sh.cells.set(at, c),
Some(c) => sh.set_cell(at, c),
None => {
sh.cells.remove(at);
sh.remove_cell(at);
}
}
cx.touch(sheet, at);
@@ -297,8 +341,7 @@ fn range_fill(s: &mut Session, p: &Json) -> Result<Json> {
let input = str_param(p, "input").unwrap_or("").to_string();
let origin = s.doc()?.selection.active;
edit(s, |cx| {
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(origin)).cloned();
let base = input_to_cell(&input, old.as_ref(), &mut cx.wb)?;
let base = input_to_cell(&input, sheet, origin, &mut cx.wb)?;
for r in &ranges {
if r.count() > 2_000_000 {
return Err(bad("range.fill", "range too large"));
@@ -312,7 +355,7 @@ fn range_fill(s: &mut Session, p: &Json) -> Result<Json> {
cell.formula = Some(std::sync::Arc::new(Formula::from_expr(shifted)));
}
cell.style = cx.wb.sheet(sheet).and_then(|sh| sh.cell(at)).map(|c| c.style).unwrap_or(cell.style);
cx.sheet_mut(sheet)?.cells.set(at, cell);
cx.sheet_mut(sheet)?.set_cell(at, cell);
cx.touch(sheet, at);
}
}
@@ -333,8 +376,9 @@ fn selection_set(s: &mut Session, p: &Json) -> Result<Json> {
s.doc_mut()?.wb_switch_sheet(i);
}
let ranges = target_ranges(s, p)?;
let active = cell_param(s, p, "active")?;
let d = s.doc_mut()?;
let active = cell_param(p, "active").or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default();
let active = active.or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default();
let mut sel = crate::Selection { active, anchor: ranges.last().map(|r| r.start).unwrap_or(active), ranges };
if let Some(sh) = d.wb.active() {
sel.expand_merges(sh);
@@ -401,9 +445,9 @@ fn selection_move(s: &mut Session, p: &Json) -> Result<Json> {
if !extend && let Some(m) = sheet.merge_at(from) {
// Leaving a merged cell moves from its edge.
if dr > 0 {
t = CellRef::new((m.end.row + dr as u32).min(MAX_ROWS - 1), from.col);
t = CellRef::new(m.end.offset_clamped(dr, 0).row, from.col);
} else if dc > 0 {
t = CellRef::new(from.row, (m.end.col + dc as u32).min(MAX_COLS - 1));
t = CellRef::new(from.row, m.end.offset_clamped(0, dc).col);
}
}
t
@@ -478,7 +522,8 @@ fn go_to(s: &mut Session, p: &Json) -> Result<Json> {
if let Some(n) = d.wb.name(reference, sheet) {
n.formula.clone()
} else if let Some((si, ti)) = d.wb.table(reference) {
let t = d.wb.sheet(si).and_then(|sh| sh.tables.get(ti)).map(|t| t.range.a1()).unwrap_or_default();
// As in Excel, a table's name stands for its data, without the header and totals rows.
let t = d.wb.sheet(si).and_then(|sh| sh.tables.get(ti)).map(|t| t.data_range().unwrap_or(t.range).a1()).unwrap_or_default();
format!("'{}'!{}", d.wb.sheet(si).map(|s| s.name.clone()).unwrap_or_default(), t)
} else {
return Err(EngineError::Other("Reference isn't valid.".into()));
@@ -563,6 +608,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
let steps = u32_param(p, "steps").unwrap_or(1).max(1);
let d = s.doc_mut()?;
let mut label = String::new();
let now = d.wb.clone();
for _ in 0..steps {
let Some(e) = d.undo.pop() else { break };
let cur = crate::HistoryEntry { label: e.label.clone(), wb: d.wb.clone(), selection: d.selection.clone() };
@@ -571,6 +617,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
d.wb = e.wb;
d.selection = e.selection;
}
super::extra::keep_watch_list(&now, &mut d.wb);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"undone": label}))
@@ -580,6 +627,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
let steps = u32_param(p, "steps").unwrap_or(1).max(1);
let d = s.doc_mut()?;
let mut label = String::new();
let now = d.wb.clone();
for _ in 0..steps {
let Some(e) = d.redo.pop() else { break };
let cur = crate::HistoryEntry { label: e.label.clone(), wb: d.wb.clone(), selection: d.selection.clone() };
@@ -588,6 +636,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
d.wb = e.wb;
d.selection = e.selection;
}
super::extra::keep_watch_list(&now, &mut d.wb);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"redone": label}))
@@ -596,24 +645,119 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
// ---------------------------------------------------------------- clipboard
fn copy_impl(s: &mut Session, p: &Json, cut: bool) -> Result<Json> {
let multiple = || EngineError::Other("This action won't work on multiple selections.".into());
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
if ranges.len() > 1 {
return Err(EngineError::Other("This action won't work on multiple selections.".into()));
if ranges.len() > 1 && cut {
return Err(multiple());
}
let range = ranges.first().copied().unwrap_or_default();
// The selection as made (untrimmed), for Insert Copied Cells.
let selected = ranges.first().copied().unwrap_or_default();
let d = s.doc()?;
let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
let range = if range.is_full_cols() || range.is_full_rows() {
let used = sh.used_range().unwrap_or(RangeRef::cell(range.start));
range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range)
} else {
range
let trim = |range: RangeRef| {
if range.is_full_cols() || range.is_full_rows() {
let used = sh.used_range().unwrap_or(RangeRef::cell(range.start));
range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range)
} else {
range
}
};
let text = crate::display::range_text(&d.wb, sheet, range);
let clip = Clipboard { wb: d.wb.clone(), sheet, range, cut, doc_uid: d.uid, text: text.clone() };
let (wb, range, areas) = if ranges.len() > 1 {
let areas: Vec<RangeRef> = ranges.iter().map(|r| trim(*r)).collect();
let (wb, block) = slide_together(&d.wb, sheet, &areas).ok_or_else(multiple)?;
(std::sync::Arc::new(wb), block, areas)
} else {
(d.wb.clone(), trim(ranges.first().copied().unwrap_or_default()), Vec::new())
};
let text = crate::display::range_text(&wb, sheet, range);
// The HTML rendering is for the host clipboard (UI); it can reach 4 MB, so agents and
// scripts get it only when they ask for it.
let html = if p.get("html").and_then(Json::as_bool) == Some(true) { crate::io::range_html(&wb, sheet, range, &text) } else { None };
let clip = Clipboard { wb, sheet, range, cut, doc_uid: d.uid, text: text.clone(), areas, selected };
s.clipboard = Some(clip);
Ok(json!({"range": range.a1(), "text": text}))
let mut result = json!({"range": range.a1(), "text": text});
if let Some(html) = html {
result["html"] = Json::String(html);
}
Ok(result)
}
/// Excel copies a multi-area selection only when the areas line up: all cover the same rows (they
/// slide together side by side, left to right) or all cover the same columns (stacked, top to
/// bottom), without overlapping. Returns a copy of the workbook whose sheet holds the areas packed
/// into one block at the first area's place, and that block. Formulas travel as their values, as
/// in Excel. `None` when the areas don't line up.
fn slide_together(wb: &gridcraft_model::Workbook, sheet: usize, areas: &[RangeRef]) -> Option<(gridcraft_model::Workbook, RangeRef)> {
let first = *areas.first()?;
let across = areas.iter().all(|a| a.start.row == first.start.row && a.end.row == first.end.row);
let down = areas.iter().all(|a| a.start.col == first.start.col && a.end.col == first.end.col);
let mut sorted = areas.to_vec();
if across {
sorted.sort_by_key(|a| a.start.col);
} else if down {
sorted.sort_by_key(|a| a.start.row);
} else {
return None;
}
if sorted.windows(2).any(|w| matches!(w, [a, b] if a.intersects(b))) {
return None;
}
let anchor = sorted.first()?.start;
let (h, w) = if across {
(first.height(), sorted.iter().map(RangeRef::width).fold(0u32, u32::saturating_add))
} else {
(sorted.iter().map(RangeRef::height).fold(0u32, u32::saturating_add), first.width())
};
let block = RangeRef::new(anchor, anchor.offset(i64::from(h) - 1, i64::from(w) - 1)?);
let src = wb.sheet(sheet)?;
let mut out = wb.clone();
let dst = out.sheet_mut(sheet)?;
dst.take_cells(block);
dst.spill.retain(|c, _| !block.contains(*c));
dst.spill_ranges.retain(|c, _| !block.contains(*c));
dst.comments.retain(|c, _| !block.contains(*c));
dst.merges.retain(|m| !m.intersects(&block));
if across {
dst.cols.retain(|c, _| !(block.start.col..=block.end.col).contains(c));
} else {
dst.rows.retain(|r, _| !(block.start.row..=block.end.row).contains(r));
}
let mut next = if across { anchor.col } else { anchor.row };
for a in &sorted {
let (dr, dc) = if across { (0, i64::from(next) - i64::from(a.start.col)) } else { (i64::from(next) - i64::from(a.start.row), 0) };
let cells = src.cells.iter_range(*a).map(|(c, _)| c).chain(src.spill.keys().copied().filter(|c| a.contains(*c)));
for c in cells {
let Some(to) = c.offset(dr, dc) else { continue };
let style = src.cell(c).map(|x| x.style).unwrap_or_default();
dst.set_cell(to, Cell { value: src.value(c), formula: None, style });
if let Some(picture) = src.cell_pictures.get(&c) {
dst.cell_pictures.insert(to, picture.clone());
}
}
for (c, comment) in src.comments.iter().filter(|(c, _)| a.contains(**c)) {
if let Some(to) = c.offset(dr, dc) {
dst.comments.insert(to, comment.clone());
}
}
for m in src.merges.iter().filter(|m| a.contains_range(m)) {
if let (Some(s), Some(e)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
dst.merges.push(RangeRef::new(s, e));
}
}
// Column widths (side by side) or row heights and hidden rows (stacked) follow their cells.
if across {
for (c, info) in src.cols.range(a.start.col..=a.end.col) {
dst.cols.insert(next.saturating_add(c.saturating_sub(a.start.col)), *info);
}
} else {
for (r, info) in src.rows.range(a.start.row..=a.end.row) {
dst.rows.insert(next.saturating_add(r.saturating_sub(a.start.row)), *info);
}
}
next = next.saturating_add(if across { a.width() } else { a.height() });
}
Some((out, block))
}
fn copy(s: &mut Session, p: &Json) -> Result<Json> {
@@ -657,21 +801,25 @@ fn paste(s: &mut Session, p: &Json) -> Result<Json> {
fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "at").unwrap_or(s.doc()?.selection.current().start);
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(s.doc()?.selection.current().start);
let rows: Vec<Vec<String>> = parse_tsv(text);
// The HTML flavour, when the host passed it: the number behind each cell's shown text.
let html = str_param(p, "html").map(crate::clip_html::table_cells).unwrap_or_default();
let h = rows.len();
let w = rows.iter().map(Vec::len).max().unwrap_or(0);
edit(s, |cx| {
for (ri, row) in rows.iter().enumerate() {
for (ci, v) in row.iter().enumerate() {
let Some(c) = at.offset(ri as i64, ci as i64) else { continue };
let old = cx.wb.sheet(sheet).and_then(|sh| sh.cell(c)).cloned();
let cell = input_to_cell(v, old.as_ref(), &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str()))));
let mut cell = input_to_cell(v, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str()))));
if let Some(cl) = cell.as_mut() {
numeric_from_html(cl, v, html.get(ri).and_then(|r| r.get(ci)), &mut cx.wb);
}
let sh = cx.sheet_mut(sheet)?;
match cell {
Some(cell) => sh.cells.set(c, cell),
Some(cell) => sh.set_cell(c, cell),
None => {
sh.cells.remove(c);
sh.remove_cell(c);
}
}
cx.touch(sheet, c);
@@ -686,6 +834,27 @@ fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result<Json> {
Ok(json!({"rows": h, "cols": w}))
}
/// A pasted cell that came out as text ("Rp10,000.00" isn't en-US input) becomes the number the
/// source recorded for it in its HTML, with a format that shows the same text when one can be
/// inferred and the cell has none. The HTML cell must show the same text as the tab-separated
/// field, so HTML that belongs to another copy (or a table laid out differently) changes nothing.
fn numeric_from_html(cell: &mut Cell, field: &str, html: Option<&crate::clip_html::HtmlCell>, wb: &mut gridcraft_model::Workbook) {
let Some(hc) = html else { return };
let Some(n) = hc.num else { return };
if cell.formula.is_some() || !matches!(cell.value, Value::Text(_)) || wb.styles.get(cell.style).num_fmt.as_str() == "@" {
return;
}
if crate::clip_html::normalized(&hc.text) != crate::clip_html::normalized(field) {
return;
}
cell.value = Value::number(n);
if wb.styles.get(cell.style).num_fmt.as_str() == "General"
&& let Some(code) = crate::clip_html::format_for(field, n)
{
cell.style = wb.styles.derive(cell.style, |s| s.num_fmt = gridcraft_model::NumFmt::new(&code));
}
}
/// Tab-separated text with Excel-style quoting.
pub(crate) fn parse_tsv(text: &str) -> Vec<Vec<String>> {
let mut rows = Vec::new();
@@ -755,16 +924,19 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
let skip_blanks = bool_param(p, "skipBlanks").unwrap_or(false);
let transpose = bool_param(p, "transpose").unwrap_or(false);
let link = bool_param(p, "link").unwrap_or(false);
if link && !clip.areas.is_empty() {
return Err(EngineError::Other("This action won't work on multiple selections.".into()));
}
let dest_sheet = target_sheet(s, p)?;
let sel = s.doc()?.selection.current();
let at = cell_param(p, "at").unwrap_or(sel.start);
let at = cell_param_on(s, p, "at", dest_sheet)?.unwrap_or(sel.start);
let src = clip.range;
let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) };
// Tile the copy over a larger destination that is a multiple of its size.
let tile = sel.height() % h == 0
&& sel.width() % w == 0
&& !sel.is_single()
&& cell_param(p, "at").is_none()
&& cell_param_on(s, p, "at", dest_sheet)?.is_none()
&& !sel.is_full_cols()
&& !sel.is_full_rows()
&& sel.count() <= 4_000_000;
@@ -784,9 +956,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
*style_map.entry(id).or_insert_with(|| wb.styles.intern(src_wb.styles.get(id).clone()))
};
let mut moved_formulas = Vec::new();
let mut moved_pictures = std::collections::BTreeMap::new();
if cut_move {
// Remove the source first (contents and formats), and fix references to it.
let taken = cx.sheet_mut(clip.sheet)?.cells.take_range(src);
let source = cx.sheet_mut(clip.sheet)?;
moved_pictures = source.cell_pictures.iter().filter(|(c, _)| src.contains(**c)).map(|(c, p)| (*c, p.clone())).collect();
let taken = source.take_cells(src);
for (c, _) in &taken {
cx.touch(clip.sheet, *c);
}
@@ -805,16 +980,36 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
src_sheet.cell(sc).cloned()
};
let src_val = src_sheet.value(sc);
if skip_blanks && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none()) {
let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned();
if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none()) {
continue;
}
let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default();
let old_picture = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell_pictures.get(&dest)).cloned();
let mut new_picture = old_picture.clone();
let mut new = old.clone();
let shift = |cell: &Cell| -> Option<std::sync::Arc<Formula>> {
let f = cell.formula.as_ref()?;
let e = f.expr()?;
if cut_move {
return Some(std::sync::Arc::new(Formula::from_expr(e)));
// A moved formula still reads cells on its original sheet. Qualify
// those references before the workbook-wide move adjustment below.
let e = if dest_sheet != clip.sheet {
e.map(&mut |x| match x {
gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => {
r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone());
gridcraft_formula::Expr::Ref(r)
}
other => other,
})
} else {
e
};
let mut moved = Formula::from_expr(e);
// The array range moves with its formula.
let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?)));
return Some(std::sync::Arc::new(moved));
}
let moved =
gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
@@ -828,10 +1023,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
};
new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1()))));
new.value = Value::Empty;
new_picture = None;
} else {
let sc_cell = src_cell.clone().unwrap_or_default();
match what {
What::All | What::AllExceptBorders => {
new_picture = src_picture.clone();
new.formula = shift(&sc_cell);
new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() };
let st = map_style(sc_cell.style, &mut cx.wb);
@@ -843,6 +1040,7 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
};
}
What::Formulas | What::FormulasAndNumberFormats => {
new_picture = src_picture.clone();
new.formula = shift(&sc_cell);
new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() };
if what == What::FormulasAndNumberFormats {
@@ -851,6 +1049,7 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
}
}
What::Values | What::ValuesAndNumberFormats => {
new_picture = src_picture.clone();
new.formula = None;
new.value = src_val.clone();
if what == What::ValuesAndNumberFormats {
@@ -866,10 +1065,16 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
&& matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas)
&& new.formula.is_none()
{
if old_picture.is_some() || new_picture.is_some() {
new_picture = None;
new.value = Value::Error(gridcraft_core::CellError::Value);
}
let a = old.value.clone();
let b = new.value.clone();
// Numbers stored as text take part (multiplying by 1 turns them into
// numbers); other text and errors stay as they are.
if let (Ok(x), Ok(y)) = (a.to_number(), b.to_number())
&& (a.is_number() || a.is_empty())
&& (a.is_number() || a.is_empty() || a.is_text())
&& (b.is_number() || b.is_empty())
{
new.value = match op.as_str() {
@@ -883,8 +1088,26 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
Value::number(x / y)
}
}
_ => b,
_ => b.clone(),
};
} else if (a.is_text() || a.is_error()) && (b.is_number() || b.is_empty()) {
new.value = a;
}
// A formula already there is kept and combined with the pasted number.
if let Some(f) = &old.formula
&& let Ok(y) = b.to_number()
&& (b.is_number() || b.is_empty())
&& let Some(sym) = match op.as_str() {
"add" => Some('+'),
"subtract" => Some('-'),
"multiply" => Some('*'),
"divide" => Some('/'),
_ => None,
}
{
let text = format!("=({}){sym}{}", f.text, gridcraft_core::number_to_text(y));
new.formula = Some(std::sync::Arc::new(Formula::new(&text)));
new.value = Value::Empty;
}
}
}
@@ -903,9 +1126,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
if let Some(cm) = src_sheet.comments.get(&sc).cloned() {
cx.sheet_mut(dest_sheet)?.comments.insert(dest, cm);
}
cx.sheet_mut(dest_sheet)?.cells.set(dest, new);
cx.sheet_mut(dest_sheet)?.set_cell(dest, new);
}
_ => cx.sheet_mut(dest_sheet)?.cells.set(dest, new),
_ => cx.sheet_mut(dest_sheet)?.set_cell(dest, new),
}
if let Some(picture) = new_picture {
cx.sheet_mut(dest_sheet)?.cell_pictures.insert(dest, picture);
}
cx.touch(dest_sheet, dest);
}
@@ -929,11 +1155,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
if cut_move {
// References elsewhere to the moved block now point to its new place.
let dest_name = cx.wb.sheet(dest_sheet).map(|s| s.name.clone()).unwrap_or_default();
if dest_sheet == clip.sheet {
let e = gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col };
rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e);
}
let _ = dest_name;
let e = if dest_sheet == clip.sheet {
gridcraft_formula::adjust::Edit::Move { from: src, to_row: at.row, to_col: at.col }
} else {
gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name, to_row: at.row, to_col: at.col }
};
rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e);
cx.structural = true;
}
let end = at.offset_clamped((tiles_r * h) as i64 - 1, (tiles_c * w) as i64 - 1);
@@ -946,8 +1173,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
Ok(json!({"pasted": s.doc()?.selection.a1()}))
}
/// Applies a reference adjustment to every formula in the workbook (and names, CF, DV).
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) {
use gridcraft_formula::adjust::Edit;
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
// (a cut moves its arrays itself).
let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
for si in 0..wb.sheets.len() {
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
@@ -955,16 +1186,21 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
if keys.is_empty() {
continue;
}
let on_target = moves_arrays && host.eq_ignore_ascii_case(target);
let Some(sheet) = wb.sheet_mut(si) else { continue };
for (c, f) in keys {
let Some(expr) = f.expr() else { continue };
let new = gridcraft_formula::adjust::adjust(expr, &host, target, e);
let text = gridcraft_formula::print(&new);
if text != f.text
let array = match f.array {
Some(a) if on_target => super::sheet::map_range(a, e),
a => a,
};
if (text != f.text || array != f.array)
&& let Some(cell) = sheet.cells.get_mut(c)
{
let mut nf = Formula::from_expr(new);
nf.array = f.array;
nf.array = array;
cell.formula = Some(std::sync::Arc::new(nf));
}
}
@@ -983,6 +1219,18 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
// Delete on checkboxes works in two passes (as in Excel): checked boxes are unchecked first,
// and only when every box in the selection is unchecked are the boxes removed.
let uncheck_only = what == "contents" && {
let d = s.doc()?;
d.wb.sheet(sheet).is_some_and(|sh| {
ranges.iter().any(|r| {
r.intersection(&sh.used_range().unwrap_or(RangeRef::cell(r.start))).is_some_and(|r| {
sh.cells.iter_range(r).any(|(c, x)| x.value == Value::Bool(true) && super::extra::is_checkbox_cell(&d.wb, sh, c))
})
})
})
};
edit(s, |cx| {
for r in &ranges {
let r = match cx.wb.sheet(sheet).and_then(|sh| sh.used_range()) {
@@ -994,16 +1242,29 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
};
let cells: Vec<(CellRef, Cell)> =
cx.wb.sheet(sheet).map(|sh| sh.cells.iter_range(r).map(|(c, x)| (c, x.clone())).collect()).unwrap_or_default();
let mut cells = cells;
if what == "contents" {
for (_, cell) in cells.iter_mut() {
let checkbox = cx.wb.styles.get(cell.style).num_fmt.as_str() == "checkbox";
cell.formula = None;
if checkbox && uncheck_only {
cell.value = Value::Bool(false);
} else {
cell.value = Value::Empty;
if checkbox {
cell.style = cx.wb.styles.derive(cell.style, |st| st.num_fmt = gridcraft_model::NumFmt::new("General"));
}
}
}
}
let sh = cx.sheet_mut(sheet)?;
for (c, mut cell) in cells {
match what {
"all" => {
sh.cells.remove(c);
sh.remove_cell(c);
}
"contents" => {
cell.value = Value::Empty;
cell.formula = None;
sh.cells.set(c, cell);
sh.set_cell(c, cell);
}
"formats" => {
cell.style = StyleId::DEFAULT;
@@ -1034,6 +1295,16 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
fn fill_dir(s: &mut Session, p: &Json, dr: i64, dc: i64) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let mut r = target_range(s, p)?;
// Whole rows or columns fill only where the sheet has content (nothing on an empty sheet).
if r.is_full_cols() || r.is_full_rows() {
match s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()).and_then(|u| r.intersection(&u)) {
Some(u) => r = u,
None => return Ok(Json::Null),
}
}
if r.count() > 5_000_000 {
return Err(bad("edit.fill", "range too large"));
}
// With one row selected, Fill Down copies from the row above (Excel behaviour).
if dr == 1 && r.height() == 1 {
r.start.row = r.start.row.saturating_sub(1);
@@ -1050,8 +1321,6 @@ fn fill_dir(s: &mut Session, p: &Json, dr: i64, dc: i64) -> Result<Json> {
} else {
RangeRef::new(CellRef::new(r.start.row, r.end.col), r.end)
};
let used = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range());
let r = if r.is_full_cols() || r.is_full_rows() { used.and_then(|u| r.intersection(&u)).unwrap_or(r) } else { r };
edit(s, |cx| {
crate::fill::fill(cx, sheet, src, r, crate::fill::FillMode::Copy)?;
Ok(Json::Null)
@@ -1064,12 +1333,13 @@ fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
let Some(target) = str_param(p, "target").and_then(RangeRef::parse) else { return Err(bad("edit.autoFill", "missing `target`")) };
let mode = match str_param(p, "mode").unwrap_or("series") {
"copy" => crate::fill::FillMode::Copy,
"alternate" => crate::fill::FillMode::Alternate,
"formats" => crate::fill::FillMode::Formats,
"values" => crate::fill::FillMode::ValuesOnly,
_ => crate::fill::FillMode::Series,
};
if target.count() > 5_000_000 {
return Err(bad("edit.autoFill", "target too large"));
if target.count() > 5_000_000 || src.count() > 5_000_000 {
return Err(bad("edit.autoFill", "range too large"));
}
edit(s, |cx| {
crate::fill::fill(cx, sheet, src, target, mode)?;
@@ -1175,7 +1445,11 @@ fn find(s: &mut Session, p: &Json) -> Result<Json> {
.cells
.iter()
.filter_map(|(c, cell)| {
let text = if values || cell.formula.is_none() { crate::display::cell_text(&d.wb, sh, c) } else { cell.input_text() };
let text = if values || cell.formula.is_none() || crate::display::formula_hidden(&d.wb, sh, c) {
crate::display::cell_text(&d.wb, sh, c)
} else {
cell.input_text()
};
matches(&text, &what, case, whole).then_some((c, text))
})
.collect();
@@ -1219,7 +1493,7 @@ fn replace(s: &mut Session, p: &Json) -> Result<Json> {
let mut n = 0;
for si in sheets {
let cells: Vec<(CellRef, String)> =
cx.wb.sheet(si).map(|sh| sh.cells.iter().map(|(c, cell)| (c, cell.input_text())).collect()).unwrap_or_default();
cx.wb.sheet(si).map(|sh| sh.cells.iter().map(|(c, _)| (c, sh.input_text(c))).collect()).unwrap_or_default();
for (c, text) in cells {
if !all && c != active {
continue;
@@ -1234,13 +1508,12 @@ fn replace(s: &mut Session, p: &Json) -> Result<Json> {
} else {
replace_ci(&text, &what, &with)
};
let old = cx.wb.sheet(si).and_then(|sh| sh.cell(c)).cloned();
let cell = input_to_cell(&new, old.as_ref(), &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(new.as_str()))));
let cell = input_to_cell(&new, si, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(new.as_str()))));
let sh = cx.sheet_mut(si)?;
match cell {
Some(cell) => sh.cells.set(c, cell),
Some(cell) => sh.set_cell(c, cell),
None => {
sh.cells.remove(c);
sh.remove_cell(c);
}
}
cx.touch(si, c);
@@ -1310,6 +1583,38 @@ fn begin_edit(s: &mut Session, _: &Json) -> Result<Json> {
mod tests {
use super::*;
#[test]
fn legacy_array_entry() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B2", "values": [[1], [2]]})).unwrap();
s.execute("cell.set", json!({"cell": "C4", "input": "old"})).unwrap();
s.execute("selection.set", json!({"range": "C2:C4"})).unwrap();
s.execute("cell.set", json!({"cell": "C2", "input": "=B2:B3*2", "array": true})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
assert_eq!(get(&mut s, "C3")["value"], json!(4.0));
// Past the result Excel shows #N/A; the old content of the range is replaced.
assert_eq!(get(&mut s, "C4")["text"], "#N/A");
let bar = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("C2").unwrap()).map(|c| c.bar_text());
assert_eq!(bar.as_deref(), Some("{=B2:B3*2}"));
}
#[test]
fn an_array_entered_outside_the_selection_covers_only_its_cell() {
// Found by the command-sequence fuzzer: the array took the selection's range even with
// `cell` elsewhere (or on another sheet), so its formula sat outside its own range and the
// selected cells were wiped.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "K20", "input": "keep"})).unwrap();
s.execute("selection.set", json!({"range": "K20:K22"})).unwrap();
s.execute("cell.set", json!({"cell": "H5", "input": "=1+1", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
let f = sh.cell(CellRef::parse("H5").unwrap()).and_then(|c| c.formula.clone()).unwrap();
assert_eq!(f.array, Some(RangeRef::parse("H5").unwrap()));
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
}
#[test]
fn wildcards() {
assert!(wildcard("hello", "h*o"));
@@ -1327,6 +1632,28 @@ mod tests {
assert_eq!(parse_tsv("\"he said \"\"hi\"\"\""), vec![vec!["he said \"hi\""]]);
}
#[test]
fn paste_special_operations_keep_text_errors_and_formulas() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [["'123", "Total", "=NA()", "=B3*2", 5], [1, null, null, null, null], [null, 4, null, null, null]]}),
)
.unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
assert_eq!(get(&mut s, "A1")["value"], "123");
s.execute("edit.copy", json!({"range": "A2"})).unwrap();
s.execute("selection.set", json!({"range": "A1:E1"})).unwrap();
s.execute("edit.pasteSpecial", json!({"what": "values", "operation": "multiply"})).unwrap();
assert_eq!(get(&mut s, "A1")["value"], json!(123.0));
assert_eq!(get(&mut s, "B1")["value"], "Total");
assert_eq!(get(&mut s, "C1")["value"]["error"], "#N/A");
assert_eq!(get(&mut s, "D1")["formula"], "=(B3*2)*1");
assert_eq!(get(&mut s, "D1")["value"], json!(8.0));
assert_eq!(get(&mut s, "E1")["value"], json!(5.0));
}
#[test]
fn replace_case_insensitive() {
assert_eq!(replace_ci("Apple apple APPLE", "apple", "pear"), "pear pear pear");
+220 -38
View File
@@ -15,7 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Chart Element",
["Chart Design", "Chart Layouts"],
None,
"{chart?, element: title|legend|dataLabels|gridlines|axisTitles, on?: bool, position?: bottom|top|left|right}",
"{chart?, element: title|legend|dataLabels|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}",
has_doc,
add_element
),
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Data…",
["Chart Design", "Data"],
None,
"{chart?, range: \"Sheet1!A1:D7\", byRows?: bool}",
"{chart?, range?: \"Sheet1!A1:D7\", byRows?: bool, categories?: \"Sheet1!A2:A7\" (Horizontal (Category) Axis Labels for every series; \"\" clears), removeSeries?: [index…]}",
has_doc,
select_data
),
@@ -116,9 +116,29 @@ pub fn specs() -> Vec<CommandSpec> {
rotate
),
// Views
cmd!(noundo "view.normal", "Normal", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "normal")),
cmd!(noundo "view.pageLayout", "Page Layout", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "pageLayout")),
cmd!(noundo "view.pageBreakPreview", "Page Break Preview", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "pageBreakPreview")),
cmd!(noundo "view.normal", "Normal", ["View", "Workbook Views"], None, "{sheet?} → {view} (per sheet, saved with the file)", has_doc, |s, p| set_view(
s,
p,
SheetViewMode::Normal
)),
cmd!(
noundo "view.pageLayout",
"Page Layout",
["View", "Workbook Views"],
None,
"{sheet?} → {view}: pages on paper with rulers; headers and footers are edited in place (per sheet, saved with the file)",
has_doc,
|s, p| set_view(s, p, SheetViewMode::PageLayout)
),
cmd!(
noundo "view.pageBreakPreview",
"Page Break Preview",
["View", "Workbook Views"],
None,
"{sheet?} → {view} (per sheet, saved with the file)",
has_doc,
|s, p| set_view(s, p, SheetViewMode::PageBreakPreview)
),
cmd!(noundo "view.customViews", "Custom Views…", ["View", "Workbook Views"], None, "{save?: name, show?: name, delete?: name} → list", has_doc, custom_views),
cmd!(noundo "view.split", "Split", ["View", "Window"], None, "{} (toggles a split at the active cell; shown as frozen panes in this version)", has_doc, split),
cmd!(noundo "view.newWindow", "New Window", ["View", "Window"], None, "{} opens a second window on the same workbook (a linked copy)", has_doc, new_window),
@@ -126,7 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "view.hideWindow", "Hide", ["View", "Window"], None, "{}", has_doc, hide_window),
cmd!(noundo "view.unhideWindow", "Unhide…", ["View", "Window"], None, "{index?}", has_doc, unhide_window),
cmd!(query "view.switchWindows", "Switch Windows", ["View", "Window"], None, "{} → open windows", always, switch_windows),
cmd!(noundo "view.ruler", "Ruler", ["View", "Show"], None, "{on?}", has_doc, |_, _| ok()),
cmd!(noundo "view.ruler", "Ruler", ["View", "Show"], None, "{on?} → {on}: rulers in Page Layout view (an application option)", has_doc, ruler),
cmd!(query "view.macros", "Macros", ["View", "Macros"], None, "{} → scripts", has_doc, all_scripts),
// Table tools
cmd!("table.resize", "Resize Table", ["Table Design", "Properties"], None, "{table?, range: \"A1:F20\"}", has_doc, table_resize),
@@ -181,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Checkbox",
["Insert", "Cell Controls"],
None,
"{range?} (cells hold TRUE/FALSE and draw as checkboxes; Space toggles)",
"{range?} (TRUE/FALSE and empty cells draw as checkboxes, empty ones become FALSE, other values show as they are; click or Space toggles; Delete unchecks, then removes; Clear Formats removes and keeps the values)",
has_doc,
checkbox
),
@@ -291,12 +311,73 @@ fn add_element(s: &mut Session, p: &Json) -> Result<Json> {
c.x_title = on.then(|| c.x_title.clone().unwrap_or_else(|| "Axis Title".into()));
c.y_title = on.then(|| c.y_title.clone().unwrap_or_else(|| "Axis Title".into()));
}
"smooth" => {
for s in &mut c.series {
s.smooth = on;
}
}
"trendline" => {
let only = u32_param(p, "series").map(|i| i as usize);
if only.is_some_and(|i| i >= c.series.len()) {
return Err(bad("chart.addElement", "no such series"));
}
let targets: Vec<usize> = (0..c.series.len()).filter(|i| only.is_none_or(|o| o == *i)).collect();
if !on {
for i in targets {
if let Some(se) = c.series.get_mut(i) {
se.trendlines.clear();
}
}
return Ok(());
}
let t = trendline_param(p)?;
let eligible: Vec<usize> =
targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect();
if eligible.is_empty() {
return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series"));
}
for i in eligible {
if let Some(se) = c.series.get_mut(i) {
se.trendlines.push(t.clone());
}
}
}
other => return Err(bad("chart.addElement", format!("unknown element `{other}`"))),
}
Ok(())
})
}
/// The trendline described by `chart.addElement`'s trendline parameters (Excel's Add Chart
/// Element ▸ Trendline choices, plus the Format Trendline options).
fn trendline_param(p: &Json) -> Result<Trendline> {
let num = |k: &str| f64_param(p, k).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(0.0);
let mut t = Trendline {
forward: num("forward"),
backward: num("backward"),
display_equation: bool_param(p, "displayEquation").unwrap_or(false),
display_r_squared: bool_param(p, "displayRSquared").unwrap_or(false),
..Trendline::default()
};
t.kind = match str_param(p, "type").unwrap_or("linear") {
"linear" => TrendlineKind::Linear,
// Excel's Linear Forecast: a linear trendline projected two periods ahead.
"linearForecast" => {
if t.forward == 0.0 {
t.forward = 2.0;
}
TrendlineKind::Linear
}
"exponential" => TrendlineKind::Exponential,
"logarithmic" => TrendlineKind::Logarithmic,
"power" => TrendlineKind::Power,
"polynomial" => TrendlineKind::Polynomial(u32_param(p, "order").unwrap_or(2).clamp(2, 6) as u8),
"movingAverage" => TrendlineKind::MovingAverage(u32_param(p, "period").unwrap_or(2).clamp(2, 255)),
other => return Err(bad("chart.addElement", format!("unknown trendline type `{other}`"))),
};
Ok(t)
}
fn quick_layout(s: &mut Session, p: &Json) -> Result<Json> {
let n = u32_param(p, "layout").unwrap_or(1);
with_chart(s, p, |c| {
@@ -345,22 +426,71 @@ fn change_colors(s: &mut Session, p: &Json) -> Result<Json> {
}
fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
let range = str_param(p, "range").ok_or_else(|| bad("chart.selectData", "missing `range`"))?.to_string();
let (sheet_name, body) = split_sheet(&range);
let d = s.doc()?;
let src_si = match sheet_name {
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
None => d.wb.active_sheet,
// A new data range rebuilds the series, as in Excel's Select Data › Chart data range.
let rebuilt = match str_param(p, "range") {
Some(range) => {
let range = range.trim_start_matches('=');
let (sheet_name, body) = split_sheet(range);
let src_si = match sheet_name {
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
None => d.wb.active_sheet,
};
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?;
if r.count() > 1_000_000 {
return Err(bad("chart.selectData", "range too large for a chart"));
}
let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?;
let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1);
let series = super::insert::series_from_range(src, r, by_rows);
Some((series, format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1()), by_rows))
}
None => None,
};
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?;
let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?;
let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1);
let series = super::insert::series_from_range(src, r, by_rows);
let source = format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1());
// Horizontal (Category) Axis Labels › Edit: one labels range for every series ("" clears).
let categories = match str_param(p, "categories") {
None => None,
Some(t) if t.trim().trim_start_matches('=').is_empty() => Some(None),
Some(t) => {
let t = t.trim().trim_start_matches('=');
let (sheet_name, body) = split_sheet(t);
let si = match sheet_name {
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
None => d.wb.active_sheet,
};
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "`categories` is not a range"))?;
let name = d.wb.sheet(si).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?;
let abs = |c: CellRef| format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1);
Some(Some(format!("{}!{}:{}", gridcraft_formula::quote_sheet(&name), abs(r.start), abs(r.end))))
}
};
let mut remove: Vec<usize> = p
.get("removeSeries")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(Json::as_u64).filter_map(|i| usize::try_from(i).ok()).collect())
.unwrap_or_default();
remove.sort_unstable();
remove.dedup();
if rebuilt.is_none() && categories.is_none() && remove.is_empty() {
return Err(bad("chart.selectData", "missing `range`, `categories` or `removeSeries`"));
}
with_chart(s, p, move |c| {
c.series = series;
c.source = Some(source);
c.by_rows = by_rows;
if let Some((series, source, by_rows)) = rebuilt {
c.series = series;
super::insert::scatter_x_from_first(c.kind, &mut c.series);
c.source = Some(source);
c.by_rows = by_rows;
}
for i in remove.iter().rev() {
if *i < c.series.len() && c.series.len() > 1 {
c.series.remove(*i);
}
}
if let Some(cats) = categories {
for se in &mut c.series {
se.categories = cats.clone();
}
}
Ok(())
})
}
@@ -371,7 +501,7 @@ fn move_chart(s: &mut Session, p: &Json) -> Result<Json> {
Some(n) => Some(s.doc()?.wb.sheet_index(n).ok_or_else(|| bad("chart.move", "no such sheet"))?),
None => None,
};
let at = cell_param(p, "at");
let at = cell_param_on(s, p, "at", target.unwrap_or(si))?;
edit(s, |cx| {
let mut chart = cx.sheet_mut(si)?.charts.remove(ci);
if let Some(a) = at {
@@ -468,13 +598,13 @@ fn selection_pane(s: &mut Session, _: &Json) -> Result<Json> {
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let mut v = Vec::new();
for c in &sh.shapes {
v.push(json!({"kind": "shape", "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1()}));
v.push(json!({"kind": "shape", "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)}));
}
for c in &sh.images {
v.push(json!({"kind": "image", "id": c.id, "name": format!("Picture {}", c.id), "at": c.anchor.cell.a1()}));
v.push(json!({"kind": "image", "id": c.id, "name": format!("Picture {}", c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)}));
}
for c in &sh.charts {
v.push(json!({"kind": "chart", "id": c.id, "name": format!("Chart {}", c.id), "title": c.title, "at": c.anchor.cell.a1()}));
v.push(json!({"kind": "chart", "id": c.id, "name": format!("Chart {}", c.id), "title": c.title, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)}));
}
Ok(Json::Array(v))
}
@@ -535,9 +665,26 @@ fn rotate(s: &mut Session, p: &Json) -> Result<Json> {
with_shape(s, p, |sh| std::mem::swap(&mut sh.anchor.width, &mut sh.anchor.height))
}
fn set_view(s: &mut Session, mode: &str) -> Result<Json> {
s.view_mode = mode.to_string();
Ok(json!({"view": mode}))
/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it
/// neither records an undo step nor marks a clean workbook as changed.
fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
let dirty = d.is_dirty();
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.view = mode;
}
if !dirty {
d.saved = d.wb.clone();
}
Ok(json!({"view": mode.as_str()}))
}
fn ruler(s: &mut Session, p: &Json) -> Result<Json> {
let on = bool_param(p, "on").unwrap_or(s.hide_ruler);
s.hide_ruler = !on;
Ok(json!({"on": on}))
}
const VIEWS_NAME: &str = "_sc_custom_views";
@@ -561,6 +708,19 @@ fn stash_set(wb: &mut Workbook, key: &str, v: &Json) {
wb.names.push(DefinedName { name: key.into(), scope: None, formula, comment: String::new(), hidden: true });
}
/// The Watch Window list isn't an edit (Excel doesn't undo it): undo and redo keep the current
/// list when they swap in another snapshot of the workbook.
pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>) {
let find = |wb: &Workbook| wb.names.iter().find(|n| n.name == WATCH_NAME).cloned();
let keep = find(from);
if keep == find(to) {
return;
}
let wb = std::sync::Arc::make_mut(to);
wb.names.retain(|n| n.name != WATCH_NAME);
wb.names.extend(keep);
}
fn custom_views(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let mut views = stash_get(&d.wb, VIEWS_NAME);
@@ -786,10 +946,16 @@ fn new_script(s: &mut Session, p: &Json) -> Result<Json> {
}
fn all_scripts(s: &mut Session, _: &Json) -> Result<Json> {
let all = stash_get(&s.doc()?.wb, SCRIPTS_NAME);
Ok(Json::Array(
all.as_object().map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len)})).collect()).unwrap_or_default(),
))
let wb = &s.doc()?.wb;
let all = stash_get(wb, SCRIPTS_NAME);
let mut list: Vec<Json> =
all.as_object().map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len)})).collect()).unwrap_or_default();
// A preserved VBA project is reported alongside GridCraft's own scripts; it is carried on
// save but never executed here, so it has no step count.
if let Some(bytes) = &wb.vba_project {
list.push(json!({"name": "(VBA)", "steps": 0, "kind": "vba", "size": bytes.len(), "executed": false}));
}
Ok(Json::Array(list))
}
fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
@@ -823,6 +989,11 @@ fn delete_script(s: &mut Session, p: &Json) -> Result<Json> {
/// Number format that marks checkbox cells (TRUE/FALSE values drawn as boxes).
pub const CHECKBOX_FORMAT: &str = "\"☐\";\"☐\";\"☐\";[=1]\"☑\"";
/// Whether `c` has checkbox formatting.
pub(crate) fn is_checkbox_cell(wb: &gridcraft_model::Workbook, sh: &gridcraft_model::Sheet, c: CellRef) -> bool {
wb.styles.get(sh.style_id(c)).num_fmt.as_str() == "checkbox"
}
fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let si = target_sheet(s, p)?;
@@ -838,9 +1009,14 @@ fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
s.align.h = HAlign::Center;
});
let sh = cx.sheet_mut(si)?;
let v = sh.value(c);
let value = if matches!(v, Value::Bool(_)) { v } else { Value::Bool(false) };
sh.cells.set(c, Cell { value, formula: None, style: new });
// Values and formulas already there stay (only TRUE/FALSE draw as a box); an empty
// cell starts unchecked.
let mut cell = sh.cell(c).cloned().unwrap_or_default();
if cell.value.is_empty() && cell.formula.is_none() {
cell.value = Value::Bool(false);
}
cell.style = new;
sh.set_cell(c, cell);
cx.touch(si, c);
}
}
@@ -851,18 +1027,24 @@ fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
fn toggle_checkbox(s: &mut Session, p: &Json) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc()?;
let cells: Vec<CellRef> = match cell_param(p, "cell") {
let cells: Vec<CellRef> = match cell_param_on(s, p, "cell", si)? {
Some(c) => vec![c],
None => d.selection.ranges.iter().flat_map(|r| r.iter().take(100_000).collect::<Vec<_>>()).collect(),
};
edit(s, |cx| {
for c in cells {
let checkbox = cx.wb.sheet(si).is_some_and(|sh| is_checkbox_cell(&cx.wb, sh, c));
let sh = cx.sheet_mut(si)?;
if let Some(cell) = sh.cells.get_mut(c)
&& let Value::Bool(b) = cell.value
&& cell.formula.is_none()
{
cell.value = Value::Bool(!b);
// An empty checkbox cell counts as FALSE.
let next = match cell.value {
Value::Bool(b) if checkbox => Value::Bool(!b),
Value::Empty if checkbox => Value::Bool(true),
_ => continue,
};
cell.value = next;
cx.changed.push((si, c));
}
}
@@ -917,7 +1099,7 @@ fn new_cell_style(s: &mut Session, p: &Json) -> Result<Json> {
let name = str_param(p, "name").ok_or_else(|| bad("home.newCellStyle", "missing `name`"))?.to_string();
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let c = cell_param(p, "fromCell").unwrap_or(d.selection.active);
let c = cell_param(s, p, "fromCell")?.unwrap_or(d.selection.active);
let style = d.wb.styles.get(sh.style_id(c)).clone();
edit(s, |cx| {
cx.wb.cell_styles.retain(|(n, _)| !n.eq_ignore_ascii_case(&name));
+57 -7
View File
@@ -1,4 +1,4 @@
//! File menu: new, open, save, close, export, properties.
//! File menu: new, open, save, close, export, properties, options.
use serde_json::{Value as Json, json};
@@ -8,14 +8,23 @@ use crate::DocState;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64} (xlsx, xlsm, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html by extension)", has_doc, save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, save_as),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool}", 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.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!(
query "file.options",
"Options",
["File"],
None,
"{} → {calculation: {mode, iterative, maxIterations, maxChange}} for the active workbook (the interface opens File › Options; change settings with their own commands, e.g. formulas.calculationOptions, view.theme, app.language.set)",
always,
options
),
cmd!(noundo "window.activate", "Switch Window", ["Window"], None, "{index}", has_doc, activate_window),
]
}
@@ -46,9 +55,20 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({})));
return ok();
};
let (wb, warnings) = crate::io::open_bytes(&name, &bytes)?;
let title = std::path::Path::new(&name).file_name().and_then(|n| n.to_str()).unwrap_or("Book").to_string();
let path = str_param(p, "path").map(str::to_string).filter(|p| crate::io::FileKind::from_path(p) == Some(crate::io::FileKind::Xlsx) || true);
let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted;
let (wb, warnings) = crate::io::open_bytes_with_password(&name, &bytes, str_param(p, "password"))?;
let imported =
matches!(crate::io::FileKind::from_path(&name), Some(crate::io::FileKind::Ods | crate::io::FileKind::Xlsb | crate::io::FileKind::Xls))
|| matches!(gridcraft_xlsx::sniff(&bytes), gridcraft_xlsx::Format::Ods | gridcraft_xlsx::Format::Xlsb | gridcraft_xlsx::Format::Xls);
let title = if imported {
format!("{} (imported).xlsx", std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Book"))
} else {
std::path::Path::new(&name).file_name().and_then(|n| n.to_str()).unwrap_or("Book").to_string()
};
// An import has no save target: ordinary Save must ask for a new destination. Neither does a
// workbook decrypted with its password, so Save never replaces the encrypted original with
// an unprotected copy.
let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string);
// Replace an untouched blank Book1 like Excel does.
if s.documents().len() == 1
&& s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty()))
@@ -56,6 +76,15 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
s.close_document(0);
}
let i = s.add_document(DocState::new(wb, path, title));
// The decrypted-workbook notice is for the info bar, not a message box.
let shown: Vec<&str> = warnings.iter().map(String::as_str).filter(|w| *w != crate::io::DECRYPTED_NOTICE).collect();
if !shown.is_empty() {
let mut message = shown.iter().take(5).copied().collect::<Vec<_>>().join("\n\n");
if shown.len() > 5 {
message.push_str(&format!("\n\n{} additional import warnings.", shown.len() - 5));
}
s.ui_requests.push(crate::UiRequest::Message(message));
}
let d = s.doc()?;
Ok(
json!({"index": i, "title": d.display_title(), "sheets": d.wb.sheets.iter().map(|s| s.name.clone()).collect::<Vec<_>>(), "warnings": warnings}),
@@ -70,6 +99,11 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
return ok();
}
};
// A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the
// document keeps its file and its unsaved changes.
if std::path::Path::new(&path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
return super::print::export_pdf(s, &json!({"path": path}));
}
let d = s.doc_mut()?;
let bytes = crate::io::save_bytes(&d.wb, &path)?;
crate::io::write_file(&path, &bytes)?;
@@ -142,6 +176,22 @@ fn properties(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// File › Options: reports the workbook-level settings and asks the interface to show its Options
/// page. Nothing changes here; every setting has its own command.
fn options(s: &mut Session, _: &Json) -> Result<Json> {
s.ui_requests.push(crate::UiRequest::Dialog("options".into(), json!({})));
let calculation = s.active().map(|d| {
let c = &d.wb.calc;
let mode = match c.mode {
gridcraft_model::CalcMode::Automatic => "automatic",
gridcraft_model::CalcMode::AutomaticExceptTables => "automaticExceptTables",
gridcraft_model::CalcMode::Manual => "manual",
};
json!({"mode": mode, "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change})
});
Ok(json!({"calculation": calculation}))
}
fn activate_window(s: &mut Session, p: &Json) -> Result<Json> {
let i = u32_param(p, "index").ok_or_else(|| bad("window.activate", "missing `index`"))? as usize;
if i >= s.documents().len() {
+548
View File
@@ -0,0 +1,548 @@
//! Data › Forecast › Forecast Sheet: a new sheet with the history, a FORECAST.ETS column, the
//! FORECAST.ETS.CONFINT confidence bounds, optional FORECAST.ETS.STAT statistics and a chart.
//!
//! Like Excel, the sheet holds a copy of the timeline and values (sorted by time) and live
//! formulas over that copy, so the forecast follows edits to the copied history.
use std::sync::Arc;
use gridcraft_core::{CellRef, RangeRef, Value};
use gridcraft_functions::Timeline;
use gridcraft_model::{Anchor, Cell, Chart, ChartKind, Formula, LegendPos, Series, Sheet, StyleId, Table, TableColumn, TotalsFn};
use serde_json::{Value as Json, json};
use super::*;
use crate::selection::current_region;
const CMD: &str = "data.forecastSheet";
/// Most history rows a forecast sheet copies.
const MAX_HISTORY: u64 = 10_000;
/// Most forecast rows.
const MAX_PERIODS: u32 = 10_000;
/// Most history rows × forecast rows. Every forecast row holds three ETS formulas that each refit
/// the model over the whole history (about 3 µs per history point in a release build), so this
/// bounds a sheet's recalculation to a few seconds: 10,000 rows of history get 50 forecast rows,
/// 50 rows of history the full 10,000.
const MAX_WORK: u64 = 500_000;
/// Forecast rows by default: a third of the history, within [`max_periods`].
fn default_periods(history: usize) -> u32 {
u32::try_from(history.div_ceil(3)).unwrap_or(u32::MAX).clamp(1, max_periods(history))
}
/// Most forecast rows for `history` rows of history.
fn max_periods(history: usize) -> u32 {
let h = u64::try_from(history).unwrap_or(u64::MAX).max(1);
u32::try_from(MAX_WORK / h).unwrap_or(u32::MAX).clamp(1, MAX_PERIODS)
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"data.forecastSheet",
"Forecast Sheet",
["Data", "Forecast"],
None,
"{timeline?: \"A2:A25\", values?: \"B2:B25\" (default: the first two columns of `range`, the selection or the current region; a text first cell is the header), end?: timeline value or date text | periods?: n (default: a third of the history, at least 1; ≤10,000 and history × periods ≤ 500,000; history ≤ 10,000 rows), confidenceInterval?: bool (default true), confidence?: 0.95 or 95, seasonality?: \"auto\" | 0 (none) | 2–8,760, fillMissing?: interpolate|zeros, aggregate?: average|count|counta|max|median|min|sum, statistics?: bool, chart?: line|column} → {sheet, table, chart, history, periods}. Inserts a sheet before the active one: timeline, values, Forecast (FORECAST.ETS), Lower/Upper Confidence Bound (FORECAST.ETS.CONFINT), optional FORECAST.ETS.STAT table, and a chart.",
has_doc,
forecast_sheet
)]
}
/// The cells of a one-row or one-column range, at most `MAX_HISTORY + 1`.
fn line_cells(r: RangeRef) -> Result<Vec<CellRef>> {
if r.count() > MAX_HISTORY + 1 {
return Err(bad(CMD, format!("at most {MAX_HISTORY} rows of history")));
}
if r.width() == 1 {
Ok((r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect())
} else if r.height() == 1 {
Ok((r.start.col..=r.end.col).map(|col| CellRef::new(r.start.row, col)).collect())
} else {
Err(bad(CMD, "the timeline and the values are each one row or one column"))
}
}
/// A range parameter on any sheet (whole columns trimmed to the used range).
fn range_on(s: &Session, t: &str) -> Result<(usize, RangeRef)> {
let d = s.doc()?;
let (sh, body) = split_sheet(t);
let si = match sh {
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad(CMD, format!("no sheet named `{n}`")))?,
None => d.wb.active_sheet,
};
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(CMD, format!("not a range: `{t}`")))?;
let r = if r.is_full_cols() || r.is_full_rows() {
match d.wb.sheet(si).and_then(|s| s.used_range()) {
Some(u) => r.intersection(&RangeRef::new(CellRef::new(0, 0), u.end)).unwrap_or(RangeRef::cell(r.start)),
None => RangeRef::cell(r.start),
}
} else {
r
};
Ok((si, r))
}
/// (sheet, timeline cells, value cells).
fn source(s: &Session, p: &Json) -> Result<(usize, Vec<CellRef>, Vec<CellRef>)> {
let text = |k: &str| str_param(p, k).map(str::trim).filter(|t| !t.is_empty());
match (text("timeline"), text("values")) {
(Some(t), Some(v)) => {
let (ts, tr) = range_on(s, t)?;
let (vs, vr) = range_on(s, v)?;
if ts != vs {
return Err(bad(CMD, "the timeline and the values must be on one sheet"));
}
Ok((ts, line_cells(tr)?, line_cells(vr)?))
}
(None, None) => {
let d = s.doc()?;
let (si, r) = match text("range") {
Some(t) => range_on(s, t)?,
None => {
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let sel = d.selection.current();
(d.wb.active_sheet, if sel.is_single() { current_region(sh, d.selection.active) } else { sel })
}
};
if r.width() < 2 {
return Err(EngineError::Other("Select a timeline column and a values column for the forecast.".into()));
}
let col = |c: u32| RangeRef::new(CellRef::new(r.start.row, c), CellRef::new(r.end.row, c));
Ok((si, line_cells(col(r.start.col))?, line_cells(col(r.start.col + 1))?))
}
_ => Err(bad(CMD, "give both `timeline` and `values`, or neither")),
}
}
/// A number parameter given as a number or as text.
fn number(p: &Json, key: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Json::Null) => Ok(None),
Some(Json::Number(n)) => Ok(n.as_f64()),
Some(Json::String(t)) if t.trim().is_empty() => Ok(None),
Some(Json::String(t)) => {
t.trim().trim_end_matches('%').trim().parse::<f64>().map(Some).map_err(|_| bad(CMD, format!("`{key}` is not a number")))
}
Some(_) => Err(bad(CMD, format!("`{key}` is not a number"))),
}
}
struct Options {
seasonality: u32,
fill: u8,
aggregate: Option<u8>,
confidence: Option<f64>,
statistics: bool,
column_chart: bool,
}
fn options(p: &Json) -> Result<Options> {
let seasonality = match p.get("seasonality") {
Some(Json::String(t)) if t.trim().is_empty() || t.trim().eq_ignore_ascii_case("auto") => 1,
None | Some(Json::Null) => 1,
_ => match number(p, "seasonality")? {
Some(n) if n == n.trunc() && (0.0..=8760.0).contains(&n) => n as u32,
_ => return Err(bad(CMD, "`seasonality` is \"auto\", 0 (none) or a season length from 2 to 8,760")),
},
};
let fill = match str_param(p, "fillMissing").map(|t| t.trim().to_ascii_lowercase()) {
None => 1,
Some(t) if t.is_empty() || t == "interpolate" || t == "interpolation" => 1,
Some(t) if t == "zeros" || t == "zero" => 0,
Some(t) => return Err(bad(CMD, format!("`fillMissing` is interpolate or zeros, not `{t}`"))),
};
let aggregate = match str_param(p, "aggregate").map(|t| t.trim().to_ascii_lowercase()) {
None => None,
Some(t) => match t.as_str() {
"" | "average" => None,
"count" => Some(2),
"counta" => Some(3),
"max" => Some(4),
"median" => Some(5),
"min" => Some(6),
"sum" => Some(7),
_ => return Err(bad(CMD, format!("unknown `aggregate`: `{t}`"))),
},
};
let confidence = if bool_param(p, "confidenceInterval").unwrap_or(true) {
let c = number(p, "confidence")?.unwrap_or(0.95);
let c = if c >= 1.0 { c / 100.0 } else { c };
if !(c > 0.0 && c < 1.0) {
return Err(bad(CMD, "`confidence` is between 0 and 1 (or 0 and 100%)"));
}
Some(c)
} else {
None
};
let column_chart = match str_param(p, "chart").map(|t| t.trim().to_ascii_lowercase()) {
None => false,
Some(t) if t.is_empty() || t == "line" => false,
Some(t) if t == "column" => true,
Some(t) => return Err(bad(CMD, format!("`chart` is line or column, not `{t}`"))),
};
Ok(Options { seasonality, fill, aggregate, confidence, statistics: bool_param(p, "statistics").unwrap_or(false), column_chart })
}
fn col_letters(c: u32) -> String {
gridcraft_core::col_to_letters(c)
}
fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let opts = options(p)?;
let (si, tcells, vcells) = source(s, p)?;
if tcells.len() != vcells.len() {
return Err(bad(CMD, "the timeline and the values need the same number of cells"));
}
let d = s.doc()?;
if d.wb.protected_structure {
return Err(EngineError::Other("The workbook is protected and cannot be changed.".into()));
}
let sys = d.wb.date_system;
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
// A text first cell is the header.
let header = tcells.first().is_some_and(|c| sh.value(*c).is_text()) || vcells.first().is_some_and(|c| sh.value(*c).is_text());
let name_of = |c: Option<&CellRef>, fallback: &str| match c.map(|c| sh.value(*c)) {
Some(v) if header && !v.is_empty() => v.display(),
_ => fallback.to_string(),
};
let (tname, vname) = (name_of(tcells.first(), "Timeline"), name_of(vcells.first(), "Values"));
let skip = usize::from(header);
let mut rows: Vec<(f64, Value)> = Vec::new();
for (t, v) in tcells.iter().zip(&vcells).skip(skip) {
let (tv, vv) = (sh.value(*t), sh.value(*v));
match tv {
Value::Number(x) => rows.push((x, if matches!(vv, Value::Number(_)) { vv } else { Value::Empty })),
Value::Empty if vv.is_empty() => {}
_ => return Err(EngineError::Other(format!("The timeline must hold numbers or dates ({} isn't one).", t.a1()))),
}
}
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
let times: Vec<f64> = rows.iter().map(|r| r.0).collect();
let timeline =
Timeline::detect(&times, sys).ok_or_else(|| EngineError::Other("The timeline needs at least two points a constant step apart.".into()))?;
if !rows.iter().any(|r| matches!(r.1, Value::Number(_))) {
return Err(EngineError::Other("There are no values to forecast.".into()));
}
let end = match p.get("end") {
Some(Json::Number(n)) => n.as_f64(),
Some(Json::String(t)) if !t.trim().is_empty() => match gridcraft_core::parse::parse_input(t.trim(), sys).value {
Value::Number(end) => Some(end),
_ => return Err(bad(CMD, format!("`end` is not a number or a date: `{t}`"))),
},
_ => None,
};
let cap = max_periods(rows.len());
let periods = match end {
Some(end) => steps_to(&timeline, end, cap)?,
None => match number(p, "periods")? {
Some(n) if n >= 1.0 && n.ceil() <= f64::from(cap) => n.ceil() as u32,
Some(_) => return Err(bad(CMD, format!("`periods` is from 1 to {cap} for {} rows of history", rows.len()))),
None => default_periods(rows.len()),
},
};
let future: Vec<f64> =
(1..=periods).map(|k| timeline.after_last(k)).collect::<Option<_>>().ok_or_else(|| bad(CMD, "the forecast runs past the last date"))?;
let fmt_of = |c: Option<&CellRef>| c.map(|c| d.wb.styles.get(sh.style_id(*c)).num_fmt.clone()).unwrap_or_default();
let (tfmt, vfmt) = (fmt_of(tcells.get(skip)), fmt_of(vcells.get(skip)));
let sheet_name = d.wb.next_sheet_name();
let table_name = (1..).map(|n| format!("Table{n}")).find(|n| d.wb.table(n).is_none()).unwrap_or_else(|| "Table".into());
let chart_id = d.wb.next_object_id();
let table_id = chart_id.saturating_add(1);
// Columns: A timeline, B values, C forecast, D/E bounds.
let n = rows.len() as u32;
let last = n + 1; // 1-based row of the last history point
let end_row = last + periods; // 1-based row of the last forecast
let hist = |col: u32| format!("${0}$2:${0}${last}", col_letters(col));
let mut tail = format!("{},{}", opts.seasonality, opts.fill);
if let Some(a) = opts.aggregate {
tail.push_str(&format!(",{a}"));
}
let mut headers = vec![tname, vname.clone(), format!("Forecast({vname})")];
if opts.confidence.is_some() {
headers.push(format!("Lower Confidence Bound({vname})"));
headers.push(format!("Upper Confidence Bound({vname})"));
}
// Table column names are unique.
for i in 1..headers.len() {
let base = headers.get(i).cloned().unwrap_or_default();
let mut name = base.clone();
let mut k = 2;
while headers.iter().take(i).any(|h| h.eq_ignore_ascii_case(&name)) {
name = format!("{base}{k}");
k += 1;
}
if let Some(h) = headers.get_mut(i) {
*h = name;
}
}
let width = headers.len() as u32;
let stats_col = width + 1;
let chart_col = if opts.statistics { stats_col + 3 } else { width + 1 };
let at = s.doc()?.wb.active_sheet;
let index = edit(s, |cx| {
let at = at.min(cx.wb.sheets.len());
let bold = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.font.bold = true);
let tstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = tfmt.clone());
let vstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = vfmt.clone());
let mut sheet = Sheet::new(sheet_name.clone());
let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| {
sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style });
};
let formula = |sheet: &mut Sheet, row: u32, col: u32, text: String, style: StyleId| {
let mut cell = Cell::formula(Formula::new(&text));
cell.style = style;
sheet.set_cell(CellRef::new(row, col), cell);
};
for (c, h) in headers.iter().enumerate() {
put(&mut sheet, 0, c as u32, Value::text(h.as_str()), StyleId::DEFAULT);
}
for (i, (t, v)) in rows.iter().enumerate() {
let r = i as u32 + 1;
put(&mut sheet, r, 0, Value::Number(*t), tstyle);
if !v.is_empty() {
put(&mut sheet, r, 1, v.clone(), vstyle);
}
}
// The last history point starts the forecast lines, so they join the values.
formula(&mut sheet, n, 2, format!("=B{last}"), vstyle);
if opts.confidence.is_some() {
formula(&mut sheet, n, 3, format!("=C{last}"), vstyle);
formula(&mut sheet, n, 4, format!("=C{last}"), vstyle);
}
let (tl, vl) = (hist(0), hist(1));
for (k, t) in future.iter().enumerate() {
let r = last + k as u32 + 1; // 1-based
put(&mut sheet, r - 1, 0, Value::Number(*t), tstyle);
formula(&mut sheet, r - 1, 2, format!("=FORECAST.ETS(A{r},{vl},{tl},{tail})"), vstyle);
if let Some(c) = opts.confidence {
let ci = format!("FORECAST.ETS.CONFINT(A{r},{vl},{tl},{c},{tail})");
formula(&mut sheet, r - 1, 3, format!("=C{r}-{ci}"), vstyle);
formula(&mut sheet, r - 1, 4, format!("=C{r}+{ci}"), vstyle);
}
}
if opts.statistics {
put(&mut sheet, 0, stats_col, Value::text("Statistic"), bold);
put(&mut sheet, 0, stats_col + 1, Value::text("Value"), bold);
for (k, label) in ["Alpha", "Beta", "Gamma", "MASE", "SMAPE", "MAE", "RMSE"].iter().enumerate() {
let r = k as u32 + 1;
put(&mut sheet, r, stats_col, Value::text(*label), StyleId::DEFAULT);
formula(&mut sheet, r, stats_col + 1, format!("=FORECAST.ETS.STAT({vl},{tl},{},{tail})", k + 1), StyleId::DEFAULT);
}
}
for c in 0..width {
sheet.cols.insert(
c,
gridcraft_model::LineInfo {
size: Some(match c {
0 | 1 => 90.0,
2 => 130.0,
_ => 230.0,
}),
..Default::default()
},
);
}
let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(end_row - 1, width - 1));
sheet.tables.push(Table {
id: table_id,
name: table_name.clone(),
range,
header_row: true,
totals_row: false,
columns: headers.iter().map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None }).collect(),
style: "TableStyleMedium2".into(),
banded_rows: true,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: true,
filter: vec![],
});
let q = gridcraft_formula::quote_sheet(&sheet_name);
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
let series = (1..width)
.map(|c| Series {
name: Some(format!("{q}!${}$1", col_letters(c))),
categories: Some(col_ref(0)),
values: col_ref(c),
bubble_sizes: None,
color: None,
secondary: false,
kind: (opts.column_chart && c >= 3).then_some(ChartKind::Line),
smooth: false,
trendlines: Vec::new(),
})
.collect();
sheet.charts.push(Chart {
id: chart_id,
kind: if opts.column_chart { ChartKind::ColumnClustered } else { ChartKind::Line },
anchor: Anchor { cell: CellRef::new(1, chart_col), dx: 0.0, dy: 0.0, width: 480.0, height: 288.0, mode: Default::default() },
title: None,
series,
legend: LegendPos::Bottom,
data_labels: false,
gridlines: true,
style: 1,
x_title: None,
y_title: None,
source: None,
by_rows: false,
pivot: None,
});
cx.wb.sheets.insert(at, Arc::new(sheet));
for nm in cx.wb.names.iter_mut() {
if let Some(sc) = nm.scope.as_mut()
&& *sc >= at
{
*sc += 1;
}
}
cx.wb.active_sheet = at;
*cx.sel = crate::Selection::at(CellRef::new(0, 0));
cx.structural = true;
Ok(at)
})?;
if let Ok(d) = s.doc_mut() {
d.sheet_selections.insert(index.min(d.sheet_selections.len()), crate::Selection::default());
}
Ok(json!({"sheet": sheet_name, "table": table_name, "chart": chart_id, "history": n, "periods": periods}))
}
/// Forecast rows needed to reach `end` (rounded up to whole steps).
fn steps_to(timeline: &Timeline, end: f64, cap: u32) -> Result<u32> {
let steps = timeline.steps_after_last(end).ok_or_else(|| bad(CMD, "`end` is not on the timeline"))?;
if steps < 1e-9 {
return Err(EngineError::Other("The forecast end must be after the last point of the timeline.".into()));
}
let steps = steps.ceil();
if steps > f64::from(cap) {
return Err(bad(CMD, format!("at most {cap} forecast steps for this much history")));
}
Ok(steps as u32)
}
#[cfg(test)]
mod tests {
use gridcraft_core::{CellRef, Value};
use serde_json::json;
use crate::Session;
fn session_with_history() -> Session {
let mut s = Session::new();
s.new_workbook();
let mut rows = vec![json!(["Month", "Sales"])];
// y = 10 + 2t with a four-step season.
let season = [3.0, -1.0, 4.0, -6.0];
for t in 1..=16 {
rows.push(json!([t, 10.0 + 2.0 * t as f64 + season[(t - 1) % 4]]));
}
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s
}
fn value(s: &Session, sheet: usize, a1: &str) -> Value {
s.doc().unwrap().wb.sheet(sheet).unwrap().value(CellRef::parse(a1).unwrap())
}
fn formula(s: &Session, sheet: usize, a1: &str) -> String {
let wb = &s.doc().unwrap().wb;
wb.sheet(sheet).unwrap().cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap_or_default()
}
#[test]
fn forecast_sheet_builds_table_formulas_and_chart() {
let mut s = session_with_history();
s.execute("selection.set", json!({"range": "A1:B17"})).unwrap();
let r = s.execute("data.forecastSheet", json!({"periods": 4, "statistics": true})).unwrap();
assert_eq!(r["history"], 16);
assert_eq!(r["periods"], 4);
let wb = &s.doc().unwrap().wb;
// Inserted before the data sheet and activated.
assert_eq!(wb.active_sheet, 0);
let sh = wb.sheet(0).unwrap();
assert_eq!(sh.name, r["sheet"].as_str().unwrap());
assert_eq!(value(&s, 0, "C1"), Value::text("Forecast(Sales)"));
assert_eq!(value(&s, 0, "D1"), Value::text("Lower Confidence Bound(Sales)"));
assert_eq!(value(&s, 0, "E1"), Value::text("Upper Confidence Bound(Sales)"));
assert_eq!(formula(&s, 0, "C17"), "B17");
assert_eq!(formula(&s, 0, "C18"), "FORECAST.ETS(A18,$B$2:$B$17,$A$2:$A$17,1,1)");
assert_eq!(formula(&s, 0, "D18"), "C18-FORECAST.ETS.CONFINT(A18,$B$2:$B$17,$A$2:$A$17,0.95,1,1)");
assert_eq!(formula(&s, 0, "H2"), "FORECAST.ETS.STAT($B$2:$B$17,$A$2:$A$17,1,1,1)");
// Future timeline and the exact continuation of the seasonal series (t = 17 → 10 + 34 + 3).
assert_eq!(value(&s, 0, "A18"), Value::Number(17.0));
assert_eq!(value(&s, 0, "A21"), Value::Number(20.0));
let c18 = value(&s, 0, "C18").as_f64().unwrap();
assert!((c18 - 47.0).abs() < 1e-6, "{c18}");
let (lo, hi) = (value(&s, 0, "D19").as_f64().unwrap(), value(&s, 0, "E19").as_f64().unwrap());
assert!(lo <= hi);
assert_eq!(sh.tables.first().map(|t| t.range.a1()), Some("A1:E21".into()));
let chart = sh.charts.first().unwrap();
assert_eq!(chart.series.len(), 4);
assert_eq!(chart.series[1].values, format!("{}!$C$2:$C$21", r["sheet"].as_str().unwrap()));
// One undo step removes the sheet again.
let sheets = s.doc().unwrap().wb.sheets.len();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets - 1);
}
#[test]
fn history_and_periods_are_capped() {
use super::{MAX_HISTORY, MAX_PERIODS, MAX_WORK, default_periods, max_periods};
// The default (a third of the history) never exceeds the caps.
assert_eq!(default_periods(16), 6);
assert_eq!(default_periods(1_200), 400);
assert_eq!(default_periods(3_000), 166);
assert_eq!(default_periods(100_000), 5);
assert_eq!(max_periods(10), MAX_PERIODS);
assert_eq!(max_periods(0), MAX_PERIODS);
for h in [1usize, 2, 3, 50, 51, 1_000, 1_300, 3_000, 10_000, 100_000, usize::MAX] {
let (d, m) = (default_periods(h), max_periods(h));
assert!(d >= 1 && d <= m && m <= MAX_PERIODS, "{h}: {d} {m}");
assert!(u64::try_from(h).unwrap_or(u64::MAX).saturating_mul(u64::from(m)) <= MAX_WORK.max(u64::try_from(h).unwrap_or(u64::MAX)), "{h}");
}
// Explicit periods or an end past the cap are refused before anything is built.
let mut s = Session::new();
s.new_workbook();
let mut rows = vec![json!(["t", "y"])];
rows.extend((1..=1_300).map(|t| json!([t, (t % 7) as f64 + t as f64 * 0.5])));
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
let sheets = s.doc().unwrap().wb.sheets.len();
let cap = max_periods(1_300); // 384
let err = |r: crate::Result<serde_json::Value>| r.err().map(|e| e.to_string()).unwrap_or_default();
assert!(err(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "periods": cap + 1}))).contains("from 1 to 384"));
assert!(err(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "end": 1_300 + cap + 1}))).contains("at most 384"));
assert!(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "periods": 10_000})).is_err());
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets);
// More history rows than MAX_HISTORY are refused.
let big = MAX_HISTORY + 2;
let r = s.execute("data.forecastSheet", json!({"timeline": format!("A1:A{big}"), "values": format!("B1:B{big}")}));
assert!(r.is_err());
}
#[test]
fn forecast_sheet_parameters_and_errors() {
let mut s = session_with_history();
let r = s
.execute(
"data.forecastSheet",
json!({"timeline": "A2:A17", "values": "B2:B17", "end": "22", "confidenceInterval": false, "seasonality": 4, "fillMissing": "zeros", "aggregate": "sum", "chart": "column"}),
)
.unwrap();
assert_eq!(r["periods"], 6);
assert_eq!(value(&s, 0, "B1"), Value::text("Values"));
assert_eq!(formula(&s, 0, "C18"), "FORECAST.ETS(A18,$B$2:$B$17,$A$2:$A$17,4,0,7)");
assert_eq!(value(&s, 0, "D1"), Value::Empty);
let sh = s.doc().unwrap().wb.sheet(0).unwrap();
assert_eq!(sh.charts.first().map(|c| c.kind), Some(gridcraft_model::ChartKind::ColumnClustered));
// Errors: end before the data, bad seasonality, uneven timeline, one column only.
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17", "end": 3})).is_err());
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17", "seasonality": 9000})).is_err());
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!B1:B17"})).is_err());
s.execute("cell.set", json!({"cell": "A5", "input": "4.5"})).unwrap();
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17"})).is_err());
}
}
+55 -8
View File
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
// Alignment
cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)),
cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)),
cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], Some("Cmd+R"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)),
cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)),
cmd!("home.justify", "Justify", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Justify)),
cmd!("home.alignTop", "Top Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Top)),
cmd!("home.alignMiddle", "Middle Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Center)),
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Row Height…",
["Home", "Cells", "Format"],
None,
"{rows?: \"2:5\", height: 20 (points on screen)}",
"{rows?: \"2:5\" | \"2:2,4:5\", height: 20 (points on screen)}",
has_doc,
row_height
),
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Column Width…",
["Home", "Cells", "Format"],
None,
"{cols?: \"B:D\", width: 64 (points) | chars: 8.43}",
"{cols?: \"B:D\" | \"B:B,D:F\", width: 64 (points) | chars: 8.43}",
has_doc,
col_width
),
@@ -365,6 +365,9 @@ fn borders(s: &mut Session, p: &Json) -> Result<Json> {
let base = border_style(str_param(p, "style").unwrap_or("thin"));
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
if s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.protection.as_ref().is_some_and(|pr| !pr.format_cells)) {
return Err(EngineError::Other("The cell or chart you're trying to change is on a protected sheet.".into()));
}
edit(s, |cx| {
for r in &ranges {
if r.count() > 2_000_000 {
@@ -453,7 +456,29 @@ fn borders(s: &mut Session, p: &Json) -> Result<Json> {
}
});
cx.sheet_mut(sheet)?.set_style(c, new);
// Clear the neighbour's facing edge when removing borders, so it really goes.
if preset == "none" {
// A shared line can be stored on either cell. Selected cells are handled
// by this loop; remove only facing edges outside this range.
for (boundary, dr, dc) in [(top, -1, 0), (bottom, 1, 0), (left, 0, -1), (right, 0, 1)] {
if !boundary {
continue;
}
let Some(neighbor) = c.offset(dr, dc) else { continue };
let st = cx.wb.sheet(sheet).map(|sh| sh.style_id(neighbor)).unwrap_or_default();
let new = cx.wb.styles.derive(st, |s| {
let edge = match (dr, dc) {
(-1, _) => &mut s.borders.bottom,
(1, _) => &mut s.borders.top,
(_, -1) => &mut s.borders.right,
_ => &mut s.borders.left,
};
*edge = BorderLine::default();
});
if new != st {
cx.sheet_mut(sheet)?.set_style(neighbor, new);
}
}
}
}
}
Ok(Json::Null)
@@ -536,8 +561,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
edit(s, |cx| {
let mut touched = Vec::new();
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
let mut areas: Vec<RangeRef> = ranges.clone();
for r in &ranges {
let sh = cx.sheet_mut(sheet)?;
areas.extend(sh.merges.iter().filter(|m| m.intersects(r)));
sh.merges.retain(|m| !m.intersects(r));
match how {
"unmerge" => {}
@@ -560,7 +588,7 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
if let Some(mut cell) = sh.cells.get(c).cloned() {
cell.value = gridcraft_core::Value::Empty;
cell.formula = None;
sh.cells.set(c, cell);
sh.set_cell(c, cell);
}
touched.push((sheet, c));
}
@@ -568,6 +596,17 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
}
}
}
// Spills over the areas, and blocked ones that could reach them, are evaluated again.
let sh = cx.sheet_mut(sheet)?;
for a in &areas {
touched.extend(sh.spill_ranges.iter().filter(|(_, r)| r.intersects(a)).map(|(anchor, _)| (sheet, *anchor)));
let reach = RangeRef::new(CellRef::new(0, 0), a.end);
let blocked = sh
.cells
.iter_range(reach)
.filter(|(_, x)| x.formula.is_some() && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill));
touched.extend(blocked.map(|(c, _)| (sheet, c)));
}
cx.changed.extend(touched);
Ok(())
})?;
@@ -885,8 +924,14 @@ fn cell_style(s: &mut Session, p: &Json) -> Result<Json> {
fn line_targets(s: &Session, p: &Json, rows: bool) -> Result<Vec<(u32, u32)>> {
let key = if rows { "rows" } else { "cols" };
if let Some(t) = str_param(p, key) {
let r = RangeRef::parse(t).ok_or_else(|| bad(key, format!("not a range: {t}")))?;
return Ok(vec![if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }]);
// A comma-separated list ("B:B,D:F") targets several areas, like a multi-area selection.
return t
.split(',')
.map(|part| {
let r = RangeRef::parse(part).ok_or_else(|| bad(key, format!("not a range: {part}")))?;
Ok(if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) })
})
.collect();
}
Ok(s.doc()?.selection.ranges.iter().map(|r| if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }).collect())
}
@@ -988,7 +1033,9 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let st = cx.wb.styles.get(sh.style_id(cell));
let text = crate::display::cell_text(&cx.wb, sh, cell);
for line in text.lines() {
max = max.max(approx_text_width(line, st.font.size, st.font.bold) + 6.0 + st.align.indent as f32 * 9.0);
max = max.max(
approx_text_width(line, st.font.size, st.font.bold) + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell),
);
}
}
if max > 0.0 {
+191 -44
View File
@@ -1,7 +1,7 @@
//! Formulas tab: AutoSum, Insert Function, names, auditing, calculation.
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_model::{CalcMode, DefinedName};
use gridcraft_model::{CalcMode, DefinedName, Formula};
use serde_json::{Value as Json, json};
use super::*;
@@ -32,18 +32,18 @@ pub fn specs() -> Vec<CommandSpec> {
"Define Name…",
["Formulas", "Defined Names"],
None,
"{name, refersTo?: \"=Sheet1!$A$1:$A$10\" (default: the selection), scope?: \"Workbook\"|sheet name, comment?}",
"{name, refersTo?: \"=Sheet1!$A$1:$A$10\" (default: the selection), scope?: \"Workbook\"|sheet name, comment?, oldName?, oldScope?} (oldName: edit that name (Name Manager › Edit); a new name also renames it in formulas)",
has_doc,
define_name
),
cmd!("formulas.deleteName", "Delete Name", [], None, "{name, scope?}", has_doc, delete_name),
cmd!("formulas.deleteName", "Delete Name", [], None, "{name, scope?: \"Workbook\"|sheet name (default: every scope)}", has_doc, delete_name),
cmd!(query "formulas.nameManager", "Name Manager", ["Formulas", "Defined Names"], Some("Cmd+F3"), "{} → names with values", has_doc, name_manager),
cmd!(
"formulas.createFromSelection",
"Create from Selection",
["Formulas", "Defined Names"],
Some("Cmd+Shift+F3"),
"{range?, top?: true, left?: false, bottom?, right?}",
"{range?, top?: true, left?: false, bottom?: false, right?: false, replace?: false (existing names are kept and listed in `skipped`)}",
has_doc,
create_from_selection
),
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Calculation Options",
["Formulas", "Calculation"],
None,
"{mode: automatic|automaticExceptTables|manual, iterative?, maxIterations?, maxChange?}",
"{mode?: automatic|automaticExceptTables|manual, iterative?: bool (Enable iterative calculation), maxIterations?: 1–32767 (100), maxChange?: number (0.001)} → the settings. File › Options › Formulas › Calculation options; stored in the workbook.",
has_doc,
calc_options
),
@@ -78,18 +78,28 @@ fn auto_sum(s: &mut Session, p: &Json) -> Result<Json> {
};
if !sel.is_single() {
// A block: totals below each column (and to the right when a blank column is included).
let num_end = sel.end;
let below = CellRef::new(num_end.row + 1, 0);
let mut writes = Vec::new();
let last_row_blank = (sel.start.col..=sel.end.col).all(|c| sh.value(CellRef::new(sel.end.row, c)).is_empty());
let (data_end_row, out_row) = if last_row_blank { (sel.end.row.saturating_sub(1), sel.end.row) } else { (sel.end.row, below.row) };
for c in sel.start.col..=sel.end.col {
let r = RangeRef::new(CellRef::new(sel.start.row, c), CellRef::new(data_end_row, c));
writes.push((CellRef::new(out_row, c), format!("={func}({})", r.a1())));
}
for (c, f) in writes {
s.execute("cell.set", json!({"cell": c.a1(), "input": f}))?;
// Columns past the sheet's data get no total (a whole-row selection doesn't write 16,384
// formulas), and all totals are one edit (one undo step).
let Some(last_col) = sh.cells.used_range().map(|u| u.end.col.min(sel.end.col)) else { return ok() };
let last_row_blank = (sel.start.col..=last_col).all(|c| sh.value(CellRef::new(sel.end.row, c)).is_empty());
let (data_end_row, out_row) = if last_row_blank { (sel.end.row.saturating_sub(1), sel.end.row) } else { (sel.end.row, sel.end.row + 1) };
if out_row >= gridcraft_core::MAX_ROWS {
return Err(EngineError::Other("There's no room below the selection for the totals.".into()));
}
let writes: Vec<(CellRef, String)> = (sel.start.col..=last_col)
.map(|c| {
(CellRef::new(out_row, c), format!("={func}({})", RangeRef::new(CellRef::new(sel.start.row, c), CellRef::new(data_end_row, c)).a1()))
})
.collect();
let sheet = d.wb.active_sheet;
edit(s, |cx| {
for (c, f) in &writes {
let cell = super::edit::input_to_cell(f, sheet, *c, &mut cx.wb)?.unwrap_or_default();
cx.sheet_mut(sheet)?.set_cell(*c, cell);
cx.touch(sheet, *c);
}
Ok(())
})?;
return ok();
}
// Single cell: guess the range above, else to the left.
@@ -185,6 +195,7 @@ pub fn function_list() -> Vec<Json> {
("SHEET", "Information", "SHEET([value])", "Sheet number."),
("SHEETS", "Information", "SHEETS([reference])", "Number of sheets."),
("AREAS", "Lookup", "AREAS(reference)", "Number of areas in a reference."),
("TRIMRANGE", "Lookup", "TRIMRANGE(range, [trim_rows], [trim_cols])", "A range or array without its blank outer rows and columns."),
("ISOMITTED", "Information", "ISOMITTED(argument)", "TRUE when a LAMBDA argument was left out."),
];
for (n, c, sig, d) in specials {
@@ -218,15 +229,26 @@ fn valid_name(n: &str) -> bool {
if !(first.is_alphabetic() || first == '_' || first == '\\') {
return false;
}
if n.len() > 255 || n.eq_ignore_ascii_case("R") || n.eq_ignore_ascii_case("C") {
return false;
}
if CellRef::parse(n).is_some() {
if n.len() > 255 || CellRef::parse(n).is_some() || is_r1c1(n) {
return false;
}
n.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | '\\' | '?'))
}
/// Looks like an R1C1 reference (`R`, `C`, `RC`, `R2`, `C3`, `R1C1`), which Excel doesn't
/// accept as a name.
fn is_r1c1(n: &str) -> bool {
let digits = |s: &str| s.bytes().take_while(u8::is_ascii_digit).count();
let mut rest = n;
if let Some(r) = rest.strip_prefix(['R', 'r']) {
rest = r.get(digits(r)..).unwrap_or("");
}
if let Some(c) = rest.strip_prefix(['C', 'c']) {
rest = c.get(digits(c)..).unwrap_or("");
}
rest.is_empty() && !n.is_empty()
}
fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
let Some(name) = str_param(p, "name").map(str::to_string) else {
s.ui_requests.push(crate::UiRequest::Dialog("defineName".into(), json!({})));
@@ -241,7 +263,15 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
Some(sh) => Some(d.wb.sheet_index(sh).ok_or_else(|| bad("formulas.defineName", "no such sheet"))?),
};
let refers = match str_param(p, "refersTo") {
Some(r) => r.trim_start_matches('=').to_string(),
// As in Excel, relative references are relative to the active cell; names keep them
// relative to A1, as files do.
Some(r) => match gridcraft_formula::parse(r.trim_start_matches('=')) {
Ok(e) if gridcraft_formula::adjust::has_relative_refs(&e) => {
let at = d.selection.active;
gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative_wrapping(e, -(at.row as i64), -(at.col as i64)))
}
_ => r.trim_start_matches('=').to_string(),
},
None => {
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let r = d.selection.current();
@@ -254,7 +284,32 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
return Err(EngineError::Other("There's a problem with this formula.".into()));
}
let comment = str_param(p, "comment").unwrap_or("").to_string();
// Editing an existing name (Name Manager › Edit…): it must exist, and its new name must not
// collide with another name in the target scope.
let old = match str_param(p, "oldName") {
Some(old_name) => {
let old_scope = match str_param(p, "oldScope") {
None | Some("Workbook") => None,
Some(sh) => Some(d.wb.sheet_index(sh).ok_or_else(|| bad("formulas.defineName", "no such sheet"))?),
};
if !d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(old_name) && n.scope == old_scope) {
return Err(bad("formulas.defineName", "no such name to edit"));
}
let same = old_name.eq_ignore_ascii_case(&name) && old_scope == scope;
if !same && d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(&name) && n.scope == scope) {
return Err(EngineError::Other("The name entered already exists. Enter a unique name.".into()));
}
Some((old_name.to_string(), old_scope))
}
None => None,
};
edit(s, |cx| {
if let Some((old_name, old_scope)) = &old {
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope));
if !old_name.eq_ignore_ascii_case(&name) {
rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name);
}
}
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope));
cx.wb.names.push(DefinedName { name: name.clone(), scope, formula: refers.clone(), comment: comment.clone(), hidden: false });
cx.structural = true;
@@ -262,11 +317,61 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on
/// the sheets where `old` resolves to the renamed name (its own sheet for a sheet-scoped name;
/// every sheet without a same-named sheet-level name for a workbook-level one).
fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option<usize>, new: &str) {
let shadowed: Vec<usize> = wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(old)).filter_map(|n| n.scope).collect();
let applies = |sheet: usize| match old_scope {
Some(s) => s == sheet,
None => !shadowed.contains(&sheet),
};
// The renamed expression, or `None` when the name doesn't occur in it.
let rename = |e: gridcraft_formula::Expr| {
let mut hit = false;
let out = e.map(&mut |x| match x {
gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(old) => {
hit = true;
gridcraft_formula::Expr::Name(new.to_string())
}
o => o,
});
hit.then_some(out)
};
for i in 0..wb.sheets.len() {
if !applies(i) {
continue;
}
let Some(sh) = wb.sheet_mut(i) else { continue };
let formulas: Vec<(CellRef, std::sync::Arc<Formula>)> = sh.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect();
for (c, f) in formulas {
let Some(e) = f.expr().and_then(rename) else { continue };
let mut nf = Formula::from_expr(e);
nf.array = f.array;
if let Some(cell) = sh.cells.get_mut(c) {
cell.formula = Some(std::sync::Arc::new(nf));
}
}
}
for n in wb.names.iter_mut() {
if n.scope.is_none_or(applies)
&& let Some(e) = gridcraft_formula::parse(&n.formula).ok().and_then(rename)
{
n.formula = gridcraft_formula::print(&e);
}
}
}
fn delete_name(s: &mut Session, p: &Json) -> Result<Json> {
let name = str_param(p, "name").ok_or_else(|| bad("formulas.deleteName", "missing `name`"))?.to_string();
let scope = match str_param(p, "scope") {
None => None,
Some("Workbook") => Some(None),
Some(sh) => Some(Some(s.doc()?.wb.sheet_index(sh).ok_or_else(|| bad("formulas.deleteName", "no such sheet"))?)),
};
edit(s, |cx| {
let before = cx.wb.names.len();
cx.wb.names.retain(|n| !n.name.eq_ignore_ascii_case(&name));
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && scope.is_none_or(|sc| n.scope == sc)));
if cx.wb.names.len() == before {
return Err(bad("formulas.deleteName", "no such name"));
}
@@ -295,6 +400,9 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
let r = target_range(s, p)?;
let top = bool_param(p, "top").unwrap_or(true);
let left = bool_param(p, "left").unwrap_or(false);
let bottom = bool_param(p, "bottom").unwrap_or(false);
let right = bool_param(p, "right").unwrap_or(false);
let replace = bool_param(p, "replace").unwrap_or(false);
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let q = gridcraft_formula::quote_sheet(&sh.name);
@@ -309,28 +417,38 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
};
let clean = |t: String| -> String {
let mut n: String = t.trim().chars().map(|c| if c.is_alphanumeric() || c == '.' { c } else { '_' }).collect();
if n.chars().next().is_some_and(|c| c.is_ascii_digit()) || CellRef::parse(&n).is_some() {
if !n.is_empty() && !valid_name(&n) {
n.insert(0, '_');
}
n
if valid_name(&n) { n } else { String::new() }
};
// The labels in the chosen edge rows/columns name the cells between them.
let (r0, r1) = (r.start.row + top as u32, r.end.row.saturating_sub(bottom as u32));
let (c0, c1) = (r.start.col + left as u32, r.end.col.saturating_sub(right as u32));
let mut made = Vec::new();
if top && r.height() > 1 {
for c in r.start.col..=r.end.col {
let name = clean(sh.value(CellRef::new(r.start.row, c)).display());
if !name.is_empty() {
made.push((name, abs(RangeRef::new(CellRef::new(r.start.row + 1, c), CellRef::new(r.end.row, c)))));
if r0 <= r1 && c0 <= c1 {
for (on, row) in [(top, r.start.row), (bottom, r.end.row)] {
for c in (c0..=c1).filter(|_| on) {
let name = clean(sh.value(CellRef::new(row, c)).display());
if !name.is_empty() {
made.push((name, abs(RangeRef::new(CellRef::new(r0, c), CellRef::new(r1, c)))));
}
}
}
}
if left && r.width() > 1 {
for row in r.start.row + top as u32..=r.end.row {
let name = clean(sh.value(CellRef::new(row, r.start.col)).display());
if !name.is_empty() {
made.push((name, abs(RangeRef::new(CellRef::new(row, r.start.col + 1), CellRef::new(row, r.end.col)))));
for (on, col) in [(left, r.start.col), (right, r.end.col)] {
for row in (r0..=r1).filter(|_| on) {
let name = clean(sh.value(CellRef::new(row, col)).display());
if !name.is_empty() {
made.push((name, abs(RangeRef::new(CellRef::new(row, c0), CellRef::new(row, c1)))));
}
}
}
}
// Excel asks before replacing an existing name; here it's kept unless `replace` is set, and
// reported.
let exists = |n: &str| d.wb.names.iter().any(|x| x.name.eq_ignore_ascii_case(n) && x.scope.is_none());
let (made, skipped): (Vec<_>, Vec<_>) = made.into_iter().partition(|(n, _)| replace || !exists(n));
let skipped: Vec<String> = skipped.into_iter().map(|(n, _)| n).collect();
let n = made.len();
edit(s, |cx| {
for (name, f) in made {
@@ -338,13 +456,13 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
cx.wb.names.push(DefinedName { name, scope: None, formula: f, comment: String::new(), hidden: false });
}
cx.structural = true;
Ok(json!({"created": n}))
Ok(json!({"created": n, "skipped": skipped}))
})
}
fn trace_precedents(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let areas = d.calc.graph.precedents_of((d.wb.active_sheet, at));
let v: Vec<Json> = areas.iter().map(|a| json!({"sheet": d.wb.sheet(a.sheet).map(|s| s.name.clone()), "range": a.range.a1()})).collect();
Ok(Json::Array(v))
@@ -352,7 +470,7 @@ fn trace_precedents(s: &mut Session, p: &Json) -> Result<Json> {
fn trace_dependents(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let mut deps = Vec::new();
d.calc.graph.dependents(d.wb.active_sheet, at, &mut deps);
deps.sort();
@@ -393,7 +511,7 @@ fn error_checking(s: &mut Session, _: &Json) -> Result<Json> {
fn evaluate_formula(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let sheet = d.wb.active_sheet;
let text = match str_param(p, "formula") {
Some(f) => f.trim_start_matches('=').to_string(),
@@ -425,7 +543,7 @@ fn evaluate_formula(s: &mut Session, p: &Json) -> Result<Json> {
fn evaluate(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let f = str_param(p, "formula").ok_or_else(|| bad("formulas.evaluate", "missing `formula`"))?;
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let v = gridcraft_calc::evaluate(&d.wb, d.wb.active_sheet, at, f);
Ok(crate::cmd::inspect::value_json(&v))
}
@@ -446,6 +564,7 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
_ => None,
};
edit(s, |cx| {
let before = cx.wb.calc.clone();
if let Some(m) = mode {
cx.wb.calc.mode = m;
}
@@ -453,14 +572,42 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
cx.wb.calc.iterative = v;
}
if let Some(v) = u32_param(p, "maxIterations") {
cx.wb.calc.max_iterations = v.clamp(1, 32767);
cx.wb.calc.set_max_iterations(v);
}
if let Some(v) = f64_param(p, "maxChange") {
cx.wb.calc.max_change = v.abs();
cx.wb.calc.set_max_change(v);
}
if mode == Some(CalcMode::Automatic) {
let c = &cx.wb.calc;
// Switching to automatic, or changing how circular references are calculated outside
// manual mode, recalculates the workbook.
let iteration_changed = (c.iterative, c.max_iterations, c.max_change) != (before.iterative, before.max_iterations, before.max_change);
if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) {
cx.structural = true;
}
Ok(json!({"mode": format!("{:?}", cx.wb.calc.mode)}))
Ok(json!({"mode": format!("{:?}", c.mode), "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change}))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_with_relative_references() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap();
// Defined from B2, `=Sheet1!A2` is "the cell to the left".
s.execute("selection.set", json!({"range": "B2"})).unwrap();
let r = s.execute("formulas.defineName", json!({"name": "LeftCell", "refersTo": "=Sheet1!A2"})).unwrap();
assert_eq!(r["refersTo"], "=Sheet1!XFD1");
s.execute("cell.set", json!({"cell": "B1", "input": "=LeftCell"})).unwrap();
s.execute("cell.set", json!({"cell": "B3", "input": "=LeftCell*10"})).unwrap();
let v = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
assert_eq!(v(&mut s, "B1"), json!(1.0));
assert_eq!(v(&mut s, "B3"), json!(30.0));
// Absolute references are kept as they are.
let r = s.execute("formulas.defineName", json!({"name": "First", "refersTo": "=Sheet1!$A$1"})).unwrap();
assert_eq!(r["refersTo"], "=Sheet1!$A$1");
}
}
+371 -50
View File
@@ -1,7 +1,7 @@
//! Insert tab: tables, charts, sparklines, pictures, shapes, hyperlinks, comments and notes,
//! conditional formatting (Home › Styles) and symbols.
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_core::{CellRef, MAX_ROWS, RangeRef};
use gridcraft_model::*;
use serde_json::{Value as Json, json};
@@ -67,10 +67,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
insert_chart
),
cmd!("insert.recommendedCharts", "Recommended Charts", ["Insert", "Charts"], None, "{range?}", has_doc, |s, p| insert_chart(
s,
&with(p, "type", json!("auto"))
)),
cmd!(
"insert.recommendedCharts",
"Recommended Charts",
["Insert", "Charts"],
None,
"{range?, type?, subtype?} (no type: the first of insert.chartRecommendations; the ribbon button opens the dialog)",
has_doc,
|s, p| insert_chart(s, &if p.get("type").is_some() { p.clone() } else { with(p, "type", json!("auto")) })
),
cmd!(
query "insert.chartRecommendations",
"Chart Recommendations",
[],
None,
"{range?} → [{type, subtype, label}] chart types that suit the data's shape, best first",
has_doc,
|s, p| Ok(Json::Array(recommend_charts(s, p)?.into_iter().map(|(t, sub, label)| json!({"type": t, "subtype": sub, "label": label})).collect()))
),
cmd!(
"chart.set",
"Chart Properties",
@@ -96,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Picture",
["Insert", "Illustrations"],
None,
"{path? | base64?: \"...\", mime?, at?: \"B2\", width?, height?, alt?}",
"{path? | base64?: \"...\", mime?, at?: \"B2\", width?, height?, alt?, mode?: moveOnly|moveAndSize|absolute, placement?: cell|overCells}",
has_doc,
insert_picture
),
@@ -122,8 +136,18 @@ pub fn specs() -> Vec<CommandSpec> {
s,
&with(p, "kind", json!("textBox"))
)),
cmd!("shape.setText", "Edit Text Box", [], None, "{id: textBox id, text: string}", has_doc, shape_set_text),
cmd!("object.delete", "Delete Object", [], None, "{kind: chart|image|shape, id}", has_doc, delete_object),
cmd!("object.move", "Move Object", [], None, "{kind: chart|image|shape, id, at?: \"C3\", dx?, dy?, width?, height?}", has_doc, move_object),
cmd!(
"object.setAnchorMode",
"Object Properties",
[],
None,
"{kind: chart|image|shape, id, mode: moveAndSize|moveOnly|absolute}",
has_doc,
set_anchor_mode
),
cmd!(
"insert.link",
"Link",
@@ -133,8 +157,10 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
insert_link
),
cmd!("review.newNote", "New Note", ["Review", "Notes"], None, "{cell?, text, author?}", has_doc, |s, p| comment(s, p, false)),
cmd!("review.newComment", "New Comment", ["Review", "Comments"], None, "{cell?, text, author?}", has_doc, |s, p| comment(s, p, true)),
cmd!("review.newNote", "New Note", ["Review", "Notes"], Some("Shift+F2"), "{cell?, text, author?}", has_doc, |s, p| comment(s, p, false)),
cmd!("review.newComment", "New Comment", ["Review", "Comments"], Some("Cmd+Shift+F2"), "{cell?, text, author?}", has_doc, |s, p| comment(
s, p, true
)),
cmd!("review.replyComment", "Reply", [], None, "{cell?, text, author?}", has_doc, reply_comment),
cmd!("review.resolveComment", "Resolve Thread", [], None, "{cell?, resolved?: true}", has_doc, resolve_comment),
cmd!("review.deleteComment", "Delete Comment", ["Review", "Comments"], None, "{cell?}", has_doc, delete_comment),
@@ -198,6 +224,12 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
if d.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&r))) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
}
let arrays = |sh: &gridcraft_model::Sheet| {
sh.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r)))
};
if d.wb.sheet(sheet).is_some_and(arrays) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
if r.count() > 50_000_000 {
return Err(bad("insert.table", "range too large"));
}
@@ -208,9 +240,19 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
let name = str_param(p, "name")
.map(str::to_string)
.unwrap_or_else(|| (1..).map(|n| format!("Table{n}")).find(|n| d.wb.table(n).is_none()).unwrap_or_else(|| "Table".into()));
if name.is_empty() || name.contains(' ') || name.chars().next().is_some_and(|c| c.is_ascii_digit()) || CellRef::parse(&name).is_some() {
return Err(EngineError::Other("The name that you entered is not valid.".into()));
}
if d.wb.table(&name).is_some() || d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(&name)) {
return Err(EngineError::Other("The name entered already exists. Enter a unique name.".into()));
}
// Without a header row, the data moves down a row to make room for one: never a table with it.
let moves_a_table = |sh: &gridcraft_model::Sheet| {
sh.tables.iter().any(|t| t.range.end.row >= r.start.row && t.range.start.col <= r.end.col && t.range.end.col >= r.start.col)
};
if !header && d.wb.sheet(sheet).is_some_and(moves_a_table) {
return Err(EngineError::Other("This operation isn't allowed: it would shift cells in a table on your worksheet.".into()));
}
let style = str_param(p, "style").unwrap_or("TableStyleMedium2").to_string();
let id = d.wb.next_object_id();
edit(s, |cx| {
@@ -219,26 +261,45 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
r
} else {
let sh = cx.sheet_mut(sheet)?;
// The header row pushes the data down one row: never off the end of the sheet.
let last = RangeRef::new(CellRef::new(MAX_ROWS - 1, r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col));
if sh.cells.iter_range(last).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) {
return Err(EngineError::Other("To prevent possible loss of data, cells can't be pushed off the end of the worksheet.".into()));
}
sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.start.row, 1);
sh.cell_pictures = std::mem::take(&mut sh.cell_pictures)
.into_iter()
.filter_map(|(c, v)| {
let dest = if c.col >= r.start.col && c.col <= r.end.col && c.row >= r.start.row { c.offset(1, 0) } else { Some(c) };
dest.map(|c| (c, v))
})
.collect();
for (i, c) in (r.start.col..=r.end.col).enumerate() {
sh.set_value(CellRef::new(r.start.row, c), gridcraft_core::Value::text(format!("Column{}", i + 1)));
}
cx.structural = true;
RangeRef::new(r.start, CellRef::new(r.end.row + 1, r.end.col))
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
};
let sh = cx.sheet_mut(sheet)?;
let mut names: Vec<String> = Vec::new();
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
// headers don't take cubic time.
let mut taken = std::collections::HashSet::new();
let mut next_suffix = std::collections::HashMap::new();
for c in r.start.col..=r.end.col {
let mut n = sh.value(CellRef::new(r.start.row, c)).display();
if n.is_empty() {
n = format!("Column{}", c - r.start.col + 1);
}
let base = n.clone();
let mut k = 2;
while names.iter().any(|x| x.eq_ignore_ascii_case(&n)) {
let key = base.to_ascii_lowercase();
let mut k = next_suffix.get(&key).copied().unwrap_or(2);
while taken.contains(&n.to_ascii_lowercase()) {
n = format!("{base}{k}");
k += 1;
}
next_suffix.insert(key, k);
taken.insert(n.to_ascii_lowercase());
// Headers are text.
sh.set_value(CellRef::new(r.start.row, c), gridcraft_core::Value::text(n.as_str()));
names.push(n);
@@ -256,6 +317,7 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
first_col: false,
last_col: false,
filter_button: true,
filter: vec![],
});
cx.structural = true;
Ok(json!({"table": name, "range": r.a1()}))
@@ -304,7 +366,7 @@ fn table_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
t.range.end.row = t.range.end.row.saturating_sub(1);
let (c0, c1) = (t.range.start.col, t.range.end.col);
for c in c0..=c1 {
sh.cells.remove(CellRef::new(row, c));
sh.remove_cell(CellRef::new(row, c));
}
}
write_totals(sh, ti);
@@ -315,7 +377,12 @@ fn table_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
"bandedCols" => t.banded_cols = on.unwrap_or(!t.banded_cols),
"firstCol" => t.first_col = on.unwrap_or(!t.first_col),
"lastCol" => t.last_col = on.unwrap_or(!t.last_col),
"header" => t.filter_button = on.unwrap_or(!t.filter_button),
"header" => {
t.filter_button = on.unwrap_or(!t.filter_button);
if !t.filter_button {
t.filter.clear();
}
}
_ => {}
}
Ok(Json::Null)
@@ -333,12 +400,11 @@ fn write_totals(sh: &mut Sheet, ti: usize) {
let c = CellRef::new(row, t.range.start.col + i as u32);
if let Some(code) = col.totals.subtotal_code() {
let f = format!("=SUBTOTAL({code},{}[{}])", t.name, col.name);
sh.cells
.set(c, Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c) });
sh.set_cell(c, Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c) });
} else if let Some(l) = &col.totals_label {
sh.set_value(c, gridcraft_core::Value::text(l.as_str()));
} else {
sh.cells.remove(c);
sh.remove_cell(c);
}
}
}
@@ -495,7 +561,12 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
let header_row = r.height() > 1
&& (r.start.col..=r.end.col).any(|c| sh.value(CellRef::new(r.start.row, c)).is_text())
&& (r.start.col..=r.end.col).filter(|c| *c != r.start.col).all(|c| is_text(CellRef::new(r.start.row, c)));
let label_col = r.width() > 1 && (r.start.row + header_row as u32..=r.end.row).all(|row| is_text(CellRef::new(row, r.start.col)));
// A blank top-left cell above a header row marks the first column as the category labels even
// when it holds numbers (years, X values), the usual spreadsheet convention, so it isn't
// plotted as a series of its own (#287).
let blank_corner = header_row && sh.value(r.start).is_empty();
let label_col =
r.width() > 1 && (blank_corner || (r.start.row + header_row as u32..=r.end.row).all(|row| is_text(CellRef::new(row, r.start.col))));
let data = RangeRef::new(CellRef::new(r.start.row + header_row as u32, r.start.col + label_col as u32), r.end);
let mut out = Vec::new();
if !by_rows {
@@ -508,6 +579,8 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
});
}
} else {
@@ -521,35 +594,120 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
});
}
}
out
}
fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
/// A scatter plot of a block without category labels takes its first column (or row) as the X
/// values of the others, as Excel does: two plain columns make one series of points, not two (#428).
pub fn scatter_x_from_first(kind: ChartKind, series: &mut Vec<Series>) {
if matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines) && series.len() > 1 && series[0].categories.is_none() {
let x = series.remove(0).values;
for se in series.iter_mut() {
se.categories = Some(x.clone());
}
}
}
/// Most cells a chart's source block may span (bounds the series it builds).
const MAX_CHART_CELLS: u64 = 1_000_000;
/// Chart types that suit the shape of the data, best first, as `(type, subtype, label)` for
/// `insert.chart`. Our own heuristic from the shape of the block (series count, points per
/// series, text categories, negative values), not a copy of Excel's ranking: two numeric columns
/// without labels → scatter; one short series → column, pie, bar; long series → line; several
/// series → clustered and stacked columns and bars, line.
pub fn recommend_charts(s: &Session, p: &Json) -> Result<Vec<(&'static str, &'static str, &'static str)>> {
let r = block(s, p)?;
if r.count() > 1_000_000 {
if r.count() > MAX_CHART_CELLS {
return Err(bad("insert.chart", "range too large for a chart"));
}
let sheet = target_sheet(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
let by_rows = r.width() > r.height() + 1;
let series = series_from_range(sh, r, by_rows);
let ranges: Vec<RangeRef> = series
.iter()
.filter_map(|x| match gridcraft_formula::parse(&x.values) {
Ok(gridcraft_formula::Expr::Ref(rf)) => Some(rf.range()),
_ => None,
})
.collect();
let points = ranges.first().map_or(0, RangeRef::count);
let (mut any_number, mut non_negative) = (false, true);
for n in ranges.iter().flat_map(|rr| rr.iter()).filter_map(|c| sh.value(c).as_f64()) {
any_number = true;
non_negative &= n >= 0.0;
}
if series.is_empty() || !any_number {
return Err(EngineError::Other("Select data for the chart first.".into()));
}
let labelled = series.first().is_some_and(|x| x.categories.is_some());
const COLUMN: (&str, &str, &str) = ("column", "", "Clustered Column");
const BAR: (&str, &str, &str) = ("bar", "", "Clustered Bar");
const LINE: (&str, &str, &str) = ("line", "", "Line");
const LINE_MARKERS: (&str, &str, &str) = ("line", "markers", "Line with Markers");
const PIE: (&str, &str, &str) = ("pie", "", "Pie");
const DOUGHNUT: (&str, &str, &str) = ("doughnut", "", "Doughnut");
const AREA: (&str, &str, &str) = ("area", "", "Area");
const SCATTER: (&str, &str, &str) = ("scatter", "", "Scatter");
const STACKED_COLUMN: (&str, &str, &str) = ("column", "stacked", "Stacked Column");
const STACKED_BAR: (&str, &str, &str) = ("bar", "stacked", "Stacked Bar");
let mut out = Vec::new();
if series.len() == 2 && !labelled && !by_rows {
out.extend([SCATTER, LINE_MARKERS, COLUMN]);
} else if series.len() == 1 {
if points > 12 {
out.extend([LINE, COLUMN, AREA]);
} else {
out.extend([COLUMN, BAR]);
if non_negative && points >= 2 {
out.extend([PIE, DOUGHNUT]);
}
out.push(LINE_MARKERS);
}
} else if points > 12 {
out.extend([LINE, COLUMN, AREA, STACKED_COLUMN]);
} else {
out.extend([COLUMN, BAR, STACKED_COLUMN, LINE_MARKERS, STACKED_BAR]);
}
Ok(out)
}
/// The chart `insert.chart` would insert for these params, without inserting it: the sheet it
/// goes on and the chart (previews in the Recommended Charts dialog).
pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
let r = block(s, p)?;
if r.count() > MAX_CHART_CELLS {
return Err(bad("insert.chart", "range too large for a chart"));
}
let mut t = str_param(p, "type").unwrap_or("column").to_string();
let mut sub = str_param(p, "subtype").unwrap_or("").to_string();
if t == "auto" {
let first = recommend_charts(s, p)?.into_iter().next().unwrap_or(("column", "", ""));
t = first.0.into();
sub = first.1.into();
}
let sheet = target_sheet(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// Excel plots series by the longer dimension (more rows → series in columns).
let data_h = r.height();
let data_w = r.width();
let by_rows = data_w > data_h + 1;
if t == "auto" {
t = if data_h > 12 && data_w <= 3 { "line".into() } else { "column".into() };
}
let kind = chart_kind(&t, str_param(p, "subtype").unwrap_or(""));
let series = series_from_range(sh, r, by_rows);
let kind = chart_kind(&t, &sub);
let mut series = series_from_range(sh, r, by_rows);
if series.is_empty() {
return Err(EngineError::Other("Select data for the chart first.".into()));
}
scatter_x_from_first(kind, &mut series);
let id = d.wb.next_object_id();
let at = cell_param(p, "at").unwrap_or_else(|| CellRef::new(r.start.row, r.end.col + 2));
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or_else(|| CellRef::new(r.start.row, r.end.col + 2));
let title = str_param(p, "title").map(str::to_string).or_else(|| {
if series.len() == 1 {
series[0].name.as_ref().map(|n| gridcraft_calc::evaluate(&d.wb, sheet, at, n).display())
@@ -566,6 +724,7 @@ fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
dy: 0.0,
width: f64_param(p, "width").unwrap_or(480.0) as f32,
height: f64_param(p, "height").unwrap_or(288.0) as f32,
mode: anchor_mode_param(p).unwrap_or_default(),
},
title,
series,
@@ -577,7 +736,14 @@ fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
y_title: None,
source: Some(format!("{}!{}", gridcraft_formula::quote_sheet(&sh.name), r.a1())),
by_rows,
pivot: None,
};
Ok((sheet, chart))
}
fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
let (sheet, chart) = build_chart(s, p)?;
let id = chart.id;
edit(s, |cx| {
cx.sheet_mut(sheet)?.charts.push(chart);
Ok(json!({"chart": id}))
@@ -597,6 +763,7 @@ fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> {
fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
let (si, ci) = find_chart(s, p)?;
let at = cell_param_on(s, p, "at", si)?;
edit(s, |cx| {
let sh = cx.sheet_mut(si)?;
let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) };
@@ -630,7 +797,7 @@ fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
if let Some(t) = p.get("yTitle") {
c.y_title = t.as_str().map(str::to_string);
}
if let Some(at) = cell_param(p, "at") {
if let Some(at) = at {
c.anchor.cell = at;
}
if let Some(w) = f64_param(p, "width") {
@@ -654,21 +821,56 @@ fn chart_switch(s: &mut Session, p: &Json) -> Result<Json> {
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
let Some(c) = sh.charts.get(ci) else { return Ok(Json::Null) };
let Some(src) = c.source.clone() else { return Ok(Json::Null) };
// Charts read from a file have no source range: take the block their series span.
let Some((src, by_rows)) = c.source.clone().map(|s| (s, c.by_rows)).or_else(|| series_block(&c.series)) else { return Ok(Json::Null) };
let (sheet_name, body) = split_sheet(&src);
let src_sheet = sheet_name.and_then(|n| cx.wb.sheet_index(&n)).unwrap_or(si);
let Some(r) = RangeRef::parse(body) else { return Ok(Json::Null) };
let Some(mut r) = RangeRef::parse(body) else { return Ok(Json::Null) };
let Some(ssh) = cx.wb.sheet(src_sheet) else { return Ok(Json::Null) };
let by_rows = !c.by_rows;
// Whole-column/row references (common in files) span a million cells: clip the block's
// far edges to the cells in use, then refuse anything still too large to chart.
if let Some(used) = ssh.used_range() {
r.end.row = r.end.row.min(used.end.row).max(r.start.row);
r.end.col = r.end.col.min(used.end.col).max(r.start.col);
}
if r.count() > MAX_CHART_CELLS {
return Err(bad("chart.switchRowColumn", "range too large for a chart"));
}
let by_rows = !by_rows;
let series = series_from_range(ssh, r, by_rows);
if let Some(c) = cx.sheet_mut(si)?.charts.get_mut(ci) {
c.source.get_or_insert(src);
c.by_rows = by_rows;
c.series = series;
scatter_x_from_first(c.kind, &mut c.series);
}
Ok(Json::Null)
})
}
/// The block a chart's series come from, and whether each series is a row of it: the bounding
/// range of the series names, categories and values, when they're all references to one sheet.
fn series_block(series: &[Series]) -> Option<(String, bool)> {
let mut sheet: Option<String> = None;
let mut bounds: Option<RangeRef> = None;
let mut rows = 0;
for s in series {
for (i, f) in [Some(&s.values), s.categories.as_ref(), s.name.as_ref()].into_iter().flatten().enumerate() {
let Ok(gridcraft_formula::Expr::Ref(r)) = gridcraft_formula::parse(f) else { return None };
let gridcraft_formula::SheetSel::Named(n) = &r.sheet else { return None };
if !sheet.get_or_insert_with(|| n.clone()).eq_ignore_ascii_case(n) {
return None;
}
let range = r.range();
if i == 0 && range.height() == 1 && range.width() > 1 {
rows += 1;
}
bounds = Some(bounds.map_or(range, |b| b.union(&range)));
}
}
Some((format!("{}!{}", gridcraft_formula::quote_sheet(&sheet?), bounds?.a1()), rows > 0 && rows == series.len()))
}
fn chart_delete(s: &mut Session, p: &Json) -> Result<Json> {
let (si, ci) = find_chart(s, p)?;
edit(s, |cx| {
@@ -679,7 +881,7 @@ fn chart_delete(s: &mut Session, p: &Json) -> Result<Json> {
fn insert_sparkline(s: &mut Session, p: &Json) -> Result<Json> {
let src = str_param(p, "range").ok_or_else(|| bad("insert.sparkline", "missing `range`"))?.to_string();
let loc = cell_param(p, "location").ok_or_else(|| bad("insert.sparkline", "missing `location`"))?;
let loc = cell_param(s, p, "location")?.ok_or_else(|| bad("insert.sparkline", "missing `location`"))?;
let kind = match str_param(p, "type") {
Some("column") => SparklineKind::Column,
Some("winLoss") => SparklineKind::WinLoss,
@@ -696,14 +898,39 @@ fn insert_sparkline(s: &mut Session, p: &Json) -> Result<Json> {
}
fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
let placement = str_param(p, "placement").unwrap_or("overCells");
if !matches!(placement, "cell" | "overCells") {
return Err(bad("insert.picture", "placement must be cell or overCells"));
}
let data = if let Some(b) = str_param(p, "base64") {
crate::io::base64_decode(b).ok_or_else(|| bad("insert.picture", "invalid base64"))?
} else if let Some(path) = str_param(p, "path") {
crate::io::read_file(path)?
} else {
s.ui_requests.push(crate::UiRequest::Dialog("insertPicture".into(), json!({})));
s.ui_requests.push(crate::UiRequest::Dialog("insertPicture".into(), json!({"placement": placement})));
return ok();
};
if placement == "cell" {
let mime = validate_cell_picture(&data)?;
let d = s.doc()?;
let sheet = d.wb.active_sheet;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let at = match str_param(p, "at") {
Some(a) => CellRef::parse(a).ok_or_else(|| bad("insert.picture", "invalid cell address"))?,
None => d.selection.active,
};
let at = sh.merge_at(at).map(|r| r.start).unwrap_or(at);
let style = sh.style_id(at);
if sh.is_protected() && d.wb.styles.get(style).protection.locked && locked_cell_error(sh, at, &d.unlocked_ranges).is_some() {
return Err(EngineError::Other("The cell you're trying to change is on a protected sheet.".into()));
}
let picture = CellPicture { data, mime: mime.into(), alt: str_param(p, "alt").unwrap_or("").into() };
return edit(s, |cx| {
cx.sheet_mut(sheet)?.set_picture(at, std::sync::Arc::new(picture));
cx.touch(sheet, at);
Ok(json!({"cell": at.a1(), "placement": "cell"}))
});
}
if data.len() > 64 * 1024 * 1024 {
return Err(bad("insert.picture", "image larger than 64 MB"));
}
@@ -713,7 +940,7 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
let (w, h) = crate::io::image_size(&data).unwrap_or((320, 240));
let d = s.doc()?;
let id = d.wb.next_object_id();
let at = cell_param(p, "at").unwrap_or(d.selection.active);
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
let scale = (640.0 / w.max(1) as f32).min(1.0);
let img = Image {
id,
@@ -723,6 +950,8 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
dy: 0.0,
width: f64_param(p, "width").map(|v| v as f32).unwrap_or(w as f32 * scale),
height: f64_param(p, "height").map(|v| v as f32).unwrap_or(h as f32 * scale),
// Excel inserts pictures as "Move but don't size with cells" (`editAs="oneCell"`).
mode: anchor_mode_param(p).unwrap_or(gridcraft_model::AnchorMode::MoveOnly),
},
data,
mime,
@@ -735,6 +964,33 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Validate before mutating the workbook; header dimensions alone do not prove the pixels decode.
fn validate_cell_picture(data: &[u8]) -> Result<&'static str> {
if data.len() > 16 * 1024 * 1024 {
return Err(bad("insert.picture", "cell pictures must be at most 16 MiB"));
}
let format = image::guess_format(data).map_err(|_| bad("insert.picture", "choose a valid PNG or JPEG picture"))?;
let mime = match format {
image::ImageFormat::Png => "image/png",
image::ImageFormat::Jpeg => "image/jpeg",
_ => return Err(bad("insert.picture", "cell pictures support PNG and JPEG")),
};
let (width, height) = image::ImageReader::with_format(std::io::Cursor::new(data), format)
.into_dimensions()
.map_err(|_| bad("insert.picture", "invalid image dimensions"))?;
if width == 0 || height == 0 || width > 8192 || height > 8192 || u64::from(width) * u64::from(height) > 16_000_000 {
return Err(bad("insert.picture", "cell pictures are limited to 8192 pixels per side and 16 million pixels"));
}
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(data), format);
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(64 * 1024 * 1024);
reader.limits(limits);
reader.decode().map_err(|_| bad("insert.picture", "picture cannot be decoded within the 64 MiB limit"))?;
Ok(mime)
}
fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
let kind = match str_param(p, "kind").unwrap_or("rectangle") {
"roundedRectangle" => ShapeKind::RoundedRectangle,
@@ -747,7 +1003,7 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
};
let d = s.doc()?;
let id = d.wb.next_object_id();
let at = cell_param(p, "at").unwrap_or(d.selection.active);
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
let fill =
super::format::color_param(p.get("fill")).unwrap_or(if kind == ShapeKind::TextBox { Color::rgb(255, 255, 255) } else { Color::Theme(4, 0) });
let line = super::format::color_param(p.get("line")).unwrap_or(if kind == ShapeKind::TextBox {
@@ -764,10 +1020,12 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
dy: 0.0,
width: f64_param(p, "width").unwrap_or(144.0) as f32,
height: f64_param(p, "height").unwrap_or(if kind == ShapeKind::Line { 0.0 } else { 96.0 }) as f32,
mode: anchor_mode_param(p).unwrap_or_default(),
},
fill,
line,
text: str_param(p, "text").unwrap_or("").into(),
format: Default::default(),
};
let sheet = d.wb.active_sheet;
edit(s, |cx| {
@@ -776,6 +1034,37 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// A text box holds at most as many characters as a cell.
const SHAPE_TEXT_MAX_CHARS: usize = 32_767;
fn shape_set_text(s: &mut Session, p: &Json) -> Result<Json> {
let id =
p.get("id").and_then(Json::as_u64).and_then(|id| u32::try_from(id).ok()).ok_or_else(|| bad("shape.setText", "`id` must be a text box id"))?;
let text = str_param(p, "text").ok_or_else(|| bad("shape.setText", "`text` must be a string"))?;
if text.chars().nth(SHAPE_TEXT_MAX_CHARS).is_some() {
return Err(bad("shape.setText", "`text` is longer than 32,767 characters"));
}
let d = s.doc()?;
let sheet = d.wb.active_sheet;
let sh = d.wb.active().ok_or_else(|| bad("shape.setText", "no such text box"))?;
let shape = sh.shapes.iter().find(|shape| shape.id == id).ok_or_else(|| bad("shape.setText", "no such text box"))?;
if shape.kind != ShapeKind::TextBox {
return Err(bad("shape.setText", "the shape is not a text box"));
}
// Sheet protection locks drawing objects (there is no "edit objects" allowance yet).
if sh.is_protected() {
return Err(EngineError::Other(PROTECTED.into()));
}
if shape.text == text {
return ok();
}
edit(s, |cx| {
let shape = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|shape| shape.id == id).ok_or_else(|| bad("shape.setText", "no such text box"))?;
shape.text = text.into();
Ok(Json::Null)
})
}
fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
let id = u32_param(p, "id").ok_or_else(|| bad("object.delete", "missing `id`"))?;
let kind = str_param(p, "kind").unwrap_or("").to_string();
@@ -785,6 +1074,7 @@ fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
match kind.as_str() {
"chart" => sh.charts.retain(|c| c.id != id),
"image" => sh.images.retain(|c| c.id != id),
"slicer" => sh.slicers.retain(|c| c.id != id),
_ => sh.shapes.retain(|c| c.id != id),
}
Ok(Json::Null)
@@ -795,15 +1085,18 @@ fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
let id = u32_param(p, "id").ok_or_else(|| bad("object.move", "missing `id`"))?;
let kind = str_param(p, "kind").unwrap_or("").to_string();
let sheet = s.doc()?.wb.active_sheet;
let at = cell_param(s, p, "at")?;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let anchor = match kind.as_str() {
"chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
"image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
_ => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
"slicer" => sh.slicers.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
"shape" => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
_ => None,
};
let Some(a) = anchor else { return Err(bad("object.move", "no such object")) };
if let Some(at) = cell_param(p, "at") {
if let Some(at) = at {
a.cell = at;
}
if let Some(v) = f64_param(p, "dx") {
@@ -822,11 +1115,35 @@ fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Sets an object's anchor mode (Excel's "Move and size with cells" / "Move but don't size with
/// cells" / "Don't move or size with cells"), so it follows — or ignores — its rows and columns
/// when the sheet is sorted or edited structurally.
fn set_anchor_mode(s: &mut Session, p: &Json) -> Result<Json> {
let id = u32_param(p, "id").ok_or_else(|| bad("object.setAnchorMode", "missing `id`"))?;
let kind = str_param(p, "kind").unwrap_or("").to_string();
if !matches!(kind.as_str(), "chart" | "image" | "shape") {
return Err(bad("object.setAnchorMode", "kind must be chart, image or shape"));
}
let mode = anchor_mode_param(p).ok_or_else(|| bad("object.setAnchorMode", "mode must be moveAndSize, moveOnly or absolute"))?;
let sheet = s.doc()?.wb.active_sheet;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let anchor = match kind.as_str() {
"chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
"image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
_ => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
};
let Some(a) = anchor else { return Err(bad("object.setAnchorMode", "no such object")) };
a.mode = mode;
Ok(json!({"mode": anchor_mode_name(mode)}))
})
}
// ---------------------------------------------------------------- links & comments
fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
if bool_param(p, "remove").unwrap_or(false) {
return edit(s, |cx| {
cx.sheet_mut(sheet)?.hyperlinks.remove(&at);
@@ -846,7 +1163,7 @@ fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
});
let sh = cx.sheet_mut(sheet)?;
if let Some(t) = text.clone().or_else(|| sh.value(at).is_empty().then(|| target.clone())) {
sh.cells.set(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style });
sh.set_cell(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style });
} else {
sh.set_style(at, link_style);
}
@@ -858,20 +1175,21 @@ fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
fn comment(s: &mut Session, p: &Json, threaded: bool) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
let text = str_param(p, "text").unwrap_or("").to_string();
let author = str_param(p, "author").map(str::to_string).unwrap_or_else(|| s.prefs.user_name.clone());
edit(s, |cx| {
cx.sheet_mut(sheet)?
.comments
.insert(at, Comment { author: author.clone(), text: text.clone(), replies: vec![], threaded, resolved: false, visible: false });
cx.sheet_mut(sheet)?.comments.insert(
at,
Comment { author: author.clone(), text: text.clone(), replies: vec![], threaded, resolved: false, visible: false, dates: vec![] },
);
Ok(json!({"cell": at.a1()}))
})
}
fn reply_comment(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
let text = str_param(p, "text").unwrap_or("").to_string();
let author = str_param(p, "author").map(str::to_string).unwrap_or_else(|| s.prefs.user_name.clone());
edit(s, |cx| {
@@ -883,7 +1201,7 @@ fn reply_comment(s: &mut Session, p: &Json) -> Result<Json> {
fn resolve_comment(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
let v = bool_param(p, "resolved").unwrap_or(true);
edit(s, |cx| {
if let Some(c) = cx.sheet_mut(sheet)?.comments.get_mut(&at) {
@@ -904,7 +1222,7 @@ fn delete_comment(s: &mut Session, p: &Json) -> Result<Json> {
fn show_note(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
edit(s, |cx| {
if let Some(c) = cx.sheet_mut(sheet)?.comments.get_mut(&at) {
c.visible = !c.visible;
@@ -983,15 +1301,17 @@ fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
};
let rule = match kind.as_str() {
"cellIs" => {
// Excel's file and VBA names (`lessThan`, …) are accepted too.
let op = match g("operator").as_deref().unwrap_or("greater") {
"between" => CfOperator::Between,
"notBetween" => CfOperator::NotBetween,
"equal" => CfOperator::Equal,
"notEqual" => CfOperator::NotEqual,
"less" => CfOperator::Less,
"greaterOrEqual" => CfOperator::GreaterOrEqual,
"lessOrEqual" => CfOperator::LessOrEqual,
_ => CfOperator::Greater,
"less" | "lessThan" => CfOperator::Less,
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
"greater" | "greaterThan" => CfOperator::Greater,
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
};
let a = rule.get("value").map(super::edit::json_to_input).unwrap_or_default();
let b = rule.get("value2").map(super::edit::json_to_input);
@@ -1129,15 +1449,16 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
let size = f64_param(p, "size").unwrap_or(48.0).clamp(8.0, 1000.0) as f32;
let d = s.doc()?;
let id = d.wb.next_object_id();
let at = cell_param(p, "at").unwrap_or(d.selection.active);
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
let color = super::format::color_param(p.get("color")).unwrap_or(Color::Theme(1, 0));
let shape = Shape {
id,
kind: ShapeKind::Icon,
anchor: Anchor { cell: at, dx: 4.0, dy: 4.0, width: size, height: size },
anchor: Anchor { cell: at, dx: 4.0, dy: 4.0, width: size, height: size, mode: anchor_mode_param(p).unwrap_or_default() },
fill: color,
line: Color::Auto,
text: name,
format: Default::default(),
};
let sheet = d.wb.active_sheet;
edit(s, |cx| {
+5 -4
View File
@@ -46,7 +46,7 @@ fn inspect(s: &mut Session, _: &Json) -> Result<Json> {
"freeze": sh.freeze,
"merges": sh.merges.iter().map(|m| m.a1()).collect::<Vec<_>>(),
"tables": sh.tables.iter().map(|t| json!({"name": t.name, "range": t.range.a1(), "style": t.style, "totals": t.totals_row, "columns": t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),
"charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len()})).collect::<Vec<_>>(),
"charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len(), "trendlines": c.series.iter().flat_map(|s| s.trendlines.iter().map(|t| format!("{:?}", t.kind))).collect::<Vec<_>>()})).collect::<Vec<_>>(),
"images": sh.images.len(),
"shapes": sh.shapes.len(),
"conditionalFormats": sh.cond_formats.len(),
@@ -119,16 +119,17 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
let c = cell_param(p, "cell").unwrap_or(d.selection.active);
let c = cell_param_on(s, p, "cell", sheet)?.unwrap_or(d.selection.active);
let cell = sh.cell(c);
let style = d.wb.styles.get(sh.style_id(c));
Ok(json!({
"cell": c.a1(),
"value": value_json(&sh.value(c)),
"type": match sh.value(c) { Value::Empty => "empty", Value::Number(_) => "number", Value::Text(_) => "text", Value::Bool(_) => "boolean", Value::Error(_) => "error", Value::Array(_) => "array" },
"type": if sh.cell_pictures.contains_key(&c) { "picture" } else { match sh.value(c) { Value::Empty => "empty", Value::Number(_) => "number", Value::Text(_) => "text", Value::Bool(_) => "boolean", Value::Error(_) => "error", Value::Array(_) => "array" } },
"formula": cell.and_then(|x| x.formula.as_ref()).map(|f| format!("={}", f.text)),
"text": crate::display::cell_text(&d.wb, sh, c),
"input": cell.map(|x| x.input_text()).unwrap_or_default(),
"input": sh.input_text(c),
"picture": sh.cell_pictures.get(&c).map(|picture| json!({"mime": picture.mime, "alt": picture.alt, "bytes": picture.data.len()})),
"spilledFrom": sh.spill_ranges.iter().find(|(a, r)| **a != c && r.contains(c)).map(|(a, _)| a.a1()),
"spill": sh.spill_ranges.get(&c).map(|r| r.a1()),
"style": style,
+214 -11
View File
@@ -1,11 +1,13 @@
//! The command registry. Ids follow Excel's ribbon (`home.bold`, `insert.chart`,
//! `data.sortAscending`) plus primitive editing commands (`cell.set`, `selection.set`).
pub mod analysis;
pub mod data;
pub mod draw;
pub mod edit;
pub mod extra;
pub mod file;
pub mod forecast;
pub mod format;
pub mod formulas;
pub mod insert;
@@ -14,6 +16,8 @@ pub mod pivot;
pub mod print;
pub mod review;
pub mod sheet;
pub mod slicer;
pub mod solver;
pub mod spelling;
pub mod view;
pub mod whatif;
@@ -69,6 +73,21 @@ impl CommandSpec {
}
}
/// Params that hold a secret: `password`, or a name ending in `Password`.
pub fn is_secret_param(key: &str) -> bool {
key == "password" || key.ends_with("Password")
}
/// The params as the journal records them: secret params are left out, so a password never
/// reaches the journal dialog, `engine.journal` or a recorded script (saved in the workbook).
/// Replaying such an entry runs the command without that param.
pub fn journal_params(params: &Json) -> Json {
match params {
Json::Object(o) => Json::Object(o.iter().filter(|(k, _)| !is_secret_param(k)).map(|(k, v)| (k.clone(), v.clone())).collect()),
other => other.clone(),
}
}
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
@@ -118,15 +137,54 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(extra::specs());
v.extend(draw::specs());
v.extend(spelling::specs());
v.extend(solver::specs());
v.extend(pivot::specs());
v.extend(slicer::specs());
v.extend(whatif::specs());
v.extend(forecast::specs());
v.extend(analysis::specs());
v.extend(print::specs());
v
})
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
if let Some(spec) = command_specs().iter().find(|c| c.id == id) {
return Some(spec);
}
// Commands registered by UI integration tests (pending keytips go live
// the moment their command lands, with no table edit).
test_commands().iter().find(|c| c.id == id).copied()
}
static TEST_COMMANDS: std::sync::Mutex<Vec<&'static CommandSpec>> = std::sync::Mutex::new(Vec::new());
/// Test-only: register an extra command so UI integration tests can prove a pending
/// keytip becomes live the moment its command lands (see crates/ui-egui/tests/keytips.rs).
/// Not part of the public API; harmless no-op for production callers who never call it.
#[doc(hidden)]
pub fn register_test_command(id: &'static str, run: Run) {
// Leaked intentionally: test commands live for the whole process.
let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec {
id,
label: id,
menu: &[],
shortcut: None,
params: "",
enabled: |_| Ok(()),
run,
journal: true,
undoable: false,
}));
test_commands().push(spec);
}
fn test_commands() -> std::sync::MutexGuard<'static, Vec<&'static CommandSpec>> {
#[allow(clippy::unwrap_used)] // a poisoned test registry has no meaningful recovery
match TEST_COMMANDS.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
// ---------------------------------------------------------------- param helpers
@@ -146,6 +204,30 @@ pub(crate) fn bool_param(p: &Json, key: &str) -> Option<bool> {
pub(crate) fn u32_param(p: &Json, key: &str) -> Option<u32> {
p.get(key).and_then(Json::as_u64).map(|v| v.min(u32::MAX as u64) as u32)
}
/// An object anchor mode from Excel's wording or the model's: `"moveAndSize"`/`"twoCell"`,
/// `"moveOnly"`/`"oneCell"`, `"absolute"`/`"don't move or size"` (case-insensitive).
pub(crate) fn anchor_mode_param(p: &Json) -> Option<gridcraft_model::AnchorMode> {
parse_anchor_mode(str_param(p, "mode").or_else(|| str_param(p, "anchorMode"))?)
}
pub(crate) fn parse_anchor_mode(s: &str) -> Option<gridcraft_model::AnchorMode> {
match s.to_ascii_lowercase().replace([' ', '-', '_', '\''], "").as_str() {
"moveandsize" | "moveandsizeandcells" | "twocell" => Some(gridcraft_model::AnchorMode::MoveAndSize),
"moveonly" | "movebutdontsize" | "movebutdontsizewithcells" | "onecell" => Some(gridcraft_model::AnchorMode::MoveOnly),
"absolute" | "dontmoveorsize" | "dontmoveorsizewithcells" | "none" => Some(gridcraft_model::AnchorMode::Absolute),
_ => None,
}
}
/// The wire name of an anchor mode (matches the `mode` param of [`anchor_mode_param`]).
pub(crate) fn anchor_mode_name(m: gridcraft_model::AnchorMode) -> &'static str {
match m {
gridcraft_model::AnchorMode::MoveAndSize => "moveAndSize",
gridcraft_model::AnchorMode::MoveOnly => "moveOnly",
gridcraft_model::AnchorMode::Absolute => "absolute",
}
}
pub(crate) fn ok() -> Result<Json> {
Ok(Json::Null)
}
@@ -195,8 +277,28 @@ pub(crate) fn split_sheet(r: &str) -> (Option<String>, &str) {
}
}
pub(crate) fn cell_param(p: &Json, key: &str) -> Option<CellRef> {
str_param(p, key).and_then(|t| CellRef::parse(split_sheet(t).1))
/// A single-cell parameter. Absent or null is `Ok(None)` (callers default it); a value that is not
/// a cell reference, or that names a sheet other than the active one, is an error rather than a
/// silent fallback to some other cell.
pub(crate) fn cell_param(s: &Session, p: &Json, key: &str) -> Result<Option<CellRef>> {
cell_param_on(s, p, key, s.doc()?.wb.active_sheet)
}
/// Like [`cell_param`], for a command that operates on `sheet` (a `Sheet!` prefix must name it).
pub(crate) fn cell_param_on(s: &Session, p: &Json, key: &str, sheet: usize) -> Result<Option<CellRef>> {
let t = match p.get(key) {
None | Some(Json::Null) => return Ok(None),
Some(Json::String(t)) => t,
Some(v) => return Err(bad("cell", format!("invalid cell reference `{v}` for `{key}`"))),
};
let (sh, body) = split_sheet(t);
let c = CellRef::parse(body).ok_or_else(|| bad("cell", format!("invalid cell reference `{t}` for `{key}`")))?;
if let Some(name) = sh
&& s.doc()?.wb.sheet_index(&name) != Some(sheet)
{
return Err(bad("cell", format!("`{t}` for `{key}` names a sheet other than the one this command works on")));
}
Ok(Some(c))
}
/// Applies an edit to a copy of the active workbook, then recalculates and commits it.
@@ -209,24 +311,39 @@ pub struct Ctx<'a> {
pub sel: &'a mut Selection,
/// Rows whose automatic height should be recomputed (sheet, row).
pub fit_rows: Vec<(usize, u32)>,
/// The command applied sheet protection itself (row/column inserts and deletes the
/// protection allows), so cells it shifts aren't refused as edits of locked cells.
pub protection_checked: bool,
}
pub(crate) fn edit<R>(s: &mut Session, f: impl FnOnce(&mut Ctx) -> Result<R>) -> Result<R> {
let d = s.doc_mut()?;
commit(d, f)
commit(d, |cx| {
let r = f(cx)?;
crate::tables::sync_headers(cx);
Ok(r)
})
}
pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>) -> Result<R> {
let prof = std::env::var_os("GRIDCRAFT_PROFILE").is_some();
let t0 = std::time::Instant::now();
// `GRIDCRAFT_PROFILE` timing. Read the clock only when profiling, and never on wasm: there
// `Instant::now` traps (`RuntimeError: unreachable`), which broke every edit in the web app.
#[allow(clippy::disallowed_methods)]
let t0 = if cfg!(target_arch = "wasm32") { None } else { std::env::var_os("GRIDCRAFT_PROFILE").map(|_| std::time::Instant::now()) };
let mut sel = d.selection.clone();
let mut ctx = Ctx { wb: (*d.wb).clone(), changed: Vec::new(), structural: false, sel: &mut sel, fit_rows: Vec::new() };
let mut ctx = Ctx { wb: (*d.wb).clone(), changed: Vec::new(), structural: false, sel: &mut sel, fit_rows: Vec::new(), protection_checked: false };
let r = f(&mut ctx)?;
let Ctx { mut wb, changed, structural, mut fit_rows, .. } = ctx;
let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, .. } = ctx;
if !protection_checked {
check_protection(&d.wb, &wb, &d.unlocked_ranges)?;
}
if !structural {
check_arrays(&d.wb, &wb)?;
}
if changed.len() <= 200_000 {
fit_rows.extend(changed.iter().map(|(s, c)| (*s, c.row)));
}
if prof {
if let Some(t0) = t0 {
eprintln!("commit: edit {:?}, {} changed", t0.elapsed(), changed.len());
}
if structural {
@@ -234,7 +351,7 @@ pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>)
} else if !changed.is_empty() {
d.calc.cells_changed(&mut wb, &changed);
}
if prof {
if let Some(t0) = t0 {
eprintln!("commit: + recalc {:?}", t0.elapsed());
}
fit_rows.sort_unstable();
@@ -242,7 +359,7 @@ pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>)
for (si, row) in fit_rows {
auto_row_height(&mut wb, si, row);
}
if prof {
if let Some(t0) = t0 {
eprintln!("commit: + rows {:?}", t0.elapsed());
}
d.wb = std::sync::Arc::new(wb);
@@ -250,6 +367,92 @@ pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>)
Ok(r)
}
/// Excel's message for an edit of a locked cell on a protected sheet.
pub(crate) const PROTECTED: &str = "The cell or chart you're trying to change is on a protected sheet.";
/// Refuses an edit that changed what a locked cell on a protected sheet holds (its value or
/// formula), whichever command made it. Sheets are matched by name, so moving, renaming or
/// deleting a sheet isn't an edit of its cells.
fn check_protection(old: &Workbook, new: &Workbook, unlocked: &[(String, String)]) -> Result<()> {
for sh in &old.sheets {
if !sh.is_protected() {
continue;
}
let Some(after) = new.sheet_index(&sh.name).and_then(|i| new.sheets.get(i)) else { continue };
if std::sync::Arc::ptr_eq(sh, after) || !after.is_protected() {
continue;
}
for c in sh.cells.diff(&after.cells) {
if !same_content(sh.cell(c), after.cell(c))
&& old.styles.get(sh.style_id(c)).protection.locked
&& let Some(m) = locked_cell_error(sh, c, unlocked)
{
return Err(EngineError::Other(m));
}
}
}
Ok(())
}
/// Whether a locked cell on a protected sheet stays locked: `None` when it's in an Allow Edit
/// Range without a password or one unlocked in this session, else the message to show.
pub(crate) fn locked_cell_error(sh: &gridcraft_model::Sheet, c: CellRef, unlocked: &[(String, String)]) -> Option<String> {
let mut needs_password = None;
for r in sh.edit_ranges.iter().filter(|r| r.contains(c)) {
if r.password.is_none() || unlocked.iter().any(|(s, t)| *s == sh.name && *t == r.title) {
return None;
}
needs_password.get_or_insert(r.title.as_str());
}
Some(match needs_password {
Some(t) => format!("The range \"{t}\" needs its password before it can be changed (Review › Allow Edit Ranges)."),
None => PROTECTED.into(),
})
}
/// Refuses an edit that put something into a cell of a multi-cell legacy array other than its
/// formula cell, while the array stays (Excel: "You can't change part of an array."). The array
/// would show its value there while the file kept the new content. Cells shifted by row and
/// column edits aren't edits of their content, so structural commits aren't checked.
fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> {
for sh in &old.sheets {
if sh.spill.is_empty() {
continue;
}
let Some(after) = new.sheet_index(&sh.name).and_then(|i| new.sheets.get(i)) else { continue };
if std::sync::Arc::ptr_eq(sh, after) {
continue;
}
for c in sh.cells.diff(&after.cells) {
let filled = after.cell(c).is_some_and(|x| x.formula.is_some() || !x.value.is_empty());
if !filled || !sh.spill.contains_key(&c) || same_content(sh.cell(c), after.cell(c)) {
continue;
}
let in_array = sh.spill_ranges.keys().any(|&anchor| {
anchor != c
&& after.cell(anchor).and_then(|x| x.formula.as_ref()).and_then(|f| f.array).is_some_and(|a| a.start == anchor && a.contains(c))
});
if in_array {
return Err(EngineError::Other("You can't change part of an array.".into()));
}
}
}
Ok(())
}
/// Two cells hold the same value or formula (formats aside).
fn same_content(a: Option<&gridcraft_model::Cell>, b: Option<&gridcraft_model::Cell>) -> bool {
let empty = |c: Option<&gridcraft_model::Cell>| c.is_none_or(|c| c.formula.is_none() && c.value.is_empty());
match (a, b) {
(Some(a), Some(b)) => match (&a.formula, &b.formula) {
(Some(x), Some(y)) => x.text == y.text && x.array == y.array,
(None, None) => a.value == b.value,
_ => false,
},
_ => empty(a) && empty(b),
}
}
/// Recomputes an automatic row height from its content: the largest font, and wrapped or
/// multi-line text. Rows with a user-set height keep it.
pub fn auto_row_height(wb: &mut Workbook, si: usize, row: u32) {
+352 -5
View File
@@ -43,6 +43,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
summarize_table
),
cmd!(
"pivot.calculatedField",
"Calculated Field",
["PivotTable Analyze", "Calculations"],
None,
"{pivot?, name, formula?: \"=Sales*0.1\" (fields bare or 'quoted'; evaluated on each cell's sums), delete?: bool, values?: bool (add a new field to Values, default true)} adds, changes or deletes a calculated field; without `name` opens the dialog → {name, formula, calculatedFields}",
has_doc,
calculated_field
),
cmd!(
"insert.pivotChart",
"PivotChart",
["Insert", "Charts"],
None,
"{pivot?: name | id | a cell of the report (\"Sheet2!B5\"; default: the PivotTable at the active cell), type?: column|bar|line|pie|area|… (default column), subtype?, title?, at?: \"H2\", width?, height?} adds a chart bound to the PivotTable's report: categories are the innermost row items, series the column items × value fields; it follows refreshes and layout changes → {chart, pivot, series}",
has_doc,
insert_pivot_chart
),
cmd!(query "pivot.fields", "PivotTable Fields", [], None, "{pivot?} → source fields (name, numeric, date, samples, areas) and the current layout", has_doc, fields),
cmd!(query "pivot.fieldList", "Field List", ["PivotTable Analyze", "Show"], None, "{pivot?} (same as pivot.fields)", has_doc, fields),
cmd!(query "pivot.list", "PivotTables", [], None, "{} → every PivotTable in the workbook", has_doc, list),
@@ -320,6 +338,19 @@ fn canonical(cmd: &str, src: &pv::Source, field: &str) -> Result<String> {
src.col(field).and_then(|c| src.headers.get(c).cloned()).ok_or_else(|| bad(cmd, format!("no field `{field}` in the source data")))
}
/// The calculated field named `field`, if any.
fn calc_field<'a>(pt: &'a PivotTable, field: &str) -> Option<&'a PivotCalcField> {
pt.calculated_fields.iter().find(|c| c.name.eq_ignore_ascii_case(field.trim()))
}
/// The canonical name of a source or calculated field.
fn canonical_any(cmd: &str, pt: &PivotTable, src: &pv::Source, field: &str) -> Result<String> {
match calc_field(pt, field) {
Some(c) if src.col(field).is_none() => Ok(c.name.clone()),
_ => canonical(cmd, src, field),
}
}
fn unique_value_name(pt: &PivotTable, base: &str, except: Option<usize>) -> String {
let taken = |n: &str| pt.values.iter().enumerate().any(|(i, v)| Some(i) != except && v.name.eq_ignore_ascii_case(n));
if !taken(base) {
@@ -343,7 +374,11 @@ fn add_to_area(
name: Option<&str>,
position: Option<usize>,
) -> Result<()> {
let field = canonical(cmd, src, field)?;
let is_calc = src.col(field).is_none() && calc_field(pt, field).is_some();
if is_calc && area != "values" {
return Err(other("A calculated field can only be placed in the Values area."));
}
let field = canonical_any(cmd, pt, src, field)?;
match area {
"rows" | "columns" => {
if pt.rows.len() + pt.columns.len() >= pv::MAX_AXIS_FIELDS && !in_axes(pt, &field) {
@@ -369,7 +404,7 @@ fn add_to_area(
if pt.values.len() >= pv::MAX_VALUE_FIELDS {
return Err(other(format!("A PivotTable can have at most {} value fields.", pv::MAX_VALUE_FIELDS)));
}
let numeric = src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
let numeric = is_calc || src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
let f = func.unwrap_or(if numeric { PivotFunc::Sum } else { PivotFunc::Count });
let base = match name {
Some(n) if !n.trim().is_empty() => {
@@ -663,6 +698,7 @@ fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
"subtotals": if !pt.subtotals { "none" } else if pt.subtotals_top { "top" } else { "bottom" },
"style": pt.style,
"showHeaders": pt.show_headers,
"calculatedFields": pt.calculated_fields.iter().map(|c| json!({"name": c.name, "formula": c.formula})).collect::<Vec<_>>(),
})
}
@@ -702,6 +738,11 @@ fn fields(s: &mut Session, p: &Json) -> Result<Json> {
.collect(),
Err(_) => vec![],
};
let mut list = list;
for c in &pt.calculated_fields {
let areas: Vec<&str> = if pt.values.iter().any(|v| v.source_col.eq_ignore_ascii_case(&c.name)) { vec!["values"] } else { vec![] };
list.push(json!({"name": c.name, "numeric": true, "date": false, "samples": [], "areas": areas, "calculated": true, "formula": c.formula}));
}
if let Some(m) = out.as_object_mut() {
m.insert("fields".into(), Json::Array(list));
if let Ok(src) = &src {
@@ -743,7 +784,76 @@ fn add_field(s: &mut Session, p: &Json) -> Result<Json> {
let pos = position_param(p);
update(s, p, |pt, src, _| {
add_to_area(C, pt, src, &field, area, func, name.as_deref(), pos)?;
Ok(json!({"field": canonical(C, src, &field)?, "area": area}))
Ok(json!({"field": canonical_any(C, pt, src, &field)?, "area": area}))
})
}
fn calculated_field(s: &mut Session, p: &Json) -> Result<Json> {
const C: &str = "pivot.calculatedField";
let Some(name) = str_param(p, "name").map(|n| n.trim().to_string()) else {
// Menu-style call: the Insert Calculated Field dialog.
let (si, pi) = find_pivot(s, p)?;
let d = s.doc()?;
let pt = d.wb.sheet(si).and_then(|sh| sh.pivots.get(pi)).ok_or_else(|| other("There's no such PivotTable."))?;
let n = (1..).map(|k| format!("Field{k}")).find(|n| calc_field(pt, n).is_none()).unwrap_or_else(|| "Field1".into());
let pivot = pt.name.clone();
s.ui_requests.push(crate::UiRequest::Dialog("pivotCalculatedField".into(), json!({"pivot": pivot, "name": n, "formula": "= 0"})));
return ok();
};
if name.is_empty() || name.chars().count() > 255 {
return Err(bad(C, "`name` must be 1 to 255 characters"));
}
let delete = bool_param(p, "delete").unwrap_or(false);
let formula = str_param(p, "formula").map(|f| {
let f = f.trim();
if f.starts_with('=') { f.to_string() } else { format!("={f}") }
});
let to_values = bool_param(p, "values").unwrap_or(true);
if !delete && formula.is_none() {
return Err(bad(C, "missing `formula`"));
}
update(s, p, |pt, src, _| {
let existing = pt.calculated_fields.iter().position(|c| c.name.eq_ignore_ascii_case(&name));
if delete {
let i = existing.ok_or_else(|| bad(C, format!("no calculated field `{name}`")))?;
let gone = pt.calculated_fields.remove(i);
pt.values.retain(|v| !v.source_col.eq_ignore_ascii_case(&gone.name));
return Ok(json!({"name": gone.name, "deleted": true}));
}
let formula = formula.clone().unwrap_or_default();
if src.col(&name).is_some() {
return Err(other("PivotTable field name already exists."));
}
let canon = match existing {
Some(i) => {
let c = pt.calculated_fields.get_mut(i).ok_or_else(|| other("There's no such calculated field."))?;
c.formula = formula.clone();
c.name.clone()
}
None => {
if pt.calculated_fields.len() >= crate::pivot_calc::MAX_CALC_FIELDS {
return Err(other(format!("A PivotTable can have at most {} calculated fields.", crate::pivot_calc::MAX_CALC_FIELDS)));
}
pt.calculated_fields.push(PivotCalcField { name: name.clone(), formula: formula.clone() });
name.clone()
}
};
let set = crate::pivot_calc::CalcSet::new(pt, &src.headers);
let i = set.index(&canon).ok_or_else(|| other("There's no such calculated field."))?;
if let Some(e) = set.error(i) {
return Err(bad(C, e.to_string()));
}
if set.is_cyclic(i) {
return Err(bad(C, format!("`{canon}` refers to itself through its formula")));
}
if existing.is_none() && to_values && !pt.values.iter().any(|v| v.source_col.eq_ignore_ascii_case(&canon)) {
add_to_area(C, pt, src, &canon, "values", Some(PivotFunc::Sum), None, None)?;
}
Ok(json!({
"name": canon,
"formula": formula,
"calculatedFields": pt.calculated_fields.iter().map(|c| json!({"name": c.name, "formula": c.formula})).collect::<Vec<_>>(),
}))
})
}
@@ -1171,6 +1281,18 @@ fn change_source(s: &mut Session, p: &Json) -> Result<Json> {
fn delete(s: &mut Session, p: &Json) -> Result<Json> {
let (si, pi) = find_pivot(s, p)?;
edit(s, |cx| {
// Its PivotCharts become ordinary charts.
let link = cx.wb.sheet(si).and_then(|sh| sh.pivots.get(pi).map(|pt| (sh.name.clone(), pt.name.clone())));
if let Some((sheet, name)) = link {
for i in 0..cx.wb.sheets.len() {
let linked = |c: &Chart| c.pivot.as_deref().is_some_and(|l| pv::links_to(l, &sheet, &name));
if cx.wb.sheet(i).is_some_and(|sh| sh.charts.iter().any(linked)) {
for c in cx.sheet_mut(i)?.charts.iter_mut().filter(|c| linked(c)) {
c.pivot = None;
}
}
}
}
pv::clear_output(&mut cx.wb, si, pi);
let sh = cx.sheet_mut(si)?;
if pi < sh.pivots.len() {
@@ -1181,6 +1303,81 @@ fn delete(s: &mut Session, p: &Json) -> Result<Json> {
})
}
// ---------------------------------------------------------------- PivotChart
/// The PivotTable a PivotChart call targets: `pivot` may also be a cell of its report.
fn chart_pivot(s: &Session, p: &Json) -> Result<(usize, usize)> {
if let Some(t) = str_param(p, "pivot") {
let d = s.doc()?;
let (sheet, addr) = match t.rsplit_once('!') {
Some((sh, a)) => {
let sh = sh.trim();
let sh = sh.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')).map(|x| x.replace("''", "'")).unwrap_or_else(|| sh.to_string());
(d.wb.sheet_index(&sh), a)
}
None => (Some(d.wb.active_sheet), t),
};
if let (Some(si), Some(c)) = (sheet, CellRef::parse(addr.trim().replace('$', "").as_str())) {
let hit = d.wb.sheet(si).and_then(|sh| sh.pivots.iter().position(|pt| pt.last_range.is_some_and(|r| r.contains(c)) || pt.anchor == c));
return hit.map(|pi| (si, pi)).ok_or_else(|| bad("insert.pivotChart", format!("{t} is not in a PivotTable")));
}
}
find_pivot(s, p)
}
fn insert_pivot_chart(s: &mut Session, p: &Json) -> Result<Json> {
let (si, pi) = chart_pivot(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
let pt = sh.pivots.get(pi).ok_or_else(|| other("There's no such PivotTable."))?;
let area = pt.last_range.ok_or_else(|| other("Refresh the PivotTable before adding a PivotChart."))?;
let out = pv::compute(&d.wb, pt, si).map_err(other)?;
if out.chart_rows.is_empty() || out.chart_cols.is_empty() {
return Err(other("Add a field to the Values area and one to Rows or Columns before creating a PivotChart."));
}
let series = pv::chart_series(&sh.name, area.start, &out);
let t = str_param(p, "type").unwrap_or("column");
let kind = super::insert::chart_kind(t, str_param(p, "subtype").unwrap_or(""));
let at =
cell_param(s, p, "at")?.unwrap_or_else(|| CellRef::new(area.start.row, area.end.col.saturating_add(2).min(gridcraft_core::MAX_COLS - 1)));
let title = match p.get("title") {
Some(Json::String(t)) => Some(t.clone()),
Some(Json::Null) => None,
_ => Some(if series.len() == 1 { "Total".to_string() } else { "Chart Title".to_string() }),
};
let id = d.wb.next_object_id();
let link = pv::chart_link(&sh.name, &pt.name);
let pivot_name = pt.name.clone();
let n = series.len();
let chart = Chart {
id,
kind,
anchor: Anchor {
cell: at,
dx: 0.0,
dy: 0.0,
width: f64_param(p, "width").unwrap_or(480.0).clamp(10.0, 10_000.0) as f32,
height: f64_param(p, "height").unwrap_or(288.0).clamp(10.0, 10_000.0) as f32,
mode: anchor_mode_param(p).unwrap_or_default(),
},
title,
series,
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
data_labels: false,
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
style: 1,
x_title: None,
y_title: None,
source: None,
by_rows: false,
pivot: Some(link),
};
edit(s, |cx| {
cx.sheet_mut(si)?.charts.push(chart);
Ok(json!({"chart": id, "pivot": pivot_name, "series": n}))
})
}
// ---------------------------------------------------------------- recommended
fn suggestions(wb: &Workbook, src: &pv::Source) -> Vec<Json> {
@@ -1280,8 +1477,8 @@ fn recommended(s: &mut Session, p: &Json) -> Result<Json> {
#[cfg(test)]
mod tests {
use gridcraft_core::{CellRef, Value};
use serde_json::json;
use gridcraft_core::{CellError, CellRef, Value};
use serde_json::{Value as Json, json};
use crate::Session;
@@ -1550,6 +1747,133 @@ mod tests {
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
}
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
}
fn plotted(s: &Session) -> Vec<Vec<Option<f64>>> {
let d = s.doc().unwrap();
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet, &pivot_chart(s));
data.series.into_iter().map(|x| x.values).collect()
}
#[test]
fn pivot_chart_follows_the_report() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
// Any cell of the report picks the PivotTable.
let r = s.execute("insert.pivotChart", json!({"pivot": "B5"})).unwrap();
assert_eq!(r["series"], 1);
let ch = pivot_chart(&s);
assert_eq!(ch.pivot.as_deref(), Some("Sheet2!PivotTable1"));
assert_eq!(ch.title.as_deref(), Some("Total"));
assert_eq!(ch.series[0].values, "Sheet2!$B$4:$B$6");
assert_eq!(ch.series[0].categories.as_deref(), Some("Sheet2!$A$4:$A$6"));
assert_eq!(plotted(&s), vec![vec![Some(415.0), Some(135.0), Some(285.0)]]);
// A column field: one series per item, rebound by the layout change.
s.execute("pivot.addField", json!({"field": "Product", "area": "columns"})).unwrap();
let ch = pivot_chart(&s);
let names: Vec<_> = ch.series.iter().map(|x| x.name.clone().unwrap_or_default()).collect();
assert_eq!(names, vec!["\"Apples\"", "\"Pears\"", "\"Plums\""]);
assert_eq!(plotted(&s)[0], vec![Some(160.0), Some(90.0), Some(170.0)]);
// Nested row fields: the innermost items only, as a union around the parent rows.
s.execute("pivot.moveField", json!({"field": "Product", "from": "columns", "to": "rows"})).unwrap();
let ch = pivot_chart(&s);
assert!(ch.series[0].values.starts_with('('), "{}", ch.series[0].values);
let pts = plotted(&s);
assert_eq!(pts[0].len(), 9);
assert_eq!(pts[0].iter().flatten().sum::<f64>(), TOTAL);
// Survives an XLSX round trip as a PivotChart.
let wb = (*s.doc().unwrap().wb).clone();
let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap();
let si = back.sheet_index("Sheet2").unwrap();
assert_eq!(back.sheet(si).unwrap().charts.first().and_then(|c| c.pivot.clone()).as_deref(), Some("Sheet2!PivotTable1"));
// Renaming the sheet keeps the link; a refresh still rebinds.
s.execute("sheet.rename", json!({"name": "Report"})).unwrap();
assert_eq!(pivot_chart(&s).pivot.as_deref(), Some("Report!PivotTable1"));
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
assert_eq!(pivot_chart(&s).series.len(), 3);
// Deleting the PivotTable leaves an ordinary chart.
s.execute("pivot.delete", json!({})).unwrap();
assert_eq!(pivot_chart(&s).pivot, None);
}
#[test]
fn pivot_chart_errors() {
let mut s = sales();
// No PivotTable yet.
assert!(s.execute("insert.pivotChart", json!({})).is_err());
s.execute("insert.pivotTable", json!({"rows": ["Region"]})).unwrap();
// Not in the report; no values.
assert!(s.execute("insert.pivotChart", json!({"pivot": "Z99"})).is_err());
assert!(s.execute("insert.pivotChart", json!({})).unwrap_err().to_string().contains("Values"));
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
let r = s.execute("insert.pivotChart", json!({"pivot": "PivotTable1", "type": "line", "title": null})).unwrap();
assert_eq!(r["series"], 1);
let ch = pivot_chart(&s);
assert_eq!(ch.kind, gridcraft_model::ChartKind::Line);
assert_eq!(ch.title, None);
// One undo step.
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().charts.is_empty());
}
#[test]
fn calculated_field_on_sums() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
let r = s.execute("pivot.calculatedField", json!({"name": "Price", "formula": "Sales / Units"})).unwrap();
assert_eq!(r["formula"], "=Sales / Units");
assert_eq!(text(&s, "C3"), "Sum of Price");
assert_eq!(text(&s, "A4"), "East");
// East: 415 sales over 33 units, from the sums.
let east = val(&s, "C4").as_f64().unwrap();
assert!((east - 415.0 / 33.0).abs() < 1e-12, "{east}");
// The grand total applies the formula to the totals, not the sum of the rows.
assert_eq!(text(&s, "A7"), "Grand Total");
let total = val(&s, "C7").as_f64().unwrap();
assert!((total - TOTAL / 72.0).abs() < 1e-12, "{total}");
// Quoted names, functions, and another calculated field.
s.execute("pivot.calculatedField", json!({"name": "Rounded", "formula": "=ROUND('Price'*2,1)"})).unwrap();
assert_eq!(val(&s, "D4"), Value::Number(25.2));
// Division by zero shows #DIV/0! cells.
s.execute("pivot.calculatedField", json!({"name": "Zero", "formula": "=Sales/(Units-Units)"})).unwrap();
assert_eq!(val(&s, "E4"), Value::Error(CellError::Div0));
// Change and delete.
s.execute("pivot.calculatedField", json!({"name": "zero", "formula": "=Units*2"})).unwrap();
assert_eq!(val(&s, "E4"), Value::Number(66.0));
s.execute("pivot.calculatedField", json!({"name": "Zero", "delete": true})).unwrap();
assert_eq!(pt(&s).values.len(), 3);
assert_eq!(pt(&s).calculated_fields.len(), 2);
// The field list shows calculated fields.
let f = s.execute("pivot.fields", json!({})).unwrap();
assert!(f["fields"].as_array().unwrap().iter().any(|x| x["name"] == "Price" && x["calculated"] == true));
}
#[test]
fn calculated_field_errors() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
let mut e = |p: Json| s.execute("pivot.calculatedField", p).unwrap_err().to_string();
assert!(e(json!({"name": "Bad", "formula": "=Sales*Bogus"})).contains("Bogus"));
assert!(e(json!({"name": "Bad", "formula": "=A1*2"})).contains("cells"));
assert!(e(json!({"name": "Bad", "formula": "=Sales*("})).contains("error"));
assert!(e(json!({"name": "Sales", "formula": "=1"})).contains("already exists"));
assert!(e(json!({"name": "Bad"})).contains("formula"));
assert!(e(json!({"name": "Gone", "delete": true})).contains("Gone"));
// A cycle is refused.
s.execute("pivot.calculatedField", json!({"name": "X", "formula": "=Sales"})).unwrap();
s.execute("pivot.calculatedField", json!({"name": "Y", "formula": "=X*2"})).unwrap();
let err = s.execute("pivot.calculatedField", json!({"name": "X", "formula": "=Y"})).unwrap_err().to_string();
assert!(err.contains("itself"), "{err}");
// Calculated fields only go to Values; nothing changed after the failures.
assert!(s.execute("pivot.addField", json!({"field": "Y", "area": "rows"})).is_err());
assert_eq!(pt(&s).calculated_fields.len(), 2);
// Without a name the dialog opens (menu-style call).
s.ui_requests.clear();
s.execute("pivot.calculatedField", json!({})).unwrap();
assert!(matches!(s.ui_requests.last(), Some(crate::UiRequest::Dialog(n, _)) if n == "pivotCalculatedField"));
}
#[test]
fn replace_protection() {
let mut s = sales();
@@ -1621,6 +1945,29 @@ mod tests {
assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0));
}
#[test]
fn repeated_headers_get_numbered_names() {
let mut s = Session::new();
s.new_workbook();
let mut header = vec![json!("a"), json!("A"), json!("a"), json!("a2")];
// Thousands of equal headers (a row of check boxes, say) used to take cubic time; this would
// hang rather than fail a wall-clock check, which is flaky on a loaded machine.
header.extend((0..3000).map(|_| json!("x")));
let data: Vec<_> = (0..header.len()).map(|i| json!(i)).collect();
let end = CellRef::new(1, header.len() as u32 - 1).a1();
s.execute("range.setValues", json!({"range": "A1", "values": [header, data]})).unwrap();
let src = crate::pivot::read_source(&s.doc().unwrap().wb, &format!("Sheet1!A1:{end}"), 0).unwrap();
assert_eq!(&src.headers[..4], ["a", "A2", "a3", "a22"]);
assert_eq!(src.headers[4], "x");
assert_eq!(src.headers.last().map(String::as_str), Some("x3000"));
// Table column names follow the same rule.
s.execute("insert.table", json!({"range": format!("A1:{end}"), "header": true})).unwrap();
let text = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].clone();
assert_eq!(text(&mut s, "B1"), "A2");
let last = CellRef::new(0, 3003).a1();
assert_eq!(text(&mut s, &last), "x3000");
}
#[test]
fn hostile_params_never_panic() {
let mut s = sales();
+369 -47
View File
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// Sheet geometry is in pixels at 96 dpi; PDF units are points.
const PX_TO_PT: f32 = 0.75;
pub(crate) const PX_TO_PT: f32 = 0.75;
/// Most pages one export produces.
pub const MAX_PAGES: usize = 2000;
/// Cells in a page block above which only stored cells are visited (not every grid position).
@@ -110,13 +110,15 @@ pub struct SheetLayout {
/// Heading sizes in sheet pixels (0 when headings are off).
pub heading_w: f32,
pub heading_h: f32,
/// Manual page breaks apply (they don't when the sheet is fitted to pages).
pub manual_breaks: bool,
}
impl SheetLayout {
fn k(&self) -> f32 {
PX_TO_PT * self.scale
}
fn avail(&self) -> (f32, f32) {
pub(crate) fn avail(&self) -> (f32, f32) {
let [l, r, t, b, ..] = self.margins;
((self.page_w - l - r).max(36.0), (self.page_h - t - b).max(36.0))
}
@@ -271,30 +273,11 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid
title_cols,
heading_w,
heading_h,
manual_breaks: fit.is_none(),
};
let paginate = |lay: &mut SheetLayout, manual: bool| {
let k = lay.k();
let (aw, ah) = lay.avail();
let (aw, ah) = (aw / k, ah / k);
let rb: Vec<u32> = if manual { st.row_breaks.clone() } else { vec![] };
let cb: Vec<u32> = if manual { st.col_breaks.clone() } else { vec![] };
let (mut rb, mut cb) = (rb, cb);
rb.sort_unstable();
cb.sort_unstable();
let title_h = |start: u32| -> f32 {
match title_rows {
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|r| sh.row_height(r)).sum(),
_ => 0.0,
}
};
let title_w = |start: u32| -> f32 {
match title_cols {
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|c| sh.col_width(c)).sum(),
_ => 0.0,
}
};
lay.row_bands = bands(area.start.row, area.end.row, |r| sh.row_height(r), |start| (ah - heading_h - title_h(start)).max(1.0), &rb, MAX_PAGES);
lay.col_bands = bands(area.start.col, area.end.col, |c| sh.col_width(c), |start| (aw - heading_w - title_w(start)).max(1.0), &cb, MAX_PAGES);
lay.manual_breaks = manual;
(lay.row_bands, lay.col_bands) = split_bands(sh, lay, MAX_PAGES);
lay.pages.clear();
'outer: for ci in 0..lay.col_bands.len() {
for ri in 0..lay.row_bands.len() {
@@ -332,6 +315,37 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid
Some(lay)
}
/// Splits a layout's area into row and column bands that fit its pages (at most `cap` of each),
/// honouring manual breaks (when `lay.manual_breaks`), print headings and repeated titles. The
/// one pagination rule shared by printing, PDF export, Page Break Preview and Page Layout view.
pub(crate) fn split_bands(sh: &Sheet, lay: &SheetLayout, cap: usize) -> (Vec<(u32, u32)>, Vec<(u32, u32)>) {
let k = lay.k();
let (aw, ah) = lay.avail();
let (aw, ah) = (aw / k, ah / k);
let st = &lay.settings;
let mut rb: Vec<u32> = if lay.manual_breaks { st.row_breaks.clone() } else { vec![] };
let mut cb: Vec<u32> = if lay.manual_breaks { st.col_breaks.clone() } else { vec![] };
rb.sort_unstable();
cb.sort_unstable();
let (title_rows, title_cols) = (lay.title_rows, lay.title_cols);
let title_h = |start: u32| -> f32 {
match title_rows {
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|r| sh.row_height(r)).sum(),
_ => 0.0,
}
};
let title_w = |start: u32| -> f32 {
match title_cols {
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|c| sh.col_width(c)).sum(),
_ => 0.0,
}
};
let area = lay.area;
let rows = bands(area.start.row, area.end.row, |r| sh.row_height(r), |start| (ah - lay.heading_h - title_h(start)).max(1.0), &rb, cap);
let cols = bands(area.start.col, area.end.col, |c| sh.col_width(c), |start| (aw - lay.heading_w - title_w(start)).max(1.0), &cb, cap);
(rows, cols)
}
/// Lays out every sheet a print command covers.
pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
let mut out = Vec::new();
@@ -375,6 +389,132 @@ pub struct HfContext {
pub time: String,
}
/// Today's date and the current time as headers and footers show them (`&D`, `&T`).
pub fn hf_date_time(wb: &Workbook) -> (String, String) {
let now = gridcraft_calc::now_serial();
let date = crate::display::format(&Value::Number(now.floor()), "m/d/yyyy", wb).text;
let time = crate::display::format(&Value::Number(now), "h:mm AM/PM", wb).text;
(date, time)
}
/// Header/footer codes and the field names the Page Layout view shows for them while editing.
pub const HF_FIELDS: [(char, &str); 8] = [
('P', "&[Page]"),
('N', "&[Pages]"),
('D', "&[Date]"),
('T', "&[Time]"),
('Z', "&[Path]"),
('F', "&[File]"),
('A', "&[Tab]"),
('G', "&[Picture]"),
];
/// Splits a header/footer string into its raw left, centre and right sections (codes kept).
/// Text before the first `&L`/`&C`/`&R` belongs to the centre, as when printing.
pub fn split_header_footer(spec: &str) -> [String; 3] {
let mut out: [String; 3] = Default::default();
let mut cur = 1usize;
let chars: Vec<char> = spec.chars().take(10_000).collect();
let mut i = 0;
while let Some(&c) = chars.get(i) {
let next = chars.get(i + 1).copied();
let sec = cur.min(2);
match (c, next) {
('&', Some('L' | 'l')) => cur = 0,
('&', Some('C' | 'c')) => cur = 1,
('&', Some('R' | 'r')) => cur = 2,
('&', Some('"')) => {
// &"Font,Style" is kept whole.
let end = chars[i + 2..].iter().position(|ch| *ch == '"').map_or(chars.len(), |p| i + 3 + p);
out[sec].extend(&chars[i..end.min(chars.len())]);
i = end;
continue;
}
('&', Some(n)) => {
out[sec].push('&');
out[sec].push(n);
}
('&', None) => {}
(ch, _) => {
out[sec].push(ch);
i += 1;
continue;
}
}
i += 2;
}
out
}
/// Joins raw left, centre and right sections into one header/footer string.
pub fn join_header_footer(sections: &[String; 3]) -> String {
let mut s = String::new();
for (code, text) in ["&L", "&C", "&R"].iter().zip(sections) {
if !text.is_empty() {
s.push_str(code);
s.push_str(text);
}
}
s
}
/// A raw section as the user edits it: `&P` shows as `&[Page]`, `&N` as `&[Pages]`, and so on.
pub fn codes_to_fields(raw: &str) -> String {
let mut out = String::new();
let mut it = raw.chars().peekable();
while let Some(c) = it.next() {
if c != '&' {
out.push(c);
continue;
}
// A dangling `&` at the end is dropped (printing ignores it too).
if let Some(n) = it.next() {
match HF_FIELDS.iter().find(|(code, _)| *code == n.to_ascii_uppercase()) {
Some((_, field)) => out.push_str(field),
None => {
out.push('&');
out.push(n);
}
}
}
}
out
}
/// The inverse of [`codes_to_fields`]: field names become codes again; a dangling `&` at the end
/// becomes a literal ampersand so it can't swallow the next section's code.
pub fn fields_to_codes(text: &str) -> String {
let chars: Vec<char> = text.chars().take(10_000).collect();
let mut out = String::new();
let mut i = 0;
while let Some(&c) = chars.get(i) {
if c != '&' {
out.push(c);
i += 1;
continue;
}
if chars.get(i + 1) == Some(&'&') {
out.push_str("&&");
i += 2;
continue;
}
let rest: String = chars[i..].iter().take(12).collect();
if let Some((code, field)) = HF_FIELDS.iter().find(|(_, f)| rest.starts_with(f)) {
out.push('&');
out.push(*code);
i += field.chars().count();
continue;
}
if i + 1 == chars.len() {
out.push_str("&&");
} else {
out.push('&');
}
i += 1;
}
out
}
/// One header/footer section: its text and whether `&B` made it bold.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HfSection {
@@ -847,11 +987,41 @@ fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Option<crate::
if w <= 0.0 || h <= 0.0 {
continue;
}
draw_text(pg, b, *c, l, (x, y, w, h), merged, &merges, (bx, bx + bw));
if let Some(picture) = sh.cell_pictures.get(c) {
draw_cell_picture(pg, &picture.data, (x, y, w, h), b.k);
} else {
draw_text(pg, b, *c, l, (x, y, w, h), merged, &merges, (bx, bx + bw));
}
}
pg.restore();
}
/// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio.
fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
let (x, y, w, h) = rect;
let pad = 2.0 * k;
let (w, h) = ((w - 2.0 * pad).max(0.0), (h - 2.0 * pad).max(0.0));
if w <= 0.0 || h <= 0.0 || data.len() > 16 * 1024 * 1024 {
return;
}
let Some((iw, ih)) = crate::io::image_size(data) else { return };
if iw == 0 || ih == 0 || iw > 8192 || ih > 8192 || u64::from(iw) * u64::from(ih) > 16_000_000 {
return;
}
let Ok(mut reader) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format() else { return };
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(64 * 1024 * 1024);
reader.limits(limits);
let Ok(image) = reader.decode() else { return };
let image =
image.thumbnail(((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32).to_rgba8();
let fit = (w / iw as f32).min(h / ih as f32);
let (pw, ph) = (iw as f32 * fit, ih as f32 * fit);
pg.image_rgba(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph, image.as_raw(), image.width(), image.height());
}
/// Is a cell free for text to overflow into?
fn empty_for_overflow(sh: &Sheet, c: CellRef, merges: &[RangeRef]) -> bool {
sh.value_ref(c).is_none_or(|v| v.is_empty()) && !merges.iter().any(|m| m.contains(c))
@@ -923,7 +1093,15 @@ fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f3
HAlign::Justify | HAlign::Fill => HAlign::Left,
other => other,
};
let lines: Vec<String> = if wrap { wrap_lines(&text, font, size, avail.max(size)) } else { vec![text] };
let rot = st.align.rotation;
let rotated = rot != 0 && rot != 255;
// Rotated text wraps along its own direction: upright (±90°) text to the row height.
let lines: Vec<String> = match (wrap, rotated) {
(true, false) => wrap_lines(&text, font, size, avail.max(size)),
(true, true) if rot.abs() == 90 => wrap_lines(&text, font, size, (h - 2.0 * pad).max(size)),
(true, true) => vec![text.lines().next().unwrap_or_default().to_string()],
(false, _) => vec![text],
};
let line_h = size * 1.2;
let n = lines.len().max(1) as f32;
let first_baseline = match st.align.v {
@@ -933,7 +1111,7 @@ fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f3
};
// Overflow into empty neighbours (single-line text, not merged).
let (mut clip_l, mut clip_r) = (x, x + w);
if !wrap && !merged && !is_num && tw + 2.0 * pad + indent > w {
if !wrap && !merged && !is_num && rot.abs() != 90 && tw + 2.0 * pad + indent > w {
let need = tw + 2.0 * pad + indent - w;
let grow = |dir: i64, mut need: f32| -> f32 {
let mut ext = 0.0;
@@ -966,13 +1144,20 @@ fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f3
let clip_r = clip_r.min(limits.1);
pg.save();
pg.clip_rect(clip_l, y, (clip_r - clip_l).max(0.0), h);
let rot = st.align.rotation;
if rot != 0 && rot != 255 && !wrap {
if rotated {
// Rotated text: anchored at the bottom-left (upward) or top-left (downward) of the cell.
// Wrapped lines stack rightward for upward text and leftward for downward text, so
// downward text starts its first line far enough in for the last to end at the left pad.
let deg = (rot as f32).clamp(-90.0, 90.0);
let angle = -deg.to_radians();
let (ox, oy) = if deg > 0.0 { (x + pad + size * 0.8 * deg.to_radians().sin(), y + h - pad) } else { (x + pad, y + pad + size * 0.8) };
if let Some(t) = lines.first() {
let last = lines.len().saturating_sub(1) as f32;
for (i, t) in lines.iter().enumerate() {
let i = i as f32;
let (ox, oy) = if deg > 0.0 {
(x + pad + size * 0.8 * deg.to_radians().sin() + i * line_h, y + h - pad)
} else {
(x + pad + (last - i) * line_h, y + pad + size * 0.8)
};
pg.text_rotated(ox, oy, size, font, color, t, angle);
}
pg.restore();
@@ -1082,7 +1267,7 @@ fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block)
}
let (x, y, w, h) = place(r);
let fill = rgb_of(shp.fill, wb);
let line = rgb_of(shp.line, wb).map(|c| (c, (0.75 * b.k).max(0.25)));
let line = rgb_of(shp.line, wb).filter(|_| !shp.format.no_line).map(|c| (c, (0.75 * b.k).max(0.25)));
match shp.kind {
ShapeKind::Ellipse => {
let pts: Vec<[f32; 2]> = (0..72)
@@ -1109,13 +1294,29 @@ fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block)
}
}
if !shp.text.is_empty() {
let size = 11.0 * b.scale;
let lines = wrap_lines(&shp.text, Font::Helvetica, size, (w - 4.0 * b.k).max(size));
let mut yy = y + 2.0 * b.k + size * 0.8;
use gridcraft_model::{ShapeTextAlign, ShapeTextAnchor};
let fm = &shp.format;
let text_box = shp.kind == ShapeKind::TextBox;
let size = fm.font_size.unwrap_or(11.0).clamp(1.0, 4000.0) * b.scale;
let font = Font::styled(Font::family_for(fm.font.as_deref().unwrap_or("")), fm.bold, fm.italic);
let color = fm.text_color.and_then(|c| rgb_of(c, wb)).unwrap_or([0, 0, 0]);
let align = fm.align.unwrap_or(if text_box { ShapeTextAlign::Left } else { ShapeTextAlign::Center });
let anchor = fm.anchor.unwrap_or(if text_box { ShapeTextAnchor::Top } else { ShapeTextAnchor::Middle });
let lines = wrap_lines(&shp.text, font, size, (w - 4.0 * b.k).max(size));
let block_h = lines.len().min(500) as f32 * size * 1.2;
let mut yy = match anchor {
ShapeTextAnchor::Top => y + 2.0 * b.k,
ShapeTextAnchor::Middle => y + (h - block_h) / 2.0,
ShapeTextAnchor::Bottom => y + h - 2.0 * b.k - block_h,
} + size * 0.8;
for l in lines.iter().take(500) {
let lw = gridcraft_pdf::text_width(Font::Helvetica, size, l);
let lx = if shp.kind == ShapeKind::TextBox { x + 2.0 * b.k } else { x + (w - lw) / 2.0 };
pg.text(lx, yy, size, Font::Helvetica, [0, 0, 0], l);
let lw = gridcraft_pdf::text_width(font, size, l);
let lx = match align {
ShapeTextAlign::Left => x + 2.0 * b.k,
ShapeTextAlign::Center => x + (w - lw) / 2.0,
ShapeTextAlign::Right => x + w - 2.0 * b.k - lw,
};
pg.text(lx, yy, size, font, color, l);
yy += size * 1.2;
}
}
@@ -1168,11 +1369,11 @@ fn draw_headings(pg: &mut Page, b: &Block, col_heads: bool, row_heads: bool, at:
}
}
fn draw_header_footer(pg: &mut Page, lay: &SheetLayout, cx: &HfContext) {
fn draw_header_footer(pg: &mut Page, lay: &SheetLayout, which: gridcraft_model::HfPage, cx: &HfContext) {
let [l, r, _, _, hm, fm] = lay.margins;
let pw = lay.page_w;
let ph = lay.page_h;
for (spec, header) in [(&lay.settings.header, true), (&lay.settings.footer, false)] {
for (spec, header) in [(lay.settings.hf(which, false), true), (lay.settings.hf(which, true), false)] {
if spec.is_empty() {
continue;
}
@@ -1241,16 +1442,14 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
doc.info.author = wb.props.author.clone();
let total: usize = layouts.iter().map(|l| l.pages.len()).sum();
let now = gridcraft_calc::now_serial();
let date = crate::display::format(&Value::Number(now.floor()), "m/d/yyyy", wb).text;
let time = crate::display::format(&Value::Number(now), "h:mm AM/PM", wb).text;
let (date, time) = hf_date_time(wb);
let mut page_no = 0usize;
for lay in layouts {
let Some(sh) = wb.sheet(lay.sheet) else { continue };
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
let k = lay.k();
let (aw, ah) = lay.avail();
for (ri, ci) in &lay.pages {
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
page_no += 1;
let (Some(rband), Some(cband)) = (lay.row_bands.get(*ri).copied(), lay.col_bands.get(*ci).copied()) else { continue };
let rsegs = segments(lay.title_rows, rband);
@@ -1294,7 +1493,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
date: date.clone(),
time: time.clone(),
};
draw_header_footer(pg, lay, &cx);
draw_header_footer(pg, lay, lay.settings.hf_page(pi == 0, page_no), &cx);
}
}
let n = doc.page_count();
@@ -1311,7 +1510,7 @@ fn build_pdf(s: &Session, p: &Json, cmd: &str) -> Result<(Vec<u8>, usize)> {
Ok(render_pdf(&d.wb, &lays, &d.display_title(), &path))
}
fn export_pdf(s: &mut Session, p: &Json) -> Result<Json> {
pub(crate) fn export_pdf(s: &mut Session, p: &Json) -> Result<Json> {
let (bytes, pages) = build_pdf(s, p, "file.exportPdf")?;
match str_param(p, "path").filter(|x| !x.is_empty()) {
Some(path) => {
@@ -1542,6 +1741,63 @@ mod tests {
hay.windows(needle.len()).any(|w| w == needle.as_bytes())
}
#[test]
fn header_sections_split_join_and_field_names() {
let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D";
let parts = split_header_footer(spec);
assert_eq!(parts, ["&\"Arial,Bold\"Sales &&Co".to_string(), "Page &P of &N".into(), "&D".into()]);
assert_eq!(join_header_footer(&parts), spec);
// Text before any section code is the centre section, as when printing.
assert_eq!(split_header_footer("Report"), [String::new(), "Report".into(), String::new()]);
assert_eq!(codes_to_fields("Page &P of &N, &A (&F) &&"), "Page &[Page] of &[Pages], &[Tab] (&[File]) &&");
assert_eq!(fields_to_codes("Page &[Page] of &[Pages], &[Tab] (&[File]) &&"), "Page &P of &N, &A (&F) &&");
// A dangling ampersand stays literal instead of eating the next section's code.
assert_eq!(fields_to_codes("R&"), "R&&");
let joined = join_header_footer(&[fields_to_codes("R&"), "x".into(), String::new()]);
assert_eq!(split_header_footer(&joined)[0], "R&&");
let cx = HfContext { page: 2, pages: 5, sheet: "Data".into(), ..Default::default() };
let out = expand_header_footer(&join_header_footer(&[String::new(), fields_to_codes("&[Page] / &[Pages]"), fields_to_codes("&[Tab]")]), &cx);
assert_eq!((out[1].text.as_str(), out[2].text.as_str()), ("2 / 5", "Data"));
// Hostile input never panics.
for t in ["&", "&\"", "&\"unterminated", "&&&", "&[Pag", "\u{1F600}&[Page]"] {
let _ = join_header_footer(&split_header_footer(t));
let _ = fields_to_codes(&codes_to_fields(t));
}
}
#[test]
fn header_footer_section_edits_are_undoable_and_views_are_per_sheet() {
let mut s = s();
s.execute("pageLayout.headerFooter", json!({"header": "&LLeft&RRight"})).unwrap();
let r = s.execute("pageLayout.headerFooter", json!({"part": "header", "section": "center", "text": "Page &[Page] of &[Pages]"})).unwrap();
assert_eq!(r["header"], "&LLeft&CPage &P of &N&RRight");
s.execute("pageLayout.headerFooter", json!({"part": "footer", "section": "right", "text": "&[Date]"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.footer, "&R&D");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.header, "&LLeft&RRight");
assert!(s.execute("pageLayout.headerFooter", json!({"part": "middle", "text": "x"})).is_err());
assert!(s.execute("pageLayout.headerFooter", json!({"section": "top"})).is_err());
let long = "x".repeat(1000);
s.execute("pageLayout.headerFooter", json!({"part": "header", "section": "left", "text": long})).unwrap();
assert!(s.doc().unwrap().wb.sheet(0).unwrap().print.header.chars().count() <= 255);
// The view is per sheet and doesn't dirty a clean workbook.
let mut fresh = Session::new();
fresh.new_workbook();
fresh.execute("home.insertSheet", json!({})).unwrap();
fresh.doc_mut().unwrap().saved = fresh.doc().unwrap().wb.clone();
fresh.execute("view.pageLayout", json!({"sheet": 0})).unwrap();
let wb = &fresh.doc().unwrap().wb;
assert_eq!((wb.sheet(0).unwrap().view, wb.sheet(1).unwrap().view), (SheetViewMode::PageLayout, SheetViewMode::Normal));
assert!(!fresh.doc().unwrap().is_dirty(), "switching views is not an edit");
s.execute("view.pageLayout", json!({"sheet": 0})).unwrap();
s.execute("view.normal", json!({"sheet": 0})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().view, SheetViewMode::Normal);
assert_eq!(s.execute("view.ruler", json!({"on": false})).unwrap()["on"], false);
assert!(s.hide_ruler);
assert_eq!(s.execute("view.ruler", json!({})).unwrap()["on"], true);
}
#[test]
fn page_count_300_rows_letter_portrait() {
let mut s = s();
@@ -1586,6 +1842,32 @@ mod tests {
assert_eq!(pv["pageList"][2]["range"], "K1:O45");
}
#[test]
fn first_and_even_pages_print_their_own_headers() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]]})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [2, 4]})).unwrap();
let r = s
.execute(
"pageLayout.headerFooter",
json!({"header": "&COdd &P", "evenHeader": "&CEven &P", "firstHeader": "&CCover", "differentFirst": true, "differentOddEven": true}),
)
.unwrap();
assert_eq!(r["firstHeader"], "&CCover");
let (pdf, pages) = pdf_of(&mut s, json!({}));
assert_eq!(pages, 3);
assert!(contains(&pdf, "(Cover) Tj") && contains(&pdf, "(Even 2) Tj") && contains(&pdf, "(Odd 3) Tj"));
assert!(!contains(&pdf, "(Odd 1) Tj"), "the first page has its own header");
// One section of the even-page footer, edited in place.
s.execute("pageLayout.headerFooter", json!({"page": "even", "part": "footer", "section": "right", "text": "&[Tab]"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.even_footer, "&R&A");
assert!(s.execute("pageLayout.headerFooter", json!({"page": "last", "part": "header", "text": "x"})).is_err());
// Turned off, every page prints the odd header again.
s.execute("pageLayout.headerFooter", json!({"differentFirst": false, "differentOddEven": false})).unwrap();
let (pdf, _) = pdf_of(&mut s, json!({}));
assert!(contains(&pdf, "(Odd 1) Tj") && contains(&pdf, "(Odd 2) Tj") && !contains(&pdf, "(Cover) Tj"));
}
#[test]
fn pdf_contains_text_and_header_codes_expand() {
let mut s = s();
@@ -1641,6 +1923,24 @@ mod tests {
assert!(r["base64"].as_str().unwrap().len() > 100);
}
#[test]
fn save_as_pdf_writes_a_pdf_and_keeps_the_workbook_file() {
let mut s = s();
s.execute("cell.set", json!({"cell": "B2", "input": "hello"})).unwrap();
let dir = std::env::temp_dir().join(format!("gridcraft-save-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Out.PDF");
let r = s.execute("file.saveAs", json!({"path": path.to_str().unwrap()})).unwrap();
assert_eq!(r["pages"], 1);
let bytes = std::fs::read(&path).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
assert!(contains(&bytes, "(hello) Tj"));
// The PDF is a print, not the workbook's file: Save still asks where to put the workbook.
let d = s.doc().unwrap();
assert!(d.path.is_none() && d.is_dirty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn rich_sheet_renders() {
let mut s = Session::new();
@@ -1673,7 +1973,7 @@ mod tests {
let id = wb.next_object_id();
wb.sheet_mut(0).unwrap().images.push(Image {
id,
anchor: Anchor { cell: CellRef::new(5, 5), dx: 0.0, dy: 0.0, width: 40.0, height: 40.0 },
anchor: Anchor { cell: CellRef::new(5, 5), dx: 0.0, dy: 0.0, width: 40.0, height: 40.0, mode: gridcraft_model::AnchorMode::MoveAndSize },
data: png,
mime: "image/png".into(),
alt: String::new(),
@@ -1762,4 +2062,26 @@ mod tests {
let w = wrap_lines("Supercalifragilistic", Font::Helvetica, 10.0, 20.0);
assert!(w.len() > 2);
}
#[test]
fn rotated_wrapped_text_prints_rotated() {
// Upright headers over narrow columns (mark sheets) combine rotation with Wrap Text.
let mut s = s();
let header = "Term 1 : Drama : Continuous Assessment";
s.execute("range.setValues", json!({"range": "A1", "values": [[header, header]]})).unwrap();
s.execute("home.wrapText", json!({"range": "A1:B1", "on": true})).unwrap();
s.execute("home.orientation", json!({"range": "A1", "angle": "up"})).unwrap();
s.execute("home.orientation", json!({"range": "B1", "angle": "down"})).unwrap();
s.execute("home.columnWidth", json!({"cols": "A:B", "chars": 6})).unwrap();
s.execute("home.rowHeight", json!({"rows": "1:1", "height": 267})).unwrap();
let (pdf, _) = pdf_of(&mut s, json!({}));
let pdf = String::from_utf8_lossy(&pdf);
// The page holds only these two cells, so every text block on it is a piece of a header.
let blocks: Vec<&str> = pdf.split("BT\n").skip(1).filter(|b| b.contains(" Tj")).collect();
let up = blocks.iter().filter(|b| b.contains("\n0 1 -1 0 ")).count();
let down = blocks.iter().filter(|b| b.contains("\n0 -1 1 0 ")).count();
// Every piece of both headers is rotated, each wrapped along the row height into a few long lines.
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:?}");
}
}
+447 -10
View File
@@ -1,6 +1,8 @@
//! Review tab: protection, spelling (basic), workbook statistics.
//! Review tab: protection, spelling (basic), workbook statistics, comment navigation and the
//! Comments pane, Show All Notes and Convert to Comments.
use gridcraft_model::{SheetProtection, password_hash};
use gridcraft_core::CellRef;
use gridcraft_model::{EditRange, PasswordHash, SheetProtection, Visibility, password_hash};
use serde_json::{Value as Json, json};
use super::*;
@@ -17,17 +19,129 @@ pub fn specs() -> Vec<CommandSpec> {
protect_sheet
),
cmd!("review.unprotectSheet", "Unprotect Sheet", ["Review", "Protect"], None, "{password?}", has_doc, unprotect_sheet),
cmd!("review.protectWorkbook", "Protect Workbook", ["Review", "Protect"], None, "{on?: bool}", has_doc, protect_workbook),
cmd!(
"review.protectWorkbook",
"Protect Workbook",
["Review", "Protect"],
None,
"{on?: bool (default: toggle), password?} (structure protection; unprotecting needs the password when one was set)",
has_doc,
protect_workbook
),
cmd!(query "review.workbookStatistics", "Workbook Statistics", ["Review", "Proofing"], None, "{}", has_doc, stats),
// Not journaled: the params can hold a password.
CommandSpec {
id: "review.allowEditRanges",
label: "Allow Edit Ranges…",
menu: &["Review", "Protect"],
shortcut: None,
params: "{action?: list (default) | add | modify | delete | unlock, title?, range?, password?, newTitle?, sheet?} → ranges",
enabled: has_doc,
run: allow_edit_ranges,
journal: false,
undoable: true,
},
cmd!(query "review.checkAccessibility", "Check Accessibility", ["Review", "Accessibility"], None, "{} → issues", has_doc, accessibility),
cmd!(noundo "review.previousComment", "Previous Comment", ["Review", "Comments"], None, "{} → {sheet, cell}", has_comments, |s, _| {
step_comment(s, false)
}),
cmd!(noundo "review.nextComment", "Next Comment", ["Review", "Comments"], None, "{} → {sheet, cell}", has_comments, |s, _| step_comment(
s, true
)),
cmd!(query "review.showComments", "Show Comments", ["Review", "Comments"], None, "{on?: bool} (toggles the Comments pane)", has_doc, |s, p| {
s.comments_pane = bool_param(p, "on").unwrap_or(!s.comments_pane);
Ok(json!({"on": s.comments_pane}))
}),
cmd!(query "review.showAllNotes", "Show All Notes", ["Review", "Notes"], None, "{on?: bool}", has_doc, |s, p| {
s.show_all_notes = bool_param(p, "on").unwrap_or(!s.show_all_notes);
Ok(json!({"on": s.show_all_notes}))
}),
cmd!(
"review.convertToComments",
"Convert to Comments",
["Review", "Notes"],
None,
"{} (every note in the workbook) → {converted}",
has_doc,
convert_notes
),
]
}
/// Threaded comments in navigation order: visible sheets in tab order, then row by row.
fn comment_cells(s: &Session) -> Vec<(usize, CellRef)> {
let Some(d) = s.active() else { return vec![] };
d.wb.sheets
.iter()
.enumerate()
.filter(|(_, sh)| sh.visibility == Visibility::Visible)
// `CellRef` orders by row, then column: reading order.
.flat_map(|(i, sh)| sh.comments.iter().filter(|(_, c)| c.threaded).map(move |(at, _)| (i, *at)))
.collect()
}
fn has_comments(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if comment_cells(s).is_empty() { Err("there are no comments in this workbook".into()) } else { Ok(()) }
}
/// Selects the next (or previous) threaded comment after the active cell, moving on to the next
/// sheet and wrapping around at the end of the workbook.
fn step_comment(s: &mut Session, forward: bool) -> Result<Json> {
let list = comment_cells(s);
let d = s.doc()?;
let here = (d.wb.active_sheet, d.selection.active);
let target = if forward {
list.iter().find(|c| **c > here).or_else(|| list.first())
} else {
list.iter().rev().find(|c| **c < here).or_else(|| list.last())
};
let Some(&(sheet, at)) = target else {
return Err(EngineError::Other("There are no comments in this workbook.".into()));
};
let d = s.doc_mut()?;
d.wb_switch_sheet(sheet);
d.selection = crate::Selection::at(at);
if let Some(sh) = d.wb.active() {
d.selection.expand_merges(sh);
}
let name = d.wb.active().map(|sh| sh.name.clone()).unwrap_or_default();
Ok(json!({"sheet": name, "cell": at.a1()}))
}
/// Review › Notes › Convert to Comments: every note in the workbook becomes a threaded comment
/// with the same author and text.
fn convert_notes(s: &mut Session, _: &Json) -> Result<Json> {
let sheets: Vec<usize> =
s.doc()?.wb.sheets.iter().enumerate().filter(|(_, sh)| sh.comments.values().any(|c| !c.threaded)).map(|(i, _)| i).collect();
if sheets.is_empty() {
return Ok(json!({"converted": 0}));
}
edit(s, |cx| {
let mut n = 0usize;
for i in &sheets {
for c in cx.sheet_mut(*i)?.comments.values_mut().filter(|c| !c.threaded) {
c.threaded = true;
c.visible = false;
n += 1;
}
}
Ok(json!({"converted": n}))
})
}
fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
// Re-protecting a password-protected sheet would replace the password without knowing it:
// unprotect it first, as in Excel. One without a password can take new options directly.
let has_password = |pr: &SheetProtection| pr.password.is_some() || pr.legacy_password_hash.is_some();
if s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()).is_some_and(has_password) {
return Err(EngineError::Other("The sheet is protected with a password. Unprotect it first (Review › Unprotect Sheet).".into()));
}
let b = |k: &str| bool_param(p, k).unwrap_or(false);
let prot = SheetProtection {
password_hash: str_param(p, "password").filter(|x| !x.is_empty()).map(password_hash),
password: None,
legacy_password_hash: None,
select_locked: true,
select_unlocked: true,
format_cells: b("formatCells"),
@@ -40,6 +154,9 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
sort: b("sort"),
autofilter: b("autofilter"),
};
let d = s.doc()?;
let what = d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_password_hash(d, &what, pw)), ..prot };
edit(s, |cx| {
cx.sheet_mut(sheet)?.protection = Some(prot.clone());
Ok(Json::Null)
@@ -48,11 +165,16 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ph = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()).and_then(|pr| pr.password_hash);
if let Some(h) = ph
&& str_param(p, "password").map(password_hash) != Some(h)
{
return Err(EngineError::Other("The password you supplied is not correct.".into()));
if let Some(pr) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()) {
let pw = str_param(p, "password").unwrap_or("");
let ok = match (&pr.password, pr.legacy_password_hash) {
(Some(h), _) => h.verify(pw).map_err(EngineError::Other)?,
(None, Some(h)) => password_hash(pw) == h,
(None, None) => true,
};
if !ok {
return Err(EngineError::Other("The password you supplied is not correct.".into()));
}
}
edit(s, |cx| {
cx.sheet_mut(sheet)?.protection = None;
@@ -60,11 +182,143 @@ fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// A new Excel-compatible (SHA-512, salted) hash of `pw`. The salt mixes `what` is protected
/// with the document, a counter and the clock, so equal passwords get different hashes.
fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
static SALT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = SALT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let seed = format!("{what}\u{0}{n}\u{0}{}\u{0}{}", d.uid, gridcraft_calc::now_serial().to_bits());
PasswordHash::new_sha512(pw, &gridcraft_model::password::salt_from(seed.as_bytes()))
}
fn range_text(r: &EditRange) -> String {
r.ranges.iter().map(|x| x.a1()).collect::<Vec<_>>().join(",")
}
/// Review › Allow Edit Ranges: list, add, modify or delete the ranges that stay editable on a
/// protected sheet, or unlock a password range for this session.
fn allow_edit_ranges(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let action = str_param(p, "action").unwrap_or("list");
let title = str_param(p, "title").map(str::trim).filter(|t| !t.is_empty());
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
let sheet_name = sh.name.clone();
let find = |t: Option<&str>| -> Result<usize> {
let t = t.ok_or_else(|| bad("review.allowEditRanges", "missing `title`"))?;
sh.edit_ranges
.iter()
.position(|r| r.title.eq_ignore_ascii_case(t))
.ok_or_else(|| bad("review.allowEditRanges", format!("no range titled `{t}`")))
};
let hash = |pw: &str, title: &str| new_password_hash(d, &format!("{sheet_name}\u{0}{title}"), pw);
if matches!(action, "add" | "modify" | "delete") && sh.is_protected() {
return Err(EngineError::Other("Unprotect the sheet to change its edit ranges.".into()));
}
match action {
"list" => {}
"unlock" => {
let i = find(title)?;
let Some(r) = sh.edit_ranges.get(i) else { return Err(bad("review.allowEditRanges", "no such range")) };
if let Some(h) = &r.password {
let pw = str_param(p, "password").unwrap_or("");
if !h.verify(pw).map_err(EngineError::Other)? {
return Err(EngineError::Other("The password you supplied is not correct.".into()));
}
let key = (sheet_name.clone(), r.title.clone());
let d = s.doc_mut()?;
if !d.unlocked_ranges.contains(&key) {
d.unlocked_ranges.push(key);
}
}
}
"add" => {
let t = match title {
Some(t) => t.to_string(),
None => {
(1..).map(|n| format!("Range{n}")).find(|t| !sh.edit_ranges.iter().any(|r| r.title.eq_ignore_ascii_case(t))).unwrap_or_default()
}
};
if sh.edit_ranges.iter().any(|r| r.title.eq_ignore_ascii_case(&t)) {
return Err(bad("review.allowEditRanges", format!("a range titled `{t}` already exists")));
}
let ranges = target_ranges(s, p)?;
let password = str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| hash(pw, &t));
let r = EditRange { title: t, ranges, password, security_descriptor: None };
edit(s, |cx| {
cx.sheet_mut(sheet)?.edit_ranges.push(r.clone());
Ok(())
})?;
}
"modify" => {
let i = find(title)?;
let mut r = sh.edit_ranges.get(i).cloned().ok_or_else(|| bad("review.allowEditRanges", "no such range"))?;
if let Some(n) = str_param(p, "newTitle").map(str::trim).filter(|n| !n.is_empty()) {
if sh.edit_ranges.iter().enumerate().any(|(j, x)| j != i && x.title.eq_ignore_ascii_case(n)) {
return Err(bad("review.allowEditRanges", format!("a range titled `{n}` already exists")));
}
r.title = n.to_string();
}
if let Some(pw) = str_param(p, "password") {
r.password = (!pw.is_empty()).then(|| hash(pw, &r.title));
}
if p.get("range").is_some() {
r.ranges = target_ranges(s, p)?;
}
edit(s, |cx| {
if let Some(x) = cx.sheet_mut(sheet)?.edit_ranges.get_mut(i) {
*x = r.clone();
}
Ok(())
})?;
}
"delete" => {
let i = find(title)?;
edit(s, |cx| {
let list = &mut cx.sheet_mut(sheet)?.edit_ranges;
if i < list.len() {
list.remove(i);
}
Ok(())
})?;
}
other => return Err(bad("review.allowEditRanges", format!("unknown action `{other}`"))),
}
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
Ok(Json::Array(
sh.edit_ranges
.iter()
.map(|r| {
let unlocked = r.password.is_none() || d.unlocked_ranges.iter().any(|(s, t)| *s == sh.name && *t == r.title);
json!({"title": r.title, "range": range_text(r), "password": r.password.is_some(), "unlocked": unlocked})
})
.collect(),
))
}
/// Review › Protect Workbook: lock the workbook structure (sheets can't be added, moved,
/// renamed, hidden or deleted), optionally with a password that unprotecting must match.
fn protect_workbook(s: &mut Session, p: &Json) -> Result<Json> {
let cur = s.doc()?.wb.protected_structure;
let d = s.doc()?;
let cur = d.wb.protected_structure;
let on = bool_param(p, "on").unwrap_or(!cur);
if on == cur {
return Ok(json!({"on": on}));
}
let password = if on {
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_password_hash(d, "workbook", pw))
} else {
if let Some(h) = &d.wb.structure_password
&& !h.verify(str_param(p, "password").unwrap_or("")).map_err(EngineError::Other)?
{
return Err(EngineError::Other("The password you supplied is not correct.".into()));
}
None
};
edit(s, |cx| {
cx.wb.protected_structure = on;
cx.wb.structure_password = password.clone();
Ok(json!({"on": on}))
})
}
@@ -97,3 +351,186 @@ fn accessibility(s: &mut Session, _: &Json) -> Result<Json> {
}
Ok(Json::Array(issues))
}
#[cfg(test)]
mod tests {
use super::*;
fn book() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
for (sheet, cell) in [(0, "C1"), (0, "A3"), (1, "B2")] {
s.execute("review.newComment", json!({"sheet": sheet, "cell": cell, "text": "c", "author": "Ann"})).unwrap();
}
s.execute("review.newNote", json!({"sheet": 0, "cell": "A2", "text": "note", "author": "Bob"})).unwrap();
s
}
fn at(s: &Session) -> (usize, String) {
let d = s.doc().unwrap();
(d.wb.active_sheet, d.selection.active.a1())
}
#[test]
fn next_and_previous_comment_go_in_reading_order_across_sheets_and_wrap() {
let mut s = book();
s.execute("selection.set", json!({"cell": "B1"})).unwrap();
// Notes are skipped: A2 holds a note, not a comment.
let order = [(0, "C1"), (0, "A3"), (1, "B2"), (0, "C1")];
for (sheet, cell) in order {
s.execute("review.nextComment", json!({})).unwrap();
assert_eq!(at(&s), (sheet, cell.to_string()));
}
for (sheet, cell) in [(1, "B2"), (0, "A3"), (0, "C1")] {
s.execute("review.previousComment", json!({})).unwrap();
assert_eq!(at(&s), (sheet, cell.to_string()));
}
}
#[test]
fn comment_navigation_is_disabled_without_comments() {
let mut s = Session::new();
s.new_workbook();
s.execute("review.newNote", json!({"cell": "A1", "text": "note"})).unwrap();
assert!(s.execute("review.nextComment", json!({})).is_err());
assert!(s.execute("review.previousComment", json!({})).is_err());
assert_eq!(at(&s), (0, "A1".to_string()));
}
#[test]
fn sheet_passwords_use_excel_hashes_and_old_json_hashes_still_verify() {
let mut s = book();
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
let prot = s.doc().unwrap().wb.active().unwrap().protection.clone().unwrap();
assert!(matches!(&prot.password, Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
assert!(s.execute("review.unprotectSheet", json!({})).is_err());
assert!(s.execute("review.unprotectSheet", json!({"password": "pass"})).is_err());
// Protecting again can't swap the password out from under it.
assert!(s.execute("review.protectSheet", json!({})).is_err());
assert_eq!(s.doc().unwrap().wb.active().unwrap().protection.as_ref(), Some(&prot));
s.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
assert!(!s.doc().unwrap().wb.active().unwrap().is_protected());
// A GridCraft JSON workbook saved before carried the internal hash under `password_hash`.
let old = format!(
r#"{{"password_hash": {}, "select_locked": true, "select_unlocked": true, "format_cells": false, "format_columns": false, "format_rows": false, "insert_columns": false, "insert_rows": false, "delete_columns": false, "delete_rows": false, "sort": false, "autofilter": false}}"#,
password_hash("old")
);
let prot: SheetProtection = serde_json::from_str(&old).unwrap();
assert_eq!((prot.legacy_password_hash, prot.password.is_none()), (Some(password_hash("old")), true));
let i = s.doc().unwrap().wb.active_sheet;
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
std::sync::Arc::make_mut(&mut wb.sheets[i]).protection = Some(prot);
assert!(s.execute("review.unprotectSheet", json!({"password": "new"})).is_err());
s.execute("review.unprotectSheet", json!({"password": "old"})).unwrap();
}
#[test]
fn protect_workbook_with_a_password_really_verifies() {
let mut s = book();
s.execute("review.protectWorkbook", json!({"password": "pa55"})).unwrap();
assert!(s.doc().unwrap().wb.protected_structure);
assert!(s.execute("home.insertSheet", json!({"name": "Three"})).is_err(), "the structure is locked");
// A second Protect keeps it protected; unprotecting needs the right password.
assert_eq!(s.execute("review.protectWorkbook", json!({"on": true})).unwrap()["on"], true);
assert!(s.execute("review.protectWorkbook", json!({})).is_err());
assert!(s.execute("review.protectWorkbook", json!({"on": false, "password": "pass"})).is_err());
assert!(s.doc().unwrap().wb.protected_structure);
s.execute("review.protectWorkbook", json!({"on": false, "password": "pa55"})).unwrap();
let wb = &s.doc().unwrap().wb;
assert!(!wb.protected_structure && wb.structure_password.is_none());
// Without a password it toggles freely.
s.execute("review.protectWorkbook", json!({})).unwrap();
s.execute("review.protectWorkbook", json!({})).unwrap();
assert!(!s.doc().unwrap().wb.protected_structure);
}
#[test]
fn convert_to_comments_turns_every_note_into_a_comment_and_undoes() {
let mut s = book();
s.execute("review.newNote", json!({"sheet": 1, "cell": "D4", "text": "second", "author": "Cy"})).unwrap();
s.execute("review.showNote", json!({"sheet": 1, "cell": "D4"})).unwrap();
let r = s.execute("review.convertToComments", json!({})).unwrap();
assert_eq!(r["converted"], 2);
let wb = &s.doc().unwrap().wb;
let a2 = &wb.sheets[0].comments[&CellRef::parse("A2").unwrap()];
let d4 = &wb.sheets[1].comments[&CellRef::parse("D4").unwrap()];
assert!(a2.threaded && d4.threaded && !d4.visible);
assert_eq!((a2.author.as_str(), a2.text.as_str(), d4.author.as_str(), d4.text.as_str()), ("Bob", "note", "Cy", "second"));
// Nothing left to convert; one undo restores the notes.
assert_eq!(s.execute("review.convertToComments", json!({})).unwrap()["converted"], 0);
s.execute("edit.undo", json!({})).unwrap();
assert!(!s.doc().unwrap().wb.sheets[0].comments[&CellRef::parse("A2").unwrap()].threaded);
}
#[test]
fn show_comments_and_show_all_notes_toggle() {
let mut s = book();
assert_eq!(s.execute("review.showComments", json!({})).unwrap()["on"], true);
assert_eq!(s.execute("review.showComments", json!({})).unwrap()["on"], false);
assert_eq!(s.execute("review.showComments", json!({"on": true})).unwrap()["on"], true);
assert!(s.comments_pane);
assert_eq!(s.execute("review.showAllNotes", json!({})).unwrap()["on"], true);
assert_eq!(s.execute("review.showAllNotes", json!({"on": false})).unwrap()["on"], false);
assert!(!s.show_all_notes);
}
}
#[cfg(test)]
mod edit_range_tests {
use super::*;
fn protected_book() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Open", "range": "A1:A3"})).unwrap();
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Budget", "range": "B1:B3,D1", "password": "pa55"})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
s
}
#[test]
fn edit_ranges_open_locked_cells_and_passwords_really_verify() {
let mut s = protected_book();
s.execute("cell.set", json!({"cell": "A2", "input": "1"})).unwrap();
assert!(s.execute("cell.set", json!({"cell": "C1", "input": "1"})).is_err());
let err = s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap_err().to_string();
assert!(err.contains("Budget"), "{err}");
// A paste or fill is checked the same way.
assert!(s.execute("range.setValues", json!({"range": "B2", "values": [[5]]})).is_err());
assert!(s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Budget", "password": "pass"})).is_err());
assert!(s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Budget"})).is_err());
let list = s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "budget", "password": "pa55"})).unwrap();
assert_eq!(list[1]["unlocked"], true);
s.execute("range.setValues", json!({"range": "B2", "values": [[5]]})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "2"})).unwrap();
// Ranges can't change while the sheet is protected.
assert!(s.execute("review.allowEditRanges", json!({"action": "delete", "title": "Open"})).is_err());
}
#[test]
fn edit_ranges_add_modify_delete_list_and_undo() {
let mut s = Session::new();
s.new_workbook();
// Empty params list; nothing to list yet.
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap(), json!([]));
s.execute("selection.set", json!({"range": "C3:D4"})).unwrap();
let list = s.execute("review.allowEditRanges", json!({"action": "add"})).unwrap();
assert_eq!(list, json!([{"title": "Range1", "range": "C3:D4", "password": false, "unlocked": true}]));
assert!(s.execute("review.allowEditRanges", json!({"action": "add", "title": "range1", "range": "A1"})).is_err());
let list = s
.execute("review.allowEditRanges", json!({"action": "modify", "title": "Range1", "newTitle": "Mine", "range": "E5", "password": "x"}))
.unwrap();
assert_eq!((list[0]["title"].as_str(), list[0]["range"].as_str(), list[0]["password"].as_bool()), (Some("Mine"), Some("E5"), Some(true)));
// Inserting a row above moves the range with its cells.
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap()[0]["range"], "E6");
s.execute("review.allowEditRanges", json!({"action": "delete", "title": "Mine"})).unwrap();
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap(), json!([]));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap()[0]["title"], "Mine");
assert!(s.execute("review.allowEditRanges", json!({"action": "nope"})).is_err());
assert!(s.execute("review.allowEditRanges", json!({"action": "delete"})).is_err());
}
}
+563 -74
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
use gridcraft_formula::adjust::{Axis, Edit};
use gridcraft_model::{Sheet, Visibility};
use gridcraft_model::{Anchor, AnchorMode, Sheet, Visibility};
use serde_json::{Value as Json, json};
use super::*;
@@ -35,7 +35,17 @@ pub fn specs() -> Vec<CommandSpec> {
p,
Axis::Cols
)),
cmd!("sheet.moveColumns", "Move Columns", [], None, "{cols?: \"B:C\", before: zero-based column index}", has_doc, move_columns),
cmd!("home.insertCells", "Insert Cells…", ["Home", "Cells", "Insert"], None, "{range?, shift: right|down|row|column}", has_doc, insert_cells),
cmd!(
"home.insertCopiedCells",
"Insert Copied Cells",
["Home", "Cells", "Insert"],
None,
"{at?: \"B3\", shift?: down|right}: inserts the copied cells at `at` (the active cell) and pastes them there. Whole copied rows or columns insert whole rows or columns; other blocks shift the cells at `at` down (default) or right. A cut of whole rows or columns moves them (Insert Cut Cells)",
has_clipboard,
insert_copied_cells
),
cmd!("home.deleteCells", "Delete Cells…", ["Home", "Cells", "Delete"], None, "{range?, shift: left|up|row|column}", has_doc, delete_cells),
cmd!("home.insertSheet", "Insert Sheet", ["Home", "Cells", "Insert"], Some("Shift+F11"), "{name?, before?: index}", has_doc, insert_sheet),
cmd!("home.deleteSheet", "Delete Sheet", ["Home", "Cells", "Delete"], None, "{sheet?}", has_doc, delete_sheet),
@@ -61,6 +71,46 @@ fn lines(s: &Session, p: &Json, axis: Axis) -> Result<(u32, u32)> {
Ok((a, count))
}
/// Bottom-right line of an anchor (the `to` marker of a two-cell anchor) and the offset of that
/// corner inside it, in points. Measured against `sh`'s current geometry.
fn anchor_corner(sh: &Sheet, a: &Anchor) -> (u32, u32, f32, f32) {
let x2 = sh.col_left(a.cell.col) + a.dx as f64 + a.width.max(0.0) as f64;
let y2 = sh.row_top(a.cell.row) + a.dy as f64 + a.height.max(0.0) as f64;
let tc = sh.col_at(x2);
let tr = sh.row_at(y2);
(tc, tr, (x2 - sh.col_left(tc)) as f32, (y2 - sh.row_top(tr)) as f32)
}
/// Repositions one floating object's anchor for a structural insert/delete, honouring its
/// [`AnchorMode`]: absolute objects ("Don't move or size with cells") stay put; "move but don't
/// size" follows its cell and keeps its size; "move and size" is re-fitted to the lines it lands
/// on. `corner` is the pre-edit bottom-right line/offset (from [`anchor_corner`]); a line deleted
/// out from under an edge collapses that edge onto `at`. `sh` is the post-edit grid, used to
/// measure the re-fitted size.
fn shift_anchor(sh: &Sheet, a: Anchor, corner: (u32, u32, f32, f32), axis: Axis, at: u32, map_line: &impl Fn(u32) -> Option<u32>) -> Anchor {
if a.mode == AnchorMode::Absolute {
return a;
}
let main = if axis == Axis::Rows { a.cell.row } else { a.cell.col };
// A deleted anchor line collapses onto the line that takes its place.
let nmain = map_line(main).unwrap_or(at);
let (nr, nc) = if axis == Axis::Rows { (nmain, a.cell.col) } else { (a.cell.row, nmain) };
if a.mode == AnchorMode::MoveOnly {
return Anchor { cell: CellRef::new(nr, nc), ..a };
}
// Move and size: re-fit to the lines the object lands on. A far edge whose line was deleted
// collapses onto the near cell, shrinking the object.
let (tc, tr, tdx, tdy) = corner;
let far = if axis == Axis::Rows { tr } else { tc };
let nfar = map_line(far).unwrap_or(nmain);
let (nbr, nbc) = if axis == Axis::Rows { (nfar, tc) } else { (tr, nfar) };
let x1 = sh.col_left(nc) + a.dx as f64;
let y1 = sh.row_top(nr) + a.dy as f64;
let xn = sh.col_left(nbc) + tdx as f64;
let yn = sh.row_top(nbr) + tdy as f64;
Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: (xn - x1).max(0.0) as f32, height: (yn - y1).max(0.0) as f32, mode: a.mode }
}
/// Shifts everything that has a position on the sheet for an insert/delete.
fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: bool) {
let map_line = |v: u32| -> Option<u32> {
@@ -74,26 +124,24 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
None
}
};
let map_range = |r: RangeRef| -> Option<RangeRef> {
let e = if insert { Edit::Insert { axis, at, count } } else { Edit::Delete { axis, at, count } };
let expr = gridcraft_formula::Expr::Ref(gridcraft_formula::Reference {
sheet: gridcraft_formula::SheetSel::Current,
kind: gridcraft_formula::RefKind::Range(
gridcraft_formula::Anchor { row: r.start.row, col: r.start.col, row_abs: false, col_abs: false },
gridcraft_formula::Anchor { row: r.end.row, col: r.end.col, row_abs: false, col_abs: false },
),
});
match gridcraft_formula::adjust::adjust(expr, "S", "S", &e) {
gridcraft_formula::Expr::Ref(r) => Some(r.range()),
_ => None,
}
};
let e = if insert { Edit::Insert { axis, at, count } } else { Edit::Delete { axis, at, count } };
let map_range = |r: RangeRef| map_range(r, &e);
let map_cell = |c: CellRef| -> Option<CellRef> {
match axis {
Axis::Rows => map_line(c.row).map(|r| CellRef::new(r, c.col)),
Axis::Cols => map_line(c.col).map(|x| CellRef::new(c.row, x)),
}
};
// Floating objects: snapshot their bottom-right corners against the pre-shift geometry, so a
// re-fit after the shift measures against the grid the object actually lands on.
let obj_corners: Vec<(u32, u32, f32, f32)> = sh
.charts
.iter()
.map(|o| &o.anchor)
.chain(sh.images.iter().map(|o| &o.anchor))
.chain(sh.shapes.iter().map(|o| &o.anchor))
.map(|a| anchor_corner(sh, a))
.collect();
// Line info.
let lines = if axis == Axis::Rows { &mut sh.rows } else { &mut sh.cols };
let old = std::mem::take(lines);
@@ -108,6 +156,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
for cf in sh.cond_formats.iter_mut() {
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r)).collect();
}
for er in sh.edit_ranges.iter_mut() {
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect();
}
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
for dv in sh.validations.iter_mut() {
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r)).collect();
@@ -115,27 +167,8 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
sh.validations.retain(|dv| !dv.ranges.is_empty());
for t in sh.tables.iter_mut() {
if let Some(r) = map_range(t.range) {
// Columns inserted inside a table become new table columns.
if axis == Axis::Cols && insert && at > t.range.start.col && at <= t.range.end.col {
let idx = (at - t.range.start.col) as usize;
for k in 0..count {
let name = format!("Column{}", t.columns.len() + 1);
t.columns.insert(
(idx + k as usize).min(t.columns.len()),
gridcraft_model::TableColumn { name, totals: Default::default(), totals_label: None, formula: None },
);
}
}
if axis == Axis::Cols && !insert {
let lo = at.max(t.range.start.col);
let hi = (at + count).min(t.range.end.col + 1);
if hi > lo {
let a = (lo - t.range.start.col) as usize;
let b = (hi - t.range.start.col) as usize;
if b <= t.columns.len() {
t.columns.drain(a..b);
}
}
if axis == Axis::Cols {
shift_table_columns(t, at, count, insert);
}
t.range = r;
} else {
@@ -149,17 +182,26 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
None => sh.autofilter = None,
}
}
sh.cell_pictures =
std::mem::take(&mut sh.cell_pictures).into_iter().filter_map(|(c, v)| map_cell(c).filter(CellRef::is_valid).map(|c| (c, v))).collect();
sh.comments = std::mem::take(&mut sh.comments).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect();
sh.hyperlinks = std::mem::take(&mut sh.hyperlinks).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect();
for ch in sh.charts.iter_mut() {
if let Some(c) = map_cell(ch.anchor.cell) {
ch.anchor.cell = c;
}
// Floating objects follow their anchor lines per their [`AnchorMode`]. Corners were snapshotted
// as charts ++ images ++ shapes, matching the three slices below. New anchors are computed
// against the post-shift grid first (the re-fit needs its sizes), then written back.
let anchored = |ui: usize, a: Anchor| -> Anchor { obj_corners.get(ui).map_or(a, |&corner| shift_anchor(sh, a, corner, axis, at, &map_line)) };
let new_charts: Vec<Anchor> = sh.charts.iter().enumerate().map(|(i, o)| anchored(i, o.anchor)).collect();
let new_images: Vec<Anchor> = sh.images.iter().enumerate().map(|(i, o)| anchored(new_charts.len() + i, o.anchor)).collect();
let base = new_charts.len() + new_images.len();
let new_shapes: Vec<Anchor> = sh.shapes.iter().enumerate().map(|(i, o)| anchored(base + i, o.anchor)).collect();
for (o, a) in sh.charts.iter_mut().zip(new_charts) {
o.anchor = a;
}
for im in sh.images.iter_mut() {
if let Some(c) = map_cell(im.anchor.cell) {
im.anchor.cell = c;
}
for (o, a) in sh.images.iter_mut().zip(new_images) {
o.anchor = a;
}
for (o, a) in sh.shapes.iter_mut().zip(new_shapes) {
o.anchor = a;
}
for sp in sh.sparklines.iter_mut() {
if let Some(c) = map_cell(sp.cell) {
@@ -196,8 +238,18 @@ fn rewrite(wb: &mut gridcraft_model::Workbook, target: &str, e: &Edit) {
}
}
/// Inserting or deleting cells moves the copied block away from the stored source range, so, like
/// Excel, it cancels copy/cut mode for this workbook (a later paste would take the wrong cells).
fn cancel_copy_mode(s: &mut Session) {
let uid = s.doc().map(|d| d.uid).ok();
if s.clipboard.as_ref().is_some_and(|c| Some(c.doc_uid) == uid) {
s.clipboard = None;
}
}
fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
let (at, count) = lines(s, p, axis)?;
check_lines_protection(s, p, axis, at, count, true)?;
let sheet = target_sheet(s, p)?;
// Refuse to push data off the sheet.
let limit = if axis == Axis::Rows { MAX_ROWS } else { MAX_COLS };
@@ -207,8 +259,9 @@ fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
return Err(EngineError::Other("To prevent possible loss of data, Excel cannot shift nonblank cells off of the worksheet.".into()));
}
}
edit(s, |cx| {
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
cx.protection_checked = true;
{
let sh = cx.sheet_mut(sheet)?;
match axis {
@@ -230,21 +283,25 @@ fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
rewrite(&mut cx.wb, &name, &Edit::Insert { axis, at, count });
cx.structural = true;
Ok(Json::Null)
})
})?;
cancel_copy_mode(s);
Ok(out)
}
fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
let (at, count) = lines(s, p, axis)?;
check_lines_protection(s, p, axis, at, count, false)?;
let sheet = target_sheet(s, p)?;
edit(s, |cx| {
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
cx.protection_checked = true;
{
let sh = cx.sheet_mut(sheet)?;
let block = match axis {
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
};
sh.cells.take_range(block);
sh.take_cells(block);
match axis {
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
@@ -254,7 +311,108 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
rewrite(&mut cx.wb, &name, &Edit::Delete { axis, at, count });
cx.structural = true;
Ok(Json::Null)
})
})?;
cancel_copy_mode(s);
Ok(out)
}
/// Reorders a contiguous block of whole columns without replacing the destination columns.
/// `before` is a boundary in the original sheet: moving B:C before E produces A,D,B,C,E.
fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
let (from, count) = lines(s, p, Axis::Cols)?;
let before = u32_param(p, "before").ok_or_else(|| bad("sheet.moveColumns", "missing `before`"))?;
let end =
from.checked_add(count).filter(|end| *end <= MAX_COLS).ok_or_else(|| bad("sheet.moveColumns", "source columns are outside the worksheet"))?;
if before >= MAX_COLS || before.checked_add(count).is_none_or(|end| end > MAX_COLS) {
return Err(bad("sheet.moveColumns", "destination columns are outside the worksheet"));
}
if (from..=end).contains(&before) {
return Ok(json!({"cols": RangeRef::cols(from, end.saturating_sub(1)).a1()}));
}
let sheet = target_sheet(s, p)?;
if let Some(u) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range())
&& u.end.col >= before
&& u.end.col as u64 + count as u64 >= MAX_COLS as u64
{
return Err(EngineError::Other("To prevent possible loss of data, columns cannot be shifted off of the worksheet.".into()));
}
check_lines_protection(s, &json!({"cols": RangeRef::cols(before, before).a1()}), Axis::Cols, before, count, true)?;
check_lines_protection(s, &json!({"cols": RangeRef::cols(from, end - 1).a1()}), Axis::Cols, from, count, false)?;
let moved_from = if before <= from { from + count } else { from };
if moved_from.checked_add(count).is_none_or(|end| end > MAX_COLS) {
return Err(bad("sheet.moveColumns", "the move is too close to the worksheet boundary"));
}
let destination = before;
let delete_at = moved_from;
let final_start = if before > from { before - count } else { before };
let active_row = s.doc()?.selection.active.row;
let source = RangeRef::cols(moved_from, moved_from + count - 1);
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
cx.protection_checked = true;
{
let sh = cx.sheet_mut(sheet)?;
sh.cells.shift_cols(before, count as i64);
shift_sheet_features(sh, Axis::Cols, before, count, true);
}
rewrite(&mut cx.wb, &name, &Edit::Insert { axis: Axis::Cols, at: before, count });
let mut touched = Vec::new();
{
let sh = cx.sheet_mut(sheet)?;
let pictures: Vec<_> =
sh.cell_pictures.iter().filter(|(cell, _)| source.contains(**cell)).map(|(cell, picture)| (*cell, picture.clone())).collect();
let cells = sh.take_cells(source);
let moved_lines: Vec<_> = (0..count).filter_map(|offset| sh.cols.remove(&(moved_from + offset)).map(|info| (offset, info))).collect();
let movement = Edit::Move { from: source, to_row: 0, to_col: destination };
shift_cell_features(sh, &movement);
for object in sh
.charts
.iter_mut()
.map(|o| &mut o.anchor)
.chain(sh.images.iter_mut().map(|o| &mut o.anchor))
.chain(sh.shapes.iter_mut().map(|o| &mut o.anchor))
{
if object.mode != AnchorMode::Absolute && (moved_from..moved_from + count).contains(&object.cell.col) {
object.cell.col = destination + (object.cell.col - moved_from);
}
}
for (cell, value) in cells {
let dest = CellRef::new(cell.row, destination + (cell.col - moved_from));
sh.cells.set(dest, value);
touched.extend([cell, dest]);
}
for (cell, picture) in pictures {
let dest = CellRef::new(cell.row, destination + (cell.col - moved_from));
sh.cell_pictures.insert(dest, picture);
}
for (offset, info) in moved_lines {
sh.cols.insert(destination + offset, info);
}
}
for cell in touched {
cx.touch(sheet, cell);
}
rewrite(&mut cx.wb, &name, &Edit::Move { from: source, to_row: 0, to_col: destination });
{
let sh = cx.sheet_mut(sheet)?;
sh.cells.shift_cols(delete_at + count, -(count as i64));
shift_sheet_features(sh, Axis::Cols, delete_at, count, false);
}
rewrite(&mut cx.wb, &name, &Edit::Delete { axis: Axis::Cols, at: delete_at, count });
*cx.sel = crate::Selection {
active: CellRef::new(active_row, final_start),
anchor: CellRef::new(active_row, final_start),
ranges: vec![RangeRef::cols(final_start, final_start + count - 1)],
};
cx.structural = true;
Ok(json!({"cols": RangeRef::cols(final_start, final_start + count - 1).a1()}))
})?;
cancel_copy_mode(s);
Ok(out)
}
fn insert_cells(s: &mut Session, p: &Json) -> Result<Json> {
@@ -265,27 +423,27 @@ fn insert_cells(s: &mut Session, p: &Json) -> Result<Json> {
"column" | "entireColumn" => return insert_lines(s, &json!({"cols": RangeRef::cols(r.start.col, r.end.col).a1()}), Axis::Cols),
_ => {}
}
let e = Edit::InsertCells { axis: if shift == "right" { Axis::Cols } else { Axis::Rows }, range: r };
let sheet = target_sheet(s, p)?;
if let Some(sh) = s.doc()?.wb.sheet(sheet) {
check_table_shift(sh, &e)?;
}
let right = shift == "right";
edit(s, |cx| {
let out = edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
if right {
sh.cells.shift_cols_in_rows(r.start.row, r.end.row, r.start.col, r.width() as i64);
} else {
sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.start.row, r.height() as i64);
}
// Formulas referring to cells that moved: approximate with a whole-sheet move edit.
let moved = if right {
RangeRef::new(r.start, CellRef::new(r.end.row, MAX_COLS - 1 - r.width()))
} else {
RangeRef::new(r.start, CellRef::new(MAX_ROWS - 1 - r.height(), r.end.col))
};
shift_cell_features(sh, &e);
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
let to = if right { (r.start.row, r.start.col + r.width()) } else { (r.start.row + r.height(), r.start.col) };
super::edit::rewrite_all_formulas(&mut cx.wb, &name, &Edit::Move { from: moved, to_row: to.0, to_col: to.1 });
rewrite(&mut cx.wb, &name, &e);
cx.structural = true;
Ok(Json::Null)
})
})?;
cancel_copy_mode(s);
Ok(out)
}
fn delete_cells(s: &mut Session, p: &Json) -> Result<Json> {
@@ -296,31 +454,150 @@ fn delete_cells(s: &mut Session, p: &Json) -> Result<Json> {
"column" | "entireColumn" => return delete_lines(s, &json!({"cols": RangeRef::cols(r.start.col, r.end.col).a1()}), Axis::Cols),
_ => {}
}
let e = Edit::DeleteCells { axis: if shift == "left" { Axis::Cols } else { Axis::Rows }, range: r };
let sheet = target_sheet(s, p)?;
if let Some(sh) = s.doc()?.wb.sheet(sheet) {
check_table_shift(sh, &e)?;
}
let left = shift == "left";
edit(s, |cx| {
let out = edit(s, |cx| {
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
{
let sh = cx.sheet_mut(sheet)?;
sh.cells.take_range(r);
sh.take_cells(r);
if left {
sh.cells.shift_cols_in_rows(r.start.row, r.end.row, r.end.col + 1, -(r.width() as i64));
} else {
sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.end.row + 1, -(r.height() as i64));
}
shift_cell_features(sh, &e);
}
// References into the deleted block become #REF!; the rest move.
let deleted = Edit::Move { from: r, to_row: r.start.row, to_col: r.start.col };
let _ = deleted;
let moved_from = if left {
RangeRef::new(CellRef::new(r.start.row, r.end.col + 1), CellRef::new(r.end.row, MAX_COLS - 1))
} else {
RangeRef::new(CellRef::new(r.end.row + 1, r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col))
};
super::edit::rewrite_all_formulas(&mut cx.wb, &name, &Edit::Move { from: moved_from, to_row: r.start.row, to_col: r.start.col });
// References into the deleted cells become #REF!; the rest move.
rewrite(&mut cx.wb, &name, &e);
cx.structural = true;
Ok(Json::Null)
})
})?;
cancel_copy_mode(s);
Ok(out)
}
/// Insert Copied Cells / Insert Cut Cells: makes room at the destination, then pastes (or, for a
/// cut, moves) the clipboard there, as one undo step.
fn insert_copied_cells(s: &mut Session, p: &Json) -> Result<Json> {
let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) };
let sheet = target_sheet(s, p)?;
let d = s.doc()?;
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(d.selection.current().start);
let shift = str_param(p, "shift").unwrap_or("down");
if shift != "down" && shift != "right" {
return Err(bad("home.insertCopiedCells", format!("unknown `shift`: {shift} (down or right)")));
}
let sel = clip.selected;
let rows = sel.is_full_rows();
let cols = sel.is_full_cols();
if rows && cols {
return Err(EngineError::Other("The copy area is the whole sheet; there is no room to insert it.".into()));
}
let same_doc = d.uid == clip.doc_uid;
let cut = clip.cut && same_doc;
if cut && !rows && !cols {
return Err(EngineError::Other("Insert Cut Cells works on whole rows or columns; cut whole rows or columns, or use Paste.".into()));
}
// A moved block can't be inserted inside itself.
if cut && clip.sheet == sheet {
let inside = if rows { at.row > sel.start.row && at.row <= sel.end.row } else { at.col > sel.start.col && at.col <= sel.end.col };
if inside {
return Err(EngineError::Other("The cut rows or columns can't be inserted inside themselves.".into()));
}
}
let revision = d.revision;
let before = (d.wb.clone(), d.selection.clone());
let result = insert_copied_steps(s, &clip, sheet, at, shift, cut);
let d = s.doc_mut()?;
// The nested steps collapse into this command's single undo step.
for _ in 0..d.revision.saturating_sub(revision) {
d.undo.pop();
}
match result {
Ok((final_range, out)) => {
d.selection = crate::Selection { active: final_range.start, anchor: final_range.start, ranges: vec![final_range] };
// Like inserting cells, this ends copy mode (the copied block may have moved).
cancel_copy_mode(s);
Ok(out)
}
Err(e) => {
d.wb = before.0;
d.selection = before.1;
d.calc.rebuild(&d.wb);
s.clipboard = Some(clip);
Err(e)
}
}
}
fn insert_copied_steps(s: &mut Session, clip: &crate::Clipboard, sheet: usize, at: CellRef, shift: &str, cut: bool) -> Result<(RangeRef, Json)> {
let sel = clip.selected;
let rows = sel.is_full_rows();
let cols = sel.is_full_cols();
// Where the copied block's top-left lands, relative to the (untrimmed) copied lines.
let (inserted, paste_at) = if rows {
let h = sel.height();
let start = at.row;
let r = format!("{}:{}", start as u64 + 1, start as u64 + h as u64);
s.execute("home.insertRows", json!({"rows": r, "sheet": sheet}))?;
let dr = clip.range.start.row.saturating_sub(sel.start.row);
(RangeRef::rows(start, start.saturating_add(h - 1).min(MAX_ROWS - 1)), CellRef::new(start.saturating_add(dr), clip.range.start.col))
} else if cols {
let w = sel.width();
let start = at.col;
let end = start.saturating_add(w - 1).min(MAX_COLS - 1);
s.execute("home.insertColumns", json!({"cols": RangeRef::cols(start, end).a1(), "sheet": sheet}))?;
let dc = clip.range.start.col.saturating_sub(sel.start.col);
(RangeRef::cols(start, end), CellRef::new(clip.range.start.row, start.saturating_add(dc)))
} else {
let end = at
.offset(clip.range.height() as i64 - 1, clip.range.width() as i64 - 1)
.ok_or_else(|| EngineError::Other("The copied cells don't fit on the sheet at this position.".into()))?;
let block = RangeRef::new(at, end);
s.execute("home.insertCells", json!({"range": block.a1(), "shift": shift, "sheet": sheet}))?;
(block, at)
};
// Inserting ended copy mode; bring the clipboard back for the paste. A cut reads the live
// workbook, so it follows the source if the insert pushed it along.
let mut clip = clip.clone();
if cut {
let pushed = clip.sheet == sheet && if rows { sel.start.row >= at.row } else { sel.start.col >= at.col };
if pushed {
let (dr, dc) = if rows { (inserted.height() as i64, 0) } else { (0, inserted.width() as i64) };
clip.range = RangeRef::new(clip.range.start.offset_clamped(dr, dc), clip.range.end.offset_clamped(dr, dc));
clip.selected = RangeRef::new(sel.start.offset_clamped(dr, dc), sel.end.offset_clamped(dr, dc));
}
clip.wb = s.doc()?.wb.clone();
}
let source_lines = clip.selected;
s.clipboard = Some(clip.clone());
let out = s.execute("edit.pasteSpecial", json!({"what": "all", "at": paste_at.a1(), "sheet": sheet}))?;
if !cut {
return Ok((inserted, out));
}
// Close the gap the moved lines left behind.
let (removed, before_dest) = if rows {
s.execute(
"home.deleteRows",
json!({"rows": format!("{}:{}", source_lines.start.row as u64 + 1, source_lines.end.row as u64 + 1), "sheet": clip.sheet}),
)?;
(source_lines.height(), clip.sheet == sheet && source_lines.start.row < inserted.start.row)
} else {
s.execute("home.deleteColumns", json!({"cols": RangeRef::cols(source_lines.start.col, source_lines.end.col).a1(), "sheet": clip.sheet}))?;
(source_lines.width(), clip.sheet == sheet && source_lines.start.col < inserted.start.col)
};
let moved = if before_dest {
let (dr, dc) = if rows { (-(removed as i64), 0) } else { (0, -(removed as i64)) };
RangeRef::new(inserted.start.offset_clamped(dr, dc), inserted.end.offset_clamped(dr, dc))
} else {
inserted
};
Ok((moved, out))
}
fn insert_sheet(s: &mut Session, p: &Json) -> Result<Json> {
@@ -359,6 +636,39 @@ fn edit_doc<R>(d: &mut crate::DocState, f: impl FnOnce(&mut Ctx) -> Result<R>) -
super::commit(d, f)
}
/// Sheet protection for inserting or deleting rows/columns: the protection must allow it, and
/// deleted lines must not hold locked cells.
fn check_lines_protection(s: &Session, p: &Json, axis: Axis, at: u32, count: u32, insert: bool) -> Result<()> {
let sheet = target_sheet(s, p)?;
let wb = &s.doc()?.wb;
let Some(sh) = wb.sheet(sheet) else { return Ok(()) };
let Some(pr) = &sh.protection else { return Ok(()) };
let allowed = match (axis, insert) {
(Axis::Rows, true) => pr.insert_rows,
(Axis::Rows, false) => pr.delete_rows,
(Axis::Cols, true) => pr.insert_columns,
(Axis::Cols, false) => pr.delete_columns,
};
let locked = |st: gridcraft_model::StyleId| wb.styles.get(st).protection.locked;
let refuse = || EngineError::Other(PROTECTED.into());
if !allowed {
return Err(refuse());
}
if insert {
return Ok(());
}
let end = at.saturating_add(count - 1).min(if axis == Axis::Rows { MAX_ROWS - 1 } else { MAX_COLS - 1 });
let infos = if axis == Axis::Rows { &sh.rows } else { &sh.cols };
if (at..=end).any(|i| locked(infos.get(&i).and_then(|x| x.style).unwrap_or_default())) {
return Err(refuse());
}
let block = if axis == Axis::Rows { RangeRef::rows(at, end) } else { RangeRef::cols(at, end) };
if sh.cells.iter_range(block).any(|(_, cell)| locked(cell.style)) {
return Err(refuse());
}
Ok(())
}
fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let i = target_sheet(s, p)?;
let d = s.doc()?;
@@ -369,6 +679,7 @@ fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
return Err(EngineError::Other("A workbook must contain at least one visible worksheet.".into()));
}
let name = d.wb.sheet(i).map(|s| s.name.clone()).unwrap_or_default();
let order: Vec<String> = d.wb.sheets.iter().map(|s| s.name.clone()).collect();
let d = s.doc_mut()?;
edit_doc(d, |cx| {
cx.wb.sheets.remove(i);
@@ -378,7 +689,7 @@ fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
for (c, f) in keys {
if let Some(e) = f.expr() {
let ne = gridcraft_formula::adjust::delete_sheet(e, &name);
let ne = gridcraft_formula::adjust::delete_sheet(e, &name, &order);
if let Some(cell) = sh.cells.get_mut(c) {
cell.formula = Some(Arc::new(gridcraft_model::Formula::from_expr(ne)));
}
@@ -392,6 +703,13 @@ fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
{
*sc -= 1;
}
// Names referring to the sheet become #REF!.
if let Ok(e) = gridcraft_formula::parse(&n.formula) {
let ne = gridcraft_formula::adjust::delete_sheet(e.clone(), &name, &order);
if ne != e {
n.formula = gridcraft_formula::print(&ne);
}
}
}
if cx.wb.active_sheet >= cx.wb.sheets.len() || cx.wb.active_sheet > i {
cx.wb.active_sheet = cx.wb.active_sheet.saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1));
@@ -439,6 +757,12 @@ fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
se.categories = se.categories.as_deref().map(fix);
se.name = se.name.as_deref().map(fix);
}
// A PivotChart follows its PivotTable's sheet.
if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link)
&& sheet.eq_ignore_ascii_case(&old)
{
ch.pivot = Some(crate::pivot::chart_link(&name, &pivot));
}
}
}
for n in cx.wb.names.iter_mut() {
@@ -461,10 +785,40 @@ fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
if copy {
let mut sh = (*src).clone();
let base = sh.name.clone();
let name = (2..).map(|k| format!("{base} ({k})")).find(|nm| cx.wb.sheet_index(nm).is_none()).unwrap_or(base);
sh.name = name.chars().take(31).collect();
// `Name (2)`: the name is shortened so the suffix fits in Excel's 31 characters.
let name = (2..)
.map(|k| {
let suffix = format!(" ({k})");
let keep = 31usize.saturating_sub(suffix.chars().count());
format!("{}{suffix}", base.chars().take(keep).collect::<String>().trim_end())
})
.find(|nm| cx.wb.sheet_index(nm).is_none())
.unwrap_or(base.clone());
sh.name = name;
sh.tables.clear(); // table names must be unique
sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original
let at = to.min(n);
// The copy gets its own copies of the sheet's names, referring to the copy.
let copies: Vec<gridcraft_model::DefinedName> = cx
.wb
.names
.iter()
.filter(|nm| nm.scope == Some(i))
.map(|nm| {
let formula = gridcraft_formula::parse(&nm.formula)
.map(|e| gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &base, &sh.name)))
.unwrap_or_else(|_| nm.formula.clone());
gridcraft_model::DefinedName { scope: Some(at), formula, ..nm.clone() }
})
.collect();
for nm in cx.wb.names.iter_mut() {
if let Some(sc) = nm.scope.as_mut()
&& *sc >= at
{
*sc += 1;
}
}
cx.wb.names.extend(copies);
cx.wb.sheets.insert(at, Arc::new(sh));
cx.wb.active_sheet = at;
} else {
@@ -472,6 +826,17 @@ fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
let at = to.min(n - 1);
cx.wb.sheets.insert(at, sh);
cx.wb.active_sheet = at;
// Sheet-level names follow their sheet.
for nm in cx.wb.names.iter_mut() {
if let Some(sc) = nm.scope.as_mut() {
*sc = match *sc {
x if x == i => at,
x if i < x && x <= at => x - 1,
x if at <= x && x < i => x + 1,
x => x,
};
}
}
}
cx.structural = true;
Ok(Json::Null)
@@ -538,3 +903,127 @@ fn step_sheet(s: &mut Session, dir: i64) -> Result<Json> {
s.doc_mut()?.wb_switch_sheet(i as usize);
ok()
}
/// Where a range of the edited sheet goes after a structural edit (`None` = deleted).
pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
let expr = gridcraft_formula::Expr::Ref(gridcraft_formula::Reference {
sheet: gridcraft_formula::SheetSel::Current,
kind: gridcraft_formula::RefKind::Range(
gridcraft_formula::Anchor { row: r.start.row, col: r.start.col, row_abs: false, col_abs: false },
gridcraft_formula::Anchor { row: r.end.row, col: r.end.col, row_abs: false, col_abs: false },
),
});
match gridcraft_formula::adjust::adjust(expr, "S", "S", e) {
gridcraft_formula::Expr::Ref(r) => Some(r.range()),
_ => None,
}
}
/// Shifts what Insert/Delete Cells moves along with the cells: merged areas, conditional
/// format, validation, table, filter and print-area ranges, notes, links and sparklines.
fn shift_cell_features(sh: &mut Sheet, e: &Edit) {
let map_cell = |c: CellRef| map_range(RangeRef::cell(c), e).map(|r| r.start);
sh.merges = sh.merges.iter().filter_map(|m| map_range(*m, e)).filter(|m| !m.is_single()).collect();
for cf in sh.cond_formats.iter_mut() {
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
}
for er in sh.edit_ranges.iter_mut() {
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
}
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
for dv in sh.validations.iter_mut() {
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
}
sh.validations.retain(|dv| !dv.ranges.is_empty());
for t in sh.tables.iter_mut() {
// Cells inserted or deleted across a table's full height add or remove table columns.
if let Edit::InsertCells { axis: Axis::Cols, range } | Edit::DeleteCells { axis: Axis::Cols, range } = *e
&& range.start.row <= t.range.start.row
&& range.end.row >= t.range.end.row
{
shift_table_columns(t, range.start.col, range.width(), matches!(e, Edit::InsertCells { .. }));
}
t.range = map_range(t.range, e).unwrap_or_default();
}
sh.tables.retain(|t| t.range != RangeRef::default() && !t.columns.is_empty());
if let Some(af) = sh.autofilter.as_mut() {
match map_range(af.range, e) {
Some(r) => af.range = r,
None => sh.autofilter = None,
}
}
sh.cell_pictures =
std::mem::take(&mut sh.cell_pictures).into_iter().filter_map(|(c, v)| map_cell(c).filter(CellRef::is_valid).map(|c| (c, v))).collect();
sh.comments = std::mem::take(&mut sh.comments).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect();
sh.hyperlinks = std::mem::take(&mut sh.hyperlinks).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect();
for sp in sh.sparklines.iter_mut() {
if let Some(c) = map_cell(sp.cell) {
sp.cell = c;
}
}
if let Some(pa) = sh.print.print_area {
sh.print.print_area = map_range(pa, e);
}
}
/// Columns inserted inside a table become new table columns (with names no other column has);
/// deleted ones leave it.
fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, insert: bool) {
if insert {
if at > t.range.start.col && at <= t.range.end.col {
let idx = (at - t.range.start.col) as usize;
let mut n = t.columns.len();
for k in 0..count as usize {
let name = loop {
n += 1;
let name = format!("Column{n}");
if !t.columns.iter().any(|c| c.name.eq_ignore_ascii_case(&name)) {
break name;
}
};
let col = gridcraft_model::TableColumn { name, totals: Default::default(), totals_label: None, formula: None };
t.columns.insert((idx + k).min(t.columns.len()), col);
}
}
return;
}
let lo = at.max(t.range.start.col);
let hi = at.saturating_add(count).min(t.range.end.col + 1);
if hi > lo {
let a = (lo - t.range.start.col) as usize;
let b = (hi - t.range.start.col) as usize;
if b <= t.columns.len() {
t.columns.drain(a..b);
}
}
}
/// Like Excel, Insert/Delete Cells never shifts part of a table: cells shifted up or down must
/// hold whole table columns, cells shifted left or right whole table rows, and deleting cells
/// never takes a table's header row without the whole table.
pub(crate) fn check_table_shift(sh: &Sheet, e: &Edit) -> Result<()> {
let (axis, r, delete) = match *e {
Edit::InsertCells { axis, range } => (axis, range, false),
Edit::DeleteCells { axis, range } => (axis, range, true),
_ => return Ok(()),
};
for t in &sh.tables {
let tr = t.range;
let ok = match axis {
Axis::Rows => {
let moves = tr.end.row >= r.start.row && tr.start.col <= r.end.col && tr.end.col >= r.start.col;
let header_alone = delete && t.header_row && r.start.row <= tr.start.row && r.end.row >= tr.start.row && r.end.row < tr.end.row;
!moves || (r.start.col <= tr.start.col && r.end.col >= tr.end.col && !header_alone)
}
Axis::Cols => {
let moves = tr.end.col >= r.start.col && tr.start.row <= r.end.row && tr.end.row >= r.start.row;
!moves || (r.start.row <= tr.start.row && r.end.row >= tr.end.row)
}
};
if !ok {
return Err(EngineError::Other("This operation isn't allowed: it would shift cells in a table on your worksheet.".into()));
}
}
Ok(())
}
+230
View File
@@ -0,0 +1,230 @@
//! Slicers: on-sheet widgets that filter one column of a table by clicking value tiles.
//!
//! A slicer is a thin front-end over the existing filter machinery: its selection is written as a
//! [`FilterCriterion::Values`] into the sheet's [`AutoFilter`] (over the table's range) and
//! [`super::data::apply_filter`] hides the rows. Creating a slicer (`insert.slicer` /
//! `table.insertSlicer`) selects everything, i.e. applies no filter.
use gridcraft_core::CellRef;
use gridcraft_model::*;
use serde_json::{Value as Json, json};
use super::*;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"insert.slicer",
"Slicer",
["Insert", "Filters"],
None,
"{table?, column?: \"Region\", columns?: 1, at?: \"H2\", width?, height?}",
has_doc,
insert_slicer
),
cmd!(
"table.insertSlicer",
"Insert Slicer",
["Table", "Tools"],
None,
"{table?, column?: \"Region\", columns?: 1, at?, width?, height?}",
has_doc,
insert_slicer
),
cmd!("slicer.toggle", "Toggle Slicer Value", [], None, "{slicer?: id, value: \"East\", multi?: false}", has_doc, slicer_toggle),
cmd!("slicer.selectAll", "Clear Slicer Filter", [], None, "{slicer?: id}", has_doc, slicer_select_all),
cmd!("slicer.clear", "Clear Slicer Filter", [], None, "{slicer?: id}", has_doc, slicer_select_all),
cmd!("slicer.delete", "Delete Slicer", [], None, "{slicer?: id}", has_doc, slicer_delete),
]
}
/// Distinct, non-blank display values of a table column, in first-seen order. Used to populate a
/// slicer's tiles and to detect "everything selected".
pub fn column_values(wb: &Workbook, sheet: usize, table: &str, column: &str) -> Vec<String> {
let Some(sh) = wb.sheet(sheet) else { return vec![] };
let Some(t) = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(table)) else { return vec![] };
let Some(ci) = t.column_index(column) else { return vec![] };
let Some(dr) = t.data_range() else { return vec![] };
let col = dr.start.col + ci as u32;
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for row in dr.start.row..=dr.end.row {
let text = crate::display::cell_text(wb, sh, CellRef::new(row, col));
if text.is_empty() {
continue;
}
if seen.insert(text.to_lowercase()) {
out.push(text);
}
}
out
}
/// A slicer's tiles as `(value, selected)`, for the UI. `selected` is true for every tile when the
/// slicer has no filter (`selected == None`).
pub fn slicer_items(wb: &Workbook, sheet: usize, sl: &Slicer) -> Vec<(String, bool)> {
column_values(wb, sheet, &sl.table, &sl.column)
.into_iter()
.map(|v| {
let on = match &sl.selected {
None => true,
Some(set) => set.iter().any(|x| x.eq_ignore_ascii_case(&v)),
};
(v, on)
})
.collect()
}
/// Writes the slicer's current selection into the sheet filter and re-applies it.
fn reapply_slicer(wb: &mut Workbook, sheet: usize, id: u32) {
let info = wb.sheet(sheet).and_then(|sh| {
let sl = sh.slicers.iter().find(|s| s.id == id)?;
let t = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(&sl.table))?;
let ci = t.column_index(&sl.column)?;
Some((t.range, t.range.start.col + ci as u32, sl.selected.clone()))
});
let Some((table_range, abs_col, selected)) = info else { return };
{
let Some(sh) = wb.sheet_mut(sheet) else { return };
let af = sh.autofilter.get_or_insert_with(|| AutoFilter { range: table_range, criteria: vec![] });
let off = abs_col.saturating_sub(af.range.start.col);
af.criteria.retain(|(o, _)| *o != off);
if let Some(values) = selected {
af.criteria.push((off, FilterCriterion::Values { values, blanks: false }));
}
}
super::data::apply_filter(wb, sheet);
}
fn insert_slicer(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
let t = match str_param(p, "table") {
Some(name) => sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(name)),
None => sh.table_at(d.selection.active),
}
.ok_or_else(|| EngineError::Other("Select a cell inside a table first, or pass `table`.".into()))?;
let column = match str_param(p, "column") {
Some(c) => t
.columns
.iter()
.find(|tc| tc.name.eq_ignore_ascii_case(c))
.map(|tc| tc.name.clone())
.ok_or_else(|| bad("insert.slicer", format!("table has no column `{c}`")))?,
None => {
// Default to the active cell's column within the table, else the first column.
let idx = d.selection.active.col.checked_sub(t.range.start.col).map(|o| o as usize).filter(|o| *o < t.columns.len()).unwrap_or(0);
t.columns.get(idx).map(|tc| tc.name.clone()).ok_or_else(|| bad("insert.slicer", "the table has no columns"))?
}
};
let table = t.name.clone();
let at = cell_param(s, p, "at")?
.unwrap_or_else(|| CellRef::new(t.range.start.row, t.range.end.col.saturating_add(2).min(gridcraft_core::MAX_COLS - 1)));
let columns = u32_param(p, "columns").unwrap_or(1).clamp(1, 10);
let width = f64_param(p, "width").unwrap_or(168.0).clamp(60.0, 10000.0) as f32;
let height = f64_param(p, "height").unwrap_or(200.0).clamp(60.0, 10000.0) as f32;
let id = d.wb.next_object_id();
let slicer = Slicer {
id,
table,
column: column.clone(),
caption: column,
anchor: Anchor { cell: at, dx: 4.0, dy: 4.0, width, height, mode: AnchorMode::MoveOnly },
selected: None,
columns,
};
edit(s, |cx| {
cx.sheet_mut(sheet)?.slicers.push(slicer);
Ok(json!({"slicer": id}))
})
}
/// The target slicer: by `slicer` id, else the last one on the active sheet.
fn find_slicer(s: &Session, p: &Json) -> Result<(usize, u32)> {
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
let idx = match u32_param(p, "slicer") {
Some(id) => sh.slicers.iter().position(|x| x.id == id),
None => sh.slicers.len().checked_sub(1),
};
idx.and_then(|i| sh.slicers.get(i).map(|x| (i, x.id))).ok_or_else(|| bad("slicer", "no slicer on this sheet"))
}
fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
let (idx, id) = find_slicer(s, p)?;
let value = str_param(p, "value").ok_or_else(|| bad("slicer.toggle", "missing `value`"))?.to_string();
let multi = bool_param(p, "multi").unwrap_or(false);
let sheet = s.doc()?.wb.active_sheet;
let (table, column, current) = {
let d = s.doc()?;
let sl = d.wb.active().and_then(|sh| sh.slicers.get(idx)).ok_or_else(|| bad("slicer.toggle", "no slicer"))?;
(sl.table.clone(), sl.column.clone(), sl.selected.clone())
};
let all = column_values(&s.doc()?.wb, sheet, &table, &column);
if !all.iter().any(|v| v.eq_ignore_ascii_case(&value)) {
return Err(bad("slicer.toggle", "value is not in the column"));
}
let new_selected: Option<Vec<String>> = if multi {
let mut set: Vec<String> = current.unwrap_or_else(|| all.clone());
match set.iter().position(|x| x.eq_ignore_ascii_case(&value)) {
Some(pos) => {
set.remove(pos);
}
None => set.push(value.clone()),
}
// Everything selected is the same as no filter.
if set.len() == all.len() && all.iter().all(|a| set.iter().any(|x| x.eq_ignore_ascii_case(a))) { None } else { Some(set) }
} else {
// Single click: show only this value; clicking the sole selected value clears the filter.
match &current {
Some(set) if set.len() == 1 && set.iter().any(|x| x.eq_ignore_ascii_case(&value)) => None,
_ => Some(vec![value.clone()]),
}
};
edit(s, |cx| {
if let Some(sl) = cx.sheet_mut(sheet)?.slicers.get_mut(idx) {
sl.selected = new_selected;
}
reapply_slicer(&mut cx.wb, sheet, id);
cx.structural = true;
Ok(Json::Null)
})
}
fn slicer_select_all(s: &mut Session, p: &Json) -> Result<Json> {
let (idx, id) = find_slicer(s, p)?;
let sheet = s.doc()?.wb.active_sheet;
edit(s, |cx| {
if let Some(sl) = cx.sheet_mut(sheet)?.slicers.get_mut(idx) {
sl.selected = None;
}
reapply_slicer(&mut cx.wb, sheet, id);
cx.structural = true;
Ok(Json::Null)
})
}
fn slicer_delete(s: &mut Session, p: &Json) -> Result<Json> {
let (idx, id) = find_slicer(s, p)?;
let sheet = s.doc()?.wb.active_sheet;
// Absolute column of the slicer, so its filter criterion can be removed too.
let abs_col = s.doc().ok().and_then(|d| {
let sh = d.wb.active()?;
let sl = sh.slicers.get(idx)?;
let t = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(&sl.table))?;
let ci = t.column_index(&sl.column)?;
Some(t.range.start.col + ci as u32)
});
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
sh.slicers.retain(|x| x.id != id);
if let (Some(abs), Some(af)) = (abs_col, sh.autofilter.as_mut()) {
let off = abs.saturating_sub(af.range.start.col);
af.criteria.retain(|(o, _)| *o != off);
}
super::data::apply_filter(&mut cx.wb, sheet);
cx.structural = true;
Ok(Json::Null)
})
}
File diff suppressed because it is too large Load Diff
+14 -8
View File
@@ -21,17 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
fn dictionary() -> &'static HashSet<String> {
static DICT: OnceLock<HashSet<String>> = OnceLock::new();
DICT.get_or_init(|| {
let mut set = HashSet::new();
#[cfg(target_arch = "wasm32")]
{
HashSet::new()
}
#[cfg(not(target_arch = "wasm32"))]
for path in ["/usr/share/dict/words", "/usr/share/dict/american-english", "/usr/share/dict/british-english"] {
if let Ok(text) = std::fs::read_to_string(path) {
for w in text.lines().take(2_000_000) {
set.insert(w.trim().to_lowercase());
{
let mut set = HashSet::new();
for path in ["/usr/share/dict/words", "/usr/share/dict/american-english", "/usr/share/dict/british-english"] {
if let Ok(text) = std::fs::read_to_string(path) {
for w in text.lines().take(2_000_000) {
set.insert(w.trim().to_lowercase());
}
break;
}
break;
}
set
}
set
})
}
@@ -155,7 +161,7 @@ fn change(s: &mut Session, p: &Json) -> Result<Json> {
if bool_param(p, "all").unwrap_or(false) {
return s.execute("edit.replace", json!({"what": word, "with": to, "matchCase": true, "all": true}));
}
let c = cell_param(p, "cell").ok_or_else(|| bad("review.changeSpelling", "missing `cell`"))?;
let c = cell_param(s, p, "cell")?.ok_or_else(|| bad("review.changeSpelling", "missing `cell`"))?;
let text = s.doc()?.wb.active().and_then(|sh| sh.cell(c)).map(|x| x.input_text()).unwrap_or_default();
s.execute("cell.set", json!({"cell": c.a1(), "input": text.replacen(&word, &to, 1)}))
}
+97 -7
View File
@@ -28,6 +28,11 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")),
cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")),
cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| {
s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar);
Ok(json!({"on": s.prefs.formula_bar}))
}),
cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation),
cmd!("pageLayout.size", "Size", ["Page Layout", "Page Setup"], None, "{paper: Letter|Legal|A4|A3|A5|Tabloid|Executive}", has_doc, paper),
@@ -91,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Header & Footer",
["Insert", "Text"],
None,
"{header?: \"&C&P\", footer?: \"&CPage &P of &N\"}",
"{sheet?, header?: \"&C&P\", footer?: \"&CPage &P of &N\", differentFirst?: bool, differentOddEven?: bool, firstHeader?, firstFooter?, evenHeader?, evenFooter?} or one section: {sheet?, page?: odd|even|first, part: header|footer, section: left|center|right, text: \"Page &[Page] of &[Pages]\"} (field names or codes) → {header, footer, differentFirst, differentOddEven, firstHeader, firstFooter, evenHeader, evenFooter}",
has_doc,
header_footer
),
@@ -113,7 +118,7 @@ fn freeze_panes(s: &mut Session, p: &Json) -> Result<Json> {
if sh.freeze.is_some() && p.get("cell").is_none() {
return set_freeze(s, None);
}
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
let top = sh.view_top_left;
let rows = at.row.saturating_sub(top.row);
let cols = at.col.saturating_sub(top.col);
@@ -254,7 +259,7 @@ fn scale_fit(s: &mut Session, p: &Json) -> Result<Json> {
}
fn breaks(s: &mut Session, p: &Json) -> Result<Json> {
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
let at = cell_param(s, p, "cell")?.unwrap_or(s.doc()?.selection.active);
let insert = bool_param(p, "insert").unwrap_or(false);
let remove = bool_param(p, "remove").unwrap_or(false);
let reset = bool_param(p, "reset").unwrap_or(false);
@@ -281,17 +286,77 @@ fn breaks(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Excel keeps at most 255 characters per header or footer.
const MAX_HEADER_FOOTER: usize = 255;
fn header_footer(s: &mut Session, p: &Json) -> Result<Json> {
const CMD: &str = "pageLayout.headerFooter";
let si = target_sheet(s, p)?;
let cap = |t: &str| t.chars().take(MAX_HEADER_FOOTER).collect::<String>();
// One section edited in place (Page Layout view).
let section = match (str_param(p, "part"), str_param(p, "section")) {
(None, None) => None,
(part, sec) => {
let footer = match part.unwrap_or("header") {
"header" => false,
"footer" => true,
other => return Err(bad(CMD, format!("`part` must be header or footer, not `{other}`"))),
};
let idx = match sec.unwrap_or("center") {
"left" => 0usize,
"center" | "centre" => 1,
"right" => 2,
other => return Err(bad(CMD, format!("`section` must be left, center or right, not `{other}`"))),
};
let page = match str_param(p, "page") {
None => gridcraft_model::HfPage::Odd,
Some(id) => gridcraft_model::HfPage::parse(id).ok_or_else(|| bad(CMD, format!("`page` must be odd, even or first, not `{id}`")))?,
};
Some((page, footer, idx, super::print::fields_to_codes(str_param(p, "text").unwrap_or(""))))
}
};
edit(s, |cx| {
let si = cx.sheet_index();
let pr = &mut cx.sheet_mut(si)?.print;
if let Some(h) = str_param(p, "header") {
pr.header = h.to_string();
pr.header = cap(h);
}
if let Some(f) = str_param(p, "footer") {
pr.footer = f.to_string();
pr.footer = cap(f);
}
Ok(Json::Null)
for (key, slot) in [
("firstHeader", &mut pr.first_header),
("firstFooter", &mut pr.first_footer),
("evenHeader", &mut pr.even_header),
("evenFooter", &mut pr.even_footer),
] {
if let Some(t) = str_param(p, key) {
*slot = cap(t);
}
}
if let Some(on) = bool_param(p, "differentFirst") {
pr.different_first = on;
}
if let Some(on) = bool_param(p, "differentOddEven") {
pr.different_odd_even = on;
}
if let Some((page, footer, idx, text)) = &section {
let spec = pr.hf_mut(*page, *footer);
let mut parts = super::print::split_header_footer(spec);
if let Some(slot) = parts.get_mut(*idx) {
*slot = text.clone();
}
*spec = cap(&super::print::join_header_footer(&parts));
}
Ok(json!({
"header": pr.header,
"footer": pr.footer,
"differentFirst": pr.different_first,
"differentOddEven": pr.different_odd_even,
"firstHeader": pr.first_header,
"firstFooter": pr.first_footer,
"evenHeader": pr.even_header,
"evenFooter": pr.even_footer,
}))
})
}
@@ -336,3 +401,28 @@ fn theme(s: &mut Session, p: &Json) -> Result<Json> {
#[allow(dead_code)]
fn unused(_: CellRef) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zoom_100_resets_the_active_sheet_zoom() {
let mut s = Session::new();
s.new_workbook();
s.execute("view.zoom", json!({"percent": 150})).unwrap();
assert_eq!(s.execute("view.zoom100", json!({})).unwrap()["zoom"], 100);
assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100);
}
#[test]
fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() {
let mut s = Session::new();
assert!(s.prefs.formula_bar);
assert_eq!(s.execute("view.formulaBar", json!({})).unwrap()["on"], false);
assert_eq!(s.execute("view.formulaBar", json!({"on": true})).unwrap()["on"], true);
// A prefs.json saved before the option existed keeps the formula bar shown.
let old: crate::Prefs = serde_json::from_str(r#"{"userName": "Ann"}"#).unwrap();
assert!(old.formula_bar);
}
}
+12 -13
View File
@@ -108,7 +108,7 @@ fn cell_arg(s: &Session, p: &Json, key: &str, cmd: &str) -> Result<(usize, CellR
/// A range text (`"A1:C9"`, `"Sheet2!A:C"`) resolved against the workbook. Whole rows/columns
/// are trimmed to the used range.
fn parse_range(wb: &Workbook, t: &str, cmd: &str) -> Result<(usize, RangeRef)> {
pub(crate) fn parse_range(wb: &Workbook, t: &str, cmd: &str) -> Result<(usize, RangeRef)> {
let (sh, body) = split_sheet(t);
let si = sheet_named(wb, sh, wb.active_sheet, cmd)?;
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{t}`")))?;
@@ -201,7 +201,7 @@ impl Trial {
for (si, c, v) in sets {
if let Some(sh) = wb.sheet_mut(*si) {
let style = sh.style_id(*c);
sh.cells.set(*c, Cell { value: v.clone(), formula: None, style });
sh.set_cell(*c, Cell { value: v.clone(), formula: None, style });
keys.push((*si, *c));
}
}
@@ -330,7 +330,7 @@ fn goal_seek(s: &mut Session, p: &Json) -> Result<Json> {
edit(s, |cx| {
let sh = cx.sheet_mut(csi)?;
let style = sh.style_id(chg);
sh.cells.set(chg, Cell { value: Value::number(r.x), formula: None, style });
sh.set_cell(chg, Cell { value: Value::number(r.x), formula: None, style });
cx.touch(csi, chg);
Ok(())
})?;
@@ -489,13 +489,12 @@ fn scenario_show(s: &mut Session, p: &Json) -> Result<Json> {
edit(s, |cx| {
for (c, v) in cells.iter().zip(sc.values.iter()) {
let input = super::edit::json_to_input(v);
let old = cx.wb.sheet(si).and_then(|sh| sh.cell(*c)).cloned();
let cell = super::edit::input_to_cell(&input, old.as_ref(), &mut cx.wb)?;
let cell = super::edit::input_to_cell(&input, si, *c, &mut cx.wb)?;
let sh = cx.sheet_mut(si)?;
match cell {
Some(cell) => sh.cells.set(*c, cell),
Some(cell) => sh.set_cell(*c, cell),
None => {
sh.cells.remove(*c);
sh.remove_cell(*c);
}
}
cx.touch(si, *c);
@@ -572,7 +571,7 @@ fn scenario_summary(s: &mut Session, p: &Json) -> Result<Json> {
let bold = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.font.bold = true);
let mut sheet = Sheet::new(name.clone());
let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| {
sheet.cells.set(CellRef::new(row, col), Cell { value: v, formula: None, style });
sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style });
};
put(&mut sheet, 1, 1, Value::text("Scenario Summary"), bold);
put(&mut sheet, 2, 2, Value::text("Current Values:"), bold);
@@ -695,7 +694,7 @@ fn data_table(s: &mut Session, p: &Json) -> Result<Json> {
for (c, v) in out {
let sh = cx.sheet_mut(si)?;
let style = sh.style_id(c);
sh.cells.set(c, Cell { value: v, formula: None, style });
sh.set_cell(c, Cell { value: v, formula: None, style });
cx.touch(si, c);
}
Ok(())
@@ -891,10 +890,10 @@ fn advanced_filter(s: &mut Session, p: &Json) -> Result<Json> {
let shm = cx.sheet_mut(dsi)?;
let old: Vec<CellRef> = shm.cells.iter_range(extract).map(|(c, _)| c).collect();
for c in &old {
shm.cells.remove(*c);
shm.remove_cell(*c);
}
for (c, cell) in cells {
shm.cells.set(c, cell);
shm.set_cell(c, cell);
}
for c in old {
cx.touch(dsi, c);
@@ -1108,9 +1107,9 @@ fn consolidate(s: &mut Session, p: &Json) -> Result<Json> {
let sh = cx.sheet_mut(dsi)?;
let style = sh.style_id(c);
if v.is_empty() && style == StyleId::DEFAULT {
sh.cells.remove(c);
sh.remove_cell(c);
} else {
sh.cells.set(c, Cell { value: v, formula: None, style });
sh.set_cell(c, Cell { value: v, formula: None, style });
}
cx.touch(dsi, c);
}
+61 -3
View File
@@ -31,16 +31,69 @@ pub fn format(v: &Value, code: &str, wb: &Workbook) -> Formatted {
format_value(v, &parsed(code), wb.date_system)
}
/// What the cell editor and the formula bar start from. Same as `Cell::input_text`, except that a
/// constant number in a date or time format is shown as a date (as the grid shows it), not as its
/// serial. When the formatted text would not read back as the same date (for example
/// `dddd, mmmm d`), an ISO `yyyy-mm-dd` (with `hh:mm:ss` for a time of day; just `hh:mm:ss`
/// for a time alone) is used instead, and if even that would not read back, the serial.
pub fn edit_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
let raw = sheet.input_text(c);
let Some(cell) = sheet.cell(c) else { return raw };
let Value::Number(n) = &cell.value else { return raw };
let code = wb.styles.get(cell.style).num_fmt.as_str();
if cell.formula.is_some() || !parsed(code).is_date() {
return raw;
}
let reads_back = |s: &str| matches!(gridcraft_core::parse::parse_input(s, wb.date_system).value, Value::Number(m) if (m - n).abs() < 1e-9);
let shown = format(&cell.value, code, wb).text;
if reads_back(&shown) {
return shown;
}
let Some(dt) = gridcraft_core::date::datetime_from_serial(wb.date_system, *n) else { return raw };
let time = format!("{:02}:{:02}:{:02}", dt.hour, dt.minute, dt.second);
let date = format!("{:04}-{:02}-{:02}", dt.year, dt.month, dt.day);
let iso = if *n < 1.0 {
time
} else if n.fract() == 0.0 {
date
} else {
format!("{date} {time}")
};
if reads_back(&iso) { iso } else { raw }
}
/// Whether `c` has a formula that must not be shown: its cell is formatted Hidden on a
/// protected sheet. A spilled cell follows its anchor.
pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
if !sheet.is_protected() {
return false;
}
let at = match sheet.cell(c) {
Some(x) if x.formula.is_some() => c,
_ => match sheet.spill_ranges.iter().find(|(_, r)| r.contains(c)) {
Some((anchor, _)) => *anchor,
None => return false,
},
};
wb.styles.get(sheet.style_id(at)).protection.hidden
}
/// The text a cell shows (full precision General; the grid narrows General to fit the column).
pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
let v = sheet.value(c);
if sheet.show_formulas
&& let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref())
&& !formula_hidden(wb, sheet, c)
{
return format!("={}", f.text);
}
value_text(wb, sheet, c)
}
/// A cell's value with its number format applied, independent of column width: no `#####`
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result.
pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
let style = wb.styles.get(sheet.style_id(c));
let f = format(&v, style.num_fmt.as_str(), wb);
let f = format(&sheet.value(c), style.num_fmt.as_str(), wb);
match f.fill {
Some((_, pos)) => {
let mut t = f.text;
@@ -57,7 +110,7 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
pub fn range_text(wb: &Workbook, sheet: usize, r: RangeRef) -> String {
let Some(sh) = wb.sheet(sheet) else { return String::new() };
let mut out = String::new();
let r = if r.count() > 2_000_000 { RangeRef::new(r.start, r.start.offset_clamped(1999, 999)) } else { r };
let r = clipboard_range(r);
for row in r.start.row..=r.end.row {
if sh.is_row_hidden(row) {
continue;
@@ -82,6 +135,11 @@ pub fn range_text(wb: &Workbook, sheet: usize, r: RangeRef) -> String {
out
}
/// The existing plain-text clipboard limit, shared with its HTML representation.
pub(crate) fn clipboard_range(r: RangeRef) -> RangeRef {
if r.count() > 2_000_000 { RangeRef::new(r.start, r.start.offset_clamped(1999, 999)) } else { r }
}
/// Status-bar statistics for a selection: average, count (non-empty), numerical count, min,
/// max, sum.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
+47 -14
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use gridcraft_core::date::{MONTHS, WEEKDAYS, datetime_from_serial, serial_from_ymd};
use gridcraft_core::date::{MONTHS, WEEKDAYS, datetime_from_serial, days_in_month, serial_from_ymd};
use gridcraft_core::{CellRef, RangeRef, Value};
use gridcraft_model::{Cell, Formula};
@@ -13,6 +13,9 @@ use crate::cmd::Ctx;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FillMode {
Series,
/// The Ctrl+drag fill: the opposite of a plain drag. A lone number fills a
/// series stepping by 1; anything a plain drag would extend is copied.
Alternate,
Copy,
Formats,
ValuesOnly,
@@ -45,6 +48,7 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
let lanes: Vec<u32> = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() };
let src_len = if vertical { src.height() } else { src.width() };
let mut writes: Vec<(CellRef, Option<Cell>)> = Vec::new();
let mut pictures = Vec::new();
for lane in lanes {
let src_cells: Vec<(CellRef, Option<Cell>)> = (0..src_len)
.map(|i| {
@@ -61,13 +65,14 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
if forward { (src.end.col + 1..=target.end.col).collect() } else { (target.start.col..src.start.col).rev().collect() };
cols.into_iter().map(|c| CellRef::new(lane, c)).collect()
};
let pattern = if mode == FillMode::Series {
Pattern::detect(
let pattern = if matches!(mode, FillMode::Series | FillMode::Alternate) {
let detected = Pattern::detect(
&src_cells,
&custom,
cx.wb.date_system,
cx.wb.styles.get(src_cells.first().and_then(|c| c.1.as_ref()).map(|c| c.style).unwrap_or_default()).num_fmt.as_str(),
)
);
if mode == FillMode::Alternate { detected.alternate(&src_cells) } else { detected }
} else {
Pattern::Copy
};
@@ -83,7 +88,7 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
writes.push((*t, Some(existing)));
continue;
}
FillMode::ValuesOnly | FillMode::Series | FillMode::Copy => {
FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy => {
let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style };
if let Some(f) = &cell.formula {
if let Some(e) = f.expr() {
@@ -97,18 +102,23 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
cell.style = style;
}
}
if let Some(picture) = sh.cell_pictures.get(&sc) {
pictures.push((*t, picture.clone()));
}
writes.push((*t, if cell.is_blank() { None } else { Some(cell) }));
}
}
let sh = cx.sheet_mut(sheet)?;
for (c, cell) in &writes {
match cell {
Some(x) => sh.cells.set(*c, x.clone()),
Some(x) if mode == FillMode::Formats => sh.cells.set(*c, x.clone()),
Some(x) => sh.set_cell(*c, x.clone()),
None => {
sh.cells.remove(*c);
sh.remove_cell(*c);
}
}
}
sh.cell_pictures.extend(pictures);
for (c, _) in writes {
cx.touch(sheet, c);
}
@@ -225,6 +235,19 @@ impl Pattern {
Pattern::Copy
}
/// The pattern of a Ctrl+drag, which swaps copying and extending: a single
/// number (which a plain drag copies) counts up by 1, and every series a
/// plain drag would extend (numbers, dates, lists, `Item 1`) is copied.
fn alternate(self, cells: &[(CellRef, Option<Cell>)]) -> Pattern {
match (self, cells) {
(Pattern::Copy, [(_, Some(cell))]) if cell.formula.is_none() => match cell.value.as_f64() {
Some(n) if cell.value.is_number() => Pattern::Linear { last: n, first: n, step: 1.0 },
_ => Pattern::Copy,
},
_ => Pattern::Copy,
}
}
/// The value `k` steps beyond the source (forward) or before it (backward).
fn value(&self, k: i64, forward: bool, _len: usize) -> Option<Value> {
let sign = if forward { 1 } else { -1 };
@@ -258,15 +281,25 @@ impl Pattern {
}
Pattern::Months { last, first, months } => {
let base = if forward { *last } else { *first };
let d = datetime_from_serial(gridcraft_core::DateSystem::D1900, base)?;
let m = d.month as i64 + months * k * sign;
let s = serial_from_ymd(gridcraft_core::DateSystem::D1900, d.year as i64, m, d.day as i64)?;
let s = add_months_clamped(gridcraft_core::DateSystem::D1900, base, months.checked_mul(k * sign)?)?;
Some(Value::number(s))
}
}
}
}
/// `serial` shifted by `months` calendar months, keeping the day of month but clamping it to the
/// target month's last day (Jan 31 + 1 month = Feb 28/29). Always measured from the original date,
/// so a series does not drift: Jan 31, Feb 28, Mar 31, Apr 30.
fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64) -> Option<f64> {
let d = datetime_from_serial(sys, serial)?;
let total = (d.year as i64).checked_mul(12)?.checked_add(d.month as i64 - 1)?.checked_add(months)?;
let year = total.div_euclid(12);
let month = total.rem_euclid(12) + 1;
let last = days_in_month(i32::try_from(year).ok()?, month as u32);
serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64))
}
fn round15(x: f64) -> f64 {
if x == 0.0 || !x.is_finite() {
return x;
@@ -310,8 +343,8 @@ pub fn series(cx: &mut Ctx, sheet: usize, r: RangeRef, rows: bool, kind: &str, s
"date" => {
let d = datetime_from_serial(sys, v);
match (unit, d) {
("month", Some(d)) => serial_from_ymd(sys, d.year as i64, d.month as i64 + step as i64, d.day as i64).unwrap_or(v),
("year", Some(d)) => serial_from_ymd(sys, d.year as i64 + step as i64, d.month as i64, d.day as i64).unwrap_or(v),
("month", Some(_)) => (step as i64).checked_mul(i as i64).and_then(|m| add_months_clamped(sys, start, m)).unwrap_or(v),
("year", Some(_)) => (step as i64).checked_mul(i as i64 * 12).and_then(|m| add_months_clamped(sys, start, m)).unwrap_or(v),
("weekday", Some(_)) => {
let mut n = v;
let mut left = step.abs() as i64;
@@ -339,7 +372,7 @@ pub fn series(cx: &mut Ctx, sheet: usize, r: RangeRef, rows: bool, kind: &str, s
}
let sh = cx.sheet_mut(sheet)?;
for (c, cell) in &writes {
sh.cells.set(*c, cell.clone());
sh.set_cell(*c, cell.clone());
}
for (c, _) in writes {
cx.touch(sheet, c);
@@ -393,7 +426,7 @@ pub fn flash_fill(cx: &mut Ctx, sheet: usize, at: CellRef) -> Result<usize> {
}
let sh = cx.sheet_mut(sheet)?;
for (c, out) in &writes {
sh.cells.set(*c, Cell { value: Value::text(out.as_str()), formula: None, style });
sh.set_cell(*c, Cell { value: Value::text(out.as_str()), formula: None, style });
}
for (c, _) in writes {
cx.touch(sheet, c);
+397 -32
View File
@@ -1,9 +1,9 @@
//! Opening and saving files: XLSX (the native format), CSV/TSV, JSON (debug), HTML export.
//! Opening and saving files: XLSX, legacy XLS import, XLSB and ODS data import, CSV/TSV, JSON (debug), HTML export.
use std::fmt::Write as _;
use gridcraft_core::CellRef;
use gridcraft_model::Workbook;
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_model::{Sheet, Workbook};
use crate::{EngineError, Result};
@@ -11,6 +11,10 @@ use crate::{EngineError, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileKind {
Xlsx,
/// Excel 97-2003 workbook (import only).
Xls,
Xlsb,
Ods,
Csv,
Tsv,
Json,
@@ -22,6 +26,9 @@ impl FileKind {
let ext = std::path::Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"xlsx" | "xlsm" | "xltx" | "xltm" => FileKind::Xlsx,
"xls" | "xlt" => FileKind::Xls,
"xlsb" => FileKind::Xlsb,
"ods" => FileKind::Ods,
"csv" => FileKind::Csv,
"tsv" | "tab" | "txt" => FileKind::Tsv,
"json" | "scjson" => FileKind::Json,
@@ -31,11 +38,77 @@ impl FileKind {
}
}
/// The error for an encrypted workbook opened without a password contains this. The interface
/// asks for the password when it sees it; programmatic callers pass `password` instead.
pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it.";
/// The error for a wrong password contains this.
pub const WRONG_PASSWORD: &str = "The password is incorrect.";
/// The first open warning of a workbook decrypted with its password.
pub const DECRYPTED_NOTICE: &str = "This workbook was password-protected. GridCraft saves it without the password.";
/// Parses a file's bytes into a workbook. `name` picks the format by extension when the bytes
/// don't say.
/// don't say. An encrypted workbook needs [`open_bytes_with_password`].
pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
open_bytes_with_password(name, bytes, None)
}
/// [`open_bytes`], first decrypting a password-protected workbook with `password`. Errors never
/// quote the password.
pub fn open_bytes_with_password(name: &str, bytes: &[u8], password: Option<&str>) -> Result<(Workbook, Vec<String>)> {
if gridcraft_xlsx::sniff(bytes) != gridcraft_xlsx::Format::Encrypted {
return open_plain(name, bytes);
}
// A scheme no password opens is said straight away, rather than after asking for one.
let decrypt_error = |e: gridcraft_xlsx::DecryptError| EngineError::Other(decrypt_message(name, e));
let Some(password) = password else {
gridcraft_xlsx::check_encryption(bytes).map_err(decrypt_error)?;
return Err(EngineError::Other(format!("'{name}' {PASSWORD_REQUIRED}")));
};
let plain = gridcraft_xlsx::decrypt(bytes, password).map_err(decrypt_error)?;
if gridcraft_xlsx::sniff(&plain) == gridcraft_xlsx::Format::Encrypted {
return Err(EngineError::Other(format!("We can't open '{name}': the encrypted file is damaged (it holds another encrypted file).")));
}
let (wb, mut warnings) = open_plain(name, &plain)?;
warnings.insert(0, DECRYPTED_NOTICE.into());
Ok((wb, warnings))
}
/// What to tell the user when an encrypted workbook can't be decrypted. Never quotes the password.
fn decrypt_message(name: &str, e: gridcraft_xlsx::DecryptError) -> String {
match e {
gridcraft_xlsx::DecryptError::WrongPassword => format!("{WRONG_PASSWORD} Check that Caps Lock is off and try again."),
gridcraft_xlsx::DecryptError::Unsupported(scheme) => {
format!("'{name}' uses {scheme} encryption, which GridCraft can't open yet. Remove the password in Excel and try again.")
}
gridcraft_xlsx::DecryptError::Malformed(detail) => format!("We can't open '{name}': the encrypted file is damaged ({detail})."),
}
}
/// Parses bytes that aren't encrypted.
fn open_plain(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
let kind = FileKind::from_path(name);
let sniffed = gridcraft_xlsx::sniff(bytes);
if sniffed == gridcraft_xlsx::Format::Xls {
let (wb, report) = gridcraft_xlsx::read_xls(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?;
return Ok((wb, report.warnings));
}
if sniffed == gridcraft_xlsx::Format::LegacyBinary {
return Err(EngineError::Other(format!(
"'{name}' is a legacy binary file but not an Excel workbook (no workbook stream). GridCraft can't open it."
)));
}
// Content wins over the extension: an ODS or XLSB package is imported as what it is,
// whatever it is called; the extension only decides when the bytes don't say.
let import = match sniffed {
gridcraft_xlsx::Format::Ods => Some(FileKind::Ods),
gridcraft_xlsx::Format::Xlsb => Some(FileKind::Xlsb),
_ => kind.filter(|k| matches!(k, FileKind::Ods | FileKind::Xlsb)),
};
if let Some(import) = import {
let read = if import == FileKind::Ods { gridcraft_xlsx::read_ods } else { gridcraft_xlsx::read_xlsb };
let (wb, report) = read(bytes).map_err(|e| EngineError::Other(format!("We can't import '{name}': {e}")))?;
return Ok((wb, report.warnings));
}
if sniffed == gridcraft_xlsx::Format::Xlsx || kind == Some(FileKind::Xlsx) {
let (wb, report) = gridcraft_xlsx::read_xlsx(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?;
return Ok((wb, report.warnings));
@@ -52,6 +125,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
Some(FileKind::Tsv) => {
let opts = gridcraft_xlsx::CsvOptions { delimiter: b'\t', ..Default::default() };
let mut wb = gridcraft_xlsx::read_csv(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![]))
}
@@ -80,18 +155,147 @@ fn rename_first_sheet(wb: &mut Workbook, path: &str) {
pub fn save_bytes(wb: &Workbook, path: &str) -> Result<Vec<u8>> {
let sheet = wb.active_sheet;
match FileKind::from_path(path).unwrap_or(FileKind::Xlsx) {
FileKind::Xlsx => gridcraft_xlsx::write_xlsx(wb).map_err(|e| EngineError::Other(e.to_string())),
FileKind::Csv => Ok(wb.sheet(sheet).map(|sh| gridcraft_xlsx::write_csv(sh, wb, b',')).unwrap_or_default()),
FileKind::Tsv => Ok(wb.sheet(sheet).map(|sh| gridcraft_xlsx::write_csv(sh, wb, b'\t')).unwrap_or_default()),
// The extension picks the package kind; only the macro-enabled kinds (.xlsm, .xltm) carry
// the VBA project, so any other name saves without it, as Excel does.
FileKind::Xlsx => gridcraft_xlsx::write_xlsx_as(wb, gridcraft_xlsx::XlsxKind::from_path(path)).map_err(|e| EngineError::Other(e.to_string())),
FileKind::Xls => {
Err(EngineError::Other("Excel 97-2003 (.xls) is supported for import only. Save as .xlsx or another supported export format.".into()))
}
FileKind::Xlsb => Err(EngineError::Other("XLSB is supported for data import only. Save as .xlsx or another supported export format.".into())),
FileKind::Ods => Err(EngineError::Other("ODS is supported for data import only. Save as .xlsx or another supported export format.".into())),
// A workbook read from CSV keeps the separator it was read with (a `;` file stays `;`).
FileKind::Csv => Ok(wb.sheet(sheet).map(|sh| csv(wb, sh, wb.csv_delimiter.unwrap_or(b','))).unwrap_or_default()),
FileKind::Tsv => Ok(wb.sheet(sheet).map(|sh| csv(wb, sh, b'\t')).unwrap_or_default()),
FileKind::Json => serde_json::to_vec_pretty(wb).map_err(|e| EngineError::Other(e.to_string())),
FileKind::Html => Ok(to_html(wb, sheet).into_bytes()),
}
}
/// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all
/// characters in each cell" (Microsoft Support, *Excel formatting and features that are not
/// transferred to other file formats*): number formats applied, never column-width `#####`.
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Vec<u8> {
gridcraft_xlsx::write_csv(sh, delimiter, |c| {
// General's grid-width formatting rounds large identifiers to scientific notation.
// Delimited files have no column width, so preserve the whole numeric value instead.
if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General")
&& let gridcraft_core::Value::Number(number) = sh.value(c)
&& number.is_finite()
{
number.to_string()
} else {
crate::display::value_text(wb, sh, c)
}
})
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
fn html_cell_css(wb: &Workbook, sh: &Sheet, c: CellRef) -> String {
let st = wb.styles.get(sh.style_id(c));
let mut css = String::new();
if st.font.bold {
css.push_str("font-weight:bold;");
}
if st.font.italic {
css.push_str("font-style:italic;");
}
if let Some(h) = st.font.color.hex(&wb.theme) {
let _ = write!(css, "color:{h};");
}
if st.fill.pattern != gridcraft_model::PatternType::None
&& let Some(h) = st.fill.fg.hex(&wb.theme)
{
let _ = write!(css, "background:{h};");
}
let v = sh.value(c);
let align = match st.align.h {
gridcraft_model::HAlign::Center => "center",
gridcraft_model::HAlign::Right => "right",
gridcraft_model::HAlign::Left => "left",
_ if v.is_number() => "right",
_ => "left",
};
let _ = write!(css, "text-align:{align};");
css
}
const CLIPBOARD_HTML_MAX_BYTES: usize = 4 * 1024 * 1024;
const CLIPBOARD_HTML_MAX_CELLS: u64 = 10_000;
/// An HTML fragment for the same range as `plain_text`, previously produced by
/// `display::range_text`. Large copies keep plain text only; never return a partial table.
pub(crate) fn range_html(wb: &Workbook, sheet: usize, r: RangeRef, plain_text: &str) -> Option<String> {
let r = crate::display::clipboard_range(r);
if r.count() > CLIPBOARD_HTML_MAX_CELLS || plain_text.len() > CLIPBOARD_HTML_MAX_BYTES {
return None;
}
let sh = wb.sheet(sheet)?;
let mut out = ClipboardHtml(String::new());
out.write_str("<table style=\"border-collapse:collapse;font-family:Calibri,Carlito,Arial,sans-serif;font-size:11pt\">").ok()?;
for row in r.start.row..=r.end.row {
if sh.is_row_hidden(row) {
continue;
}
out.write_str("<tr>").ok()?;
for col in r.start.col..=r.end.col {
let c = CellRef::new(row, col);
let span = if let Some(merged) = sh.merges.iter().find(|m| m.contains(c)).and_then(|m| m.intersection(&r)) {
let first_row = (merged.start.row..=merged.end.row).find(|&row| !sh.is_row_hidden(row))?;
if c != CellRef::new(first_row, merged.start.col) {
continue;
}
let rows = (first_row..=merged.end.row).filter(|&row| !sh.is_row_hidden(row)).count();
format!(" rowspan=\"{rows}\" colspan=\"{}\"", merged.width())
} else {
String::new()
};
let css = html_cell_css(wb, sh, c);
write!(out, "<td style=\"border:1px solid #d4d4d4;padding:2px 4px;white-space:pre-wrap;{css}\"{span}>").ok()?;
// Use the visible selected cell, even when the merge's original anchor
// is outside the range or hidden. This matches the plain-text copy.
let text = crate::display::cell_text(wb, sh, c);
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'&' => out.write_str("&amp;"),
'<' => out.write_str("&lt;"),
'>' => out.write_str("&gt;"),
'"' => out.write_str("&quot;"),
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
}
out.write_str("<br>")
}
'\n' => out.write_str("<br>"),
_ => out.write_char(ch),
}
.ok()?;
}
out.write_str("</td>").ok()?;
}
out.write_str("</tr>").ok()?;
}
out.write_str("</table>").ok()?;
Some(out.0)
}
/// Enforce the budget while escaping, before HTML expansion can allocate a large string.
struct ClipboardHtml(String);
impl std::fmt::Write for ClipboardHtml {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
if s.len() > CLIPBOARD_HTML_MAX_BYTES.saturating_sub(self.0.len()) {
return Err(std::fmt::Error);
}
self.0.push_str(s);
Ok(())
}
}
/// A sheet as a standalone HTML table (Save as Web Page).
pub fn to_html(wb: &Workbook, sheet: usize) -> String {
let Some(sh) = wb.sheet(sheet) else { return String::new() };
@@ -112,31 +316,7 @@ pub fn to_html(wb: &Workbook, sheet: usize) -> String {
if sh.merges.iter().any(|m| m.contains(c) && m.start != c) {
continue;
}
let st = wb.styles.get(sh.style_id(c));
let mut css = String::new();
if st.font.bold {
css.push_str("font-weight:bold;");
}
if st.font.italic {
css.push_str("font-style:italic;");
}
if let Some(h) = st.font.color.hex(&wb.theme) {
let _ = write!(css, "color:{h};");
}
if st.fill.pattern != gridcraft_model::PatternType::None
&& let Some(h) = st.fill.fg.hex(&wb.theme)
{
let _ = write!(css, "background:{h};");
}
let v = sh.value(c);
let align = match st.align.h {
gridcraft_model::HAlign::Center => "center",
gridcraft_model::HAlign::Right => "right",
gridcraft_model::HAlign::Left => "left",
_ if v.is_number() => "right",
_ => "left",
};
let _ = write!(css, "text-align:{align};");
let css = html_cell_css(wb, sh, c);
let span = sh
.merges
.iter()
@@ -244,3 +424,188 @@ pub fn image_size(data: &[u8]) -> Option<(u32, u32)> {
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn macros_are_saved_only_into_xlsm() {
let mut wb = Workbook::new();
wb.vba_project = Some(b"vba".to_vec());
let has_macros = |path: &str| {
let bytes = save_bytes(&wb, path).unwrap();
gridcraft_xlsx::read_xlsx(&bytes).unwrap().0.vba_project.is_some()
};
assert!(has_macros("book.xlsm"));
assert!(has_macros("BOOK.XLSM"));
assert!(!has_macros("book.xlsx"), "an .xlsx never carries a VBA project");
assert!(has_macros("book.xltm"), "a macro-enabled template keeps the VBA project");
assert!(!has_macros("book.xltx"), "a macro-free template never carries a VBA project");
assert!(wb.vba_project.is_some(), "the open workbook keeps its macros");
}
/// A minimal compound (CFB/OLE2) file — FAT in sector 0, directory in sector 1 — holding a
/// root entry and the given stream names.
fn cfb(streams: &[&str]) -> Vec<u8> {
let mut b = vec![0u8; 512 * 3];
let mut put = |at: usize, v: &[u8]| b[at..at + v.len()].copy_from_slice(v);
put(0, &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]);
put(30, &9u16.to_le_bytes());
put(44, &1u32.to_le_bytes());
put(48, &1u32.to_le_bytes());
put(68, &0xFFFF_FFFEu32.to_le_bytes());
for i in 1..109 {
put(76 + i * 4, &0xFFFF_FFFFu32.to_le_bytes());
}
put(512, &0xFFFF_FFFDu32.to_le_bytes());
put(516, &0xFFFF_FFFEu32.to_le_bytes());
for (k, name) in std::iter::once("Root Entry").chain(streams.iter().copied()).enumerate() {
let units: Vec<u8> = name.encode_utf16().flat_map(u16::to_le_bytes).collect();
put(1024 + k * 128, &units);
put(1024 + k * 128 + 64, &(units.len() as u16 + 2).to_le_bytes());
}
b
}
/// Cut-list rows as a CAD/CAM program exports them: `;`-separated, CRLF, part codes in the last
/// two columns, a part name containing a comma.
const CUT_LIST: &str = "1;511;184;P3_L1_led;2162PE;16;1MM_2162PE;1MM_2162PE;;;1244121406FB;\r\n\
1;562.5;510;Komoda, lijevo;2162PE;19;1MM_2162PE;;;;12441214071A;124412140710\r\n";
#[test]
fn csv_save_keeps_the_separator_it_was_opened_with() {
let (wb, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap();
assert_eq!(wb.csv_delimiter, Some(b';'));
assert_eq!(String::from_utf8(save_bytes(&wb, "cut list.csv").unwrap()).unwrap(), CUT_LIST);
// Save As another .csv name keeps it too; a comma file stays a comma file (quoting only
// fields that contain the separator in use).
assert_eq!(String::from_utf8(save_bytes(&wb, "copy.CSV").unwrap()).unwrap(), CUT_LIST);
let commas = "\"Komoda, lijevo\",b\r\n1,x;y\r\n";
let (wb, _) = open_bytes("plain.csv", commas.as_bytes()).unwrap();
assert_eq!(String::from_utf8(save_bytes(&wb, "plain.csv").unwrap()).unwrap(), commas);
// A tab-separated file named .csv round-trips with tabs.
let tabs = "a\tb\r\n1\t2\r\n";
let (wb, _) = open_bytes("tabs.csv", tabs.as_bytes()).unwrap();
assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs);
}
#[test]
fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() {
let mut wb = Workbook::new();
if let Some(sh) = wb.sheet_mut(0) {
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("a"));
sh.set_value(CellRef::new(0, 1), gridcraft_core::Value::Number(1.0));
}
assert_eq!(save_bytes(&wb, "new.csv").unwrap(), b"a,1\r\n");
// Through .xlsx the CSV origin is gone, as in Excel.
let (from_csv, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap();
let (reopened, _) = open_bytes("book.xlsx", &save_bytes(&from_csv, "book.xlsx").unwrap()).unwrap();
assert_eq!(reopened.csv_delimiter, None);
assert!(String::from_utf8(save_bytes(&reopened, "again.csv").unwrap()).unwrap().starts_with("1,511,184,"));
// A .tsv/.txt saved as .csv gets commas; as .tsv it keeps tabs.
let (tsv, _) = open_bytes("list.txt", b"a\tb\r\n").unwrap();
assert_eq!(save_bytes(&tsv, "list.csv").unwrap(), b"a,b\r\n");
assert_eq!(save_bytes(&tsv, "list.tsv").unwrap(), b"a\tb\r\n");
}
#[test]
fn encrypted_workbook_is_reported_not_misread() {
let file = gridcraft_xlsx::testing::encrypt_workbook(b"package", "pw");
let msg = open_bytes("secret.xlsx", &file).unwrap_err().to_string();
assert!(msg.contains(PASSWORD_REQUIRED), "got: {msg}");
assert!(!msg.contains("zip"), "must not surface the zip error: {msg}");
// A compound file naming the streams but unreadable is damage: no password is asked for,
// and none helps.
let file = cfb(&["EncryptionInfo", "EncryptedPackage"]);
for password in [None, Some("pw")] {
let msg = open_bytes_with_password("secret.xlsx", &file, password).unwrap_err().to_string();
assert!(msg.contains("damaged") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}");
}
}
#[test]
fn encryption_no_password_opens_is_reported_without_asking_for_one() {
let info: &[u8] = &[3, 0, 2, 0, 4, 0, 0, 0]; // Standard header flags: RC4, not AES
let file = gridcraft_xlsx::testing::compound_file(&[("EncryptionInfo", info), ("EncryptedPackage", &[0; 8])]);
let msg = open_bytes("rc4.xlsx", &file).unwrap_err().to_string();
assert!(msg.contains("RC4") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}");
let irm = gridcraft_xlsx::testing::compound_file(&[("EncryptedPackage", &[0; 8])]);
let msg = open_bytes("irm.xlsx", &irm).unwrap_err().to_string();
assert!(msg.contains("rights-management") && !msg.contains("damaged"), "got: {msg}");
}
#[test]
fn other_compound_files_are_not_called_encrypted() {
let err = open_bytes("old.doc", &cfb(&["WordDocument", "\u{5}SummaryInformation"])).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("not an Excel workbook"), "got: {msg}");
assert!(!msg.contains("password"), "got: {msg}");
}
/// Save As CSV/TSV writes cells as displayed: number formats applied, formula results,
/// whole values in narrow columns (never `#####`), quoting unchanged.
#[test]
fn csv_writes_displayed_text() {
use gridcraft_core::{CellError, Value};
use gridcraft_model::{Cell, Formula, LineInfo, NumFmt, StyleId};
let mut wb = Workbook::new();
let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
let (date, money, pct, frac, text, fixed, thousands) =
(styled("yyyy-mm-dd"), styled("$#,##0.00"), styled("0.0%"), styled("# ?/?"), styled("@"), styled("0.00"), styled("#,##0"));
let sh = wb.sheet_mut(0).unwrap();
let cells = [
("A1", Cell { value: Value::Number(46023.0), formula: None, style: date }),
("B1", Cell { value: Value::Number(1234.5), formula: None, style: money }),
("C1", Cell { value: Value::Number(0.125), formula: None, style: pct }),
("D1", Cell { value: Value::Number(1.5), formula: None, style: frac }),
("E1", Cell { value: Value::text("007"), formula: None, style: text }),
("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money }),
("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT }),
("A2", Cell { value: Value::Number(46024.0), style: date, ..Cell::formula(Formula::new("A1+1")) }),
("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed }),
("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT }),
("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands }),
];
for (a, c) in cells {
sh.set_cell(CellRef::parse(a).unwrap(), c);
}
// Column B is far too narrow for its numbers: the grid shows #####, the file must not.
sh.cols.insert(1, LineInfo { size: Some(1.0), ..Default::default() });
sh.show_formulas = true;
let csv = String::from_utf8(save_bytes(&wb, "out.csv").unwrap()).unwrap();
assert_eq!(csv, "2026-01-01,\"$1,234.50\",12.5%,1 1/2,007,#N/A,TRUE\r\n2026-01-02,12345678.90,-0.25,\"1,234,567\",,,\r\n");
let tsv = String::from_utf8(save_bytes(&wb, "out.tsv").unwrap()).unwrap();
assert!(tsv.starts_with("2026-01-01\t$1,234.50\t12.5%\t"), "{tsv}");
}
#[test]
fn delimited_exports_preserve_general_precision_and_explicit_number_formats() {
use gridcraft_core::Value;
use gridcraft_model::{Cell, NumFmt, StyleId};
let mut workbook = Workbook::new();
let scientific = workbook.styles.derive(StyleId::DEFAULT, |style| style.num_fmt = NumFmt::new("0.00E+00"));
let sheet = workbook.sheet_mut(0).unwrap();
sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() });
sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() });
sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() });
for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] {
let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap();
assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n"));
}
}
#[test]
fn template_extension_saves_template_content_type() {
let bytes = save_bytes(&Workbook::new(), "Budget.xltx").unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut types = String::new();
std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut types).unwrap();
assert!(
types.contains(
r#"PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml""#
),
"{types}"
);
}
}
+74 -4
View File
@@ -8,11 +8,15 @@
pub mod catalog;
pub mod cf;
mod clip_html;
pub mod cmd;
pub mod display;
pub mod fill;
pub mod io;
pub mod outline;
pub mod paper;
pub mod pivot;
pub mod pivot_calc;
pub mod sample;
pub mod selection;
pub mod tables;
@@ -25,7 +29,7 @@ use gridcraft_model::Workbook;
use serde::Serialize;
use serde_json::Value as Json;
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command, register_test_command};
pub use gridcraft_calc as calc;
pub use gridcraft_core as core;
pub use gridcraft_formula as formula;
@@ -65,11 +69,17 @@ pub struct Clipboard {
pub wb: Arc<Workbook>,
pub sheet: usize,
pub range: RangeRef,
/// The range as copied, before whole rows/columns were trimmed to the used range
/// (Insert Copied Cells inserts whole lines for a row or column copy).
pub selected: RangeRef,
pub cut: bool,
/// Document uid of the source (a cut only moves within the same workbook).
pub doc_uid: u64,
/// Plain text (tab-separated) for the system clipboard.
pub text: String,
/// A multi-area copy: the areas as selected (for the marquee). `wb` then holds them slid
/// together into one block at `range`. Empty for a single-range copy.
pub areas: Vec<RangeRef>,
}
/// In-cell edit mode as shown in the status bar.
@@ -96,6 +106,8 @@ pub struct DocState {
pub title: String,
/// Per-sheet selection memory.
pub sheet_selections: Vec<Selection>,
/// Allow Edit Ranges unlocked with their password in this session: (sheet name, title).
pub unlocked_ranges: Vec<(String, String)>,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -119,6 +131,7 @@ impl DocState {
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
title,
sheet_selections: vec![],
unlocked_ranges: vec![],
}
}
pub fn is_dirty(&self) -> bool {
@@ -127,6 +140,35 @@ impl DocState {
pub fn sheet_index(&self) -> usize {
self.wb.active_sheet
}
/// Records the view state that is saved with the file (`sheetView topLeftCell`, the active
/// cell): the first visible cell of the scrolling area per sheet index in `tops`, and the
/// active sheet's active cell. View state never makes the workbook dirty.
pub fn store_view(&mut self, tops: &[(usize, CellRef)]) {
let active = self.selection.active;
let si = self.wb.active_sheet;
let changed = tops.iter().any(|(i, c)| self.wb.sheets.get(*i).is_some_and(|sh| sh.view_top_left != *c))
|| self.wb.sheets.get(si).is_some_and(|sh| sh.view_active != active);
if !changed {
return;
}
let dirty = self.is_dirty();
let wb = Arc::make_mut(&mut self.wb);
for (i, c) in tops {
if let Some(sh) = wb.sheets.get_mut(*i)
&& sh.view_top_left != *c
{
Arc::make_mut(sh).view_top_left = *c;
}
}
if let Some(sh) = wb.sheets.get_mut(si)
&& sh.view_active != active
{
Arc::make_mut(sh).view_active = active;
}
if !dirty {
self.saved = self.wb.clone();
}
}
pub fn display_title(&self) -> String {
self.path
.as_deref()
@@ -150,6 +192,8 @@ pub struct Prefs {
pub r1c1: bool,
/// Words added with Add to Dictionary.
pub user_dictionary: Vec<String>,
/// View › Show › Formula Bar (an application option in Excel, not saved in the file).
pub formula_bar: bool,
}
impl Default for Prefs {
@@ -163,6 +207,7 @@ impl Default for Prefs {
sheets_in_new_workbook: 1,
r1c1: false,
user_dictionary: vec![],
formula_bar: true,
}
}
}
@@ -184,14 +229,15 @@ pub struct Session {
pub clipboard: Option<Clipboard>,
pub prefs: Prefs,
pub mode: Mode,
/// Commands run so far, without their passwords ([`cmd::journal_params`]).
pub journal: Vec<(String, Json)>,
pub ui_requests: Vec<UiRequest>,
/// Format painter source style (sticky when double-clicked).
pub format_painter: Option<(Arc<Workbook>, usize, RangeRef, bool)>,
/// Find state (last search).
pub last_find: Option<Json>,
/// Workbook view: normal, pageLayout or pageBreakPreview.
pub view_mode: String,
/// View › Show › Ruler is off (rulers in Page Layout view; an application option).
pub hide_ruler: bool,
/// Journal position where action recording started.
pub recording: Option<usize>,
/// Windows hidden with View › Hide.
@@ -200,6 +246,11 @@ pub struct Session {
pub draw_tool: String,
pub draw_color: String,
pub draw_width: f32,
/// Review › Show Comments: the Comments pane is open.
pub comments_pane: bool,
/// Review › Notes › Show All Notes: every note is displayed. An application display setting
/// (like Excel's comment indicator option), so it's not saved in the file.
pub show_all_notes: bool,
}
impl Session {
@@ -284,7 +335,7 @@ impl Session {
}
};
if spec.journal && result.is_ok() {
self.journal.push((id.to_string(), params.clone()));
self.journal.push((id.to_string(), cmd::journal_params(&params)));
if self.journal.len() > 10_000 {
self.journal.drain(..5_000);
}
@@ -311,6 +362,25 @@ impl Session {
pub fn take_ui_requests(&mut self) -> Vec<UiRequest> {
std::mem::take(&mut self.ui_requests)
}
/// Runs a command for a caller with no UI (MCP, CLI): queued UI requests are dropped, and a command that only
/// queued a file dialog because it got no file (`file.open`, `file.saveAs`, `file.save` on a workbook with no
/// file yet, `data.getData`) is an error instead of a silent success.
pub fn execute_headless(&mut self, id: &str, params: Json) -> Result<Json> {
let r = self.execute(id, params);
let requests = self.take_ui_requests();
let asked_for_file = requests.iter().any(|q| matches!(q, UiRequest::Dialog(name, _) if name == "open" || name == "saveAs"));
if r.is_ok() && asked_for_file {
let what = match id {
"file.open" => "`path` or `base64`",
"data.getData" | "data.fromTextCsv" => "`path` or `text`",
_ => "`path`",
};
let msg = format!("missing {what}: programmatic calls never open dialogs");
return Err(EngineError::BadParams { cmd: id.to_string(), msg });
}
r
}
}
/// Convenience: the active workbook's active sheet.
+133
View File
@@ -0,0 +1,133 @@
//! Outline groups (Data ▸ Group) of a sheet's rows or columns: the runs of lines at or above
//! each outline level, as the grid draws them (brackets, − / + buttons, level buttons) and the
//! Show / Hide Detail commands act on them. Summary rows sit below their detail and summary
//! columns right of it (Excel's defaults; the model has no setting for the other way round).
use std::collections::BTreeMap;
use gridcraft_model::LineInfo;
/// The deepest outline level XLSX allows.
pub const MAX_LEVEL: u8 = 7;
/// One group: lines `start..=end` at outline level `level` or deeper, with its summary line
/// just after `end`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutlineGroup {
pub level: u8,
pub start: u32,
pub end: u32,
/// Every detail line is hidden: the button shows +.
pub collapsed: bool,
}
impl OutlineGroup {
/// The summary line, where the − / + button sits.
pub fn summary(&self) -> u32 {
self.end.saturating_add(1)
}
pub fn contains(&self, line: u32) -> bool {
line >= self.start && line <= self.end
}
}
/// The deepest outline level used by these lines (0 = no outline).
pub fn max_level(lines: &BTreeMap<u32, LineInfo>) -> u8 {
lines.values().map(|l| l.outline.min(MAX_LEVEL)).max().unwrap_or(0)
}
/// Every group, ordered by where it ends (inner groups before the group around them).
pub fn groups(lines: &BTreeMap<u32, LineInfo>) -> Vec<OutlineGroup> {
let mut out = Vec::new();
// Open group per level (index level - 1): start line and whether all its lines are hidden.
let mut open: [Option<(u32, bool)>; MAX_LEVEL as usize] = [None; MAX_LEVEL as usize];
let mut prev: Option<u32> = None;
let close_from = |open: &mut [Option<(u32, bool)>; MAX_LEVEL as usize], from: u8, end: u32, out: &mut Vec<OutlineGroup>| {
for level in (from..=MAX_LEVEL).rev() {
if let Some(slot) = open.get_mut(level as usize - 1)
&& let Some((start, hidden)) = slot.take()
{
out.push(OutlineGroup { level, start, end, collapsed: hidden });
}
}
};
for (&i, info) in lines.iter().filter(|(_, l)| l.outline > 0) {
let level = info.outline.min(MAX_LEVEL);
match prev {
// A gap ends every group.
Some(p) if p.checked_add(1) != Some(i) => close_from(&mut open, 1, p, &mut out),
Some(p) if level < MAX_LEVEL => close_from(&mut open, level + 1, p, &mut out),
_ => {}
}
for slot in open.iter_mut().take(level as usize) {
match slot {
Some((_, hidden)) => *hidden &= info.hidden,
None => *slot = Some((i, info.hidden)),
}
}
prev = Some(i);
}
if let Some(p) = prev {
close_from(&mut open, 1, p, &mut out);
}
out
}
/// The group at `level` that holds `line`.
pub fn group_at(lines: &BTreeMap<u32, LineInfo>, line: u32, level: u8) -> Option<OutlineGroup> {
groups(lines).into_iter().find(|g| g.level == level && g.contains(line))
}
#[cfg(test)]
mod tests {
use super::*;
fn lines(spec: &[(u32, u8, bool)]) -> BTreeMap<u32, LineInfo> {
spec.iter().map(|&(i, outline, hidden)| (i, LineInfo { outline, hidden, ..Default::default() })).collect()
}
#[test]
fn no_outline_has_no_groups() {
let l = lines(&[(3, 0, true)]);
assert_eq!(max_level(&l), 0);
assert!(groups(&l).is_empty());
}
#[test]
fn nested_and_separate_groups() {
// Rows 5..8 at level 1 with 6..7 at level 2; rows 12..13 at level 1 after a gap.
let l = lines(&[(4, 1, false), (5, 2, false), (6, 2, false), (7, 1, false), (11, 1, true), (12, 1, true)]);
assert_eq!(max_level(&l), 2);
let g = groups(&l);
assert_eq!(
g,
vec![
OutlineGroup { level: 2, start: 5, end: 6, collapsed: false },
OutlineGroup { level: 1, start: 4, end: 7, collapsed: false },
OutlineGroup { level: 1, start: 11, end: 12, collapsed: true },
]
);
assert_eq!(g[1].summary(), 8);
assert_eq!(group_at(&l, 6, 1).map(|g| g.start), Some(4));
assert_eq!(group_at(&l, 4, 2), None);
}
#[test]
fn adjacent_groups_at_one_level_split_by_a_shallower_line() {
// Two level-2 groups inside one level-1 group, separated by a level-1 line.
let l = lines(&[(0, 2, true), (1, 2, true), (2, 1, false), (3, 2, false)]);
let g = groups(&l);
assert_eq!(g.iter().filter(|g| g.level == 2).count(), 2);
assert_eq!(g.iter().find(|g| g.level == 2 && g.start == 0).map(|g| g.collapsed), Some(true));
assert_eq!(g.iter().find(|g| g.level == 1).map(|g| (g.start, g.end, g.collapsed)), Some((0, 3, false)));
}
#[test]
fn deepest_level_and_last_line_do_not_overflow() {
let l = lines(&[(u32::MAX - 1, 9, false), (u32::MAX, 7, false)]);
let g = groups(&l);
assert_eq!(g.len(), 7);
assert!(g.iter().all(|g| g.start == u32::MAX - 1 && g.end == u32::MAX));
assert_eq!(g[0].summary(), u32::MAX);
}
}
+322
View File
@@ -0,0 +1,322 @@
//! Page Layout view geometry: a sheet shown as printed pages side by side.
//!
//! The view uses the print pagination ([`crate::cmd::print::split_bands`]) over the sheet from
//! A1, so its page edges are the printed ones whenever the print area starts at A1. Pages keep
//! going right and down past the data ("Click to add data" pages), as far as the view needs.
//!
//! Coordinates are *layout units*: sheet pixels (96 dpi) at the print scale, so a cell keeps its
//! sheet size and a page is `paper / scale` big. The UI multiplies by its zoom. Pages sit in a
//! grid with a gap around each: page `(row band, column band)` starts at
//! `(gap + j·(page_w + gap), gap + i·(page_h + gap))`, and its cells start at its top-left margin.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
use gridcraft_model::{LineIndex, Sheet, Workbook};
use crate::cmd::print::{self, PX_TO_PT, PrintOptions};
/// Gap between pages on screen, in pixels at 100% zoom.
pub const PAGE_GAP: f32 = 14.0;
/// One sheet paginated for the Page Layout view.
#[derive(Clone, Debug)]
pub struct PageGrid {
/// Page size in layout units.
pub page_w: f64,
pub page_h: f64,
/// Left, right, top, bottom, header and footer margins in layout units.
pub margins: [f64; 6],
/// Gap between pages in layout units.
pub gap: f64,
/// Print scale (1.0 = 100%): screen sizes of cells are `zoom × scale`.
pub scale: f32,
/// Paper size in points (after orientation), for the rulers.
pub paper_pt: (f32, f32),
pub row_bands: Vec<(u32, u32)>,
pub col_bands: Vec<(u32, u32)>,
/// The bands reach the sheet's last row / column.
pub rows_complete: bool,
pub cols_complete: bool,
/// Bands holding printed data: `[first, last]` row bands and column bands.
pub data_rows: (usize, usize),
pub data_cols: (usize, usize),
ri: LineIndex,
ci: LineIndex,
}
/// A header or footer zone of one page.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HfZone {
pub footer: bool,
/// 0 left, 1 centre, 2 right.
pub section: usize,
}
impl PageGrid {
/// Paginates sheet `si` far enough to cover row `need_row` and column `need_col` (and at
/// least the printed area). `None` when the sheet doesn't exist.
pub fn build(wb: &Workbook, si: usize, need_row: u32, need_col: u32) -> Option<PageGrid> {
let sh = wb.sheet(si)?;
let printed = print::layout_sheet(wb, si, &PrintOptions::default(), None)?;
let mut lay = printed.clone();
let end_row = need_row.max(printed.area.end.row).min(MAX_ROWS - 1);
let end_col = need_col.max(printed.area.end.col).min(MAX_COLS - 1);
lay.area = RangeRef::new(CellRef::new(0, 0), CellRef::new(end_row, end_col));
let (row_bands, col_bands) = print::split_bands(sh, &lay, MAX_ROWS as usize);
let s = f64::from(lay.scale.clamp(0.1, 4.0));
let to_layout = |pt: f32| f64::from(pt) / f64::from(PX_TO_PT) / s;
let margins = lay.margins.map(to_layout);
let band_range = |bands: &[(u32, u32)], lo: u32, hi: u32| {
let first = bands.iter().position(|b| b.1 >= lo).unwrap_or(0);
let last = bands.iter().rposition(|b| b.0 <= hi).unwrap_or(first).max(first);
(first, last)
};
let area = printed.area;
let data_rows = band_range(&row_bands, area.start.row, area.end.row);
let data_cols = band_range(&col_bands, area.start.col, area.end.col);
Some(PageGrid {
page_w: to_layout(lay.page_w),
page_h: to_layout(lay.page_h),
margins,
gap: f64::from(PAGE_GAP) / s,
scale: lay.scale,
paper_pt: (lay.page_w, lay.page_h),
rows_complete: row_bands.last().is_some_and(|b| b.1 >= MAX_ROWS - 1),
cols_complete: col_bands.last().is_some_and(|b| b.1 >= MAX_COLS - 1),
row_bands,
col_bands,
data_rows,
data_cols,
ri: LineIndex::new(&sh.rows, sh.default_row_height, MAX_ROWS),
ci: LineIndex::new(&sh.cols, sh.default_col_width, MAX_COLS),
})
}
/// The grid covers row `r` and column `c` (else it needs a rebuild with more pages).
pub fn covers(&self, r: u32, c: u32) -> bool {
(self.rows_complete || self.row_bands.last().is_some_and(|b| b.1 >= r))
&& (self.cols_complete || self.col_bands.last().is_some_and(|b| b.1 >= c))
}
fn band_of(bands: &[(u32, u32)], line: u32) -> usize {
bands.partition_point(|b| b.1 < line).min(bands.len().saturating_sub(1))
}
/// Left edge of page column `j` / top edge of page row `i`.
pub fn page_x(&self, j: usize) -> f64 {
self.gap + j as f64 * (self.page_w + self.gap)
}
pub fn page_y(&self, i: usize) -> f64 {
self.gap + i as f64 * (self.page_h + self.gap)
}
/// The page rectangle `(x, y, w, h)` of page `(i, j)`.
pub fn page_rect(&self, i: usize, j: usize) -> (f64, f64, f64, f64) {
(self.page_x(j), self.page_y(i), self.page_w, self.page_h)
}
/// Where the cells of page `(i, j)` go: inside the margins.
pub fn content_rect(&self, i: usize, j: usize) -> (f64, f64, f64, f64) {
let [l, r, t, b, ..] = self.margins;
(self.page_x(j) + l, self.page_y(i) + t, (self.page_w - l - r).max(1.0), (self.page_h - t - b).max(1.0))
}
/// Left edge of column `col`.
pub fn col_x(&self, col: u32) -> f64 {
let j = Self::band_of(&self.col_bands, col);
let start = self.col_bands.get(j).map_or(0, |b| b.0);
self.page_x(j) + self.margins[0] + (self.ci.start(col) - self.ci.start(start))
}
/// Top edge of row `row`.
pub fn row_y(&self, row: u32) -> f64 {
let i = Self::band_of(&self.row_bands, row);
let start = self.row_bands.get(i).map_or(0, |b| b.0);
self.page_y(i) + self.margins[2] + (self.ri.start(row) - self.ri.start(start))
}
/// Page column under `x` (the nearest one in gaps).
pub fn page_col_at(&self, x: f64) -> usize {
let j = ((x - self.gap / 2.0) / (self.page_w + self.gap)).floor();
(j.max(0.0) as usize).min(self.col_bands.len().saturating_sub(1))
}
pub fn page_row_at(&self, y: f64) -> usize {
let i = ((y - self.gap / 2.0) / (self.page_h + self.gap)).floor();
(i.max(0.0) as usize).min(self.row_bands.len().saturating_sub(1))
}
/// Column under `x`, clamped to the page's columns (margins and gaps hit the nearest one).
pub fn col_at(&self, x: f64) -> u32 {
let j = self.page_col_at(x);
let Some(&(a, b)) = self.col_bands.get(j) else { return 0 };
let local = x - self.page_x(j) - self.margins[0];
if local <= 0.0 { a } else { self.ci.at(self.ci.start(a) + local).clamp(a, b) }
}
pub fn row_at(&self, y: f64) -> u32 {
let i = self.page_row_at(y);
let Some(&(a, b)) = self.row_bands.get(i) else { return 0 };
let local = y - self.page_y(i) - self.margins[2];
if local <= 0.0 { a } else { self.ri.at(self.ri.start(a) + local).clamp(a, b) }
}
/// The page `(i, j)` whose paper contains the point, if any.
pub fn page_at(&self, x: f64, y: f64) -> Option<(usize, usize)> {
let (i, j) = (self.page_row_at(y), self.page_col_at(x));
let (px, py, w, h) = self.page_rect(i, j);
(x >= px && x < px + w && y >= py && y < py + h).then_some((i, j))
}
/// The point lies on cells (inside a page's margins, on a cell of that page).
pub fn on_cells(&self, x: f64, y: f64) -> bool {
let Some((i, j)) = self.page_at(x, y) else { return false };
let (cx, cy, w, h) = self.content_rect(i, j);
let (Some(&(_, c1)), Some(&(_, r1))) = (self.col_bands.get(j), self.row_bands.get(i)) else { return false };
// Cells end where the band ends (the rest of the printable area stays blank).
let right = (self.col_x(c1) + self.ci.start(c1 + 1) - self.ci.start(c1)).min(cx + w);
let bottom = (self.row_y(r1) + self.ri.start(r1 + 1) - self.ri.start(r1)).min(cy + h);
x >= cx && x < right && y >= cy && y < bottom
}
/// The header or footer section under the point: the top or bottom margin of a page, split
/// into thirds between the side margins.
pub fn hf_zone_at(&self, x: f64, y: f64) -> Option<((usize, usize), HfZone)> {
let (i, j) = self.page_at(x, y)?;
let (px, py, _, _) = self.page_rect(i, j);
let [l, r, t, b, ..] = self.margins;
let footer = if y < py + t {
false
} else if y >= py + self.page_h - b {
true
} else {
return None;
};
let inner = (self.page_w - l - r).max(3.0);
let section = (((x - px - l) / (inner / 3.0)).floor().max(0.0) as usize).min(2);
Some(((i, j), HfZone { footer, section }))
}
/// Page `(i, j)` holds printed data (others are "Click to add data" pages).
pub fn is_data_page(&self, i: usize, j: usize) -> bool {
(self.data_rows.0..=self.data_rows.1).contains(&i) && (self.data_cols.0..=self.data_cols.1).contains(&j)
}
/// Printed page number of page `(i, j)` (down, then over) and the printed page count.
pub fn page_number(&self, i: usize, j: usize) -> Option<(usize, usize)> {
if !self.is_data_page(i, j) {
return None;
}
let rows = self.data_rows.1 - self.data_rows.0 + 1;
let cols = self.data_cols.1 - self.data_cols.0 + 1;
Some(((j - self.data_cols.0) * rows + (i - self.data_rows.0) + 1, rows * cols))
}
/// Page rows and columns overlapping the layout rectangle `[x0, x1] × [y0, y1]`.
pub fn pages_in(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> ((usize, usize), (usize, usize)) {
((self.page_row_at(y0), self.page_row_at(y1)), (self.page_col_at(x0), self.page_col_at(x1)))
}
/// Width / height of everything laid out so far.
pub fn extent(&self) -> (f64, f64) {
(self.page_x(self.col_bands.len()), self.page_y(self.row_bands.len()))
}
/// Rows `(first, last)` of a page row and columns of a page column.
pub fn row_band(&self, i: usize) -> Option<(u32, u32)> {
self.row_bands.get(i).copied()
}
pub fn col_band(&self, j: usize) -> Option<(u32, u32)> {
self.col_bands.get(j).copied()
}
}
/// Sheet-wide helper: the bottom-right cell a page grid for this sheet must reach so that the
/// layout rectangle up to `(x, y)` is covered. Layout coordinates never run ahead of sheet
/// coordinates (pages only add margins and gaps), so the sheet position is a safe bound.
pub fn need_for(sh: &Sheet, x: f64, y: f64) -> (u32, u32) {
(sh.row_at(y.max(0.0)).saturating_add(1).min(MAX_ROWS - 1), sh.col_at(x.max(0.0)).saturating_add(1).min(MAX_COLS - 1))
}
#[cfg(test)]
mod tests {
use gridcraft_model::{Orientation, Sheet};
use super::*;
fn wb_with(rows: u32, cols: u32) -> Workbook {
let mut wb = Workbook::new();
if let Some(sh) = wb.sheet_mut(0) {
for r in 0..rows {
for c in 0..cols {
sh.set_value(CellRef::new(r, c), gridcraft_core::Value::Number(1.0));
}
}
}
wb
}
#[test]
fn pages_match_print_pagination_and_cells_map_both_ways() {
let wb = wb_with(120, 14);
let g = PageGrid::build(&wb, 0, 400, 40).unwrap();
let printed = print::layout_sheet(&wb, 0, &PrintOptions::default(), None).unwrap();
// The printed area starts at A1, so the view's page edges are the printed ones (the
// last printed page simply ends with the data).
let starts = |b: &[(u32, u32)], n: usize| b.iter().take(n).map(|x| x.0).collect::<Vec<_>>();
assert!(printed.row_bands.len() > 1 && printed.col_bands.len() > 1);
assert_eq!(starts(&g.row_bands, printed.row_bands.len()), starts(&printed.row_bands, usize::MAX));
assert_eq!(starts(&g.col_bands, printed.col_bands.len()), starts(&printed.col_bands, usize::MAX));
assert_eq!(g.data_rows, (0, printed.row_bands.len() - 1));
assert!(g.covers(400, 40));
// Every cell maps to a point inside its own page's margins and back.
for (r, c) in [(0, 0), (5, 3), (60, 9), (119, 13), (300, 30)] {
let (x, y) = (g.col_x(c) + 1.0, g.row_y(r) + 1.0);
assert_eq!((g.row_at(y), g.col_at(x)), (r, c), "cell ({r},{c})");
assert!(g.on_cells(x, y));
let (i, j) = g.page_at(x, y).unwrap();
let (cx, cy, _, _) = g.content_rect(i, j);
assert!(x >= cx && y >= cy);
}
// The first row of the second page starts below the first page plus a gap.
let (a, _) = g.row_bands[1];
assert!((g.row_y(a) - (g.page_y(1) + g.margins[2])).abs() < 1e-6);
assert!(g.row_y(a) > g.page_h + g.gap);
}
#[test]
fn margins_gaps_and_header_zones() {
let mut wb = wb_with(10, 3);
if let Some(sh) = wb.sheet_mut(0) {
sh.print.orientation = Orientation::Landscape;
}
let g = PageGrid::build(&wb, 0, 50, 20).unwrap();
assert!(g.page_w > g.page_h, "landscape pages are wider than tall");
// A point in the top margin hits the header, thirds pick the section.
let (px, py, w, h) = g.page_rect(0, 0);
let mid_top = (px + w / 2.0, py + g.margins[2] / 2.0);
assert_eq!(g.hf_zone_at(mid_top.0, mid_top.1), Some(((0, 0), HfZone { footer: false, section: 1 })));
assert_eq!(g.hf_zone_at(px + g.margins[0] + 2.0, py + h - 2.0).map(|z| z.1), Some(HfZone { footer: true, section: 0 }));
assert_eq!(g.hf_zone_at(px + w - g.margins[1] - 2.0, py + 3.0).map(|z| z.1.section), Some(2));
assert!(!g.on_cells(mid_top.0, mid_top.1), "margins aren't cells");
// The gap between pages is no page at all.
assert_eq!(g.page_at(px + w + g.gap / 2.0, py + 10.0), None);
assert_eq!(g.hf_zone_at(px - 1.0, py + 3.0), None);
// Page numbers count printed pages only.
assert_eq!(g.page_number(0, 0), Some((1, 1)));
assert_eq!(g.page_number(0, 1), None);
assert!(g.is_data_page(0, 0) && !g.is_data_page(1, 0));
}
#[test]
fn print_scale_and_hostile_settings_stay_bounded() {
let mut wb = wb_with(3, 3);
if let Some(sh) = wb.sheet_mut(0) {
sh.print.scale = 50;
sh.print.margins = [f32::NAN, 1e9, -4.0, f32::INFINITY, 0.0, 0.0];
sh.print.row_breaks = vec![0, 1, 2, u32::MAX];
}
let g = PageGrid::build(&wb, 0, MAX_ROWS, MAX_COLS).unwrap();
assert!(g.rows_complete && g.cols_complete);
assert!(g.page_w.is_finite() && g.page_h.is_finite() && g.page_w > 0.0);
let (ex, ey) = g.extent();
assert!(ex.is_finite() && ey.is_finite());
assert_eq!(g.row_at(ey * 2.0), MAX_ROWS - 1);
assert_eq!(g.col_at(-5.0), 0);
assert_eq!(need_for(&Sheet::new("S"), f64::MAX, f64::MAX), (MAX_ROWS - 1, MAX_COLS - 1));
assert!(PageGrid::build(&wb, 7, 0, 0).is_none());
}
}
+238 -20
View File
@@ -12,6 +12,8 @@ use gridcraft_core::date::datetime_from_serial;
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
use gridcraft_model::*;
use crate::pivot_calc::CalcSet;
/// Largest source block read (cells).
pub const MAX_SOURCE_CELLS: u64 = 10_000_000;
/// Largest report written (cells).
@@ -126,18 +128,25 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
return Err("The source range is too large for a PivotTable.".into());
}
let mut headers: Vec<String> = Vec::new();
// Names taken so far (lower-case), and the next suffix to try for each repeated header, so
// that thousands of equal headers don't take cubic time.
let mut taken: HashSet<String> = HashSet::new();
let mut next_suffix: HashMap<String, usize> = HashMap::new();
let mut formats = Vec::new();
for c in r.start.col..=r.end.col {
let h = crate::display::cell_text(wb, sh, CellRef::new(r.start.row, c)).trim().to_string();
if h.is_empty() {
return Err(FIELD_NAME_ERR.into());
}
let key = h.to_ascii_lowercase();
let mut n = h.clone();
let mut k = 2;
while headers.iter().any(|x| x.eq_ignore_ascii_case(&n)) {
let mut k = next_suffix.get(&key).copied().unwrap_or(2);
while taken.contains(&n.to_ascii_lowercase()) {
n = format!("{h}{k}");
k += 1;
}
next_suffix.insert(key, k);
taken.insert(n.to_ascii_lowercase());
headers.push(n);
let fmt = if r.end.row > r.start.row {
wb.styles.get(sh.style_id(CellRef::new(r.start.row + 1, c))).num_fmt.as_str().to_string()
@@ -496,6 +505,12 @@ pub struct Output {
/// Rows above the body (report filters plus a blank row).
pub body_offset: u32,
pub width: u32,
/// Grid rows of the innermost (or collapsed) items: a PivotChart's categories.
pub chart_rows: Vec<u32>,
/// Grid columns of item (not total) values with their series names: a PivotChart's series.
pub chart_cols: Vec<(u32, String)>,
/// Grid column holding the innermost row labels (`None` without row fields).
pub label_col: Option<u32>,
}
impl Output {
@@ -539,6 +554,8 @@ enum LineKind {
struct Line {
kind: LineKind,
/// A category of a PivotChart: an innermost (or collapsed) item.
leaf: bool,
path: Vec<u32>,
values: bool,
/// (column, value, indent, number format)
@@ -580,14 +597,21 @@ impl Ctx<'_> {
let (col, indent) = if outline { (depth, 0) } else { (0, depth.min(250) as u8) };
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
out.push(Line { kind: LineKind::Item(depth + 1 < n), path: prefix.clone(), values: true, labels: vec![(col, v, indent, fmt)] });
out.push(Line {
kind: LineKind::Item(depth + 1 < n),
leaf: true,
path: prefix.clone(),
values: true,
labels: vec![(col, v, indent, fmt)],
});
} else {
let top = self.pt.subtotals && self.pt.subtotals_top;
out.push(Line { kind: LineKind::Item(true), path: prefix.clone(), values: top, labels: vec![(col, v, indent, fmt)] });
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: top, labels: vec![(col, v, indent, fmt)] });
self.flatten(&node.children, depth + 1, prefix, out);
if self.pt.subtotals && !self.pt.subtotals_top {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(col, Value::text(format!("{label} Total")), indent, None)],
@@ -614,12 +638,13 @@ impl Ctx<'_> {
labels.push((depth, v, 0, fmt));
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
out.push(Line { kind: LineKind::Item(false), path: prefix.clone(), values: true, labels });
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels });
} else {
self.flatten_tabular(&node.children, depth + 1, prefix, &labels, out);
if self.pt.subtotals {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(depth, Value::text(format!("{label} Total")), 0, None)],
@@ -659,13 +684,44 @@ fn flatten_cols(
type AggMap = HashMap<(Vec<u32>, Vec<u32>), Vec<Acc>>;
/// Where a value field's numbers come from.
#[derive(Clone, Copy)]
enum ValSrc {
/// A source column.
Col(usize),
/// A calculated field (index into the PivotTable's calculated fields).
Calc(usize),
}
/// Computes a PivotTable report from the workbook.
pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Output, String> {
let src = read_source(wb, &pt.source, pivot_sheet)?;
let fmt_of = |c: usize| src.formats.get(c).cloned().unwrap_or_else(|| "General".into());
let rows: Vec<(usize, &PivotField)> = pt.rows.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect();
let cols: Vec<(usize, &PivotField)> = pt.columns.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect();
let vals: Vec<(usize, &PivotValue)> = pt.values.iter().filter_map(|v| src.col(&v.source_col).map(|c| (c, v))).collect();
// Value fields: a source column, or a calculated field evaluated on sums (see `pivot_calc`).
let calc = CalcSet::new(pt, &src.headers);
let vals: Vec<(ValSrc, &PivotValue)> = pt
.values
.iter()
.filter_map(|v| match src.col(&v.source_col) {
Some(c) => Some((ValSrc::Col(c), v)),
None => calc.index(&v.source_col).map(|i| (ValSrc::Calc(i), v)),
})
.collect();
// Source columns summed for the calculated fields, accumulated after the value fields.
let mut extra: Vec<usize> = Vec::new();
for (vs, _) in &vals {
if let ValSrc::Calc(i) = vs {
for name in calc.source_refs(*i) {
if let Some(c) = src.col(&name)
&& !extra.contains(&c)
{
extra.push(c);
}
}
}
}
if rows.len() + cols.len() > MAX_AXIS_FIELDS {
return Err(format!("A PivotTable can have at most {MAX_AXIS_FIELDS} row and column fields."));
}
@@ -721,8 +777,13 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
}
for a in 0..=rp.len() {
for b in 0..=cp.len() {
let e = aggs.entry((rp[..a].to_vec(), cp[..b].to_vec())).or_insert_with(|| vec![Acc::default(); k]);
for (acc, (c, _)) in e.iter_mut().zip(vals.iter()) {
let e = aggs.entry((rp[..a].to_vec(), cp[..b].to_vec())).or_insert_with(|| vec![Acc::default(); k + extra.len()]);
for (acc, (vs, _)) in e.iter_mut().zip(vals.iter()) {
if let ValSrc::Col(c) = vs {
acc.add(rec.get(*c).unwrap_or(&Value::Empty));
}
}
for (acc, c) in e.iter_mut().skip(k).zip(extra.iter()) {
acc.add(rec.get(*c).unwrap_or(&Value::Empty));
}
}
@@ -748,7 +809,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone() };
let mut lines: Vec<Line> = Vec::new();
if rows.is_empty() {
lines.push(Line { kind: LineKind::Item(false), path: vec![], values: true, labels: vec![] });
lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![] });
} else {
if pt.layout == PivotLayout::Tabular {
ctx.flatten_tabular(&row_tree, 0, &mut Vec::new(), &[], &mut lines);
@@ -756,7 +817,13 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
ctx.flatten(&row_tree, 0, &mut Vec::new(), &mut lines);
}
if pt.grand_totals_cols {
lines.push(Line { kind: LineKind::Grand, path: vec![], values: true, labels: vec![(0, Value::text("Grand Total"), 0, None)] });
lines.push(Line {
kind: LineKind::Grand,
leaf: false,
path: vec![],
values: true,
labels: vec![(0, Value::text("Grand Total"), 0, None)],
});
}
}
let mut specs: Vec<ColSpec> = Vec::new();
@@ -822,7 +889,15 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
if empty {
let r = g.push_row(RowKind::Placeholder)?;
g.set(r, 0, Value::text(format!("{} — choose fields", pt.name)), CellKind::Placeholder, 0, None);
return Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset });
return Ok(Output {
width: g.width as u32,
grid: g.rows,
row_kinds: g.kinds,
body_offset,
chart_rows: vec![],
chart_cols: vec![],
label_col: None,
});
}
let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default();
@@ -908,8 +983,21 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
// ---- body
let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option<Value> {
let (_, v) = vals.get(vi)?;
aggs.get(&(rp.to_vec(), cp.to_vec())).and_then(|a| a.get(vi)).map(|a| a.result(v.func))
let (vs, v) = vals.get(vi)?;
let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?;
match vs {
ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)),
ValSrc::Calc(i) => {
let sum = |name: &str| -> Value {
src.col(name)
.and_then(|c| extra.iter().position(|x| *x == c))
.and_then(|j| accs.get(k + j))
.map(|a| a.result(PivotFunc::Sum))
.unwrap_or(Value::Number(0.0))
};
Some(calc.value(wb, *i, &sum))
}
}
};
let num = |v: &Option<Value>| v.as_ref().and_then(Value::as_f64);
let ratio = |a: Value, b: Option<Value>| -> Value {
@@ -928,7 +1016,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
};
let data_fmt: Vec<Option<String>> = vals
.iter()
.map(|(c, v)| match v.show_as {
.map(|(vs, v)| match v.show_as {
PivotShowAs::PercentOfGrandTotal | PivotShowAs::PercentOfColumnTotal | PivotShowAs::PercentOfRowTotal => {
Some(v.number_format.clone().unwrap_or_else(|| "0.00%".into()))
}
@@ -936,12 +1024,42 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
_ => v.number_format.clone().or_else(|| match v.func {
PivotFunc::Count | PivotFunc::CountNumbers => None,
_ => {
let f = fmt_of(*c);
let f = match vs {
ValSrc::Col(c) => fmt_of(*c),
ValSrc::Calc(_) => "General".to_string(),
};
(f != "General").then_some(f)
}
}),
})
.collect();
let mut chart_rows: Vec<u32> = Vec::new();
let chart_cols: Vec<(u32, String)> = data_cols
.iter()
.enumerate()
.filter_map(|(j, (si, vi))| {
let spec = specs.get(*si)?;
if spec.kind != ColKind::Leaf {
return None;
}
let mut parts: Vec<String> =
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect();
if let Some(vi) = vi
&& (k > 1 || parts.is_empty())
{
parts.push(val_name(*vi));
}
Some(((l + j) as u32, parts.join(" - ")))
})
.filter(|_| k > 0)
.collect();
let label_col = if rows.is_empty() {
None
} else if compact {
Some(0)
} else {
Some(rows.len().saturating_sub(1) as u32)
};
for line in &lines {
let rk = match line.kind {
LineKind::Item(b) => RowKind::Item(b),
@@ -954,6 +1072,9 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
LineKind::Grand => (CellKind::GrandTotal, CellKind::GrandTotal),
};
let r = g.push_row(rk)?;
if line.leaf && k > 0 {
chart_rows.push(r as u32);
}
for (c, v, indent, fmt) in &line.labels {
g.set(r, *c, v.clone(), ck.0, *indent, fmt.clone());
}
@@ -1008,7 +1129,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten());
}
}
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset })
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col })
}
// ---------------------------------------------------------------- styling and writing
@@ -1184,11 +1305,11 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re
}
let shm = wb.sheet_mut(sheet).ok_or("There's no such sheet.")?;
if let Some(old) = pt.last_range {
shm.cells.take_range(old);
shm.take_cells(old);
}
shm.cells.take_range(area);
shm.take_cells(area);
for (c, cell) in cells {
shm.cells.set(c, cell);
shm.set_cell(c, cell);
}
for (col, wpt) in widths {
if wpt > shm.col_width(col) && !shm.is_col_hidden(col) {
@@ -1198,14 +1319,111 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re
if let Some(p) = shm.pivots.get_mut(idx) {
p.last_range = Some(area);
}
let sheet_name = shm.name.clone();
rebind_charts(wb, &sheet_name, &pt.name, origin, &out);
Ok(area)
}
// ---------------------------------------------------------------- PivotCharts
/// The link a PivotChart stores to its PivotTable: `Sheet2!PivotTable1`.
pub fn chart_link(sheet: &str, pivot: &str) -> String {
format!("{}!{pivot}", quote_sheet(sheet))
}
/// (sheet, PivotTable name) of a PivotChart link; a leading `[Book.xlsx]` is ignored.
pub fn parse_chart_link(link: &str) -> Option<(String, String)> {
let t = link.trim();
let t = match t.strip_prefix('[') {
Some(rest) => rest.split_once(']').map(|(_, r)| r).unwrap_or(rest),
None => t,
};
let (sheet, name) = t.rsplit_once('!')?;
let sheet = sheet.trim();
let sheet = sheet.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')).map(|x| x.replace("''", "'")).unwrap_or_else(|| sheet.to_string());
let name = name.trim();
if sheet.is_empty() || name.is_empty() {
return None;
}
Some((sheet, name.to_string()))
}
/// Whether a PivotChart link points at `pivot` on `sheet`.
pub fn links_to(link: &str, sheet: &str, pivot: &str) -> bool {
parse_chart_link(link).is_some_and(|(s, n)| s.eq_ignore_ascii_case(sheet) && n.eq_ignore_ascii_case(pivot))
}
/// An absolute reference to `col` over grid `rows` (contiguous runs joined into a union).
fn rows_ref(sheet: &str, origin: CellRef, col: u32, rows: &[u32]) -> Option<String> {
let q = quote_sheet(sheet);
let c = origin.col.checked_add(col)?;
let letters = gridcraft_core::col_to_letters(c);
let mut parts: Vec<String> = Vec::new();
let mut i = 0;
while let Some(&start) = rows.get(i) {
let mut end = start;
while rows.get(i + 1).is_some_and(|n| Some(*n) == end.checked_add(1)) {
end += 1;
i += 1;
}
i += 1;
let (a, b) = (origin.row.checked_add(start)? + 1, origin.row.checked_add(end)? + 1);
parts.push(if a == b { format!("{q}!${letters}${a}") } else { format!("{q}!${letters}${a}:${letters}${b}") });
}
match parts.len() {
0 => None,
1 => parts.pop(),
_ => Some(format!("({})", parts.join(","))),
}
}
/// Most category rows a PivotChart plots.
const MAX_CHART_ROWS: usize = 10_000;
/// A PivotChart's series for a report written at `origin`: categories are the innermost row
/// items, one series per item column (column items × value fields); totals are left out.
pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec<Series> {
let rows: Vec<u32> = out.chart_rows.iter().copied().take(MAX_CHART_ROWS).collect();
let categories = out.label_col.and_then(|c| rows_ref(sheet, origin, c, &rows));
out.chart_cols
.iter()
.filter_map(|(c, name)| {
Some(Series {
name: Some(format!("\"{}\"", name.replace('"', "\"\""))),
categories: categories.clone(),
values: rows_ref(sheet, origin, *c, &rows)?,
bubble_sizes: None,
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
})
})
.collect()
}
/// Rebuilds the series of every PivotChart of a PivotTable after its report was written.
fn rebind_charts(wb: &mut Workbook, sheet: &str, pivot: &str, origin: CellRef, out: &Output) {
let linked = |ch: &Chart| ch.pivot.as_deref().is_some_and(|l| links_to(l, sheet, pivot));
let hits: Vec<usize> = (0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|sh| sh.charts.iter().any(linked))).collect();
if hits.is_empty() {
return;
}
let series = chart_series(sheet, origin, out);
for i in hits {
let Some(sh) = wb.sheet_mut(i) else { continue };
for ch in sh.charts.iter_mut().filter(|c| linked(c)) {
ch.series = series.clone();
}
}
}
/// Clears a pivot's last output area.
pub fn clear_output(wb: &mut Workbook, sheet: usize, idx: usize) {
let Some(shm) = wb.sheet_mut(sheet) else { return };
let Some(r) = shm.pivots.get(idx).and_then(|p| p.last_range) else { return };
shm.cells.take_range(r);
shm.take_cells(r);
if let Some(p) = shm.pivots.get_mut(idx) {
p.last_range = None;
}
+362
View File
@@ -0,0 +1,362 @@
//! Calculated PivotTable fields: a formula over other fields (`=Sales*0.1`,
//! `='Unit Price'*Units`, `=IF(Units>0,Sales/Units,0)`).
//!
//! As Microsoft documents for Excel, the formula operates on the *sums* of the fields it names
//! for each report cell (items, subtotals and grand totals alike), not record by record: for
//! `=Sales*1.2` a cell shows 1.2 × the sum of Sales of that cell's records. Fields are written
//! bare (`Sales`) or in single quotes (`'Unit Price'`); cell references and defined names are not
//! allowed. A calculated field may use other calculated fields; a cycle evaluates to `#REF!`.
use gridcraft_core::{CellError, CellRef, Value};
use gridcraft_formula::Expr;
use gridcraft_model::{PivotTable, Workbook};
/// Longest formula accepted.
pub const MAX_FORMULA_LEN: usize = 8_192;
/// Most calculated fields per PivotTable.
pub const MAX_CALC_FIELDS: usize = 256;
/// Deepest chain of calculated fields using calculated fields.
const MAX_DEPTH: usize = 64;
const PREFIX: &str = "__pcf";
fn placeholder(i: usize) -> String {
format!("{PREFIX}{i}")
}
/// A parsed formula: field names replaced by placeholder names `__pcf0`, `__pcf1`, … in the
/// order of `refs`.
#[derive(Clone, Debug)]
pub struct Compiled {
pub body: Expr,
/// Canonical names of the fields used.
pub refs: Vec<String>,
}
/// Parses a calculated-field formula. `field` maps a written name to the canonical name of a
/// source or calculated field.
pub fn compile(formula: &str, field: &dyn Fn(&str) -> Option<String>) -> Result<Compiled, String> {
let text = formula.trim();
let text = text.strip_prefix('=').unwrap_or(text).trim();
if text.is_empty() {
return Err("The formula is empty.".into());
}
if text.len() > MAX_FORMULA_LEN {
return Err("The formula is too long.".into());
}
let chars: Vec<char> = text.chars().collect();
let at = |i: usize| chars.get(i).copied();
let mut out = String::with_capacity(text.len() + 16);
let mut refs: Vec<String> = Vec::new();
let slot = |name: String, refs: &mut Vec<String>| -> String {
let i = refs.iter().position(|r| r.eq_ignore_ascii_case(&name)).unwrap_or_else(|| {
refs.push(name);
refs.len() - 1
});
placeholder(i)
};
let mut i = 0;
while let Some(c) = at(i) {
match c {
'"' => {
out.push('"');
i += 1;
loop {
match at(i) {
None => return Err("The formula has an unterminated text value.".into()),
Some('"') if at(i + 1) == Some('"') => {
out.push_str("\"\"");
i += 2;
}
Some('"') => {
out.push('"');
i += 1;
break;
}
Some(x) => {
out.push(x);
i += 1;
}
}
}
}
'\'' => {
let mut name = String::new();
i += 1;
loop {
match at(i) {
None => return Err("The formula has an unterminated field name.".into()),
Some('\'') if at(i + 1) == Some('\'') => {
name.push('\'');
i += 2;
}
Some('\'') => {
i += 1;
break;
}
Some(x) => {
name.push(x);
i += 1;
}
}
}
let canon = field(&name).ok_or_else(|| format!("There's no field named '{name}'."))?;
out.push_str(&slot(canon, &mut refs));
}
c if c.is_ascii_digit() || (c == '.' && at(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
while at(i).is_some_and(|d| d.is_ascii_digit() || d == '.') {
out.push(at(i).unwrap_or('0'));
i += 1;
}
if matches!(at(i), Some('e' | 'E')) {
let sign = usize::from(matches!(at(i + 1), Some('+' | '-')));
if at(i + 1 + sign).is_some_and(|d| d.is_ascii_digit()) {
for _ in 0..=sign {
out.push(at(i).unwrap_or('0'));
i += 1;
}
while at(i).is_some_and(|d| d.is_ascii_digit()) {
out.push(at(i).unwrap_or('0'));
i += 1;
}
}
}
}
c if c.is_alphabetic() || c == '_' => {
let start = i;
while at(i).is_some_and(|d| d.is_alphanumeric() || d == '_' || d == '.') {
i += 1;
}
let word: String = chars.get(start..i).map(|w| w.iter().collect()).unwrap_or_default();
let mut j = i;
while at(j).is_some_and(char::is_whitespace) {
j += 1;
}
let is_call = at(j) == Some('(');
match field(&word) {
Some(canon) if !is_call => out.push_str(&slot(canon, &mut refs)),
_ => out.push_str(&word),
}
}
c => {
out.push(c);
i += 1;
}
}
}
let body = gridcraft_formula::parse(&out).map_err(|_| "The formula contains an error.".to_string())?;
let mut problem: Option<String> = None;
body.walk(&mut |e| {
if problem.is_some() {
return;
}
match e {
Expr::Name(n) if n.starts_with(PREFIX) => {}
Expr::Name(n) => problem = Some(format!("There's no field named '{n}'.")),
Expr::Ref(_) | Expr::Struct(_) => problem = Some("A calculated field can't refer to cells or tables; use field names.".into()),
_ => {}
}
});
match problem {
Some(p) => Err(p),
None => Ok(Compiled { body, refs }),
}
}
fn literal(v: &Value) -> Expr {
match v {
Value::Number(n) => Expr::Number(*n),
Value::Error(e) => Expr::Error(*e),
Value::Text(t) => Expr::Text(t.clone()),
Value::Bool(b) => Expr::Bool(*b),
Value::Empty => Expr::Number(0.0),
Value::Array(_) => literal(&v.scalar()),
}
}
/// Evaluates a compiled formula with the given field values (in `refs` order).
pub fn eval(wb: &Workbook, c: &Compiled, args: &[Value]) -> Value {
let expr = if c.refs.is_empty() {
c.body.clone()
} else {
let mut call = Vec::with_capacity(c.refs.len() * 2 + 1);
for i in 0..c.refs.len() {
call.push(Expr::Name(placeholder(i)));
call.push(literal(args.get(i).unwrap_or(&Value::Empty)));
}
call.push(c.body.clone());
Expr::Call("LET".into(), call)
};
match gridcraft_calc::recalc::evaluate_expr(wb, 0, CellRef::default(), &expr).scalar() {
Value::Empty => Value::Number(0.0),
v => v,
}
}
/// A PivotTable's calculated fields, compiled against its source headers.
pub struct CalcSet {
names: Vec<String>,
compiled: Vec<Result<Compiled, String>>,
}
impl CalcSet {
pub fn new(pt: &PivotTable, headers: &[String]) -> CalcSet {
let names: Vec<String> = pt.calculated_fields.iter().take(MAX_CALC_FIELDS).map(|c| c.name.clone()).collect();
let lookup = |n: &str| -> Option<String> {
let n = n.trim();
headers.iter().chain(names.iter()).find(|h| h.trim().eq_ignore_ascii_case(n)).cloned()
};
let compiled = pt.calculated_fields.iter().take(MAX_CALC_FIELDS).map(|c| compile(&c.formula, &lookup)).collect();
CalcSet { names, compiled }
}
pub fn index(&self, name: &str) -> Option<usize> {
self.names.iter().position(|n| n.eq_ignore_ascii_case(name.trim()))
}
/// The compile error of a calculated field, if any.
pub fn error(&self, i: usize) -> Option<&str> {
self.compiled.get(i).and_then(|c| c.as_ref().err()).map(String::as_str)
}
/// Source fields a calculated field needs, directly or through other calculated fields.
pub fn source_refs(&self, i: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut seen = vec![false; self.names.len()];
let mut stack = vec![i];
while let Some(j) = stack.pop() {
if !seen.get(j).copied().unwrap_or(true) {
if let Some(s) = seen.get_mut(j) {
*s = true;
}
if let Some(Ok(c)) = self.compiled.get(j) {
for r in &c.refs {
match self.index(r) {
Some(k) => stack.push(k),
None => {
if !out.iter().any(|o| o.eq_ignore_ascii_case(r)) {
out.push(r.clone());
}
}
}
}
}
}
}
out
}
/// Whether a calculated field reaches itself through the fields it uses.
pub fn is_cyclic(&self, i: usize) -> bool {
let mut seen = vec![false; self.names.len()];
let mut stack: Vec<usize> = match self.compiled.get(i) {
Some(Ok(c)) => c.refs.iter().filter_map(|r| self.index(r)).collect(),
_ => vec![],
};
while let Some(j) = stack.pop() {
if j == i {
return true;
}
if seen.get(j).copied().unwrap_or(true) {
continue;
}
if let Some(s) = seen.get_mut(j) {
*s = true;
}
if let Some(Ok(c)) = self.compiled.get(j) {
stack.extend(c.refs.iter().filter_map(|r| self.index(r)));
}
}
false
}
/// The value of calculated field `i` for one report cell; `sum` gives a source field's sum
/// over that cell's records.
pub fn value(&self, wb: &Workbook, i: usize, sum: &dyn Fn(&str) -> Value) -> Value {
let mut memo: Vec<Option<Value>> = vec![None; self.names.len()];
let mut active = vec![false; self.names.len()];
self.value_in(wb, i, sum, &mut memo, &mut active, 0)
}
fn value_in(&self, wb: &Workbook, i: usize, sum: &dyn Fn(&str) -> Value, memo: &mut [Option<Value>], active: &mut [bool], depth: usize) -> Value {
if let Some(Some(v)) = memo.get(i) {
return v.clone();
}
if depth > MAX_DEPTH || active.get(i).copied().unwrap_or(true) {
return Value::Error(CellError::Ref);
}
let Some(Ok(c)) = self.compiled.get(i) else { return Value::Error(CellError::Name) };
if let Some(a) = active.get_mut(i) {
*a = true;
}
let args: Vec<Value> = c
.refs
.iter()
.map(|r| match self.index(r) {
Some(j) => self.value_in(wb, j, sum, memo, active, depth + 1),
None => sum(r),
})
.collect();
let v = eval(wb, c, &args);
if let Some(a) = active.get_mut(i) {
*a = false;
}
if let Some(m) = memo.get_mut(i) {
*m = Some(v.clone());
}
v
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fields(n: &str) -> Option<String> {
["Sales", "Units", "Unit Price", "Q1"].iter().find(|f| f.eq_ignore_ascii_case(n)).map(|f| f.to_string())
}
#[test]
fn compiles_field_names() {
let c = compile("= Sales*0.1 + 'Unit Price'/units - Sales", &fields).unwrap();
assert_eq!(c.refs, vec!["Sales", "Unit Price", "Units"]);
// A field named like a cell reference is still a field; functions stay functions.
let c = compile("=ROUND(Q1*1.5E2,0)", &fields).unwrap();
assert_eq!(c.refs, vec!["Q1"]);
let wb = Workbook::new();
assert_eq!(eval(&wb, &c, &[Value::Number(2.0)]), Value::Number(300.0));
assert!(compile("=Sales*Bogus", &fields).unwrap_err().contains("Bogus"));
assert!(compile("=A1*2", &fields).is_err());
assert!(compile("='Nope'*2", &fields).is_err());
assert!(compile("=Sales*(", &fields).is_err());
assert!(compile("=", &fields).is_err());
assert!(compile(&format!("={}", "1+".repeat(MAX_FORMULA_LEN)), &fields).is_err());
}
#[test]
fn deep_and_cyclic_chains_are_bounded() {
// 300 calculated fields, each using the previous one, and a two-field cycle.
let mut pt = PivotTable::default();
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "C0".into(), formula: "=Sales+1".into() });
for i in 1..300 {
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: format!("C{i}"), formula: format!("=C{}+1", i - 1) });
}
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "P".into(), formula: "=Q".into() });
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "Q".into(), formula: "=P*2".into() });
let set = CalcSet::new(&pt, &["Sales".to_string()]);
let wb = Workbook::new();
let sum = |_: &str| Value::Number(10.0);
assert_eq!(set.value(&wb, 0, &sum), Value::Number(11.0));
assert_eq!(set.value(&wb, 10, &sum), Value::Number(21.0));
// Past the depth bound (the list itself is capped at MAX_CALC_FIELDS).
assert_eq!(set.value(&wb, 200, &sum), Value::Error(CellError::Ref));
assert_eq!(set.index("P"), None, "P is past the cap of {MAX_CALC_FIELDS} fields");
// A small cycle within the cap.
let mut small = PivotTable::default();
small.calculated_fields.push(gridcraft_model::PivotCalcField { name: "P".into(), formula: "=Q".into() });
small.calculated_fields.push(gridcraft_model::PivotCalcField { name: "Q".into(), formula: "=P*2".into() });
let set = CalcSet::new(&small, &["Sales".to_string()]);
assert!(set.is_cyclic(0));
assert_eq!(set.value(&wb, 0, &sum), Value::Error(CellError::Ref));
assert_eq!(set.source_refs(0), Vec::<String>::new());
}
}
+2
View File
@@ -108,6 +108,8 @@ fn sales(s: &mut Session) -> bool {
color: None,
secondary: false,
kind: None,
smooth: false,
trendlines: Vec::new(),
}];
}
}
+36 -27
View File
@@ -119,6 +119,10 @@ impl Selection {
/// Ctrl+arrow: jump to the edge of the current data region (Excel's End mode).
pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef {
if dr == 0 && dc == 0 {
// No direction: nowhere to go (the search below would never advance).
return from;
}
let filled = |c: CellRef| sheet.value_ref(c).is_some_and(|v| !v.is_empty());
let Some(mut cur) = from.offset(dr, dc) else { return from };
let here = filled(from);
@@ -175,38 +179,34 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef {
/// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables).
pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef {
let filled = |c: CellRef| sheet.value_ref(c).is_some_and(|v| !v.is_empty());
let mut r = RangeRef::cell(c);
for _ in 0..10_000 {
let mut grown = r;
let r0 = r.start.row.saturating_sub(1);
let r1 = (r.end.row + 1).min(MAX_ROWS - 1);
let c0 = r.start.col.saturating_sub(1);
let c1 = (r.end.col + 1).min(MAX_COLS - 1);
// Check the ring around r.
let ring = RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1));
let mut any = false;
for (cc, cell) in sheet.cells.iter_range(ring) {
if !r.contains(cc) && (!cell.value.is_empty() || cell.formula.is_some()) {
grown = grown.union(&RangeRef::cell(cc));
any = true;
}
let filled = |c: CellRef| sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c);
// Whether a row (or column) has a filled cell between two columns (rows), inclusive.
let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col)));
let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col)));
let (mut r0, mut r1, mut c0, mut c1) = (c.row, c.row, c.col, c.col);
// Grow one side at a time while the line next to it (diagonals included) has data. Each
// pass scans only the lines next to the region, so tall regions take linear time.
loop {
let before = (r0, r1, c0, c1);
let (lo_c, hi_c) = (c0.saturating_sub(1), (c1 + 1).min(MAX_COLS - 1));
while r0 > 0 && row_has(r0 - 1, lo_c, hi_c) {
r0 -= 1;
}
for (cc, _) in sheet.spill.range(CellRef::new(r0, 0)..=CellRef::new(r1, MAX_COLS - 1)) {
if ring.contains(*cc) && !r.contains(*cc) {
grown = grown.union(&RangeRef::cell(*cc));
any = true;
}
while r1 + 1 < MAX_ROWS && row_has(r1 + 1, lo_c, hi_c) {
r1 += 1;
}
if !any || grown == r {
let (lo_r, hi_r) = (r0.saturating_sub(1), (r1 + 1).min(MAX_ROWS - 1));
while c0 > 0 && col_has(c0 - 1, lo_r, hi_r) {
c0 -= 1;
}
while c1 + 1 < MAX_COLS && col_has(c1 + 1, lo_r, hi_r) {
c1 += 1;
}
if (r0, r1, c0, c1) == before {
break;
}
r = grown;
}
if r.is_single() && !filled(c) {
return RangeRef::cell(c);
}
r
RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1))
}
#[cfg(test)]
@@ -222,6 +222,8 @@ mod tests {
}
s.set_value(CellRef::new(10, 0), Value::Number(1.0));
assert_eq!(jump(&s, CellRef::new(0, 0), 1, 0), CellRef::new(4, 0));
// Without a direction it stays put (it used to loop forever from a blank cell).
assert_eq!(jump(&s, CellRef::new(7, 0), 0, 0), CellRef::new(7, 0));
assert_eq!(jump(&s, CellRef::new(4, 0), 1, 0), CellRef::new(10, 0));
assert_eq!(jump(&s, CellRef::new(10, 0), 1, 0), CellRef::new(MAX_ROWS - 1, 0));
assert_eq!(jump(&s, CellRef::new(0, 0), 0, 1), CellRef::new(0, MAX_COLS - 1));
@@ -239,6 +241,13 @@ mod tests {
assert_eq!(current_region(&s, CellRef::new(3, 2)).a1(), "B3:D5");
assert_eq!(current_region(&s, CellRef::new(5, 4)).a1(), "B3:E6");
assert_eq!(current_region(&s, CellRef::new(20, 20)).a1(), "U21");
// Taller than 10,000 rows: it used to stop growing after 10,000 steps.
let mut s = Sheet::new("S");
for r in 0..20_000 {
s.set_value(CellRef::new(r, 0), Value::Number(r as f64));
s.set_value(CellRef::new(r, 1), Value::Number(1.0));
}
assert_eq!(current_region(&s, CellRef::new(5, 0)).a1(), "A1:B20000");
}
#[test]
+162 -2
View File
@@ -1,7 +1,7 @@
//! Table styles: how a cell inside a table looks (our own palettes, keyed by the familiar
//! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip).
use gridcraft_core::CellRef;
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_model::*;
/// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2).
@@ -9,7 +9,7 @@ pub fn parse_style_name(name: &str) -> (&'static str, u32) {
let rest = name.strip_prefix("TableStyle").unwrap_or(name);
for fam in ["Light", "Medium", "Dark"] {
if let Some(n) = rest.strip_prefix(fam) {
let k = n.parse().unwrap_or(2);
let k = n.parse::<u32>().unwrap_or(2).max(1); // the gallery starts at 1; 0 would underflow `n - 1`
return (fam, k);
}
}
@@ -147,3 +147,163 @@ pub fn gallery() -> Vec<String> {
}
v
}
/// Editing a table's header row renames the column, as in Excel: an empty or repeated header
/// gets a unique name written back into the cell, and structured references follow the rename.
pub(crate) fn sync_headers(cx: &mut crate::cmd::Ctx) {
if cx.wb.sheets.iter().all(|s| s.tables.is_empty()) {
return;
}
// (sheet, table name, table range, old column name, new column name)
let mut renames: Vec<(usize, String, RangeRef, String, String)> = Vec::new();
let heads: Vec<(usize, RangeRef)> = (0..cx.wb.sheets.len())
.flat_map(|si| cx.wb.sheet(si).into_iter().flat_map(move |sh| sh.tables.iter().filter(|t| t.header_row).map(move |t| (si, t.range))))
.map(|(si, r)| (si, RangeRef::new(r.start, CellRef::new(r.start.row, r.end.col))))
.collect();
// A structural edit can move anything into a header row: then every header is checked.
let changed: std::collections::BTreeSet<(usize, CellRef)> = if cx.structural {
heads.iter().flat_map(|(s, r)| r.iter().map(move |c| (*s, c))).collect()
} else {
cx.changed.iter().filter(|(si, c)| heads.iter().any(|(s, r)| s == si && r.contains(*c))).copied().collect()
};
// Per table: lower-case column name → column, and the next number to try for a repeated name
// (both kept up to date, so a wide header row stays linear).
type Names = (std::collections::HashMap<String, usize>, std::collections::HashMap<String, usize>);
let mut names: std::collections::HashMap<(usize, usize), Names> = std::collections::HashMap::new();
for (si, c) in changed {
let Some(sh) = cx.wb.sheet(si) else { continue };
let Some(ti) = sh.tables.iter().position(|t| t.header_row && c.row == t.range.start.row && t.range.contains(c)) else { continue };
let Some(t) = sh.tables.get(ti) else { continue };
let col = (c.col - t.range.start.col) as usize;
let Some(old) = t.columns.get(col).map(|x| x.name.clone()) else { continue };
// A text header names its column as it is: a number format only changes how it looks (an
// accounting format pads text with spaces), and the file writes the name into the cell.
let value = sh.value(c);
let text = match value.as_text() {
Some(t) => t.to_string(),
None => crate::display::cell_text(&cx.wb, sh, c),
};
// Headers hold constant text: a formula (or a spilled value) there becomes its text.
let is_text = value.is_text() && sh.cell(c).is_some_and(|x| x.formula.is_none());
if text == old && is_text {
continue;
}
let (taken, next) = names
.entry((si, ti))
.or_insert_with(|| (t.columns.iter().enumerate().map(|(i, x)| (x.name.to_lowercase(), i)).collect(), Default::default()));
if taken.get(&old.to_lowercase()) == Some(&col) {
taken.remove(&old.to_lowercase());
}
let base = if text.trim().is_empty() { format!("Column{}", col + 1) } else { text.clone() };
let k = next.entry(base.to_lowercase()).or_insert(2);
let mut name = base.clone();
while taken.contains_key(&name.to_lowercase()) {
name = format!("{base}{k}");
*k += 1;
}
taken.insert(name.to_lowercase(), col);
let (table, range) = (t.name.clone(), t.range);
let Some(sh) = cx.wb.sheet_mut(si) else { continue };
if let Some(x) = sh.tables.get_mut(ti).and_then(|t| t.columns.get_mut(col)) {
x.name = name.clone();
}
// Headers are text: a number typed there, or a generated name, is written back as text.
if name != text || !is_text {
let style = sh.style_id(c);
sh.cells.set(c, Cell { value: gridcraft_core::Value::text(name.as_str()), style, ..Default::default() });
}
if !old.eq_ignore_ascii_case(&name) {
renames.push((si, table, range, old, name));
}
}
if renames.is_empty() {
return;
}
// Structured references follow the new names.
for i in 0..cx.wb.sheets.len() {
let formulas: Vec<(CellRef, std::sync::Arc<Formula>)> =
cx.wb.sheets.get(i).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
for (c, f) in formulas {
let Some(e) = f.expr() else { continue };
let mut hit = false;
let ne = e.map(&mut |x| match x {
gridcraft_formula::Expr::Struct(mut st) => {
for (si, table, range, old, name) in &renames {
let this = if st.table.is_empty() { i == *si && range.contains(c) } else { st.table.eq_ignore_ascii_case(table) };
if this {
for end in [&mut st.col_start, &mut st.col_end].into_iter().flatten() {
if end.eq_ignore_ascii_case(old) {
*end = name.clone();
hit = true;
}
}
}
}
gridcraft_formula::Expr::Struct(st)
}
o => o,
});
if hit && let Some(cell) = cx.wb.sheet_mut(i).and_then(|s| s.cells.get_mut(c)) {
cell.formula = Some(std::sync::Arc::new(Formula::from_expr(ne)));
}
}
}
cx.structural = true;
}
#[cfg(test)]
mod tests {
use gridcraft_core::Value;
use serde_json::json;
use crate::Session;
#[test]
fn editing_a_header_renames_the_column() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c"], [1, 2, 3]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:C2", "header": true})).unwrap();
s.execute("cell.set", json!({"cell": "E1", "input": "=SUM(Table1[a])"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "zz"})).unwrap();
s.execute("edit.clearContents", json!({"range": "B1"})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": "ZZ"})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
assert_eq!(get(&mut s, "E1")["formula"], "=SUM(Table1[zz])");
assert_eq!(get(&mut s, "E1")["value"], json!(1.0));
let d = s.doc().unwrap();
let sh = d.wb.sheet(0).unwrap();
let names: Vec<&str> = sh.tables[0].columns.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["zz", "Column2", "ZZ2"]);
assert_eq!(sh.value(gridcraft_core::CellRef::new(0, 1)), Value::from("Column2"));
assert_eq!(sh.value(gridcraft_core::CellRef::new(0, 2)), Value::from("ZZ2"));
s.execute("range.setValues", json!({"range": "A1", "values": [["x", "x", 5]]})).unwrap();
let sh = s.doc().unwrap().wb.sheet(0).unwrap();
let names: Vec<&str> = sh.tables[0].columns.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["x", "x2", "5"]);
assert_eq!(sh.value(gridcraft_core::CellRef::new(0, 2)), Value::from("5"));
}
#[test]
fn go_to_a_table_selects_its_data() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b"], [1, 2], [3, 4]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:B3", "header": true})).unwrap();
assert_eq!(s.execute("edit.goTo", json!({"reference": "Table1"})).unwrap()["selection"], "A2:B3");
}
}
#[cfg(test)]
mod style_tests {
use super::*;
#[test]
fn zero_numbered_styles_do_not_underflow() {
assert_eq!(parse_style_name("TableStyleLight0"), ("Light", 1));
assert_eq!(parse_style_name("TableStyleMedium0"), ("Medium", 1));
for name in ["TableStyleLight0", "TableStyleMedium0", "TableStyleDark0"] {
let _ = look(name);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,102 @@
use gridcraft_core::CellRef;
use gridcraft_engine::Session;
use serde_json::json;
fn table() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap();
s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap();
s
}
fn fit(s: &mut Session) -> f32 {
s.execute("home.autofitColumnWidth", json!({"cols":"A:A"})).unwrap();
s.doc().unwrap().wb.active().unwrap().col_width(0)
}
#[test]
fn autofit_reserves_room_for_table_filter_button() {
let mut s = table();
s.execute("selection.set", json!({"cell":"A1"})).unwrap();
s.execute("data.filter", json!({})).unwrap();
let plain = fit(&mut s);
s.execute("data.filter", json!({})).unwrap();
let filtered = fit(&mut s);
assert!(filtered >= plain + 16.0, "filter button obscures heading: plain={plain}, filtered={filtered}");
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)).display(), "Quarterly Revenue");
}
fn sheet_mut(s: &mut Session) -> &mut gridcraft_engine::model::Sheet {
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb).sheet_mut(0).unwrap()
}
#[test]
fn autofit_skips_disabled_buttons_and_hidden_table_headers() {
let mut s = table();
sheet_mut(&mut s).tables[0].filter_button = false;
let plain = fit(&mut s);
sheet_mut(&mut s).tables[0].filter_button = true;
sheet_mut(&mut s).tables[0].header_row = false;
assert_eq!(fit(&mut s), plain);
sheet_mut(&mut s).tables[0].header_row = true;
assert!(fit(&mut s) > plain);
}
#[test]
fn autofit_matches_excel_filter_allowance_across_zoom_and_row_heights() {
for (zoom, allowance) in [(50, 12.5 * 96.0 / 72.0 * 2.0), (100, 12.5 * 96.0 / 72.0), (200, 12.5 * 96.0 / 72.0)] {
for height in [12.0_f32, 20.0, 60.0] {
let mut s = table();
s.execute("view.zoom", json!({"percent":zoom})).unwrap();
s.execute("home.rowHeight", json!({"rows":"1:1", "height":height})).unwrap();
sheet_mut(&mut s).tables[0].filter_button = false;
let plain = fit(&mut s);
sheet_mut(&mut s).tables[0].filter_button = true;
let filtered = fit(&mut s);
assert!((filtered - plain - allowance).abs() < 1.0, "zoom={zoom}, height={height}, plain={plain}, filtered={filtered}");
}
}
}
#[test]
fn autofit_supports_ordinary_autofilters_without_double_counting_table_buttons() {
let mut s = table();
let table_width = fit(&mut s);
sheet_mut(&mut s).autofilter =
Some(gridcraft_engine::model::AutoFilter { range: gridcraft_engine::core::RangeRef::parse("A1:A2").unwrap(), criteria: vec![] });
assert_eq!(fit(&mut s), table_width, "overlapping filters occupy one button slot");
sheet_mut(&mut s).tables.clear();
assert_eq!(fit(&mut s), table_width, "ordinary filter headers reserve the same space");
sheet_mut(&mut s).autofilter = None;
assert!(fit(&mut s) < table_width);
}
#[test]
fn autofit_leaves_longer_body_cells_and_unfiltered_columns_unchanged() {
let mut s = table();
s.execute("cell.set", json!({"cell":"A2", "input":"A body value much longer than the short table header above"})).unwrap();
let filtered = fit(&mut s);
sheet_mut(&mut s).tables[0].filter_button = false;
assert_eq!(fit(&mut s), filtered);
s.execute("cell.set", json!({"cell":"B1", "input":"Quarterly Revenue"})).unwrap();
s.execute("home.autofitColumnWidth", json!({"cols":"B:B"})).unwrap();
let plain = s.doc().unwrap().wb.active().unwrap().col_width(1);
sheet_mut(&mut s).tables[0].filter_button = true;
s.execute("home.autofitColumnWidth", json!({"cols":"B:B"})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(1), plain);
}
#[test]
fn autofit_filter_width_is_undoable_without_changing_selection() {
let mut s = table();
s.execute("home.columnWidth", json!({"cols":"A:A", "width":80})).unwrap();
s.execute("selection.set", json!({"range":"A:A"})).unwrap();
let selection = s.doc().unwrap().selection.clone();
s.active_mut().unwrap().undo.clear();
fit(&mut s);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(s.doc().unwrap().undo.len(), 1);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(0), 80.0);
}
File diff suppressed because it is too large Load Diff
+146
View File
@@ -0,0 +1,146 @@
use gridcraft_core::{CellRef, Value};
use gridcraft_engine::Session;
use serde_json::{Value as Json, json};
fn workbook() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn run(s: &mut Session, command: &str, params: Json) {
s.execute(command, params).unwrap();
}
fn set(s: &mut Session, cell: &str, input: &str) {
run(s, "cell.set", json!({"cell": cell, "input": input}));
}
fn activate(s: &mut Session, sheet: &str) {
run(s, "sheet.activate", json!({"sheet": sheet}));
}
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())
}
fn formula(s: &Session, sheet: &str, cell: &str) -> String {
let wb = &s.doc().unwrap().wb;
wb.sheet(wb.sheet_index(sheet).unwrap()).unwrap().cell(CellRef::parse(cell).unwrap()).unwrap().formula.as_ref().unwrap().text.clone()
}
fn cut_to(s: &mut Session, source: &str, range: &str, destination: &str, at: &str) {
activate(s, source);
run(s, "edit.cut", json!({"range": range}));
activate(s, destination);
run(s, "edit.paste", json!({"at": at}));
}
#[test]
fn cross_sheet_cut_preserves_total_through_undo_redo_and_xlsx() {
let mut s = workbook();
run(&mut s, "range.setValues", json!({"range": "A1", "values": [[10], [20]]}));
set(&mut s, "B1", "=SUM(A1:A2)");
run(&mut s, "home.insertSheet", json!({"name": "Sheet2"}));
cut_to(&mut s, "Sheet1", "A1:A2", "Sheet2", "C3");
let assert_moved = |s: &Session| {
assert_eq!(value(s, "Sheet1", "A1"), Value::Empty);
assert_eq!(value(s, "Sheet1", "A2"), Value::Empty);
assert_eq!(value(s, "Sheet2", "C3"), Value::Number(10.0));
assert_eq!(value(s, "Sheet2", "C4"), Value::Number(20.0));
assert_eq!(value(s, "Sheet1", "B1"), Value::Number(30.0));
assert_eq!(formula(s, "Sheet1", "B1"), "SUM(Sheet2!C3:C4)");
};
assert_moved(&s);
run(&mut s, "edit.undo", json!({}));
assert_eq!(value(&s, "Sheet1", "A1"), Value::Number(10.0));
assert_eq!(value(&s, "Sheet1", "A2"), Value::Number(20.0));
assert_eq!(value(&s, "Sheet2", "C3"), Value::Empty);
assert_eq!(value(&s, "Sheet2", "C4"), Value::Empty);
assert_eq!(value(&s, "Sheet1", "B1"), Value::Number(30.0));
assert_eq!(formula(&s, "Sheet1", "B1"), "SUM(A1:A2)");
run(&mut s, "edit.redo", json!({}));
assert_moved(&s);
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
run(&mut s, "file.open", json!({"name": "moved.xlsx", "base64": saved["base64"]}));
assert_moved(&s);
}
#[test]
fn references_on_all_sheets_follow_cut_but_destination_local_refs_do_not() {
let mut s = workbook();
run(&mut s, "sheet.rename", json!({"name": "Source Data"}));
run(&mut s, "range.setValues", json!({"range": "A1", "values": [[10], [20]]}));
set(&mut s, "B1", "=SUM($A$1:$A$2)");
run(&mut s, "formulas.defineName", json!({"name": "MovedData", "refersTo": "='Source Data'!$A$1:$A$2"}));
run(&mut s, "home.insertSheet", json!({"name": "Target's Data"}));
run(&mut s, "range.setValues", json!({"range": "A1", "values": [[100], [200]]}));
set(&mut s, "B1", "=SUM('Source Data'!$A$1:$A$2)");
set(&mut s, "B2", "=SUM(A1:A2)");
run(&mut s, "home.insertSheet", json!({"name": "Summary"}));
set(&mut s, "A1", "='Source Data'!$A$1+'Source Data'!A$2");
set(&mut s, "A2", "=SUM(MovedData)");
cut_to(&mut s, "Source Data", "A1:A2", "Target's Data", "C3");
for (sheet, cell) in [("Source Data", "B1"), ("Target's Data", "B1"), ("Summary", "A1"), ("Summary", "A2")] {
assert_eq!(value(&s, sheet, cell), Value::Number(30.0), "{sheet}!{cell}");
}
assert_eq!(formula(&s, "Source Data", "B1"), "SUM('Target''s Data'!$C$3:$C$4)");
assert_eq!(formula(&s, "Summary", "A1"), "'Target''s Data'!$C$3+'Target''s Data'!C$4");
assert_eq!(value(&s, "Target's Data", "B2"), Value::Number(300.0));
assert_eq!(formula(&s, "Target's Data", "B2"), "SUM(A1:A2)");
// Recalculation must keep tracking the destination after the move, not just retain a cache.
activate(&mut s, "Target's Data");
set(&mut s, "C3", "40");
for (sheet, cell) in [("Source Data", "B1"), ("Target's Data", "B1"), ("Summary", "A1"), ("Summary", "A2")] {
assert_eq!(value(&s, sheet, cell), Value::Number(60.0), "{sheet}!{cell}");
}
}
#[test]
fn moved_formulas_keep_external_source_refs_and_move_internal_refs_once() {
let mut s = workbook();
run(&mut s, "sheet.rename", json!({"name": "Source Data"}));
set(&mut s, "A1", "10");
set(&mut s, "D1", "7");
set(&mut s, "A2", "=$A$1+$D$1+'Source Data'!A1");
set(&mut s, "A3", "=A2*2");
run(&mut s, "home.insertSheet", json!({"name": "Destination"}));
set(&mut s, "D1", "1000");
// Overlapping coordinates on different sheets catch accidental double adjustment.
cut_to(&mut s, "Source Data", "A1:A3", "Destination", "A2");
assert_eq!(value(&s, "Destination", "A2"), Value::Number(10.0));
assert_eq!(value(&s, "Destination", "A3"), Value::Number(27.0));
assert_eq!(value(&s, "Destination", "A4"), Value::Number(54.0));
assert_eq!(value(&s, "Source Data", "D1"), Value::Number(7.0));
assert!(formula(&s, "Destination", "A3").contains("'Source Data'!$D$1"));
for cell in ["A1", "A2", "A3"] {
assert_eq!(value(&s, "Source Data", cell), Value::Empty);
}
activate(&mut s, "Source Data");
set(&mut s, "D1", "8");
assert_eq!(value(&s, "Destination", "A3"), Value::Number(28.0));
assert_eq!(value(&s, "Destination", "A4"), Value::Number(56.0));
}
#[test]
fn same_sheet_overlapping_cut_still_updates_references_once() {
let mut s = workbook();
run(&mut s, "range.setValues", json!({"range": "A1", "values": [[10], [20]]}));
set(&mut s, "B1", "=SUM(A1:A2)");
set(&mut s, "A3", "=A1+A2");
run(&mut s, "edit.cut", json!({"range": "A1:A3"}));
run(&mut s, "edit.paste", json!({"at": "A2"}));
assert_eq!(value(&s, "Sheet1", "A1"), Value::Empty);
assert_eq!(value(&s, "Sheet1", "A2"), Value::Number(10.0));
assert_eq!(value(&s, "Sheet1", "A3"), Value::Number(20.0));
assert_eq!(value(&s, "Sheet1", "A4"), Value::Number(30.0));
assert_eq!(value(&s, "Sheet1", "B1"), Value::Number(30.0));
assert_eq!(formula(&s, "Sheet1", "A4"), "A2+A3");
assert_eq!(formula(&s, "Sheet1", "B1"), "SUM(A2:A3)");
}
@@ -0,0 +1,40 @@
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS};
use gridcraft_engine::Session;
use serde_json::json;
#[test]
fn selection_move_clamps_extreme_displacements() {
let mut session = Session::new();
session.new_workbook();
for (dr, dc, expected) in [
(i64::MAX, 0, CellRef::new(MAX_ROWS - 1, 1)),
(0, i64::MAX, CellRef::new(1, MAX_COLS - 1)),
(i64::MAX, i64::MAX, CellRef::new(MAX_ROWS - 1, MAX_COLS - 1)),
(i64::MIN, i64::MIN, CellRef::new(0, 0)),
(i64::MAX, i64::MIN, CellRef::new(MAX_ROWS - 1, 0)),
(i64::MIN, i64::MAX, CellRef::new(0, MAX_COLS - 1)),
(2, -1, CellRef::new(3, 0)),
] {
session.execute("selection.set", json!({"cell": "B2"})).unwrap();
session.execute("selection.move", json!({"dr": dr, "dc": dc})).unwrap();
assert_eq!(session.doc().unwrap().selection.active, expected);
}
}
#[test]
fn selection_move_from_a_merged_cell_clamps_extreme_displacements() {
let mut session = Session::new();
session.new_workbook();
session.execute("selection.set", json!({"range": "B2:C3"})).unwrap();
session.execute("home.mergeCells", json!({})).unwrap();
for (dr, dc, expected) in [
(i64::MAX, 0, CellRef::new(MAX_ROWS - 1, 1)),
(0, i64::MAX, CellRef::new(1, MAX_COLS - 1)),
(4_294_967_297, 0, CellRef::new(MAX_ROWS - 1, 1)),
(1, 0, CellRef::new(3, 1)),
] {
session.execute("selection.set", json!({"cell": "B2"})).unwrap();
session.execute("selection.move", json!({"dr": dr, "dc": dc})).unwrap();
assert_eq!(session.doc().unwrap().selection.active, expected);
}
}
+95 -3
View File
@@ -16,6 +16,35 @@ pub fn shift_relative(e: Expr, dr: i64, dc: i64) -> Expr {
})
}
/// Defined names: relative parts move by `(dr, dc)`, wrapping around the sheet's edges. Files
/// store a name's relative references as seen from A1 (a name for "the cell to the left" defined
/// in B1 is `Sheet1!XFD1`), and a use in another cell moves them by that cell's offset from A1.
pub fn shift_relative_wrapping(e: Expr, dr: i64, dc: i64) -> Expr {
let wrap = |v: u32, abs: bool, d: i64, max: u32| if abs { v } else { (v as i64 + d).rem_euclid(max as i64) as u32 };
let anchor = |a: Anchor| Anchor { row: wrap(a.row, a.row_abs, dr, MAX_ROWS), col: wrap(a.col, a.col_abs, dc, MAX_COLS), ..a };
e.map(&mut |x| match x {
Expr::Ref(r) => {
let kind = match r.kind {
RefKind::Cell(a) => RefKind::Cell(anchor(a)),
RefKind::Range(a, b) => RefKind::Range(anchor(a), anchor(b)),
RefKind::Rows(r0, a0, r1, a1) => RefKind::Rows(wrap(r0, a0, dr, MAX_ROWS), a0, wrap(r1, a1, dr, MAX_ROWS), a1),
RefKind::Cols(c0, a0, c1, a1) => RefKind::Cols(wrap(c0, a0, dc, MAX_COLS), a0, wrap(c1, a1, dc, MAX_COLS), a1),
};
Expr::Ref(Reference { sheet: r.sheet, kind })
}
other => other,
})
}
/// Whether the formula has a relative (no `$`) row or column anywhere.
pub fn has_relative_refs(e: &Expr) -> bool {
e.references().iter().any(|r| match r.kind {
RefKind::Cell(a) => !a.row_abs || !a.col_abs,
RefKind::Range(a, b) => !a.row_abs || !a.col_abs || !b.row_abs || !b.col_abs,
RefKind::Rows(_, a0, _, a1) | RefKind::Cols(_, a0, _, a1) => !a0 || !a1,
})
}
fn shift_anchor(a: &Anchor, dr: i64, dc: i64) -> Option<Anchor> {
let row = if a.row_abs { a.row as i64 } else { a.row as i64 + dr };
let col = if a.col_abs { a.col as i64 } else { a.col as i64 + dc };
@@ -56,6 +85,14 @@ pub enum Edit {
Delete { axis: Axis, at: u32, count: u32 },
/// Cut-paste of a block: references into `from` now point into the block at `to` (top-left).
Move { from: RangeRef, to_row: u32, to_col: u32 },
/// Insert Cells shifting down (`Rows`) or right (`Cols`): the cells of `range` and those
/// below (right of) it move by its height (width), within its columns (rows) only.
InsertCells { axis: Axis, range: RangeRef },
/// Delete Cells shifting up (`Rows`) or left (`Cols`): `range` goes and the cells below
/// (right of) it move back by its height (width), within its columns (rows) only.
DeleteCells { axis: Axis, range: RangeRef },
/// Cut-paste to another sheet; fully contained references follow the destination sheet too.
MoveToSheet { from: RangeRef, to_sheet: String, to_row: u32, to_col: u32 },
}
/// Adjusts a formula living on sheet `host` after `edit` on sheet `target`.
@@ -158,6 +195,21 @@ fn adjust_ref(r: &Reference, edit: &Edit) -> Option<Reference> {
};
Some(Reference { sheet: r.sheet.clone(), kind })
}
Edit::InsertCells { axis, range } | Edit::DeleteCells { axis, range } => {
// Like inserting/deleting lines, for references that lie within the shifted
// columns (rows); Excel leaves references reaching outside them as they are.
let span = r.range();
let (inside, at, count) = match axis {
Axis::Rows => (range.start.col <= span.start.col && span.end.col <= range.end.col, range.start.row, range.height()),
Axis::Cols => (range.start.row <= span.start.row && span.end.row <= range.end.row, range.start.col, range.width()),
};
if !inside {
return Some(r.clone());
}
let axis = *axis;
let lines = if matches!(edit, Edit::InsertCells { .. }) { Edit::Insert { axis, at, count } } else { Edit::Delete { axis, at, count } };
adjust_ref(r, &lines)
}
Edit::Move { from, to_row, to_col } => {
let dr = *to_row as i64 - from.start.row as i64;
let dc = *to_col as i64 - from.start.col as i64;
@@ -172,10 +224,25 @@ fn adjust_ref(r: &Reference, edit: &Edit) -> Option<Reference> {
let kind = match &r.kind {
RefKind::Cell(a) => RefKind::Cell(mv(a)?),
RefKind::Range(a, b) => RefKind::Range(mv(a)?, mv(b)?),
k => k.clone(),
RefKind::Rows(a, aa, b, ba) => {
let dr = *to_row as i64 - from.start.row as i64;
RefKind::Rows(shift_line(*a, false, dr, MAX_ROWS)?, *aa, shift_line(*b, false, dr, MAX_ROWS)?, *ba)
}
RefKind::Cols(a, aa, b, ba) => {
let dc = *to_col as i64 - from.start.col as i64;
RefKind::Cols(shift_line(*a, false, dc, MAX_COLS)?, *aa, shift_line(*b, false, dc, MAX_COLS)?, *ba)
}
};
Some(Reference { sheet: r.sheet.clone(), kind })
}
Edit::MoveToSheet { from, to_sheet, to_row, to_col } => {
if !from.contains_range(&r.range()) {
return Some(r.clone());
}
let mut moved = adjust_ref(r, &Edit::Move { from: *from, to_row: *to_row, to_col: *to_col })?;
moved.sheet = SheetSel::Named(to_sheet.clone());
Some(moved)
}
}
}
@@ -197,14 +264,39 @@ pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr {
}
Expr::Ref(r)
}
// Sheet-qualified defined name `Old!MyName` is stored as one string.
Expr::Name(n) => match n.split_at_checked(old.len()) {
Some((head, rest)) if head.eq_ignore_ascii_case(old) && rest.starts_with('!') => {
Expr::Name(format!("{}{rest}", crate::printer::quote_sheet(new)))
}
_ => Expr::Name(n),
},
other => other,
})
}
/// References to a deleted sheet become `#REF!`.
pub fn delete_sheet(e: Expr, name: &str) -> Expr {
/// References to a deleted sheet become `#REF!`. `order` lists the sheet names (before the deletion) in tab order:
/// a 3-D span that loses an end sheet shrinks to the neighbouring surviving sheet, as in Excel.
pub fn delete_sheet(e: Expr, name: &str, order: &[String]) -> Expr {
let pos = |n: &str| order.iter().position(|o| o.eq_ignore_ascii_case(n));
e.map(&mut |x| match x {
Expr::Ref(r) if r.sheet_name().is_some_and(|n| n.eq_ignore_ascii_case(name)) => Expr::Error(CellError::Ref),
Expr::Ref(mut r) => {
if let SheetSel::Span(a, b) = &r.sheet
&& (a.eq_ignore_ascii_case(name) || b.eq_ignore_ascii_case(name))
{
let (Some(ia), Some(ib)) = (pos(a), pos(b)) else { return Expr::Ref(r) };
if ia == ib {
return Expr::Error(CellError::Ref);
}
// The deleted end moves one sheet towards the other end; the span keeps its direction.
let inward = |from: usize, to: usize| order.get(if from < to { from + 1 } else { from.saturating_sub(1) });
let (na, nb) = if a.eq_ignore_ascii_case(name) { (inward(ia, ib), order.get(ib)) } else { (order.get(ia), inward(ib, ia)) };
let (Some(na), Some(nb)) = (na, nb) else { return Expr::Error(CellError::Ref) };
r.sheet = if na.eq_ignore_ascii_case(nb) { SheetSel::Named(na.clone()) } else { SheetSel::Span(na.clone(), nb.clone()) };
}
Expr::Ref(r)
}
other => other,
})
}
+35
View File
@@ -88,6 +88,41 @@ pub enum UnOp {
Percent,
/// Implicit intersection `@`.
At,
/// Spill range operator `A1#`: the whole spill range of the dynamic array anchored at the
/// cell (`ANCHORARRAY` in files).
Spill,
/// Trim reference `A1.:E10` / `A1:.E10` / `A1.:.E10` around a range: the range without its
/// blank leading, trailing or outer rows and columns (`TRIMRANGE` with both trim codes set).
Trim(TrimMode),
}
/// Which blank edges a trim reference drops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TrimMode {
/// `.:` — leading blank rows and columns.
Leading,
/// `:.` — trailing blank rows and columns.
Trailing,
/// `.:.` — both.
All,
}
impl TrimMode {
pub fn symbol(self) -> &'static str {
match self {
TrimMode::Leading => ".:",
TrimMode::Trailing => ":.",
TrimMode::All => ".:.",
}
}
/// The equivalent `TRIMRANGE` trim_rows / trim_cols code.
pub fn code(self) -> u8 {
match self {
TrimMode::Leading => 1,
TrimMode::Trailing => 2,
TrimMode::All => 3,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+204
View File
@@ -0,0 +1,204 @@
//! Localized aliases accepted at user-entry boundaries; file syntax stays English.
use crate::{Expr, ParseError, parser};
/// Formula-entry syntax selected by the interface language. Other interface languages
/// currently use the canonical English function table until a translation table is supplied.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FormulaLocale {
#[default]
En,
Es,
}
const SPANISH: &[(&str, &str)] = &[
("SUM", "SUMA"),
("AVERAGE", "PROMEDIO"),
("IF", "SI"),
("COUNT", "CONTAR"),
("SUMIF", "SUMAR.SI"),
("COUNTIF", "CONTAR.SI"),
("VLOOKUP", "BUSCARV"),
("TODAY", "HOY"),
("TRUE", "VERDADERO"),
("FALSE", "FALSO"),
];
impl FormulaLocale {
pub fn list_separator(self) -> char {
if self == Self::Es { ';' } else { ',' }
}
pub fn decimal_separator(self) -> char {
if self == Self::Es { ',' } else { '.' }
}
pub fn array_column_separator(self) -> char {
if self == Self::Es { '\\' } else { ',' }
}
pub fn function_name(self, canonical: &str) -> &str {
if self == Self::Es {
SPANISH.iter().find(|(en, _)| en.eq_ignore_ascii_case(canonical)).map(|(_, es)| *es).unwrap_or(canonical)
} else {
canonical
}
}
pub fn canonical_name(self, localized: &str) -> &str {
if self == Self::Es {
SPANISH.iter().find(|(_, es)| es.eq_ignore_ascii_case(localized)).map(|(en, _)| *en).unwrap_or(localized)
} else {
localized
}
}
}
/// Parses UI input using the selected function table and separators. Existing names and
/// LET/LAMBDA bindings take precedence over aliases. File and API syntax uses [`crate::parse`].
pub fn parse_input(src: &str, locale: FormulaLocale, known_name: impl Fn(&str) -> bool) -> Result<Expr, ParseError> {
let mut expr = parser::parse_syntax(src, locale)?;
if locale == FormulaLocale::Es {
normalize(&mut expr, &known_name, &mut Vec::new(), 0, false)?;
}
Ok(expr)
}
/// Prints canonical expressions for editing. Name collisions retain the canonical spelling
/// so displaying then committing a formula never changes a defined-name reference.
pub fn print_input(expr: &Expr, locale: FormulaLocale, known_name: impl Fn(&str) -> bool) -> Result<String, ParseError> {
// Check before cloning/printing: a flat operator chain can produce a deep AST even
// though the parser itself did not recurse deeply.
let mut pending = vec![(expr, 0usize)];
while let Some((node, depth)) = pending.pop() {
if depth > parser::MAX_DEPTH {
return Err(ParseError { msg: "formula is nested too deeply".into(), pos: 0 });
}
match node {
Expr::Unary(_, child) | Expr::Paren(child) => pending.push((child, depth + 1)),
Expr::Binary(_, left, right) => {
pending.push((left, depth + 1));
pending.push((right, depth + 1));
}
Expr::Call(_, args) => pending.extend(args.iter().map(|e| (e, depth + 1))),
Expr::Invoke(callee, args) => {
pending.push((callee, depth + 1));
pending.extend(args.iter().map(|e| (e, depth + 1)));
}
Expr::Array(rows) => pending.extend(rows.iter().flatten().map(|e| (e, depth + 1))),
_ => {}
}
}
if locale == FormulaLocale::En {
return Ok(crate::print(expr));
}
let mut expr = expr.clone();
normalize(&mut expr, &known_name, &mut Vec::new(), 0, true)?;
let canonical = crate::print(&expr);
let tokens = crate::lexer::tokenize(&canonical).map_err(|e| ParseError { msg: e.msg, pos: e.pos })?;
let mut out = String::new();
let mut array_depth = 0usize;
for token in tokens {
use crate::lexer::Tok;
let text = canonical.get(token.start..token.end).unwrap_or("");
match token.tok {
Tok::LBrace => {
array_depth += 1;
out.push_str(text);
}
Tok::RBrace => {
array_depth = array_depth.saturating_sub(1);
out.push_str(text);
}
Tok::Number(_) => out.push_str(&text.replace('.', &locale.decimal_separator().to_string())),
Tok::Comma => out.push(if array_depth > 0 { locale.array_column_separator() } else { locale.list_separator() }),
_ => out.push_str(text),
}
}
Ok(out)
}
pub(crate) fn boolean_alias(name: &str) -> Option<bool> {
if name.eq_ignore_ascii_case("VERDADERO") {
Some(true)
} else if name.eq_ignore_ascii_case("FALSO") {
Some(false)
} else {
None
}
}
fn normalize(expr: &mut Expr, known_name: &impl Fn(&str) -> bool, bindings: &mut Vec<String>, depth: usize, display: bool) -> Result<(), ParseError> {
if depth > parser::MAX_DEPTH {
return Err(ParseError { msg: "formula is nested too deeply".into(), pos: 0 });
}
let bound = |name: &str, bindings: &[String]| bindings.iter().rev().any(|n| n.eq_ignore_ascii_case(name)) || known_name(name);
match expr {
Expr::Bool(value) if display => {
let alias = if *value { "VERDADERO" } else { "FALSO" };
if !bound(alias, bindings) {
*expr = Expr::Name(alias.into());
}
}
Expr::Name(name) if !display && !bound(name, bindings) => {
if let Some(value) = boolean_alias(name) {
*expr = Expr::Bool(value);
}
}
Expr::Call(name, args) if name == "LET" && args.len() >= 3 && !args.len().is_multiple_of(2) => {
let saved = bindings.len();
if let Some((body, pairs)) = args.split_last_mut() {
for pair in pairs.chunks_mut(2) {
if let [declaration, value] = pair {
// The new name is not in scope in its own value expression.
normalize(value, known_name, bindings, depth + 1, display)?;
if let Expr::Name(name) = declaration {
bindings.push(name.clone());
}
}
}
normalize(body, known_name, bindings, depth + 1, display)?;
}
bindings.truncate(saved);
}
Expr::Call(name, args) if name == "LAMBDA" => {
let saved = bindings.len();
if let Some((body, params)) = args.split_last_mut() {
for param in params {
if let Expr::Name(name) = param {
bindings.push(name.clone());
}
}
normalize(body, known_name, bindings, depth + 1, display)?;
}
bindings.truncate(saved);
}
Expr::Call(name, args) => {
let alias = if display { FormulaLocale::Es.function_name(name) } else { FormulaLocale::Es.canonical_name(name) };
if !bound(name, bindings) && (!display || !bound(alias, bindings)) {
*name = alias.to_string();
}
for arg in args {
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expr::Invoke(callee, args) => {
normalize(callee, known_name, bindings, depth + 1, display)?;
for arg in args {
normalize(arg, known_name, bindings, depth + 1, display)?;
}
}
Expr::Unary(_, child) | Expr::Paren(child) => normalize(child, known_name, bindings, depth + 1, display)?,
Expr::Binary(_, left, right) => {
normalize(left, known_name, bindings, depth + 1, display)?;
normalize(right, known_name, bindings, depth + 1, display)?;
}
Expr::Array(rows) if display => {
for row in rows {
for child in row {
normalize(child, known_name, bindings, depth + 1, display)?;
}
}
}
// Array elements have already been parsed as literals. Sheet/structured references
// contain user-defined labels and must not be translated.
_ => {}
}
Ok(())
}
+78 -14
View File
@@ -1,9 +1,11 @@
//! Tokenizer for Excel formulas (A1 style, en-US separators).
//! Tokenizer for Excel formulas (A1 style, canonical or selected UI separators).
//!
//! Token spans are byte offsets into the source, which the editor uses to colour references.
use gridcraft_core::CellError;
use crate::ast::TrimMode;
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
Number(f64),
@@ -27,6 +29,8 @@ pub enum Tok {
Comma,
Semicolon,
Colon,
/// Trim reference range operator `.:`, `:.` or `.:.`.
Trim(TrimMode),
Space,
Eof,
}
@@ -49,14 +53,34 @@ fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | '.' | '$' | '\\' | '?')
}
/// `A1`, `$A$1`, `A`, `$A`, `1`, `$1`: a word that can end a range, so `A1.:` is a trim
/// reference and not a name ending in a dot.
fn is_range_end(w: &str) -> bool {
let s = w.strip_prefix('$').unwrap_or(w);
let (letters, rest) = s.split_at(s.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(s.len()));
let digits = if letters.is_empty() { rest } else { rest.strip_prefix('$').unwrap_or(rest) };
letters.len() <= 3 && if digits.is_empty() { !letters.is_empty() && rest.is_empty() } else { digits.bytes().all(|b| b.is_ascii_digit()) }
}
/// Whether `c` can start the second end of a range after `:.` (`A1:.E10`, `A:.$C`, `1:.5`).
fn starts_range_end(c: Option<char>) -> bool {
c.is_some_and(|c| c.is_ascii_alphanumeric() || c == '$')
}
/// Tokenizes formula text (without the leading `=`).
pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
tokenize_locale(src, crate::FormulaLocale::En)
}
/// Tokenizes UI syntax while retaining byte spans in the original text.
pub fn tokenize_locale(src: &str, locale: crate::FormulaLocale) -> Result<Vec<Token>, LexError> {
let chars: Vec<(usize, char)> = src.char_indices().collect();
let n = chars.len();
let pos_of = |i: usize| chars.get(i).map(|c| c.0).unwrap_or(src.len());
let ch = |i: usize| chars.get(i).map(|c| c.1);
let mut out = Vec::new();
let mut i = 0;
let mut array_depth = 0usize;
while i < n {
let start = pos_of(i);
let Some(c) = ch(i) else { break };
@@ -124,6 +148,11 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
push(&mut out, Tok::Sheet(a, b), j + 1);
i = j + 1;
}
'#' if out.last().is_some_and(|t: &Token| t.end == start && matches!(t.tok, Tok::Word(_))) => {
// Spill range operator right after a reference: `A1#`.
push(&mut out, Tok::Op("#"), i + 1);
i += 1;
}
'#' => {
// Error literal, or #-prefixed struct specifier (only inside [] which we lex as Struct).
let rest = src.get(start..).unwrap_or("");
@@ -167,19 +196,39 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
push(&mut out, Tok::Struct(inner), j);
i = j;
}
'0'..='9' | '.' if c != '.' || ch(i + 1).is_some_and(|d| d.is_ascii_digit()) => {
'.' if ch(i + 1) == Some(':') => {
// Trim reference `A1.:E10` / `A1.:.E10` (the word before stopped at the dot).
if ch(i + 2) == Some('.') && starts_range_end(ch(i + 3)) {
push(&mut out, Tok::Trim(TrimMode::All), i + 3);
i += 3;
} else {
push(&mut out, Tok::Trim(TrimMode::Leading), i + 2);
i += 2;
}
}
c if c.is_ascii_digit() || (c == locale.decimal_separator() && ch(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
// Number, unless it is a row range like 1:3 (handled by parser via Word) — numbers
// followed by ':' and digits are row refs: lex as Word.
let mut j = i;
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
j += 1;
}
let is_row_ref = ch(j) == Some(':') && {
let mut k = j + 1;
if ch(k) == Some('$') {
// Row ranges `1:3`, and the trim forms `1.:3`, `1:.3`, `1.:.3`.
let is_row_ref = {
let mut k = j;
if ch(k) == Some('.') && ch(k + 1) == Some(':') {
k += 1;
}
ch(k).is_some_and(|d| d.is_ascii_digit())
ch(k) == Some(':') && {
k += 1;
if ch(k) == Some('.') {
k += 1;
}
if ch(k) == Some('$') {
k += 1;
}
ch(k).is_some_and(|d| d.is_ascii_digit())
}
};
// A word like "1A" can't happen in valid formulas; numbers then.
if is_row_ref {
@@ -188,7 +237,7 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
i = j;
continue;
}
if ch(j) == Some('.') {
if ch(j) == Some(locale.decimal_separator()) {
j += 1;
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
j += 1;
@@ -207,7 +256,10 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
}
}
let text = src.get(start..pos_of(j)).unwrap_or("");
let v: f64 = text.parse().map_err(|_| LexError { msg: format!("bad number `{text}`"), pos: start })?;
let v: f64 = text
.replace(locale.decimal_separator(), ".")
.parse()
.map_err(|_| LexError { msg: format!("bad number `{text}`"), pos: start })?;
push(&mut out, Tok::Number(v), j);
i = j;
}
@@ -220,14 +272,16 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
i += 1;
}
'{' => {
array_depth += 1;
push(&mut out, Tok::LBrace, i + 1);
i += 1;
}
'}' => {
array_depth = array_depth.saturating_sub(1);
push(&mut out, Tok::RBrace, i + 1);
i += 1;
}
',' => {
c if (array_depth == 0 && c == locale.list_separator()) || (array_depth > 0 && c == locale.array_column_separator()) => {
push(&mut out, Tok::Comma, i + 1);
i += 1;
}
@@ -236,8 +290,13 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
i += 1;
}
':' => {
push(&mut out, Tok::Colon, i + 1);
i += 1;
if ch(i + 1) == Some('.') && starts_range_end(ch(i + 2)) {
push(&mut out, Tok::Trim(TrimMode::Trailing), i + 2);
i += 2;
} else {
push(&mut out, Tok::Colon, i + 1);
i += 1;
}
}
'+' | '-' | '*' | '/' | '^' | '&' | '%' | '@' | '=' => {
let op = match c {
@@ -268,7 +327,7 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
}
c if is_word_char(c) => {
let mut j = i;
while ch(j).is_some_and(is_word_char) {
while ch(j).is_some_and(|c| is_word_char(c) && !(array_depth > 0 && c == locale.array_column_separator())) {
j += 1;
}
let w: String = chars.get(i..j).map(|s| s.iter().map(|c| c.1).collect()).unwrap_or_default();
@@ -278,13 +337,13 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
} else if ch(j) == Some(':') && {
// Sheet1:Sheet3!A1 — look ahead for word then '!'
let mut k = j + 1;
while ch(k).is_some_and(is_word_char) {
while ch(k).is_some_and(|c| is_word_char(c) && !(array_depth > 0 && c == locale.array_column_separator())) {
k += 1;
}
k > j + 1 && ch(k) == Some('!')
} {
let mut k = j + 1;
while ch(k).is_some_and(is_word_char) {
while ch(k).is_some_and(|c| is_word_char(c) && !(array_depth > 0 && c == locale.array_column_separator())) {
k += 1;
}
let w2: String = chars.get(j + 1..k).map(|s| s.iter().map(|c| c.1).collect()).unwrap_or_default();
@@ -299,6 +358,11 @@ pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
} else if w.eq_ignore_ascii_case("FALSE") && ch(j) != Some('[') {
push(&mut out, Tok::Bool(false), j);
i = j;
} else if w.len() > 1 && w.ends_with('.') && ch(j) == Some(':') && is_range_end(w.get(..w.len() - 1).unwrap_or("")) {
// `A1.:E10`: the dot belongs to the trim operator, lexed next.
let w = w.get(..w.len() - 1).unwrap_or("").to_string();
push(&mut out, Tok::Word(w), j - 1);
i = j - 1;
} else {
push(&mut out, Tok::Word(w), j);
i = j;
+3 -1
View File
@@ -5,11 +5,13 @@
pub mod adjust;
pub mod ast;
mod input;
pub mod lexer;
pub mod parser;
pub mod printer;
pub use ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, UnOp};
pub use ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, TrimMode, UnOp};
pub use input::{FormulaLocale, parse_input, print_input};
pub use parser::{ParseError, normalize_function_name, parse};
pub use printer::{print, print_r1c1, quote_sheet};
+132 -36
View File
@@ -6,7 +6,7 @@ use gridcraft_core::addr::{letters_to_col, parse_a1_prefix};
use gridcraft_core::{CellError, MAX_ROWS};
use crate::ast::*;
use crate::lexer::{Tok, Token, tokenize};
use crate::lexer::{Tok, Token, tokenize_locale};
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{msg}")]
@@ -15,15 +15,19 @@ pub struct ParseError {
pub pos: usize,
}
const MAX_DEPTH: usize = 256;
pub(crate) const MAX_DEPTH: usize = 256;
/// Parses formula text. A leading `=` (or `+`/`-` as Lotus users type) is accepted and skipped
/// for `=`.
pub fn parse(src: &str) -> Result<Expr, ParseError> {
parse_syntax(src, crate::FormulaLocale::En)
}
pub(crate) fn parse_syntax(src: &str, locale: crate::FormulaLocale) -> Result<Expr, ParseError> {
let body = src.strip_prefix('=').unwrap_or(src);
let toks = tokenize(body).map_err(|e| ParseError { msg: e.msg, pos: e.pos })?;
let toks = tokenize_locale(body, locale).map_err(|e| ParseError { msg: e.msg, pos: e.pos })?;
let toks = significant_spaces(toks);
let mut p = Parser { toks, i: 0, depth: 0 };
let mut p = Parser { toks, i: 0, depth: 0, input: locale == crate::FormulaLocale::Es };
let e = p.expr(0, false)?;
match p.peek() {
Tok::Eof => Ok(e),
@@ -62,6 +66,7 @@ struct Parser {
toks: Vec<Token>,
i: usize,
depth: usize,
input: bool,
}
fn word_is_cols(w: &str) -> Option<(u32, bool)> {
@@ -169,6 +174,17 @@ impl Parser {
lhs = Expr::Invoke(Box::new(lhs), args);
continue;
}
if let Tok::Trim(mode) = *self.peek() {
// A trim reference is the range operator with a modifier: same binding power.
let bp = BinOp::Range.precedence();
if bp < min_bp {
break;
}
self.next();
let rhs = self.expr(bp + 1, allow_union)?;
lhs = Expr::Unary(UnOp::Trim(mode), Box::new(combine(BinOp::Range, lhs, rhs)));
continue;
}
let Some(op) = self.binop(allow_union) else { break };
let bp = op.precedence();
if bp < min_bp {
@@ -223,7 +239,34 @@ impl Parser {
Tok::LBrace => self.array(),
Tok::Func(name) => {
let name = normalize_function_name(&name);
let args = self.args()?;
let mut args = self.args()?;
// Files write `A1#` as `_xlfn.ANCHORARRAY(A1)`.
if name == "ANCHORARRAY"
&& let [Expr::Ref(Reference { kind: RefKind::Cell(_), .. })] = args.as_slice()
&& let Some(r) = args.pop()
{
return Ok(Expr::Unary(UnOp::Spill, Box::new(r)));
}
// Files write `@x` as `_xlfn.SINGLE(x)`.
if name == "SINGLE"
&& args.len() == 1
&& let Some(x) = args.pop()
{
return Ok(Expr::Unary(UnOp::At, Box::new(x)));
}
// Files may spell a trim reference as a function call (`_xlfn._TRO_ALL(A1:E10)`).
let trim = match name.as_str() {
"_TRO_LEADING" => Some(TrimMode::Leading),
"_TRO_TRAILING" => Some(TrimMode::Trailing),
"_TRO_ALL" => Some(TrimMode::All),
_ => None,
};
if let Some(mode) = trim
&& args.len() == 1
&& let Some(x) = args.pop()
{
return Ok(Expr::Unary(UnOp::Trim(mode), Box::new(x)));
}
Ok(Expr::Call(name, args))
}
Tok::Sheet(a, b) => {
@@ -241,47 +284,67 @@ impl Parser {
if let Tok::Struct(_) = self.peek()
&& word_is_cell(&w).is_none()
{
let pos = self.pos();
let Tok::Struct(body) = self.next() else { return Err(self.err("internal")) };
return Ok(Expr::Struct(parse_struct(&w, &body)));
return parse_struct(&w, &body).map(Expr::Struct).map_err(|msg| ParseError { msg, pos });
}
self.reference_from_word(SheetSel::Current, &w)
}
Tok::Struct(body) => Ok(Expr::Struct(parse_struct("", &body))),
Tok::Struct(body) => parse_struct("", &body).map(Expr::Struct).map_err(|msg| self.err(msg)),
t => Err(self.err(format!("unexpected {}", describe(&t)))),
}
}
/// A word after an optional sheet: a cell, a column/row range (`A:C`, `3:5`) or a name.
/// A word after an optional sheet: a cell, a column/row range (`A:C`, `3:5`) or a name. A
/// trim operator (`A1:.E10`, `A:.A`) in place of the colon wraps the range in
/// [`UnOp::Trim`].
fn reference_from_word(&mut self, sheet: SheetSel, w: &str) -> Result<Expr, ParseError> {
let trim = match self.peek() {
Tok::Colon => Some(None),
Tok::Trim(mode) => Some(Some(*mode)),
_ => None,
};
let wrap = |kind: RefKind, sheet: SheetSel| {
let r = Expr::Ref(Reference { sheet, kind });
match trim {
Some(Some(mode)) => Expr::Unary(UnOp::Trim(mode), Box::new(r)),
_ => r,
}
};
if let Some(a) = word_is_cell(w) {
// Cell, possibly `A1:B2` (merged here so the sheet applies to both ends).
if *self.peek() == Tok::Colon
if trim.is_some()
&& let Tok::Word(w2) = self.peek_at(1)
&& let Some(b) = word_is_cell(w2)
{
self.next();
self.next();
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Range(a, b) }));
return Ok(wrap(RefKind::Range(a, b), sheet));
}
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Cell(a) }));
let cell = Expr::Ref(Reference { sheet, kind: RefKind::Cell(a) });
if *self.peek() == Tok::Op("#") {
self.next();
return Ok(Expr::Unary(UnOp::Spill, Box::new(cell)));
}
return Ok(cell);
}
let second = match self.peek_at(1) {
Tok::Word(w2) => Some(w2.clone()),
Tok::Number(n) if n.fract() == 0.0 && *n >= 1.0 => Some(format!("{n}")),
_ => None,
};
if *self.peek() == Tok::Colon
if trim.is_some()
&& let Some(w2) = second
{
if let (Some((c0, a0)), Some((c1, a1))) = (word_is_cols(w), word_is_cols(&w2)) {
self.next();
self.next();
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Cols(c0, a0, c1, a1) }));
return Ok(wrap(RefKind::Cols(c0, a0, c1, a1), sheet));
}
if let (Some((r0, a0)), Some((r1, a1))) = (word_is_row(w), word_is_row(&w2)) {
self.next();
self.next();
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Rows(r0, a0, r1, a1) }));
return Ok(wrap(RefKind::Rows(r0, a0, r1, a1), sheet));
}
}
if sheet != SheetSel::Current {
@@ -312,6 +375,9 @@ impl Parser {
},
Tok::Text(s) => Expr::Text(Arc::from(s)),
Tok::Bool(b) => Expr::Bool(b),
Tok::Word(w) if self.input => crate::input::boolean_alias(&w)
.map(Expr::Bool)
.ok_or_else(|| self.err(format!("array constants may only contain constants, found {}", describe(&Tok::Word(w)))))?,
Tok::Error(e) => Expr::Error(e),
t => return Err(self.err(format!("array constants may only contain constants, found {}", describe(&t)))),
};
@@ -345,8 +411,10 @@ fn combine(op: BinOp, lhs: Expr, rhs: Expr) -> Expr {
Expr::Binary(op, Box::new(lhs), Box::new(rhs))
}
/// Parses the inside of `Table[...]`.
pub fn parse_struct(table: &str, body: &str) -> StructRef {
/// Parses the inside of `Table[...]`. Text between the bracketed items may only be the `,` and
/// `:` separators, except one unbracketed column after `[#This Row],` (`[[#This Row],Units]`,
/// how some writers spell `[@Units]`); anything else is an error rather than dropped.
pub fn parse_struct(table: &str, body: &str) -> Result<StructRef, String> {
let mut specifiers = Vec::new();
let mut cols: Vec<String> = Vec::new();
let body = body.trim();
@@ -374,24 +442,41 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
_ => None,
}
};
let unexpected = |gap: &str| format!("unexpected `{gap}` in structured reference");
// A column name may hold `[` and `]` only when escaped with `'`.
let column = |s: &str| -> Result<String, String> {
let mut esc = false;
for c in s.chars() {
match c {
_ if esc => esc = false,
'\'' => esc = true,
'[' | ']' => return Err(unexpected(s)),
_ => {}
}
}
Ok(unescape(s))
};
if !body.starts_with('[') {
// Simple: [Col], [@Col], [#Headers], [@]
if let Some(rest) = body.strip_prefix('@') {
specifiers.push(StructItem::ThisRow);
let rest = rest.trim().trim_start_matches('[').trim_end_matches(']');
let rest = rest.trim();
let rest = rest.strip_prefix('[').and_then(|r| r.strip_suffix(']')).unwrap_or(rest);
if !rest.is_empty() {
cols.push(unescape(rest));
cols.push(column(rest)?);
}
} else if let Some(i) = item(body) {
specifiers.push(i);
} else if !body.is_empty() {
cols.push(unescape(body));
cols.push(column(body)?);
}
} else {
// [[#Headers],[Col1]:[Col3]] or [@[Col 1]]
// [[#Headers],[Col1]:[Col3]], [[#This Row],[Col 1]] or [[#This Row],Col1]
let mut parts = Vec::new();
let mut depth = 0;
let mut cur = String::new();
// Text between bracketed items.
let mut gap = String::new();
let mut esc = false;
for c in body.chars() {
if esc {
@@ -400,17 +485,26 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
continue;
}
match c {
'\'' => {
'\'' if depth > 0 => {
cur.push(c);
esc = true;
}
'[' => {
if depth == 0 {
if !matches!(gap.trim(), "" | "," | ":") {
return Err(unexpected(gap.trim()));
}
gap.clear();
}
depth += 1;
if depth > 1 {
cur.push(c);
}
}
']' => {
if depth == 0 {
return Err(unexpected("]"));
}
depth -= 1;
if depth > 0 {
cur.push(c);
@@ -418,33 +512,35 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
parts.push(std::mem::take(&mut cur));
}
}
',' if depth == 0 => {}
':' if depth == 0 => parts.push(":".into()),
_ if depth > 0 => cur.push(c),
_ => {}
_ => gap.push(c),
}
}
let mut range_next = false;
if depth > 0 {
return Err("unclosed `[` in structured reference".to_string());
}
for p in parts {
if p == ":" {
range_next = true;
continue;
}
if let Some(i) = item(&p) {
specifiers.push(i);
} else if range_next {
cols.push(unescape(&p));
range_next = false;
} else {
cols.push(unescape(&p));
cols.push(column(&p)?);
}
}
if body.starts_with("@") {
specifiers.push(StructItem::ThisRow);
let tail = gap.trim();
if !tail.is_empty() {
let bare = tail.strip_prefix(',').map(str::trim).unwrap_or("");
let simple = !bare.is_empty() && !bare.chars().any(|c| matches!(c, '[' | ']' | '#' | '\'' | ',' | ':'));
if !(simple && specifiers == [StructItem::ThisRow] && cols.is_empty()) {
return Err(unexpected(tail));
}
cols.push(bare.to_string());
}
}
if cols.len() > 2 {
return Err("a structured reference names at most two columns".to_string());
}
let mut it = cols.into_iter();
let col_start = it.next();
let col_end = it.next();
StructRef { table: table.to_string(), specifiers, col_start, col_end }
Ok(StructRef { table: table.to_string(), specifiers, col_start, col_end })
}
+43 -6
View File
@@ -39,12 +39,17 @@ fn anchor_a1(a: &Anchor) -> String {
}
pub fn reference_a1(r: &Reference) -> String {
range_a1(r, ":")
}
/// A1 text with `sep` between the two ends of a range (`:` or a trim operator).
fn range_a1(r: &Reference, sep: &str) -> String {
let body = match &r.kind {
RefKind::Cell(a) => anchor_a1(a),
RefKind::Range(a, b) => format!("{}:{}", anchor_a1(a), anchor_a1(b)),
RefKind::Rows(r0, a0, r1, a1) => format!("{}{}:{}{}", if *a0 { "$" } else { "" }, r0 + 1, if *a1 { "$" } else { "" }, r1 + 1),
RefKind::Range(a, b) => format!("{}{sep}{}", anchor_a1(a), anchor_a1(b)),
RefKind::Rows(r0, a0, r1, a1) => format!("{}{}{sep}{}{}", if *a0 { "$" } else { "" }, r0 + 1, if *a1 { "$" } else { "" }, r1 + 1),
RefKind::Cols(c0, a0, c1, a1) => {
format!("{}{}:{}{}", if *a0 { "$" } else { "" }, col_to_letters(*c0), if *a1 { "$" } else { "" }, col_to_letters(*c1))
format!("{}{}{sep}{}{}", if *a0 { "$" } else { "" }, col_to_letters(*c0), if *a1 { "$" } else { "" }, col_to_letters(*c1))
}
};
format!("{}{}", sheet_prefix(&r.sheet), body)
@@ -64,16 +69,22 @@ fn anchor_r1c1(a: &Anchor, at: CellRef) -> String {
}
pub fn reference_r1c1(r: &Reference, at: CellRef) -> String {
range_r1c1(r, at, ":")
}
/// R1C1 text with `sep` between the two ends of a range; a trim operator never collapses
/// `R1:R1` to `R1`.
fn range_r1c1(r: &Reference, at: CellRef, sep: &str) -> String {
let body = match &r.kind {
RefKind::Cell(a) => anchor_r1c1(a, at),
RefKind::Range(a, b) => format!("{}:{}", anchor_r1c1(a, at), anchor_r1c1(b, at)),
RefKind::Range(a, b) => format!("{}{sep}{}", anchor_r1c1(a, at), anchor_r1c1(b, at)),
RefKind::Rows(r0, a0, r1, a1) => {
let (x, y) = (r1c1_part('R', *r0, *a0, at.row), r1c1_part('R', *r1, *a1, at.row));
if x == y { x } else { format!("{x}:{y}") }
if x == y && sep == ":" { x } else { format!("{x}{sep}{y}") }
}
RefKind::Cols(c0, a0, c1, a1) => {
let (x, y) = (r1c1_part('C', *c0, *a0, at.col), r1c1_part('C', *c1, *a1, at.col));
if x == y { x } else { format!("{x}:{y}") }
if x == y && sep == ":" { x } else { format!("{x}{sep}{y}") }
}
};
format!("{}{}", sheet_prefix(&r.sheet), body)
@@ -186,6 +197,32 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
write_expr(s, x, r1c1);
s.push('%');
}
UnOp::Spill => {
write_expr(s, x, r1c1);
// A reference that became #REF! (its sheet or cell was deleted) stays `#REF!`.
if !matches!(**x, Expr::Error(_)) {
s.push('#');
}
}
UnOp::Trim(mode) => match &**x {
Expr::Ref(r) if !matches!(r.kind, RefKind::Cell(_)) => match r1c1 {
Some(at) => s.push_str(&range_r1c1(r, at, mode.symbol())),
None => s.push_str(&range_a1(r, mode.symbol())),
},
Expr::Binary(BinOp::Range, a, b) => {
write_expr(s, a, r1c1);
s.push_str(mode.symbol());
write_expr(s, b, r1c1);
}
// A reference that became #REF! stays `#REF!`.
Expr::Error(_) => write_expr(s, x, r1c1),
// No operator form (e.g. a range shrunk to one cell): the equivalent call.
other => {
s.push_str("TRIMRANGE(");
write_expr(s, other, r1c1);
let _ = write!(s, ",{0},{0})", mode.code());
}
},
},
Expr::Binary(op, a, b) => {
write_expr(s, a, r1c1);
+160
View File
@@ -52,6 +52,34 @@ fn normalises() {
assert_eq!(rt("'Sheet1'!A1"), "Sheet1!A1");
}
#[test]
fn spill_operator() {
for f in ["A1#", "Sheet1!$D$1#", "SUM(B2#)", "'My Sheet'!A1#*2", "ROWS(A1#)+1", "IF(A1,#N/A,#REF!)"] {
assert_eq!(rt(f), f);
}
assert!(matches!(parse("A1#").unwrap(), Expr::Unary(UnOp::Spill, _)));
// Files spell it ANCHORARRAY.
assert_eq!(rt("_xlfn.ANCHORARRAY(Sheet1!$D$1)"), "Sheet1!$D$1#");
assert_eq!(rt("SUM(ANCHORARRAY(B2))"), "SUM(B2#)");
// Only a cell can spill.
assert!(parse("A1:B2#").is_err());
assert!(parse("Name#").is_err());
// Deleting the anchor's sheet leaves #REF!.
assert_eq!(print(&crate::adjust::delete_sheet(parse("SUM(Data!A1#)").unwrap(), "Data", &[])), "SUM(#REF!)");
}
#[test]
fn delete_sheet_shrinks_3d_span() {
let order: Vec<String> = ["Sheet1", "Sheet2", "Sheet3", "Results"].iter().map(|s| s.to_string()).collect();
let del = |f: &str, n: &str| print(&crate::adjust::delete_sheet(parse(f).unwrap(), n, &order));
assert_eq!(del("SUM(Sheet1:Sheet3!A1)", "Sheet1"), "SUM(Sheet2:Sheet3!A1)");
assert_eq!(del("SUM(Sheet1:Sheet3!A1)", "Sheet3"), "SUM(Sheet1:Sheet2!A1)");
assert_eq!(del("SUM(Sheet3:Sheet1!A1)", "Sheet1"), "SUM(Sheet3:Sheet2!A1)");
assert_eq!(del("SUM(Sheet1:Sheet3!A1)", "Sheet2"), "SUM(Sheet1:Sheet3!A1)");
assert_eq!(del("SUM(Sheet1:Sheet2!A1)", "Sheet1"), "SUM(Sheet2!A1)");
assert_eq!(del("Sheet1!A1+Sheet3!A1", "Sheet1"), "#REF!+Sheet3!A1");
}
#[test]
fn precedence() {
let e = parse("1+2*3").unwrap();
@@ -120,15 +148,66 @@ fn insert_delete() {
assert_eq!(print(&adjust(e, "S", "S", &del)), "SUM(#REF!)");
}
#[test]
fn insert_delete_cells() {
let range = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
let adj = |f: &str, e: &Edit| print(&adjust(parse(f).unwrap(), "S", "S", e));
// Insert A3:A4, shifting down: column A moves, other columns and wider ranges don't.
let ins = Edit::InsertCells { axis: Axis::Rows, range: range("A3:A4") };
assert_eq!(adj("SUM(A1:A5)+A2+A3+$A$9+B3+SUM(A1:B5)+SUM(A:A)", &ins), "SUM(A1:A7)+A2+A5+$A$11+B3+SUM(A1:B5)+SUM(A:A)");
// Insert B2 shifting right.
let ins = Edit::InsertCells { axis: Axis::Cols, range: range("B2") };
assert_eq!(adj("A2+B2+C2+B3+SUM(A2:C2)", &ins), "A2+C2+D2+B3+SUM(A2:D2)");
// Delete A3:A4 shifting up: references into it become #REF!, those below move up.
let del = Edit::DeleteCells { axis: Axis::Rows, range: range("A3:A4") };
assert_eq!(adj("A2+A3+A4+A5+B5+SUM(A1:A10)+SUM(A3:A4)+SUM(A1:B10)", &del), "A2+#REF!+#REF!+A3+B5+SUM(A1:A8)+SUM(#REF!)+SUM(A1:B10)");
// Delete B1:C2 shifting left.
let del = Edit::DeleteCells { axis: Axis::Cols, range: range("B1:C2") };
assert_eq!(adj("A1+B1+D1+D2+D3+SUM(A1:E1)", &del), "A1+#REF!+B1+B2+D3+SUM(A1:C1)");
}
#[test]
fn moves_and_renames() {
let mv = Edit::Move { from: gridcraft_core::RangeRef::parse("A1:B2").unwrap(), to_row: 9, to_col: 3 };
let e = parse("A1+B2+C3+SUM(A1:B2)").unwrap();
assert_eq!(print(&adjust(e, "S", "S", &mv)), "D10+E11+C3+SUM(D10:E11)");
let mv = Edit::Move { from: gridcraft_core::RangeRef::parse("B:C").unwrap(), to_row: 0, to_col: 4 };
assert_eq!(print(&adjust(parse("SUM(B:B)+SUM($C:$C)+D1").unwrap(), "S", "S", &mv)), "SUM(E:E)+SUM($F:$F)+D1");
let e = parse("Old!A1+'Old'!B2").unwrap();
assert_eq!(print(&rename_sheet(e, "Old", "New Name")), "'New Name'!A1+'New Name'!B2");
}
#[test]
fn rename_sheet_updates_qualified_names() {
let e = parse("Data!MyName+MyName+Other!MyName").unwrap();
assert_eq!(print(&rename_sheet(e, "data", "Numbers")), "Numbers!MyName+MyName+Other!MyName");
let e = parse("Data!MyName").unwrap();
assert_eq!(print(&rename_sheet(e, "Data", "New Name")), "'New Name'!MyName");
}
#[test]
fn moves_between_sheets() {
let mv = Edit::MoveToSheet { from: gridcraft_core::RangeRef::parse("A1:B2").unwrap(), to_sheet: "New Name".into(), to_row: 9, to_col: 3 };
for (host, input, expected) in [
("Source", "A1+$B$2+C3+SUM(A1:B2)", "'New Name'!D10+'New Name'!$E$11+C3+SUM('New Name'!D10:E11)"),
("Other", "A1+sOuRcE!$B2+Other!B2", "A1+'New Name'!$E11+Other!B2"),
("Source", "SUM(A1:C3)+SUM(Source:Other!A1)", "SUM(A1:C3)+SUM(Source:Other!A1)"),
] {
assert_eq!(print(&adjust(parse(input).unwrap(), host, "Source", &mv)), expected);
}
let edge = Edit::MoveToSheet {
from: gridcraft_core::RangeRef::parse("A1:B2").unwrap(),
to_sheet: "New Name".into(),
to_row: gridcraft_core::MAX_ROWS - 1,
to_col: 3,
};
assert_eq!(print(&adjust(parse("B2").unwrap(), "Source", "Source", &edge)), "#REF!");
for (from, input, row, col, expected) in [("A:A", "$A:$A", 0, 2, "Dest!$C:$C"), ("1:1", "$1:$1", 2, 0, "Dest!$3:$3")] {
let mv = Edit::MoveToSheet { from: gridcraft_core::RangeRef::parse(from).unwrap(), to_sheet: "Dest".into(), to_row: row, to_col: col };
assert_eq!(print(&adjust(parse(input).unwrap(), "Source", "Source", &mv)), expected);
}
}
#[test]
fn r1c1() {
let e = parse("A1+$B$2+SUM(C:C)").unwrap();
@@ -141,3 +220,84 @@ fn spans() {
let a1 = toks.iter().find(|t| t.tok == lexer::Tok::Word("A1".into())).unwrap();
assert_eq!((a1.start, a1.end), (4, 6));
}
#[test]
fn unbracketed_this_row_column() {
// Writers such as xlsxwriter spell `[@Units]` as `[[#This Row],Units]`.
let p = |f: &str| parse(f).unwrap_or_else(|e| panic!("{f}: {e}"));
let Expr::Binary(BinOp::Mul, a, _) = p("[[#This Row],Units]*[[#This Row],Price]") else { panic!() };
let Expr::Struct(s) = *a else { panic!() };
assert_eq!((s.specifiers.as_slice(), s.col_start.as_deref()), ([StructItem::ThisRow].as_slice(), Some("Units")));
assert_eq!(rt("[[#This Row],Units]*[[#This Row],Price]"), "[@Units]*[@Price]");
assert_eq!(rt("Sales[[#This Row],Units]"), "Sales[@Units]");
assert_eq!(rt("Sales[[#This Row], Units ]"), "Sales[@Units]");
assert_eq!(rt("[[#This Row],Units]+[@[Unit Price]]+Sales[[#This Row],[Qty]]"), "[@Units]+[@[Unit Price]]+Sales[@Qty]");
// Unexpected text between the brackets is an error, never silently dropped.
for bad in [
"[[#This Row]x]",
"[[#This Row],[A]]x",
"[[#Data],Col]",
"[[#This Row],A:B]",
"[x[#This Row]]",
"[[#This Row],]x",
"Sales[[#All],[A]]junk",
"Sales[[A],[B],[C]]",
"Sales[@[A]x]",
] {
assert!(parse(bad).is_err(), "{bad} should fail");
}
}
#[test]
fn trim_references() {
for f in [
"SUM(A1:.E10)",
"SUM(A1.:E10)",
"SUM(A1.:.E10)",
"SUM(A:.A)",
"SUM($A.:.$C)",
"ROWS(1:.5)",
"ROWS($1.:$5)",
"ROWS(1.:.5)",
"Sheet2!$A$1:.B9",
"Q1.2026!A1.:.B2",
"'Q1 2026'!A1:.B2",
"SUM(A1:.A9,B1.:B9)",
"A1:.A9*2",
] {
assert_eq!(rt(f), f, "round trip of {f}");
}
let Expr::Call(_, args) = parse("SUM(A1:.E10)").unwrap() else { panic!() };
assert!(matches!(args.as_slice(), [Expr::Unary(UnOp::Trim(TrimMode::Trailing), r)] if matches!(**r, Expr::Ref(_))));
// Decimals, row ranges and dotted names keep their meaning.
assert_eq!(parse("1.5+.5").unwrap(), Expr::Binary(BinOp::Add, Box::new(Expr::Number(1.5)), Box::new(Expr::Number(0.5))));
for f in ["SUM(1:5)", "Q1.2026!A1:B2", "my.name+1", "SUM(A1:B2)*1.5", "1.:5"] {
assert_eq!(rt(f), f);
}
assert_eq!(rt("'Q1.2026'!A1:B2"), "Q1.2026!A1:B2");
assert!(matches!(parse("Q1.2026!A1:B2").unwrap(), Expr::Ref(_)));
// File call forms.
assert_eq!(rt("SUM(_xlfn._TRO_TRAILING(A1:E10))"), "SUM(A1:.E10)");
assert_eq!(rt("_xlfn._TRO_LEADING(A:A)"), "A.:A");
assert_eq!(rt("_xlfn._TRO_ALL(Sheet1!A1:B2)"), "Sheet1!A1.:.B2");
// Not a range: printed as the equivalent call.
assert_eq!(rt("_xlfn._TRO_ALL(B2)"), "TRIMRANGE(B2,3,3)");
for bad in ["A1.:", ".:A1", "A1:.:B2", "A1.:.:B2"] {
assert!(parse(bad).is_err(), "{bad} should fail");
}
// R1C1 keeps the operator.
assert_eq!(print_r1c1(&parse("SUM(A1:.B2)+ROWS(2.:2)").unwrap(), gridcraft_core::CellRef::new(0, 0)), "SUM(RC:.R[1]C[1])+ROWS(R[1].:R[1])");
}
#[test]
fn trim_references_adjust() {
let ins = Edit::Insert { axis: Axis::Rows, at: 2, count: 2 };
let e = parse("SUM(A1:.A5)+SUM(B:.B)+ROWS(2.:.4)").unwrap();
assert_eq!(print(&adjust(e, "S", "S", &ins)), "SUM(A1:.A7)+SUM(B:.B)+ROWS(2.:.6)");
let del = Edit::Delete { axis: Axis::Cols, at: 0, count: 1 };
let e = parse("SUM(A1.:C1)+SUM(A:.A)").unwrap();
assert_eq!(print(&adjust(e, "S", "S", &del)), "SUM(A1.:B1)+SUM(#REF!)");
assert_eq!(print(&shift_relative(parse("SUM(A1.:.B2)").unwrap(), 1, 1)), "SUM(B2.:.C3)");
let refs: Vec<String> = parse("SUM(Sheet2!A1:.B5)").unwrap().references().iter().map(|r| printer::reference_a1(r)).collect();
assert_eq!(refs, ["Sheet2!A1:B5"]);
}
+100
View File
@@ -0,0 +1,100 @@
use gridcraft_formula::{FormulaLocale, parse, parse_input, print, print_input};
fn input(src: &str) -> String {
print(&parse_input(src, FormulaLocale::Es, |_| false).unwrap())
}
#[test]
fn spanish_aliases_and_argument_separators() {
for (src, expected) in [
("=suma(A1:A10)", "SUM(A1:A10)"),
("PROMEDIO(A1:A10)", "AVERAGE(A1:A10)"),
("SI(A1>0;\"Sí\";\"No\")", "IF(A1>0,\"Sí\",\"No\")"),
("CONTAR(A1:A10)", "COUNT(A1:A10)"),
("SUMAR.SI(A1:A10;\">0\")", "SUMIF(A1:A10,\">0\")"),
("CONTAR.SI(A1:A10;\">0\")", "COUNTIF(A1:A10,\">0\")"),
("BUSCARV(A2;D:E;2;FALSO)", "VLOOKUP(A2,D:E,2,FALSE)"),
("HOY()", "TODAY()"),
("=verdadero", "TRUE"),
("=falso", "FALSE"),
("VERDADERO()", "TRUE()"),
("FALSO()", "FALSE()"),
("SUMA(1;SUM(2;3);PROMEDIO(4;6))", "SUM(1,SUM(2,3),AVERAGE(4,6))"),
("SI(VERDADERO;;)", "IF(TRUE,,)"),
("LAMBDA(x;x+1)(2)", "LAMBDA(x,x+1)(2)"),
] {
assert_eq!(input(src), expected, "{src}");
}
}
#[test]
fn spanish_input_preserves_reference_and_array_syntax() {
for (src, expected) in [
("SUMA({1\\2;3\\4};5)", "SUM({1,2;3,4},5)"),
("{VERDADERO\\FALSO;TRUE\\FALSE}", "{TRUE,FALSE;TRUE,FALSE}"),
("SUM((A1:A3;C1:C3))", "SUM((A1:A3,C1:C3))"),
("\"SUMA;FALSO\"&\"a\"\"b\"", "\"SUMA;FALSO\"&\"a\"\"b\""),
("'SUMA;FALSO'!A1+SUMA!B2+SUMA!FALSO", "'SUMA;FALSO'!A1+SUMA!B2+SUMA!FALSO"),
("SUMA[CONTAR.SI]+FALSO[SI]+CONTAR", "SUMA[CONTAR.SI]+FALSO[SI]+CONTAR"),
] {
assert_eq!(input(src), expected, "{src}");
}
for bad in [r"SUMA({1;2\3})", "{SUMA(A1)}", "{FALSO;}"] {
assert!(parse_input(bad, FormulaLocale::Es, |_| false).is_err(), "{bad}");
}
assert_eq!(print(&parse("SUMA(1,2)+FALSO").unwrap()), "SUMA(1,2)+FALSO");
assert!(parse("SUM(1;2)").is_err());
assert!(parse("{VERDADERO}").is_err());
// Pratt parsing can produce a deep left-hand AST without deep parser recursion.
let long_chain = "FALSO+".repeat(300) + "VERDADERO";
assert!(parse_input(&long_chain, FormulaLocale::Es, |_| false).is_err());
assert!(print_input(&parse(&long_chain).unwrap(), FormulaLocale::Es, |_| false).is_err());
}
#[test]
fn spanish_input_preserves_defined_and_local_names() {
let known = |name: &str| ["SUMA", "FALSO"].iter().any(|n| n.eq_ignore_ascii_case(name));
let expr = parse_input("SUMA(2;3)+FALSO+SI(VERDADERO;4;5)", FormulaLocale::Es, known).unwrap();
assert_eq!(print(&expr), "SUMA(2,3)+FALSO+IF(TRUE,4,5)");
for (src, expected) in [
("LET(FALSO;7;FALSO)", "LET(FALSO,7,FALSO)"),
("LET(falso;FALSO;SI(falso;1;2))", "LET(falso,FALSE,IF(falso,1,2))"),
("LET(SUMA;LAMBDA(x;x+1);SUMA(2))", "LET(SUMA,LAMBDA(x,x+1),SUMA(2))"),
("LET(falso;7;valor;FALSO;valor)", "LET(falso,7,valor,FALSO,valor)"),
("LAMBDA(FALSO;FALSO)(7)", "LAMBDA(FALSO,FALSO)(7)"),
("LAMBDA(SUMA;SUMA(2))(LAMBDA(x;x+1))", "LAMBDA(SUMA,SUMA(2))(LAMBDA(x,x+1))"),
("LET(FALSO;7;FALSO)+FALSO", "LET(FALSO,7,FALSO)+FALSE"),
("LET(FALSO;7;LAMBDA(x;FALSO+x)(1))", "LET(FALSO,7,LAMBDA(x,FALSO+x)(1))"),
] {
assert_eq!(input(src), expected, "{src}");
}
}
#[test]
fn locale_controls_decimal_list_array_separators_and_display() {
let es = FormulaLocale::Es;
let en = FormulaLocale::En;
let expr = parse_input("SI(VERDADERO;SUMA(1,5;2,25);0)", es, |_| false).unwrap();
assert_eq!(print(&expr), "IF(TRUE,SUM(1.5,2.25),0)");
assert_eq!(print_input(&expr, es, |_| false).unwrap(), "SI(VERDADERO;SUMA(1,5;2,25);0)");
assert_eq!(print_input(&expr, en, |_| false).unwrap(), print(&expr));
assert!(parse_input("SUM(1;2)", en, |_| false).is_err());
assert_eq!(print(&parse_input("SUMA(1,2)+FALSO", en, |_| false).unwrap()), "SUMA(1,2)+FALSO");
assert!(parse_input("SUMA(1.5;2)", es, |_| false).is_err());
let expr = parse("SUM({1.5,2.25;3,4})+SUM((A1:A3,C1:C3))").unwrap();
let shown = print_input(&expr, es, |_| false).unwrap();
assert_eq!(print(&parse_input(&shown, es, |_| false).unwrap()), print(&expr));
let expr = parse("LET(SUMA,LAMBDA(x,x+1),SUM(SUMA(2),FALSE))").unwrap();
let shown = print_input(&expr, es, |n| n == "FALSO").unwrap();
assert_eq!(shown, "LET(SUMA;LAMBDA(x;x+1);SUM(SUMA(2);FALSE))");
assert_eq!(print(&parse_input(&shown, es, |n| n == "FALSO").unwrap()), print(&expr));
}
#[test]
fn spanish_display_round_trips_text_containing_separators() {
let es = FormulaLocale::Es;
let expr = parse(r#"IF(A1="a,b;c",CONCAT("1.5",",",";"),SUM(0.25,A1:A3 B2))"#).unwrap();
let shown = print_input(&expr, es, |_| false).unwrap();
assert_eq!(shown, r#"SI(A1="a,b;c";CONCAT("1.5";",";";");SUMA(0,25;A1:A3 B2))"#);
assert_eq!(print(&parse_input(&shown, es, |_| false).unwrap()), print(&expr));
}
+13 -4
View File
@@ -3,7 +3,7 @@
use std::cmp::Ordering;
use gridcraft_core::parse::parse_number_text;
use gridcraft_core::{CellError, Value, compare_text};
use gridcraft_core::{CellError, Value, compare_numbers, compare_text};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Op {
@@ -113,7 +113,7 @@ impl Criterion {
_ => None,
};
match cell {
Some(x) => cmp_op(self.op, x.partial_cmp(n).unwrap_or(Ordering::Equal)),
Some(x) => cmp_op(self.op, compare_numbers(x, *n)),
None => self.op == Op::Ne,
}
}
@@ -127,9 +127,9 @@ impl Criterion {
},
Operand::Text(pat) => match self.op {
Op::Eq | Op::Ne => {
// Blank cells hold no text: `"*"` skips them and `"<>*"` counts them.
let cell_text = match &v {
Value::Text(t) => Some(t.to_string()),
Value::Empty => Some(String::new()),
_ => None,
};
let m = cell_text.is_some_and(|t| wildcard_match(pat, &t));
@@ -252,7 +252,7 @@ pub(crate) fn lookup_equal(needle: &Value, hay: &Value, wild: bool) -> bool {
compare_text(p, t) == Ordering::Equal
}
}
(Value::Number(a), Value::Number(b)) => a == b,
(Value::Number(a), Value::Number(b)) => compare_numbers(*a, *b) == Ordering::Equal,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::Error(a), Value::Error(b)) => a == b,
(Value::Empty, Value::Empty) => true,
@@ -294,8 +294,17 @@ mod tests {
assert!(!m("<b", Value::Number(1.0)));
assert!(m("#N/A", Value::Error(CellError::NA)));
assert!(Criterion::parse(&Value::Number(3.0)).matches(&Value::Number(3.0)));
assert!(Criterion::parse(&Value::Number(0.3)).matches(&Value::Number(0.1 + 0.2)));
assert!(lookup_equal(&Value::Number(0.3), &Value::Number(0.1 + 0.2), false));
assert!(m("<>a*", Value::from("bcd")));
assert!(m(">1/1/2020", Value::Number(44000.0)));
// Text patterns never match blank cells, but an empty string is text.
assert!(!m("*", Value::Empty));
assert!(m("*", Value::from("")));
assert!(m("<>*", Value::Empty));
assert!(!m("<>*", Value::from("")));
assert!(!m("?*", Value::Empty));
assert!(m("<>a*", Value::Empty));
}
#[test]
+54 -4
View File
@@ -1,6 +1,6 @@
//! Date and time functions.
use gridcraft_core::date::{DateTime, datetime_from_serial, days_in_month, is_leap, serial_from_ymd};
use gridcraft_core::date::{DateTime, datetime_from_serial, days_in_month, days_in_month_in, is_leap, serial_from_ymd};
use gridcraft_core::parse::parse_input;
use gridcraft_core::{CellError, DateSystem, Value};
@@ -164,7 +164,7 @@ fn edate(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
if !(1900..=9999).contains(&y) {
return Err(CellError::Num);
}
let dd = (d.day.max(1) as i64).min(days_in_month(y as i32, mo as u32) as i64);
let dd = (d.day.max(1) as i64).min(days_in_month_in(sys, y as i32, mo as u32) as i64);
num_val(ymd_serial(sys, y, mo, dd)? as f64)
}
@@ -177,7 +177,7 @@ fn eomonth(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
if !(1900..=9999).contains(&y) {
return Err(CellError::Num);
}
num_val(ymd_serial(sys, y, mo, days_in_month(y as i32, mo as u32) as i64)? as f64)
num_val(ymd_serial(sys, y, mo, days_in_month_in(sys, y as i32, mo as u32) as i64)? as f64)
}
fn datedif(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
@@ -496,7 +496,16 @@ pub(crate) fn specs() -> Vec<FnSpec> {
f!("ISOWEEKNUM", 1, 1, DateTime, S, "ISOWEEKNUM(date)", "Returns the ISO 8601 week number of a date.", isoweeknum),
f!("EDATE", 2, 2, DateTime, S, "EDATE(start_date, months)", "Returns the date a number of months before or after a date.", edate),
f!("EOMONTH", 2, 2, DateTime, S, "EOMONTH(start_date, months)", "Returns the last day of the month a number of months away.", eomonth),
f!("DATEDIF", 3, 3, DateTime, S, "DATEDIF(start_date, end_date, unit)", "Counts whole years, months or days between two dates.", datedif),
f!(
"DATEDIF",
3,
3,
DateTime,
S,
"DATEDIF(start_date, end_date, unit)",
"Counts whole years, months or days between two dates. unit: Y, M, D, MD, YM or YD.",
datedif
),
f!("DATEVALUE", 1, 1, DateTime, S, "DATEVALUE(date_text)", "Converts a date written as text into a date serial number.", datevalue),
f!("TIMEVALUE", 1, 1, DateTime, S, "TIMEVALUE(time_text)", "Converts a time written as text into a fraction of a day.", timevalue),
f!("DAYS", 2, 2, DateTime, S, "DAYS(end_date, start_date)", "Returns the number of days between two dates.", days),
@@ -652,6 +661,36 @@ mod tests {
is_err(ev("EDATE", vec![n(1.0), n(1e12)]), CellError::Num);
}
#[test]
fn fictitious_1900_02_29() {
// Excel's 1900 calendar has 29 February 1900 = serial 60, and DATE counts day and month
// overflow through it.
assert_eq!(d(1900.0, 2.0, 29.0), 60.0);
assert_eq!(d(1900.0, 3.0, 0.0), 60.0);
assert_eq!(d(1900.0, 2.0, 28.0), 59.0);
assert_eq!(d(1900.0, 3.0, 1.0), 61.0);
assert_eq!(d(1900.0, 2.0, 30.0), 61.0);
assert_eq!(d(1900.0, 1.0, 60.0), 60.0);
assert_eq!(d(1900.0, 4.0, -31.0), 60.0);
assert_eq!(d(1901.0, -10.0, 29.0), 60.0);
assert_eq!(d(0.0, 2.0, 29.0), 60.0);
assert_eq!(d(1900.0, 1.0, 0.0), 0.0);
close(ev("DAY", vec![n(d(1900.0, 3.0, 0.0))]), 29.0);
close(ev("DATEVALUE", vec![t("1900-02-29")]), 60.0);
close(ev("DATEVALUE", vec![t("2/29/1900")]), 60.0);
close(ev("DATEVALUE", vec![t("3/1/1900")]), 61.0);
is_err(ev("DATEVALUE", vec![t("2/29/1901")]), CellError::Value);
// EDATE and EOMONTH land on it as the end of February 1900.
close(ev("EOMONTH", vec![n(d(1900.0, 1.0, 15.0)), n(1.0)]), 60.0);
close(ev("EOMONTH", vec![n(60.0), n(0.0)]), 60.0);
close(ev("EOMONTH", vec![n(d(1900.0, 3.0, 15.0)), n(-1.0)]), 60.0);
close(ev("EOMONTH", vec![n(60.0), n(12.0)]), d(1901.0, 2.0, 28.0));
close(ev("EDATE", vec![n(d(1900.0, 1.0, 31.0)), n(1.0)]), 60.0);
close(ev("EDATE", vec![n(d(1900.0, 3.0, 31.0)), n(-1.0)]), 60.0);
close(ev("EDATE", vec![n(60.0), n(1.0)]), d(1900.0, 3.0, 29.0));
close(ev("EDATE", vec![n(60.0), n(12.0)]), d(1901.0, 2.0, 28.0));
}
#[test]
fn datedif_units() {
let s = n(d(2001.0, 6.0, 1.0));
@@ -755,5 +794,16 @@ mod tests {
close(crate::call(spec, &[n(0.0)], &mut ctx), 6.0);
let spec = crate::lookup("YEAR").unwrap();
close(crate::call(spec, &[n(0.0)], &mut ctx), 1904.0);
// No fictitious day here: 1904 is a real leap year and 1900 is before the epoch.
let spec = crate::lookup("DATE").unwrap();
close(crate::call(spec, &[n(1904.0), n(2.0), n(29.0)], &mut ctx), 59.0);
close(crate::call(spec, &[n(1904.0), n(3.0), n(0.0)], &mut ctx), 59.0);
close(crate::call(spec, &[n(1904.0), n(3.0), n(1.0)], &mut ctx), 60.0);
is_err(crate::call(spec, &[n(1900.0), n(2.0), n(29.0)], &mut ctx), CellError::Num);
let spec = crate::lookup("EOMONTH").unwrap();
close(crate::call(spec, &[n(31.0), n(0.0)], &mut ctx), 59.0);
let spec = crate::lookup("DATEVALUE").unwrap();
close(crate::call(spec, &[t("2/29/1904")], &mut ctx), 59.0);
is_err(crate::call(spec, &[t("2/29/1900")], &mut ctx), CellError::Value);
}
}

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