Compare commits

..
Author SHA1 Message Date
FredApps 20dc8ccd85 Keep the replacement unsaved workbook prompt active 2026-12-04 18:27:11 +01:00
FredApps 578fa5c4bf Merge remote-tracking branch 'origin/main' into review/grid-5079-fix 2026-12-04 18:25:15 +01:00
Dylan M. Taylor fe6195d207 Merge pull request #5081 from storytold/docs/freebsd-15-1-requirement
docs: document FreeBSD 15.1 minimum for prebuilt packages
2026-12-04 09:48:56 -05:00
Dylan M. Taylor 6ee8f4b6df docs: document FreeBSD 15.1 minimum for prebuilt packages 2026-12-04 09:09:19 -05:00
arnav-hiwarkarandClaude Opus 5.5 e360fe5bcc test(ui): check the unsaved question's order on the OS its footer uses
The order test asked cfg!(windows), but the footer orders by the shell's
OS (os_of), which a test harness need not share with the host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 19:19:28 +05:30
Harrison BoothandFredApps 31f1ad07f4 XLSX: keep a table's query table on save (#2507)
* XLSX: keep a table's query table on save

A table that is the result of a data-connection query now keeps its query table part, its type and connection, and its columns' field ids when saved.

* XLSX: check the query table root and keep its column links on save

A query table part is kept only when its root is queryTable in the SpreadsheetML
namespace. On save each retained queryTableField points at its column's new id,
found through the field id the column keeps, so moved or inserted columns still
read from their own field.

* XLSX: mutate the shared sheet through Arc::make_mut in the query table test

* XLSX: keep query fields through resize and drop orphaned ones on save

A resized table keeps a renamed column's metadata by position before matching
names, and a retained query table part follows its columns' new ids for any
quote style. A field whose column was removed is dropped with the count.

* XLSX: accept a prefixed query table root and whitespace before it

The query table root check reads the local name and the xmlns binding of its
prefix, and skips whitespace-only text before the root.

* Engine: mutate the shared workbook through Arc::make_mut in the resize test

* XLSX: remap query table fields by local name so a prefixed query table keeps its links

* XLSX: remove a duplicated table relationship line after the query table block

* XLSX: fix the table resize test's active sheet index after the main merge

* Import XML parser in query table reader

* Remove unused XML reader imports

* Remove duplicate XLSX writer import

* Initialize query table fields in new tables

* Fill query table fields in test initializers

* Use quick-xml string interfaces for XLSX query fields

* Format query table integration

---------

Co-authored-by: FredApps <[email protected]>
2026-12-04 13:20:54 +01:00
9558000414 View: dashed page breaks in Normal view, turned on by Page Break Preview and in Options (#2474) (#2494)
* View: dashed page breaks in Normal view, turned on by Page Break Preview and in Options (#2474)

* View: page-break dashes get their own token, dark enough on the white grid in both themes

The dashes used text_dim, which is a light 0xB0 gray in the dark theme while
the grid stays white: about 2.2:1. page_break is 0x61 in both themes (6.2:1),
the shade light mode already drew.

* Engine fuzz: Show page breaks is view state, like the view mode it follows

* Fix page break boundaries and custom paper import

* Show printable page capacity while editing

* Initialize paper test setup directly

* Keep page break visibility with stable sheet identity

* Remove obsolete sheet type import

---------

Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-04 11:46:23 +01:00
FredApps d99ea8ca0f Merge pull request #7 from switch87/readme-gentoo
README: install on Gentoo from the ::snakebyte overlay
2026-12-04 11:42:50 +01:00
arnav-hiwarkarandClaude Opus 5.5 b3ad9a2a72 test(ui): give the macro question's button lookup a static label
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 16:02:27 +05:30
FredApps 9b15f7b3d7 Merge main for Gentoo package documentation 2026-12-04 11:29:33 +01:00
arnav-hiwarkarandClaude Opus 5.5 c2e86e97fd fix(ui): keep the close question's answer when a quit takes it over
Quitting (or the window's close button) while File › Close asks about a workbook reopens the
question as the quit's. The dialog host stores a Cancel for the question it replaces, which the
next pass took as the answer: the prompt state was dropped, and the quit's question then did
nothing when answered. The stale Cancel is now discarded on the takeover.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:35:34 +05:30
arnav-hiwarkarandClaude Opus 5.5 93a5246ec3 fix(ui): ask about a macro's unsaved steps with the shared dialog
The macro step editor asked its own "Save changes to macro?" with Save, Don't Save and Cancel
drawn right to left. It now shows the shared unsaved-changes question named for the macro
(closing, or quitting while the app quits), in the same order, words and keys as the workbook
question: Save is focused first and answers Enter, Escape cancels, Cmd+D answers Don't Save.
Each asking gets its own area so the question opens again after an answer.

Tests: the editor tests find the question by its shared wording; new tests check the editor's
question order and that Enter saves the draft, and that the workbook question starts on Save
and Enter saves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:34:37 +05:30
arnav-hiwarkarandClaude Opus 5.5 99d8754611 fix(ui): show the unsaved-changes question only in its own window's pass
A quit that moved on to the next unsaved workbook from inside another window's pass (the
macro editor closing, a Don't Save answer) opened that workbook's question and then drew
it for one frame in the window being drawn, because the check compared against the window
current after the switch. The pass now decides by the window it began drawing.

doc_windows test backend: like eframe, every pass's input lists each open window; without
the child windows listed, the UI runtime dropped a child window's dialog layers and focus
at every frame, so a question in a secondary window could never take its keys. The answer
helper also lets the question show for two frames before the key: the shared dialog takes
Cmd+D only from the pass after one in which it was already the top modal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:28:49 +05:30
arnav-hiwarkarandClaude Opus 5.5 a2df25c9bd fix(ui): ask about unsaved changes with the shared dialog
Route the engine's saveChanges dialog request to craft_ui::dialog::UnsavedChangesDialog on framework_dialogs with document wording, remove the custom saveChanges dialog and its unused i18n strings, and update UI/doc-window tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 15:28:49 +05:30
fb7ca98282 Docs: merge duplicate gaps and .xlsx rows; refresh gaps 4, 9, 15, 19 to the code (#2509)
* docs: merge duplicate gaps and .xlsx rows; refresh gaps 4, 9, 15, 19 to the code

* docs: drop the CSV clause from the gap 19 revision entry; gap 19 no longer states it

* docs: fix CodeRabbit review findings on the parity docs

- file-format-parity: the .xlsx size limits are the implemented ones (512 MiB
  package part, 64 MiB and 256 MiB pass-through); drop the unsupported 100 MB
  claim; Strict Open XML keeps none of the pass-through content
- file-format-parity: merge the duplicate .txt row
- gaps: Series formatting covers colour, smoothing and trendlines
- ui-parity: charts resize from the corner handle and Format Chart Area Size

* Avoid a stale key-tip sequence count in parity docs

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-04 10:51:44 +01:00
Hamza NaveedandFredApps 2da139915f Sheet protection: a line is locked only by a format it has (#1790)
* Sheet protection: a line is locked only by a format of its own

`unwrap_or_default()` gave the default style, which is locked, so a row or
column with no format of its own counted as locked and every delete on a
protected sheet was refused -- including one the Delete rows/columns
permission allows over cells the user had unlocked, which is the whole point
of granting it. It also left the cell scan below unreachable, so the
permission never did anything at all.

A line with no format of its own is judged by its cells, as the scan below
intends.

Rebased onto main, 352 commits on: the guard is unchanged in
engine/src/cmd/sheet.rs and the test went to engine/src/tests.rs. The test
grants the permission, unlocks the cells and deletes, which fails with the
old guard on "The cell or chart you're trying to change is on a protected
sheet."

* Protect Sheet: delete a row or column only when every cell in it is unlocked, as Excel does

* Protected delete: unformatted cells follow an unlocked Normal style

When neither the line nor the crossing line has a format, a cell takes
the workbook's Normal style. A file may unlock it, and then every such
cell is unlocked, stored or not, so the delete is allowed.

Signed-off-by: FredApps <[email protected]>

* Protected delete: the default's description allows an unlocked Normal; the test requires a protected sheet

LockedLines' doc said the default style is locked, which the Normal-style branch below it contradicts. The unlocked-Normal test set the delete permissions only if sheet 0 had protection, so without it both deletes passed unchecked; it now requires protection (review).

---------

Signed-off-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-04 10:36:14 +01:00
86ba6b5138 Charts: add Pareto charts (#1826)
* Charts: add Pareto charts

* Charts: address Pareto review findings

* Charts: cap Pareto cumulative line and guard signed values

* Charts: fix the Pareto axis at 0–100% (#1826)

The secondary axis came from nice_scale(0.0, 1.0, true), which adds headroom, so it read 0%–120% while the cumulative line filled the plot height. Use a fixed 0–1 scale with a 0.2 step, matching Excel, and add a regression test for the ticks and the line's alignment.

* Charts: translate the Pareto labels into every catalog (#1826)

The new "Pareto" and "Cumulative %" keys belong in the shared reference set, so the catalogs main added after the branch point (el, it, nl, pl, ro, tr, uk, vi) need them too; update the catalog counts.

* Docs: drop the duplicate parity rows after the rebase

The rebase kept main's Charts and Page layout rows and Pareto's updated copies, leaving both tables with each area twice. Keep main's newer rows, drop Pareto from the missing list and restore the inventory bullet.

* Charts: count Pareto in the chart lists

Adding ChartKind::Pareto grew chart's ALL_KINDS to 27 and the All Charts dialog's ALL_CHARTS to 22, but the array lengths still said 26 and 21, so both test targets failed to compile.

* Charts: use the second theme accent for the Pareto line fallback (#1826)

* Docs: keep main's rows and drop duplicates after the rebase (#1826)

The dedupe kept main's stale first Charts row and dropped the row main corrected on 2026-10-18 (kinds survive the round trip, trendlines landed). Keep the corrected text with the PR's 26-kind count and no Pareto gap, and keep one Page layout row.

* Charts: assert the Pareto cumulative line by its width and points, not the series colour (#1826)

* Docs: keep the chart-sheet limitation and drop Pareto from the remaining work (#1826)

* Docs: keep the chart-sheet limitation accurate after the main merge (#1826)

The upstream merge brought back 'chart sheets' as missing outright and
dropped the trendline round-trip note. Chart sheets are preserved
unchanged on XLSX save but cannot be edited or created; trendlines are
modelled and round-trip.

* fix(xlsx): preserve hidden Pareto series across chartex round trips

- Keep Excel's extra Pareto value columns by reading hidden clusteredColumn series from chartEx XML.
- Treat only true hidden literals as hidden, matching the pinned craft-drawingml parser so hidden="0" stays index-aligned with its parsed series.
- Cover both paths in pareto_multi_series_keeps_one_hidden_column_per_extra_series.

* test(xlsx): read the hidden="0" Pareto check straight from the chartEx part

- The zip-stream mutation was not byte-equivalent; parse the chartEx XML directly instead.

* style(xlsx): apply cargo fmt to the Pareto chartex parser

* #1819: Index ChartEx data references when importing Pareto series

---------

Co-authored-by: alosslessdev <[email protected]>
Co-authored-by: Your Name <[email protected]>
Co-authored-by: Your New Name <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-04 09:58:55 +01:00
5a850f6a72 XLSX: per-child allowances for streamed shared strings and Python scripts; warnings for repeated and out-of-order cells (#2532)
* XLSX: per-child allowances for streamed shared strings and Python scripts; warnings for repeated and out-of-order cells

The streaming parser that reads the shared-string table and the Python
part is told which children each streamed element may hold, and how
many: a shared string one `phoneticPr` and its text (`t`, `r`, `rPh`)
without a count; a `pythonScript` one `code`. An unknown name is
admitted once, for at most MAX_UNLISTED_CHILD_NAMES names. A child past
its allowance is dropped with its subtree and counted.

Inside a streamed element the element cap no longer fails the part: the
element that would pass it is dropped and counted, and so is each
element holding it up to the streamed element's own child, which is lost
whole. A child lost at the cap gives back its place in its name's
allowance, so a later child of that name can still be read. Later
children that fit, and later strings and scripts, are still read (main
kept only what came before). When the cap was already reached before the
streamed element that holds a child being dropped began (the innermost
open one, so also one that begins inside another), nothing in it can be
kept, and the part fails as on main, at the first element that closes
inside it. A streamed element that holds no element (`<si/>`,
`<si></si>`, or one holding only whitespace) is still handed out
with the cap full, as on main: the cap bounds the elements the parser
holds, and it holds none. The streamed element is marked cut
only when the child it lost has a listed name, and the mark records
which listed names it lost (a bit per name in `El::cut`, read with
`El::lost`); an unknown element holds nothing the reader reads. An
unknown name whose child is dropped at the cap gives back its place
among the unknown names the element may hold.

A shared string that lost text (a `t` or a run) at the cap keeps the
children that fit, with a warning, and drops its phonetic runs, since
their offsets point into the text as the file held it, and its phonetic
properties, which would otherwise be filed under the shortened text and
take the place of an intact string's reading of that text. The warning
counts every phonetic run dropped from a string that lost text, damaged
runs and those of a string that counts as missing included, and the
strings whose phonetic properties went. One that lost only phonetic
parts (an `rPh` or its `phoneticPr`) keeps its text and its other runs.
A string that lost text and kept none (an empty run kept before the lost
text holds none) counts as a missing string, as on main: its cells are
empty, the existing warning about missing shared strings is given, and
the strings after it keep their indexes (the table holds an Option per
string). A Python script that lost its code at the cap and kept no code
after it (none, or an empty one) counts as missing code: a cell naming
it keeps its cached value without Python code, as main does for missing
code. Unknown children of a script that fit are left out, as on main,
and a warning now counts them, also when the part turns out damaged
after them, as the shared-string reader does.

GridCraft places each worksheet cell where its address says, as on main,
a later cell read again where an earlier one was; a picture cell keeps
its picture, and an empty cell leaves a Python spill value. A warning
now counts cells that repeat an address and rows whose properties
are read again over ones already read (the later ones kept); another
counts cells out of column order or in another row's element. A cell
of a row element's own row at a column
held already, by that element or by the elements for the same row right
before it, is a repeat, whatever the reader stored for it (a bitmap of
the columns read, cleared when a row element of another row number
begins, up to the highest word the elements before it touched).
Otherwise a repeat is seen at the furthest position read so far, or
before it where a cell, a cell picture or a spill value is stored, so a
cell that repeats one the reader stores nothing for (a blank cell
without a style, a value inside another formula's array) is not counted
as a repeat when an element for another row sits between the two copies,
or one of them sits in another row's element, unless it is at the
furthest position; it is counted as out of place when it sits in another
row's element or out of column order. A cell counted as a repeat is
not also counted there; any other cell is, when it names another row
than the row element it sits in, whatever its column, or when its column
is not to the right of the rightmost column among the cells read before
it in that element. Only cells not past the furthest one are looked up.

Cell text longer than MAX_CELL_CHARS (UTF-16 units) is kept whole, and a
warning per sheet counts the long texts read: shared and inline strings,
the cached text of a formula that doesn't parse, and spill values, but
not a picture's fallback, a value inside another formula's array, or a
parsing formula's cached result. The count is taken as each cell is
read, so a long text that a later cell replaces is still counted.
The length is decided from the byte length where that is enough (up to
the limit in bytes it is within it, past three times the limit it is
over) and otherwise by counting bytes, not by decoding characters.
MAX_CELL_CHARS joins MAX_ROWS and MAX_COLS in gridcraft_core::addr,
and MAX_TEXT_CHARS in gridcraft_core::value is now derived from it;
docs/file-format-parity.md records the change.

Tests: crates/xlsx/src/tests/limits.rs (allowances at and past the
limit, unknown names, the cap at its edge and inside a run, a string
that loses only an unknown element at the cap, a string that lost all
its text at the cap, or kept only an empty run, a string that lost text
and had phonetic runs, a string that lost all its text and had phonetic
runs, one that lost text and kept its phonetic properties, before and
after an intact string with the same text, through a save, one that lost
only a phonetic run or its phonetic properties, one with empty text that
lost only a phonetic run, a string at the cap and one past it, an empty
`t` lost at the cap taken as lost text by name, run formatting and an
unknown element inside a run left out without a warning, repeated
cells and rows, repeats of cells the reader stores nothing for, in one
row element, in elements for the same row in a row, and after another
row's element, every sequence of up to three cells over two columns and
two rows split across up to three row elements against a plain reading
of the rule, out-of-order cells left of the rightmost one, cells in
columns CV and XFD of two rows in a row, long text at the limit and one
past it, a shared string over the limit in bytes but not in UTF-16
units, 20,000 repeats of a cell using a long shared string),
richdata_tests.rs (picture cells with repeats, through a save),
the parser's tests in xml.rs (a string inside another that begins with
the cap full, strings holding no element handed out with the cap full,
one under it and three in a row, which listed children a string lost at
the cap, an unknown name dropped at the cap freeing its place) and
python_part.rs, and
crates/engine/src/tests/python_files.rs (long spilled text, repeats in a
spill, code dropped at the cap, an empty script with the cap full, a
second code taken when the first is dropped at the cap, an empty code
after one dropped at the cap, a second code crossing the cap after a
kept one, a script without code whose unknown element crosses the cap, a
second code, through a save, unknown children of scripts counted in one
warning, none, and in a part damaged after them).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Preserve text boundaries when shared-string runs are dropped

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-04 09:43:08 +01:00
FredApps 0f2589bfef Merge pull request #3408 from alosslessdev/dax/eval-datetime
dax: date/time, time-intelligence and math/trig functions on the merged DAX core (#2228)
2026-12-04 07:18:47 +01:00
FredApps ba82b95ca0 Merge branch 'main' into dax/eval-datetime 2026-12-04 07:03:30 +01:00
FredApps 41a5eb8a56 Merge pull request #4272 from gmrmad1/fix/cell-style-gallery-i18n-4249
fix(ui): translate the Cell Styles gallery labels (#4249)
2026-12-04 06:35:03 +01:00
FredApps 966b87337f Merge branch 'main' into fix/cell-style-gallery-i18n-4249 2026-12-04 05:57:49 +01:00
gmrmad1andFredApps 2aa1ac4683 fix(functions): HYPGEOM.DIST clamps successes outside the support (#4032) (#4281)
* stat: HYPGEOM.DIST clamps successes outside the support (#4032)

* functions: keep HYPGEOM.DIST strict below its support

Native Excel returns #NUM! below the hypergeometric support while clamping above it to 0/1 (#4032), so only the above-support side smooths. The test now expects #NUM! for the positive below-support case in both cumulative modes and keeps the documented above-support results and the legacy strict form.

---------

Co-authored-by: FredApps <[email protected]>
2026-12-04 05:52:20 +01:00
Valentin Klein 623061303f Recalculate TRIMRANGE faster on mostly empty sheets (#5020)
* Find trim bounds without allocating a dense grid for sparse values

* Keep trim range reads fast with late formulas and verify spill bounds
2026-12-03 16:01:18 +01:00
gmrmad1 c05683be93 fix(functions): a blank XMATCH/XLOOKUP lookup reference is blank, not zero (#4044) (#4256)
* lookup: a blank XMATCH/XLOOKUP lookup reference is blank, not zero (#4044)

* review: keep a blank lookup needle blank in binary exact search (CodeRabbit)

bsearch_exact compared the blank needle through the coercing binary_order,
which reads it as numeric zero, so XMATCH(blank-ref,{0},0,2) returned 1.
Handle a blank needle first: blanks sort last in both directions, so the
first blank entry is the only possible exact match. Add binary-mode cases
and a parser-level written-blank control.

* functions: keep an exact blank match in XMATCH binary approximate mode

Blanks sort last, beyond the probes used for match_mode -1/+1, so a blank lookup value lost a present blank entry in binary search modes 2 and -2. Check the exact blank position before the approximate fallback; add both search directions for XMATCH and XLOOKUP, with and without a preceding zero key.

* review: a blank XMATCH needle never falls through to the approximate zero probe
2026-12-03 15:36:23 +01:00
Your New Name 9622664cd5 dax: check the fourth RANKX argument resolves to the model table
- The shadowing test only asserted the bound expression contained a `Table`, which the
  first argument (`Sales`) already supplies, so a `YEAR` keyword or `Sales` bind passed.
- Match the fourth argument against `BoundExpr::Table` with the pushed `YEAR` table index.
2026-12-02 09:31:14 -05:00
Madhav Agarwal 1aef9a961d a11y: name the Cell Styles swatches and expose them as buttons
Each swatch is now a labelled Button in the accessibility tree with its translated name, so assistive tech can find and activate it. A kittest regression clicks the Japanese Heading 1 swatch and checks that home.cellStyle still applies the English built-in style (15 pt bold), keeping the persisted command key unchanged.
2026-12-02 15:41:25 +05:30
FredApps f528d1233f Merge branch 'main' into dax/eval-datetime 2026-12-02 05:58:07 +01:00
Your New Name 95d904dfe2 dax: bind interval keywords ahead of variables and model names (#3408) 2026-12-01 23:21:38 -05:00
Your New Name ed6f1852c6 Merge upstream/main into dax/eval-datetime (#3408) 2026-12-01 22:51:11 -05:00
Your New Name 1ce588b785 dax: reject DATEADD over a non-contiguous date selection (#3408) 2026-11-29 14:29:06 -05:00
FredApps 8cc2732ca6 README: Gentoo steps install eselect-repository, handle both accept_keywords layouts, fetch before installing
The repository module comes from app-eselect/eselect-repository, so it
is installed first; package.accept_keywords may be a directory or a
file; and emerge --fetchonly lets the reader compare the archive's
checksum before anything is installed.

Signed-off-by: FredApps <[email protected]>
2026-11-18 17:50:30 +07:00
Madhav Agarwal 4efade7515 i18n: translate the Cell Styles gallery labels (#4249) 2026-11-15 14:08:28 +05:30
Gert Pellin a672926c91 README: the Gentoo overlay is not reviewed by the project; read the ebuild, check the tarball 2026-11-14 14:28:29 +01:00
Gert Pellin a621569d0f Contributors: credit switch87 as Gert Pellin 2026-11-14 14:28:14 +01:00
Gert Pellin 23e13497a7 README: install on Gentoo from the ::snakebyte overlay 2026-11-14 14:28:03 +01:00
alosslessdev 53403bc2dd dax: keep DATESINPERIOD intervals as keywords and NaN relationship keys unmatched (#3408)
The binder protected only DATEADD's interval from variable shadowing; DATESINPERIOD's
fourth argument is the same documented enumeration (including WEEK), so a variable
named MONTH turned it into a variable reference.

The model-row pivot path turned a NaN key into a joinable ScalarKey, pairing two NaNs
that never compare equal. Reject the source value before the index probe, like BLANK.

Both come with regression tests; cargo fmt applied to the merged relationship-key test.
2026-11-09 22:25:54 -05:00
alosslessdev 62260e6e4b dax: join numeric relationship keys across variants and keep DATEADD intervals (#3408)
ScalarKey keeps the exact variant, so an Integer fact key never matched a
Decimal dimension key even though Scalar::strict_eq says they join: filter
propagation, RELATED, RELATEDTABLE and both integrity paths now use join_key,
which folds numeric values to one key only when an f64 holds them exactly.
DATEADD's Text-typed interval also stays a keyword when a variable of that name
is in scope.
2026-11-09 21:22:04 -05:00
alosslessdev e7f9d0008b Merge remote-tracking branch 'upstream/main' into dax/eval-datetime 2026-11-05 16:53:12 -05:00
alosslessdev a72b9287f2 dax: reject empty YearEndDate components (#2228) 2026-11-05 09:43:37 -05:00
alosslessdev 5b19af3c89 Merge remote-tracking branch 'upstream/main' into dax/eval-datetime 2026-11-05 09:42:18 -05:00
alosslessdev 2a0183e3d2 dax: order same-day axis cells by time and share the YearEndDate parser (#2228) 2026-11-05 09:25:47 -05:00
alosslessdev 230bf2304f dax: seed the wasm PRNG from the browser clock and fold nonblank candidate keys (#2228) 2026-11-05 08:43:44 -05:00
alosslessdev bb0d997cfd dax: choose FIRSTDATE and LASTDATE among the visible cells (#2228) 2026-11-05 07:48:07 -05:00
alosslessdev c824ae702e Merge remote-tracking branch 'origin/dax/core' into dax/eval-datetime 2026-11-05 07:30:10 -05:00
alosslessdev 63a9c928a2 Merge remote-tracking branch 'upstream/main' into dax/eval-datetime 2026-11-05 07:30:06 -05:00
alosslessdev 8cc7cc4e38 dax: keep single-date range functions to one cell of the day (#2228) 2026-11-05 07:08:14 -05:00
alosslessdev 74014cc850 dax: one date-column rule for tables and keep same-day timestamps in the axis (#2228) 2026-11-05 06:55:31 -05:00
alosslessdev 5647e98048 dax: pick a calendar table's typed date column for the total functions (#2228) 2026-11-05 06:34:10 -05:00
alosslessdev 2c04e06499 dax: date/time, time-intelligence and math/trig functions (#2228) 2026-11-05 05:50:14 -05:00
142 changed files with 9309 additions and 704 deletions
Generated
+1 -1
View File
@@ -3050,6 +3050,7 @@ dependencies = [
"craft-host",
"craft-keymap",
"craft-print",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
@@ -3078,7 +3079,6 @@ dependencies = [
name = "gridcraft-web"
version = "0.20.0"
dependencies = [
"craft-print",
"craft-web-api",
"craft-web-host",
"eframe",
+1
View File
@@ -105,6 +105,7 @@ craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
[workspace.lints.rust]
unsafe_code = "forbid"
+29
View File
@@ -275,8 +275,37 @@ handling again for troubleshooting.
| Fedora/RHEL/openSUSE | `gridcraft-<ver>-linux-x86_64.rpm` | `gridcraft-<ver>-linux-aarch64.rpm` | |
| Tarball | `gridcraft-<ver>-linux-x86_64.tar.gz` | `gridcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
#### Community packages
These packages are maintained by community members, not by the GridCraft team, and the project
does not review them. An overlay's ebuilds run as root when you install a package, so read the
ebuild before you emerge it.
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the
Linux release as `app-office/gridcraft-bin` (prebuilt) and `app-office/gridcraft` (built from source).
`gridcraft-bin` downloads `gridcraft-<ver>-linux-x86_64.tar.gz` from this repository's releases, and
Portage refuses the file unless it matches the overlay's `Manifest`. To check that it is the
release's own file before installing it, fetch it first with `emerge --fetchonly`, run `sha256sum`
on it in your `DISTDIR` and compare with the release's `SHA256SUMS.txt`.
```sh
emerge --ask --noreplace app-eselect/eselect-repository
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
emaint sync -r snakebyte
# package.accept_keywords can be a directory or a single file
if [ -d /etc/portage/package.accept_keywords ]; then
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/gridcraft
else
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords
fi
emerge --fetchonly app-office/gridcraft-bin # then check the file in DISTDIR as above
emerge --ask app-office/gridcraft-bin
```
### FreeBSD
Current prebuilt FreeBSD downloads require FreeBSD 15.1 or later; they are not compatible with FreeBSD 14.x.
| Build | File |
|---|---|
| x86_64 | `gridcraft-<ver>-freebsd-x86_64.tar.gz` |
+1 -2
View File
@@ -25,10 +25,9 @@ log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
craft-print = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
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", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
+74 -1
View File
@@ -227,7 +227,11 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
log::error!("download of {name} failed: {e}");
}
})),
print: Some(Box::new(craft_print::browser::print_pdf)),
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 gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
@@ -276,6 +280,75 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
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 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)?;
let body = document.body().ok_or("no body")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
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)?;
if let Err(e) = body.append_child(&iframe) {
cleanup_print(&iframe, &url);
return Err(js(e));
}
// `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 || {
iframe_for_load.set_onload(None);
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
cleanup_print(&iframe_for_load, &url_for_cleanup);
log::error!("print failed: {e:?}");
}
});
iframe.set_onload(Some(on_load.unchecked_ref()));
iframe.set_src(&url);
Ok(())
}
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
// Both operations are idempotent: print can fail after dispatching `afterprint`.
web_sys::Url::revoke_object_url(url).ok();
iframe.remove();
}
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
let iframe_for_cleanup = iframe.clone();
let url_for_cleanup = url.to_owned();
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
});
// Listen before `print()`, which can dispatch `afterprint` before it returns.
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
let options = web_sys::AddEventListenerOptions::new();
options.set_once(true);
let callback = on_after_print.as_ref().unchecked_ref();
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
if let Err(e) = content_window.print() {
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
return Err(e);
}
let _ = on_after_print.into_js_value();
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",
+5
View File
@@ -119,6 +119,11 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.switch87]
real_name = "Gert Pellin"
display_name = "Gert Pellin"
sync_github_name = false
[people.gmrmad1]
real_name = "Madhav Agarwal"
+5
View File
@@ -141,6 +141,11 @@ pub trait Host {
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
range.iter().map(|c| self.cell_value(sheet, c)).collect()
}
/// Finds the smallest rectangle covering the non-empty cells of a block without reading its
/// full grid. The outer `None` leaves the read to `range_values`. `Some(None)` means all blank.
fn range_nonempty_bounds(&mut self, _sheet: usize, _range: RangeRef) -> Option<Option<RangeRef>> {
None
}
/// 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> {
+64
View File
@@ -915,6 +915,70 @@ pub(crate) mod tests {
assert!(!index_spills(5_000, 5_000, [].iter()));
}
#[test]
fn trim_references_skip_the_dense_grid_for_sparse_stored_values() {
use crate::eval::{Area, Ev, Evaluator};
use gridcraft_core::CellError;
use gridcraft_model::StyleId;
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
let at = |s: &str| CellRef::parse(s).unwrap();
sh.set_cell(at("C3"), Cell::value(Value::Number(0.0)));
let mut cached = Cell::formula(Formula::new("\"\""));
cached.value = Value::text("");
sh.set_cell(at("N39999"), cached);
sh.set_cell(at("Q40001"), Cell::styled(Value::Empty, StyleId(1)));
// These cells keep the sheet's used extent wide and tall without being in the trim range.
sh.set_cell(at("Q1"), Cell::value(Value::Number(1.0)));
sh.set_cell(at("A40001"), Cell::value(Value::Number(1.0)));
let exprs = HashMap::default();
let mut rng = 1u64;
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
let mut ev = Evaluator::new(&mut host, 0, at("S1"));
for (src, expected) in [("B2.:.Q40001", "C3:N39999"), ("TRIMRANGE(B2:Q40001,1,2)", "B3:N40001")] {
let expr = gridcraft_formula::parse(src).unwrap();
let result = ev.eval(&expr);
let area = Area { sheet: 0, range: RangeRef::parse(expected).unwrap() };
assert!(matches!(&result, Ev::R(areas) if areas.as_slice() == [area]), "{src}: {result:?}");
}
let blank = gridcraft_formula::parse("TRIMRANGE(O2:Q40001)").unwrap();
assert!(matches!(ev.eval(&blank), Ev::V(Value::Error(CellError::Calc))));
assert_eq!(host.materialized_range_cells, 0, "bounds reads must not allocate a dense grid");
}
#[test]
fn trim_range_includes_a_spill_from_outside_the_block() {
use crate::eval::Evaluator;
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
let at = |s: &str| CellRef::parse(s).unwrap();
let anchor = (0, at("C1"));
let target = at("I1");
let source = Formula::new("SEQUENCE(2,5)");
let consumer = Formula::new("COLUMNS(TRIMRANGE(C2:G4))");
let exprs = [(anchor, source.expr_arc().unwrap()), ((0, target), consumer.expr_arc().unwrap())].into_iter().collect();
sh.set_cell(anchor.1, Cell::formula(source));
sh.set_cell(target, Cell::formula(consumer));
// Extend the read area before the new spill has been committed to the sheet.
sh.set_cell(at("H5"), Cell::value(Value::Number(1.0)));
let mut rng = 1u64;
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
host.calculate(anchor);
host.calculate((0, target));
assert_eq!(host.results.get(&(0, target)), Some(&Value::Number(5.0)), "new spill in the current pass");
Calc::new().recalc_all(&mut wb);
let exprs = HashMap::default();
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
let consumer = gridcraft_formula::parse("COLUMNS(TRIMRANGE(C2:G4))").unwrap();
let result = Evaluator::new(&mut host, 0, target).value(&consumer);
assert_eq!(result, Value::Number(5.0), "stored spill from a completed recalculation");
}
/// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already
/// spilled on the sheet from the last calculation, as a full recalculation finds them.
fn big_python_spill() -> (Workbook, HashMap<Key, Value>) {
+55 -12
View File
@@ -57,6 +57,9 @@ pub(super) struct PassHost<'a> {
/// looks at none of it).
#[cfg(test)]
pub(super) spill_visits: usize,
/// Number of value slots allocated by dense range reads.
#[cfg(test)]
pub(super) materialized_range_cells: usize,
/// The formulas in `cycles`.
cycle_seen: HashSet<Key>,
/// Iterative calculation: a circular reference reads the cell's previous value instead of
@@ -114,6 +117,8 @@ impl<'a> PassHost<'a> {
suspensions: 0,
#[cfg(test)]
spill_visits: 0,
#[cfg(test)]
materialized_range_cells: 0,
cycle_seen: HashSet::default(),
iterate: false,
prev: HashMap::default(),
@@ -238,6 +243,25 @@ fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &m
}
impl PassHost<'_> {
fn range_has_spill(&mut self, sheet: usize, range: RangeRef) -> bool {
let mut arrays = Vec::new();
self.spill_index.meeting(sheet, range, &mut arrays);
if !arrays.is_empty() {
return true;
}
let Some(sh) = self.wb.sheet(sheet) else { return false };
let mut stored = false;
let _seen = stored_spill_in(sh, range, &mut |_, _| {
stored = true;
false
});
#[cfg(test)]
{
self.spill_visits += _seen;
}
stored
}
/// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would
/// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is
/// calculated from here, then the suspended ones again (reading the results kept so far).
@@ -609,6 +633,10 @@ impl Host for PassHost<'_> {
}
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
let (h, w) = (range.height() as usize, range.width() as usize);
#[cfg(test)]
{
self.materialized_range_cells += h * w;
}
let mut out = vec![Value::Empty; h * w];
let Some(sh) = self.wb.sheet(sheet) else { return out };
// Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go
@@ -698,18 +726,7 @@ impl Host for PassHost<'_> {
}
// Spilled values sit between the stored cells (and the formulas just calculated may have
// produced some): leave such blocks to `range_values`.
let mut arrays = Vec::new();
self.spill_index.meeting(sheet, range, &mut arrays);
let mut stored = false;
let _seen = stored_spill_in(sh, range, &mut |_, _| {
stored = true;
false
});
#[cfg(test)]
{
self.spill_visits += _seen;
}
if !arrays.is_empty() || stored {
if self.range_has_spill(sheet, range) {
return false;
}
for (c, cell) in sh.cells.iter_range(range) {
@@ -720,6 +737,32 @@ impl Host for PassHost<'_> {
}
true
}
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
if self.iterate || self.range_has_spill(sheet, range) {
return None;
}
let sh = self.wb.sheet(sheet)?;
// When fewer calculations are in play than cells to inspect, check their coordinates
// first. A formula near the bottom of a dense range would otherwise cost two walks.
let pass_cells = self.pending.len() + self.results.len();
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
return None;
}
let mut bounds: Option<RangeRef> = None;
for (c, cell) in sh.cells.iter_range(range) {
// With no pending or computed results in the block, formula and Python readers
// see the stored values as well. Otherwise leave their evaluation to range_values.
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
return None;
}
if !cell.value.is_empty() {
let cell_range = RangeRef::cell(c);
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
}
}
Some(bounds)
}
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
// Constants can't change during a pass, so a block's result stays valid for it. Spills
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
+19
View File
@@ -810,6 +810,7 @@ fn arrays_do_not_spill_in_tables() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
t.set("C4", "=SEQUENCE(2)");
t.set("E1", "=SEQUENCE(4)");
@@ -839,6 +840,7 @@ fn one_value_array_in_a_table_is_not_a_spill() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
@@ -1569,6 +1571,7 @@ fn subtotal_skips_filtered_rows() {
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
}],
style: String::new(),
@@ -1580,6 +1583,7 @@ fn subtotal_skips_filtered_rows() {
filter: crit(),
table_type: None,
connection_id: None,
query_table: None,
});
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.
@@ -2497,6 +2501,21 @@ fn blank_lookup_values_match_excel_windows_observation() {
}
}
#[test]
fn written_blank_lookup_argument_is_numeric_zero() {
// #4044: `XMATCH(, array)` writes a blank argument, which Excel reads as numeric zero. Only a
// reference to a blank cell (B1 here) is a blank lookup value.
let mut t = T::new();
t.set("A1", "=XMATCH(,{0,1,3})");
t.set("A2", "=XMATCH(B1,{0,1,3})");
t.set("A3", "=XLOOKUP(,{0,1,3},{10,20,30})");
t.set("A4", "=XLOOKUP(B1,{0,1,3},{10,20,30},\"none\")");
assert_eq!(t.get("A1"), Value::Number(1.0));
assert_eq!(t.get("A2"), Value::Error(CellError::NA));
assert_eq!(t.get("A3"), Value::Number(10.0));
assert_eq!(t.get("A4"), Value::from("none"));
}
#[test]
fn cell_width_is_the_column_width_dialog_value_rounded() {
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
+9 -2
View File
@@ -95,8 +95,15 @@ impl Evaluator<'_> {
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 ((r0, r1), (c0, c1)) = if let Some(nonempty) = self.host.range_nonempty_bounds(a.sheet, part) {
let nonempty = nonempty.ok_or(CellError::Calc)?;
let row = |c: CellRef| (c.row - part.start.row) as usize;
let col = |c: CellRef| (c.col - part.start.col) as usize;
((row(nonempty.start), row(nonempty.end)), (col(nonempty.start), col(nonempty.end)))
} else {
let values = self.host.range_values(a.sheet, part);
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);
+1 -1
View File
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
pub use axis::{Scale, format_number, nice_scale};
pub use raster::rasterize;
pub use render::{Swatch, legend_entries, render, supports_trendline};
pub use render::{ChartLabels, Swatch, legend_entries, legend_entries_with, render, render_with_labels, supports_trendline};
pub use resolve::{default_palette, has_volatile_series, resolve, series_color};
pub use sparkline::render_sparkline;
+11 -5
View File
@@ -20,9 +20,9 @@ mod trend;
use cartesian::{cartesian, scatter};
use frame::{Bx, axis_titles, chart_title};
use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall};
use kinds::{box_whisker, doughnut, funnel, histogram, pareto, pie, radar, stock, treemap, waterfall};
use legend::draw_legend;
pub use legend::{Swatch, legend_entries};
pub use legend::{ChartLabels, Swatch, legend_entries, legend_entries_with};
pub use trend::supports_trendline;
pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF];
@@ -40,9 +40,9 @@ const AXIS_TITLE_SIZE: f32 = 10.0;
/// Most categories drawn by category-axis charts.
const MAX_CATS: usize = 20_000;
/// Lines with more points than this are decimated (min/max per pixel column).
const MAX_LINE_PTS: usize = 2000;
pub(crate) const MAX_LINE_PTS: usize = 2000;
/// Most markers per series (after de-duplicating by pixel).
const MAX_MARKERS: usize = 5000;
pub(crate) const MAX_MARKERS: usize = 5000;
/// Data labels are skipped when a series has more points than this.
const MAX_LABELS: usize = 200;
/// Columns and bars narrower than this (in pixels) are merged per pixel column into one rectangle.
@@ -217,6 +217,11 @@ pub(crate) fn sanitized(d: &ChartData) -> Cow<'_, ChartData> {
/// Lays out and draws a chart into a `w`×`h` box at the origin. Empty for a degenerate box.
pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) -> Vec<Prim> {
render_with_labels(chart, data, w, h, m, &ChartLabels::default())
}
/// [`render`] with interface strings supplied by the UI.
pub fn render_with_labels(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure, labels: &ChartLabels<'_>) -> Vec<Prim> {
if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e7 || h > 1e7 {
return vec![];
}
@@ -233,7 +238,7 @@ pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure)
area.y += used;
area.h -= used;
}
let entries = legend_entries(chart, &data);
let entries = legend_entries_with(chart, &data, labels);
if !entries.is_empty() && area.ok() {
area = draw_legend(&mut ctx, &entries, chart.legend, area);
}
@@ -261,6 +266,7 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
BarClustered | BarStacked | BarStacked100 => cartesian(ctx, chart, data, area, true),
Scatter | ScatterLines | Bubble => scatter(ctx, chart, data, area),
Histogram => histogram(ctx, chart, data, area),
Pareto => pareto(ctx, chart, data, area),
Waterfall => waterfall(ctx, chart, data, area),
BoxWhisker => box_whisker(ctx, chart, data, area),
Stock => stock(ctx, chart, data, area),
+125 -9
View File
@@ -1,16 +1,19 @@
use std::collections::HashMap;
use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range};
use super::legend::{cat_label, point_color};
use super::legend::{cat_label, pareto_line_color, point_color};
use super::lines::decimate;
use super::{
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
QuartileMethod, Rgba, STOCK, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
QuartileMethod, Rgba, STOCK, Scale, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
};
// ---------------------------------------------------------------- histogram
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
let Some(s) = data.series.first() else { return };
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
let Some((lo, hi)) = value_range(vals.iter().copied()) else { return };
/// Histogram bins for `vals`: right-inclusive labels and counts, as Excel's histogram and the
/// numeric-only form of a Pareto chart use.
fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
let (lo, hi) = value_range(vals.iter().copied())?;
let n = vals.len();
let span = hi - lo;
let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100);
@@ -22,13 +25,12 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
// equal to an edge belongs to the bin that ends there.
let edges: Vec<f64> = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect();
let mut counts = vec![0usize; bins];
for v in &vals {
for v in vals {
let b = edges.partition_point(|e| e < v).min(bins - 1);
if let Some(c) = counts.get_mut(b) {
*c += 1;
}
}
let f = Fmt::new(&s.number_format);
let labels: Vec<String> = (0..bins)
.map(|b| {
let a = lo + b as f64 * width;
@@ -37,6 +39,15 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0)))
})
.collect();
Some((labels, counts))
}
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
let Some(s) = data.series.first() else { return };
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
let f = Fmt::new(&s.number_format);
let Some((labels, counts)) = histogram_bins(&vals, &f) else { return };
let bins = counts.len();
let maxc = counts.iter().copied().max().unwrap_or(0) as f64;
let ys = nice_scale(0.0, maxc, true);
let fc = Fmt::new("General");
@@ -55,6 +66,111 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
}
}
// ---------------------------------------------------------------- pareto
/// Sorted columns and a cumulative-percentage line on a secondary 0–100% axis.
pub(super) fn pareto(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
let Some(s) = data.series.first() else { return };
let f = Fmt::new(&s.number_format);
// With no category range Excel charts a Pareto's numbers in histogram bins (the Pareto page:
// "If you select two columns of numbers ... Excel charts your data in bins").
let binned = chart.series.first().is_some_and(|x| x.categories.is_none());
let (labels, vals): (Vec<String>, Vec<f64>) = if binned {
let raw: Vec<f64> = s.values.iter().flatten().copied().collect();
let Some((labels, counts)) = histogram_bins(&raw, &f) else { return };
let mut items: Vec<(String, f64)> = labels.into_iter().zip(counts.into_iter().map(|c| c as f64)).collect();
items.sort_by(|a, b| b.1.total_cmp(&a.1));
items.into_iter().unzip()
} else {
let n = data.categories.len().max(s.values.len()).min(MAX_CATS);
if n == 0 {
return;
}
// Excel groups equal categories and sums their values before sorting (the Pareto doc's
// "groups the same categories and sums the corresponding numbers").
let mut groups: Vec<(String, f64)> = Vec::new();
let mut index: HashMap<String, usize> = HashMap::new();
for j in 0..n {
let label = cat_label(data, j);
let v = s.values.get(j).copied().flatten().unwrap_or(0.0);
match index.get(&label) {
Some(&i) => {
if let Some(g) = groups.get_mut(i) {
g.1 += v;
}
}
None => {
index.insert(label.clone(), groups.len());
groups.push((label, v));
}
}
}
// Largest first; a stable sort keeps first-appearance order for equal sums.
groups.sort_by(|a, b| b.1.total_cmp(&a.1));
(groups.iter().map(|(l, _)| l.clone()).collect(), groups.iter().map(|(_, v)| *v).collect())
};
let n = labels.len();
if n == 0 {
return;
}
let hi = vals.iter().copied().fold(0.0f64, f64::max);
let lo = vals.iter().copied().fold(0.0f64, f64::min);
let ys = nice_scale(lo, hi, true);
let pct = Fmt::new("0%");
let value_fmt = if binned { Fmt::new("General") } else { Fmt::new(&s.number_format) };
// A cumulative percentage axis is fixed at 0–100%: Excel shows it that way, and the line
// below maps each cumulative share straight onto the plot height.
let ys2 = Scale { min: 0.0, max: 1.0, step: 0.2 };
let plot = frame(
ctx,
area,
CatAxis::Labels(&labels, &[]),
&ValAxis { scale: ys, fmt: &value_fmt },
Some(&ValAxis { scale: ys2, fmt: &pct }),
false,
chart.gridlines,
);
if !plot.ok() {
return;
}
let total: f64 = vals.iter().copied().sum();
// A cumulative percentage is only meaningful when every category is nonnegative. The binned
// path counts values, so its counts always are.
let cumulative = total.is_finite() && total != 0.0 && (binned || vals.iter().all(|v| *v >= 0.0));
let cw = plot.w / n as f32;
let bw = (cw * 0.72).clamp(1.0, 120.0);
let y0 = plot.bottom() - ys.frac(0.0) * plot.h;
let mut pts = Vec::with_capacity(n);
let mut cum = 0.0;
for (j, v) in vals.iter().enumerate() {
let x = plot.x + (j as f32 + 0.5) * cw;
let yv = plot.bottom() - ys.frac(*v) * plot.h;
ctx.rect(x - bw / 2.0, yv.min(y0), bw, (y0 - yv).abs().max(0.5), s.color, None);
if chart.data_labels && n <= MAX_LABELS {
let t = value_fmt.format(*v, None);
if *v >= 0.0 {
ctx.text(x, yv.min(y0) - 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom));
} else {
ctx.text(x, yv.max(y0) + 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Top));
}
}
if cumulative {
cum += *v;
let frac = (cum / total).clamp(0.0, 1.0) as f32;
pts.push([x, plot.bottom() - frac * plot.h]);
}
}
if pts.len() >= 2 {
let color = pareto_line_color(data);
// Keep the line and markers bounded on category-heavy charts, as the other renderers do.
let markers: Vec<[f32; 2]> = if cw >= 3.0 { pts.iter().take(MAX_MARKERS).copied().collect() } else { Vec::new() };
ctx.line(decimate(pts, MAX_LINE_PTS), color, 1.5);
for p in markers {
ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r: 2.0, fill: Some(color), stroke: Some((WHITE, 0.75)) });
}
}
}
// ---------------------------------------------------------------- waterfall
pub(super) fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
+28
View File
@@ -31,8 +31,32 @@ pub(super) fn cat_label(data: &ChartData, j: usize) -> String {
data.categories.get(j).cloned().unwrap_or_else(|| (j + 1).to_string())
}
/// The cumulative line's colour: the second palette colour, so it stands apart from the bars.
pub(super) fn pareto_line_color(data: &ChartData) -> Rgba {
data.palette.get(1).copied().or_else(|| data.series.first().map(|_| series_color(&Theme::default(), 1))).unwrap_or(TEXT)
}
/// Interface strings a chart legend can need. The UI passes translated text; the default is
/// English for callers without an interface language (PDF export, tests).
#[derive(Clone, Copy, Debug)]
pub struct ChartLabels<'a> {
/// Legend name of a Pareto chart's cumulative line.
pub cumulative: &'a str,
}
impl Default for ChartLabels<'_> {
fn default() -> Self {
Self { cumulative: "Cumulative %" }
}
}
/// Legend entries (text, colour, swatch) `render` draws for this chart; empty when hidden.
pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swatch)> {
legend_entries_with(chart, data, &ChartLabels::default())
}
/// [`legend_entries`] with interface strings supplied by the UI.
pub fn legend_entries_with(chart: &Chart, data: &ChartData, labels: &ChartLabels<'_>) -> Vec<(String, Rgba, Swatch)> {
if chart.legend == LegendPos::None {
return vec![];
}
@@ -44,6 +68,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
(0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect()
}
ChartKind::Histogram | ChartKind::Funnel | ChartKind::Stock => vec![],
ChartKind::Pareto => match data.series.first() {
Some(s) => vec![(s.name.clone(), s.color, Swatch::Box), (labels.cumulative.to_string(), pareto_line_color(data), Swatch::Line)],
None => vec![],
},
ChartKind::Waterfall => {
if data.series.is_empty() {
return vec![];
+196 -1
View File
@@ -3,12 +3,13 @@ use std::sync::Arc;
use gridcraft_core::{CellRef, Value};
use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, SparklineKind, Style, Workbook};
use crate::render::MAX_MARKERS;
use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 28] = [
const ALL_KINDS: [ChartKind; 29] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -30,6 +31,7 @@ const ALL_KINDS: [ChartKind; 28] = [
ChartKind::Bubble,
ChartKind::Radar,
ChartKind::Histogram,
ChartKind::Pareto,
ChartKind::Waterfall,
ChartKind::Funnel,
ChartKind::Treemap,
@@ -154,6 +156,198 @@ fn every_kind_renders_sanely() {
}
}
#[test]
fn pareto_sorts_categories_and_draws_the_cumulative_line() {
let mut c = chart(ChartKind::Pareto);
c.title = None;
c.legend = LegendPos::None;
c.data_labels = false;
c.gridlines = false;
// A appears twice: Excel groups equal categories and sums them (A = 15).
let cats = ["A", "B", "A", "C"];
let vals = [10.0, 40.0, 5.0, 20.0];
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: cats.iter().map(|s| s.to_string()).collect(),
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
};
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
let x_of = |label: &str| {
prims.iter().find_map(|p| match p {
Prim::Text { x, text, .. } if text == label => Some(*x),
_ => None,
})
};
let (a, b, cc) = (x_of("A").unwrap(), x_of("B").unwrap(), x_of("C").unwrap());
assert!(b < cc && cc < a, "grouped and sorted largest first: B C A");
// Three cumulative markers and the line itself.
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3);
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
let t = texts(&prims);
assert!(t.contains(&"100%"), "right percentage axis labels: {t:?}");
}
#[test]
fn pareto_secondary_axis_is_fixed_at_100_percent() {
let mut c = chart(ChartKind::Pareto);
c.title = None;
c.legend = LegendPos::None;
c.data_labels = false;
c.gridlines = false;
let cats = ["A", "B", "C", "D", "E"];
let vals = [50.0, 20.0, 10.0, 5.0, 15.0];
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: cats.iter().map(|s| s.to_string()).collect(),
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
};
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
// The secondary axis runs 0–100%, so the cumulative line can use the plot's full height.
let mut ticks: Vec<(f32, &str)> = prims
.iter()
.filter_map(|p| match p {
Prim::Text { y, text, .. } if text.ends_with('%') => Some((*y, text.as_str())),
_ => None,
})
.collect();
ticks.sort_by(|a, b| a.0.total_cmp(&b.0));
let labels: Vec<&str> = ticks.iter().map(|(_, t)| *t).collect();
// Top of the plot first: 100% down to 0%, with no 120% headroom.
assert_eq!(labels, ["100%", "80%", "60%", "40%", "20%", "0%"], "fixed 0–100% axis with a 20% step");
// Evenly spaced: 0.2 of the scale per step.
let first = ticks.first().map(|(y, _)| *y).unwrap_or_default();
let last = ticks.last().map(|(y, _)| *y).unwrap_or_default();
let step = (last - first) / 5.0;
for (i, (y, label)) in ticks.iter().enumerate() {
assert!((first + step * i as f32 - y).abs() < 0.5, "{label} sits on its 0.2 step: {ticks:?}");
}
// The cumulative line's last point (100%) lands on the 100% tick, and A's 50% midway.
let line = prims
.iter()
.find_map(|p| match p {
Prim::Line { pts, .. } if pts.len() == 5 => Some(pts.clone()),
_ => None,
})
.expect("cumulative line");
let top = first;
let mid = (first + last) / 2.0;
assert!((line[4][1] - top).abs() < 0.01, "line top {} on the 100% tick {top}", line[4][1]);
assert!((line[0][1] - mid).abs() < 0.01, "A's 50% {} halfway up the axis ({mid})", line[0][1]);
}
#[test]
fn pareto_bins_numbers_when_there_is_no_category_range() {
let mut c = chart(ChartKind::Pareto);
c.title = None;
c.legend = LegendPos::None;
c.data_labels = false;
c.gridlines = false;
c.series.push(Series { name: Some("Values".into()), values: "Data!$A$1:$A$6".into(), ..Default::default() });
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: vec![],
series: vec![series("Values", &[1.0, 1.0, 1.0, 2.0, 2.0, 3.0], [20, 96, 130, 255], ChartKind::Pareto)],
};
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3, "three bins");
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
let t = texts(&prims);
assert!(t.iter().any(|s| s.starts_with('[') && s.contains(", ")), "bin labels: {t:?}");
}
#[test]
fn pareto_skips_cumulative_line_for_signed_categories() {
let mut c = chart(ChartKind::Pareto);
c.title = None;
c.legend = LegendPos::None;
c.data_labels = false;
c.gridlines = false;
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: vec!["A".into(), "B".into()],
series: vec![series("Count", &[10.0, -5.0], [20, 96, 130, 255], ChartKind::Pareto)],
};
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
// A negative category makes the cumulative percentage meaningless, so no line or markers.
// The cumulative line is the only 1.5 px polyline a Pareto draws (bars are rects, axes 0.75).
let line = |prims: &[Prim]| prims.iter().any(|p| matches!(p, Prim::Line { pts, width, .. } if *width == 1.5 && pts.len() >= 2));
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
assert!(!line(&prims), "signed categories draw no cumulative line");
// The same chart with nonnegative values does draw it, so the check above can fail.
let d = ChartData { series: vec![series("Count", &[10.0, 5.0], [20, 96, 130, 255], ChartKind::Pareto)], ..d };
assert!(line(&render(&c, &d, 640.0, 400.0, &ApproxMeasure)), "nonnegative categories draw the cumulative line");
}
#[test]
fn pareto_caps_cumulative_line_and_markers() {
let mut c = chart(ChartKind::Pareto);
c.title = None;
c.legend = LegendPos::None;
c.data_labels = false;
c.gridlines = false;
let n = MAX_MARKERS + 1000;
let cats: Vec<String> = (0..n).map(|i| format!("C{i}")).collect();
let vals: Vec<f64> = (0..n).map(|i| (i % 7 + 1) as f64).collect();
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: cats,
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
};
// Wide enough for markers: they stop at MAX_MARKERS.
let wide = render(&c, &d, 30_000.0, 400.0, &ApproxMeasure);
assert_eq!(wide.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), MAX_MARKERS);
// Narrow columns carry no marker information; the line is decimated instead.
let narrow = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
assert_eq!(narrow.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
let longest = narrow.iter().filter_map(|p| match p {
Prim::Line { pts, .. } if pts.len() > 2 => Some(pts.len()),
_ => None,
});
assert!(longest.max().unwrap_or(0) < n, "the cumulative line is decimated");
}
#[test]
fn pareto_legend_uses_the_supplied_label() {
let mut c = chart(ChartKind::Pareto);
c.legend = LegendPos::Bottom;
let d = sample(ChartKind::Pareto);
let entries = legend_entries_with(&c, &d, &ChartLabels { cumulative: "Kumuliert %" });
assert!(entries.iter().any(|(name, _, sw)| name == "Kumuliert %" && *sw == Swatch::Line), "{entries:?}");
}
#[test]
fn pareto_line_falls_back_to_the_second_theme_accent() {
let c = chart(ChartKind::Pareto);
// A resolved short palette (one series) has no second colour: the line must still stand
// apart from the bars instead of reusing the first series colour.
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect(),
series: vec![series("Count", &[4.0, 3.0, 2.0, 1.0], [20, 96, 130, 255], ChartKind::Pareto)],
};
let accent = series_color(&gridcraft_model::Theme::default(), 1);
assert_ne!(accent, d.series[0].color);
let entries = legend_entries(&c, &d);
assert_eq!(entries.get(1).map(|e| e.1), Some(accent), "the legend swatch matches the line");
let lines: Vec<Rgba> = render(&c, &d, 640.0, 400.0, &ApproxMeasure)
.iter()
.filter_map(|p| match p {
Prim::Line { color, width, .. } if *width == 1.5 => Some(*color),
_ => None,
})
.collect();
assert!(lines.contains(&accent), "{lines:?}");
// A second palette colour still takes precedence.
let d = ChartData { palette: vec![[1, 2, 3, 255], [9, 8, 7, 255]], ..d };
assert_eq!(legend_entries(&c, &d).get(1).map(|e| e.1), Some([9, 8, 7, 255]));
}
#[test]
fn doughnut_draws_each_series_as_a_ring() {
let mut c = chart(ChartKind::Doughnut);
@@ -472,6 +666,7 @@ fn legend_counts() {
assert_eq!(legend_entries(&chart(ChartKind::Pie), &d).len(), 6);
assert_eq!(legend_entries(&chart(ChartKind::Waterfall), &d).len(), 3);
assert_eq!(legend_entries(&chart(ChartKind::Histogram), &d).len(), 0);
assert_eq!(legend_entries(&chart(ChartKind::Pareto), &d).len(), 2);
let mut c = chart(ChartKind::Line);
c.legend = LegendPos::None;
assert!(legend_entries(&c, &d).is_empty());
+19
View File
@@ -2,13 +2,32 @@
//!
//! Internally rows and columns are 0-based (`A1` = row 0, col 0). The sheet is 1,048,576 rows by
//! 16,384 columns (`XFD1048576`), like Excel.
//!
//! # Excel's limits
//!
//! The constants below are Excel's documented limits (Microsoft's "Excel specifications and
//! limits" page, the "Worksheet and workbook specifications" table). They are the size of the grid
//! and the readers' bound of legitimate input: a file Excel wrote never exceeds them, so a part
//! that does is malformed or crafted. The XLSX reader drops what the grid can't hold with a
//! warning, and keeps text longer than a cell allows whole with one, since cutting it would lose
//! data (the XLSB reader still refuses such text). Excel has raised
//! these over the years (65,536 × 256 before Excel 2007) and may again; a new value goes here, and
//! the places that still spell a number out (warning texts, a few function bounds) are pointed at
//! these constants as they are touched. The old limits need no entry: a file written under them
//! fits the current ones.
use std::fmt;
use serde::{Deserialize, Serialize};
/// Rows in a sheet (`1048576` is the last row number).
pub const MAX_ROWS: u32 = 1_048_576;
/// Columns in a sheet (`XFD` is the last column).
pub const MAX_COLS: u32 = 16_384;
/// Characters in one cell's text, counted in UTF-16 units (a character outside the Basic
/// Multilingual Plane counts as two). [`MAX_TEXT_CHARS`](crate::value::MAX_TEXT_CHARS), which
/// `cap_text` and the functions use, is this value as a `usize`.
pub const MAX_CELL_CHARS: u32 = 32_767;
/// A cell position (0-based).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
+2 -2
View File
@@ -12,8 +12,8 @@ pub mod region;
pub mod value;
pub use addr::{
CategoryLevels, CellRef, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet, sheet_needs_quotes,
split_areas, split_sheet, unquote_sheet,
CategoryLevels, CellRef, MAX_CELL_CHARS, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet,
sheet_needs_quotes, split_areas, split_sheet, unquote_sheet,
};
pub use date::DateSystem;
pub use region::Region;
+3 -2
View File
@@ -522,8 +522,9 @@ pub fn sci_text(n: f64, sig: usize) -> String {
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
}
/// Longest text a cell can hold, in UTF-16 code units.
pub const MAX_TEXT_CHARS: usize = 32_767;
/// Longest text a cell can hold, in UTF-16 code units: Excel's limit,
/// [`MAX_CELL_CHARS`](crate::addr::MAX_CELL_CHARS), as a `usize`.
pub const MAX_TEXT_CHARS: usize = crate::addr::MAX_CELL_CHARS as usize;
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
pub fn cap_text(mut s: String) -> String {
+14
View File
@@ -326,6 +326,20 @@ impl<'a> Binder<'a> {
return true;
}
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
// `DATEADD`'s, `DATESINPERIOD`'s and `PARALLELPERIOD`'s interval is catalogued as
// `Text` but is a documented enumeration, so neither a variable nor a model table
// or measure named `MONTH` may replace the written keyword: `DATEADD(d, 1, MONTH)`,
// `DATESINPERIOD(d, s, -1, MONTH)` and `PARALLELPERIOD(d, -1, MONTH)` shift by the
// written interval. `WEEK` and `DAY` are not every function's interval vocabulary.
let interval_keyword = match (spec.name, index) {
("DATEADD", 2) => ["DAY", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
("DATESINPERIOD", 3) => ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
("PARALLELPERIOD", 2) => ["MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
_ => false,
};
if interval_keyword {
return true;
}
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
!named && !variable
});
+6 -6
View File
@@ -39,19 +39,19 @@ mod support;
// marker line in both lists, in `ALL_FAMILIES` order, so a family branch replaces exactly its own
// line instead of inserting at a shared anchor and conflicting with its siblings.
mod aggregation;
// date_time
mod date_time;
// filter
// financial
mod information;
mod logical;
// math_trig
mod math_trig;
mod model_info;
// other
// parent_child
// statistical
// table_manipulation
// text
// time_intelligence
mod time_intelligence;
// visual
use std::cmp::Ordering;
@@ -108,19 +108,19 @@ pub const ALL_FAMILIES: &[&str] = &[
/// own marker line below with its `Family` entry.
const FAMILIES: &[Family] = &[
Family { name: "aggregation", scalar: aggregation::call, table: aggregation::call_table },
// date_time
Family { name: "date_time", scalar: date_time::call, table: date_time::call_table },
// filter
// financial
Family { name: "information", scalar: information::call, table: information::call_table },
Family { name: "logical", scalar: logical::call, table: logical::call_table },
// math_trig
Family { name: "math_trig", scalar: math_trig::call, table: math_trig::call_table },
Family { name: "model_info", scalar: model_info::call, table: model_info::call_table },
// other
// parent_child
// statistical
// table_manipulation
// text
// time_intelligence
Family { name: "time_intelligence", scalar: time_intelligence::call, table: time_intelligence::call_table },
// visual
];
+613
View File
@@ -0,0 +1,613 @@
//! Date and time functions.
//!
//! Dates are OLE/Excel serials (`Scalar::DateTime`), the same values Excel stores: whole days
//! since 1899-12-30 plus a fraction for the time of day. The scalar functions follow Excel's
//! documented results (`WEEKNUM` return types, `YEARFRAC` day-count bases, `NETWORKDAYS` weekend
//! codes), and the table functions build date tables from literal bounds or from the model's
//! DateTime columns.
#![allow(unused_imports)]
use std::collections::BTreeSet;
use super::time_intelligence::is_date_type;
use super::*;
/// Last serial Excel/DAX accepts as a date: 9999-12-31.
const MAX_DATE_SERIAL: f64 = 2_958_465.0;
/// Hard ceiling for date tables built row-by-row by `CALENDAR`/`CALENDARAUTO`. It mirrors the
/// `MAX_GENERATED_ROWS` limit in `eval::table_manipulation` (which is private to that module),
/// so a pathological date span fails like every other oversized generated table instead of
/// exhausting memory.
const MAX_GENERATED_ROWS: i64 = 1_000_000;
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
let upper = name.to_ascii_uppercase();
let result = match upper.as_str() {
"DATEDIFF" => datediff(ev, args, ctx),
"DATEVALUE" => datevalue(ev, args, ctx),
"TIME" => time(ev, args, ctx),
"WEEKDAY" => weekday(ev, args, ctx),
"NETWORKDAYS" => networkdays(ev, args, ctx),
"NOW" => now(),
"QUARTER" => quarter(ev, args, ctx),
"TIMEVALUE" => timevalue(ev, args, ctx),
"TODAY" => today(),
"UTCNOW" => utc_now(),
"UTCTODAY" => utc_today(),
"WEEKNUM" => weeknum(ev, args, ctx),
"YEARFRAC" => yearfrac(ev, args, ctx),
// Table functions only make sense where a table is expected. Returning an explanatory
// error beats reporting them as unimplemented when they appear in a scalar context.
"CALENDAR" | "CALENDARAUTO" => Err(EvalError::new(format!("{upper} returns a table, not a scalar value"))),
_ => return None,
};
Some(result)
}
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
let upper = name.to_ascii_uppercase();
let result = match upper.as_str() {
"CALENDAR" => calendar(ev, args, ctx),
"CALENDARAUTO" => calendar_auto(ev, args, ctx),
_ => return None,
};
Some(result)
}
// ---------------------------------------------------------------------------------------------
// Argument coercion
// ---------------------------------------------------------------------------------------------
/// Coerces a scalar to a date serial. BLANK is 0 like every other DAX numeric coercion, text is
/// read with the shared date/time parser first (so `DATEDIFF` keeps the time of day a text
/// argument carries) and with `DATEVALUE`'s whole-day forms only for the shapes that parser
/// rejects, and numbers are already serials.
fn coerce_date(value: &Scalar) -> Option<f64> {
match value {
Scalar::Blank => Some(0.0),
Scalar::String(text) => support::parse_date_text(text)
.or_else(|| parse_date_serial(text))
.or_else(|| text.trim().parse::<f64>().ok().filter(|serial| serial.is_finite())),
other => other.to_number().filter(|serial| serial.is_finite()),
}
}
fn date_arg(name: &str, values: &[Scalar], index: usize) -> Result<f64, EvalError> {
let value = values.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
let serial = coerce_date(value).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))?;
// Validating the range bounds every date loop (NETWORKDAYS, YEARFRAC) by the calendar.
if !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
return Err(EvalError::new(format!("{name} argument {} is outside the supported date range", index + 1)));
}
Ok(serial)
}
fn optional_int(name: &str, values: &[Scalar], index: usize, default: i64) -> Result<i64, EvalError> {
match values.get(index) {
Some(value) if !value.is_blank() => {
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
Ok(number as i64)
}
_ => Ok(default),
}
}
// ---------------------------------------------------------------------------------------------
// Text parsing
// ---------------------------------------------------------------------------------------------
/// Splits `DATE[ T]TIME` text at the first `T` or space. A string without a separator is all
/// date (or all time); the caller decides which.
fn split_date_time(text: &str) -> (&str, Option<&str>) {
match text.split_once(['T', ' ']) {
Some((date, time)) => (date.trim(), Some(time.trim())),
None => (text.trim(), None),
}
}
/// Parses the date forms `DATEVALUE` accepts on a US-locale client: `YYYY-MM-DD`, `YYYY/MM/DD`,
/// `MM/DD/YYYY` (two-digit years add 2000 below 30 and 1900 otherwise) and the same dates with a
/// trailing time. Returns whole-day serials; the time of day is ignored.
fn parse_date_serial(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let (date_part, _) = split_date_time(text);
let parts: Vec<&str> = date_part.split(['-', '/']).filter(|part| !part.is_empty()).collect();
if parts.len() != 3 {
return None;
}
let numbers: Option<Vec<i64>> = parts.iter().map(|part| part.parse::<i64>().ok()).collect();
let numbers = numbers?;
let leading_year = parts[0].len() >= 4 && parts[0].chars().all(|c| c.is_ascii_digit());
if leading_year {
// ISO order. The shared parser already knows this shape; re-reading the parts rejects
// impossible dates (2024-02-30) that its serial rollover would silently accept.
let serial = support::parse_date_text(date_part)?;
if support::date_parts(serial) != (numbers[0], numbers[1], numbers[2]) || !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
return None;
}
return Some(serial.floor());
}
// Month-first order, the default of the documented en-US client.
let (mut year, month, day) = (numbers[2], numbers[0], numbers[1]);
if year < 100 {
year += if year < 30 { 2000 } else { 1900 };
}
if !(1..=12).contains(&month) || day < 1 || day > support::days_in_month(year, month) {
return None;
}
let serial = support::date_serial(year, month, day, 0, 0, 0);
(0.0..=MAX_DATE_SERIAL).contains(&serial).then_some(serial)
}
/// Parses a clock time into a day fraction: `HH:MM`, `HH:MM:SS`, fractional seconds optional, and
/// an `AM`/`PM` suffix on a 12-hour clock.
fn parse_clock(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let upper = text.to_ascii_uppercase();
let (clock, meridiem) = if let Some(rest) = upper.strip_suffix("PM") {
(rest.trim(), Some(true))
} else if let Some(rest) = upper.strip_suffix("AM") {
(rest.trim(), Some(false))
} else {
(text, None)
};
let parts: Vec<&str> = clock.split(':').collect();
if parts.len() < 2 || parts.len() > 3 {
return None;
}
let hour: i64 = parts[0].trim().parse().ok()?;
let minute: i64 = parts[1].trim().parse().ok()?;
let second: f64 = match parts.get(2) {
Some(part) => part.trim().parse().ok()?,
None => 0.0,
};
if !(0..=59).contains(&minute) || !(0.0..60.0).contains(&second) {
return None;
}
let hour = match meridiem {
Some(pm) => {
if !(1..=12).contains(&hour) {
return None;
}
match (hour, pm) {
(12, true) => 12,
(12, false) => 0,
(hour, true) => hour + 12,
(hour, false) => hour,
}
}
None => {
if !(0..=23).contains(&hour) {
return None;
}
hour
}
};
Some((hour as f64 * 3600.0 + minute as f64 * 60.0 + second) / 86_400.0)
}
// ---------------------------------------------------------------------------------------------
// Scalars
// ---------------------------------------------------------------------------------------------
/// `DATEVALUE ( <DateText> )` — the date part of a text date as a whole-day serial.
fn datevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let value = values.first().ok_or_else(|| EvalError::new("DATEVALUE is missing argument 1"))?;
if let Scalar::DateTime(serial) = value {
return Ok(Scalar::DateTime(serial.floor()));
}
let text = value.to_text();
let serial = parse_date_serial(&text).ok_or_else(|| EvalError::new(format!("DATEVALUE cannot convert `{text}` to a date")))?;
Ok(Scalar::DateTime(serial))
}
/// `DATEDIFF ( <Date1>, <Date2>, <Interval> )`: the number of interval boundaries crossed between
/// the two dates, positively when Date2 is later. `Interval` is a keyword (the binder keeps it as
/// a keyword expression, which evaluates to its text).
fn datediff(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let start = date_arg("DATEDIFF", &values, 0)?;
let end = date_arg("DATEDIFF", &values, 1)?;
let interval = values.get(2).ok_or_else(|| EvalError::new("DATEDIFF is missing argument 3"))?.to_text();
let (start_year, start_month, _) = support::date_parts(start);
let (end_year, end_month, _) = support::date_parts(end);
// Sub-day intervals count boundaries, not elapsed time: floor each serial to the unit and
// subtract, so `10:59:59` to `11:00:01` is one HOUR even though only two seconds passed.
// Snap to whole seconds first: serial construction can land a hair below an exact second,
// and flooring that would count one boundary too few.
let boundaries = |serial: f64, per_day: f64| {
let seconds = (serial * 86_400.0).round();
(seconds / (86_400.0 / per_day)).floor()
};
// A week starts on Sunday; serial 1 (1900-01-01) is Excel's first Sunday, so week 0 starts
// there and every seven days is another boundary.
let week = |serial: f64| (serial.floor() - 1.0).div_euclid(7.0);
let count = match interval.trim().to_ascii_uppercase().as_str() {
"SECOND" => boundaries(end, 86_400.0) - boundaries(start, 86_400.0),
"MINUTE" => boundaries(end, 1_440.0) - boundaries(start, 1_440.0),
"HOUR" => boundaries(end, 24.0) - boundaries(start, 24.0),
"DAY" => end.floor() - start.floor(),
"WEEK" => week(end) - week(start),
"MONTH" => ((end_year - start_year) * 12 + (end_month - start_month)) as f64,
"QUARTER" => ((end_year - start_year) * 4 + (end_month - 1) / 3 - (start_month - 1) / 3) as f64,
"YEAR" => (end_year - start_year) as f64,
other => {
return Err(EvalError::new(format!("DATEDIFF interval `{other}` must be SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR")));
}
};
if !count.is_finite() || count.abs() >= 9_223_372_036_854_775_808.0 {
return Err(EvalError::new("DATEDIFF result is outside the 64-bit integer range"));
}
Ok(Scalar::Integer(count as i64))
}
/// `TIME ( <Hour>, <Minute>, <Second> )`: a time on the 1899-12-30 epoch. Each argument is capped
/// at 32,767 and the total wraps inside one day, as the catalog documents (`TIME ( 50, 0, 0 )` is
/// 02:00, not 02:00 the next day).
fn time(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
const MAX_TIME_PART: f64 = 32_767.0;
let values = support::eval_all(ev, args, ctx)?;
let mut parts = [0.0f64; 3];
for (index, part) in parts.iter_mut().enumerate() {
let value = values.get(index).ok_or_else(|| EvalError::new(format!("TIME is missing argument {}", index + 1)))?.to_number();
let value = value.filter(|value| value.is_finite()).ok_or_else(|| EvalError::new(format!("TIME argument {} must be numeric", index + 1)))?;
if !(0.0..=MAX_TIME_PART).contains(&value) {
return Err(EvalError::new(format!("TIME argument {} must be between 0 and 32767", index + 1)));
}
*part = value;
}
let seconds = parts[0] * 3_600.0 + parts[1] * 60.0 + parts[2];
Ok(Scalar::DateTime(seconds.rem_euclid(86_400.0) / 86_400.0))
}
/// `WEEKDAY ( <Date> [, <ReturnType>] )`: return type 1 numbers Sunday 1 through Saturday 7,
/// 2 numbers Monday 1 through Sunday 7, 3 numbers Monday 0 through Sunday 6, and 11-17 start the
/// week on Monday through Sunday with the first day numbered 1.
fn weekday(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let serial = date_arg("WEEKDAY", &values, 0)?;
let return_type = optional_int("WEEKDAY", &values, 1, 1)?;
// Days since the epoch, 1899-12-30 was a Saturday, so serial 0 is Saturday and the
// zero-based day of week with Sunday first is (days + 6) mod 7.
let days = serial.floor() as i64;
let sunday_first = (days + 6).rem_euclid(7);
let index = match return_type {
1 => sunday_first + 1,
2 => (sunday_first + 6).rem_euclid(7) + 1,
3 => (sunday_first + 6).rem_euclid(7),
11..=17 => {
// The first day of the week is Monday for 11 through Sunday for 17.
let first = (return_type - 10).rem_euclid(7);
(sunday_first - first).rem_euclid(7) + 1
}
other => {
return Err(EvalError::new(format!("WEEKDAY return type `{other}` must be 1, 2, 3 or 11 to 17")));
}
};
Ok(Scalar::Integer(index))
}
/// `TIMEVALUE ( <TimeText> )` — the time of day as a fraction, ignoring any date portion.
fn timevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let value = values.first().ok_or_else(|| EvalError::new("TIMEVALUE is missing argument 1"))?;
if let Scalar::DateTime(serial) = value {
return Ok(Scalar::DateTime(serial.rem_euclid(1.0)));
}
let text = value.to_text();
let fraction = parse_time_text(&text).ok_or_else(|| EvalError::new(format!("TIMEVALUE cannot convert `{text}` to a time")))?;
Ok(Scalar::DateTime(fraction))
}
fn parse_time_text(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let (date_part, time_part) = split_date_time(text);
if parse_date_serial(date_part).is_some() {
// A full date-time string keeps only its time; a date alone is midnight.
return match time_part {
Some(time) => parse_clock(time),
None => Some(0.0),
};
}
parse_clock(text)
}
/// `QUARTER ( <Date> )` — 1 (January-March) through 4 (October-December).
fn quarter(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let serial = date_arg("QUARTER", &values, 0)?;
let (_, month, _) = support::date_parts(serial);
Ok(Scalar::Integer((month - 1).div_euclid(3) + 1))
}
/// `WEEKNUM ( <Date> [, <ReturnType>] )`.
///
/// Return types 1 and 2-17 use week system 1 (the week containing January 1 is week 1) with the
/// week starting on Sunday (1), Monday (2, 11), Tuesday (12), Wednesday (13), Thursday (14),
/// Friday (15), Saturday (16) or Sunday (17). Return type 21 is ISO 8601, where the week with the
/// first Thursday is week 1 and the result follows the ISO week even across a year boundary.
fn weeknum(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let serial = date_arg("WEEKNUM", &values, 0)?.floor();
let return_type = optional_int("WEEKNUM", &values, 1, 1)?;
let week = match return_type {
21 => iso_week(serial),
1 => week_system1(serial, 7),
2 | 11 => week_system1(serial, 1),
12 => week_system1(serial, 2),
13 => week_system1(serial, 3),
14 => week_system1(serial, 4),
15 => week_system1(serial, 5),
16 => week_system1(serial, 6),
17 => week_system1(serial, 7),
other => return Err(EvalError::new(format!("WEEKNUM return type {other} is not supported"))),
};
Ok(Scalar::Integer(week))
}
/// Week number in week system 1 for a week starting on `week_start` (Monday 1 .. Sunday 7).
fn week_system1(serial: f64, week_start: i64) -> i64 {
let (year, _, _) = support::date_parts(serial);
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0);
let day_of_year = (serial - jan1) as i64 + 1;
let lead = (iso_weekday(jan1) - week_start).rem_euclid(7);
(day_of_year + lead - 1).div_euclid(7) + 1
}
/// ISO 8601 week number. Dates that belong to the neighbouring ISO year report that year's week
/// number (2021-01-01 is week 53, 2018-12-31 is week 1), matching Excel's return type 21.
fn iso_week(serial: f64) -> i64 {
// The Thursday of the week decides the ISO year: week 1 is the week that contains it.
let thursday = serial as i64 - iso_weekday(serial) + 4;
let year = if thursday < 1 { 1900 } else { support::date_parts(thursday as f64).0 };
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0) as i64;
(thursday - jan1).div_euclid(7) + 1
}
/// Weekday with Monday 1 .. Sunday 7. The shared helper returns Excel's default Sunday-first
/// numbering (`date_weekday`), which week-number arithmetic and NETWORKDAYS do not use.
fn iso_weekday(serial: f64) -> i64 {
((support::date_weekday(serial) + 5) % 7) + 1
}
/// `YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] )`.
///
/// Basis 0 is US (NASD) 30/360, 1 actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360,
/// matching Excel's `YEARFRAC` (the same rules the worksheet engine in `crates/functions` uses).
/// Excel ignores the argument order and returns the positive fraction for a reversed pair.
fn yearfrac(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let start = date_arg("YEARFRAC", &values, 0)?.floor();
let end = date_arg("YEARFRAC", &values, 1)?.floor();
let basis = optional_int("YEARFRAC", &values, 2, 0)?;
if !(0..=4).contains(&basis) {
return Err(EvalError::new(format!("YEARFRAC basis {basis} is not supported")));
}
let (start, end) = if start <= end { (start, end) } else { (end, start) };
let (year1, month1, day1) = support::date_parts(start);
let (year2, month2, day2) = support::date_parts(end);
let days = end - start;
let fraction = match basis {
0 => {
let mut day1 = day1;
let mut day2 = day2;
let start_feb_end = month1 == 2 && day1 == support::days_in_month(year1, 2);
let end_feb_end = month2 == 2 && day2 == support::days_in_month(year2, 2);
if day1 == 31 && day2 == 31 {
day1 = 30;
day2 = 30;
} else if day1 == 31 {
day1 = 30;
} else if day1 == 30 && day2 == 31 {
day2 = 30;
} else if start_feb_end && end_feb_end {
day1 = 30;
day2 = 30;
} else if start_feb_end {
day1 = 30;
}
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
}
1 => {
let within_year = year1 == year2 || (year2 == year1 + 1 && (month1 > month2 || (month1 == month2 && day1 >= day2)));
let year_length = if within_year {
let leap_day_between =
(year1..=year2).any(|year| support::is_leap_year(year) && (start..=end).contains(&support::date_serial(year, 2, 29, 0, 0, 0)));
if (year1 == year2 && support::is_leap_year(year1)) || leap_day_between || (month2 == 2 && day2 == 29) { 366.0 } else { 365.0 }
} else {
let years = (year2 - year1 + 1) as f64;
let span = support::date_serial(year2 + 1, 1, 1, 0, 0, 0) - support::date_serial(year1, 1, 1, 0, 0, 0);
span / years
};
days / year_length
}
2 => days / 360.0,
3 => days / 365.0,
_ => {
let day1 = day1.min(30);
let day2 = day2.min(30);
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
}
};
Ok(Scalar::Decimal(fraction))
}
/// `NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] )` — whole working days,
/// both ends included. Weekend codes are 1 (Saturday/Sunday, the default), 2-7 for the pairs
/// starting on Sunday through Friday, and 11-17 for a single day starting on Sunday. A reversed
/// range returns the negative count, as Excel does.
fn networkdays(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
// The optional holidays argument is a table, so it cannot go through eager scalar evaluation.
let scalars = args.iter().take(3).map(|arg| ev.eval(arg, ctx)).collect::<Result<Vec<_>, EvalError>>()?;
let start = date_arg("NETWORKDAYS", &scalars, 0)?.floor();
let end = date_arg("NETWORKDAYS", &scalars, 1)?.floor();
let code = optional_int("NETWORKDAYS", &scalars, 2, 1)?;
let weekends = weekend_days(code)?;
let holidays = match args.get(3) {
Some(expr) => {
let table = support::eval_table(ev, expr, ctx)?;
holiday_days(&table)?
}
None => BTreeSet::new(),
};
let (start, end, sign) = if start <= end { (start, end, 1) } else { (end, start, -1) };
let mut count = 0i64;
let mut day = start as i64;
let last = end as i64;
while day <= last {
let weekday = iso_weekday(day as f64) as usize;
if !weekends[weekday] && !holidays.contains(&day) {
count += 1;
}
day += 1;
}
Ok(Scalar::Integer(sign * count))
}
/// Weekend lookup indexed by weekday (Monday 1 .. Sunday 7).
fn weekend_days(code: i64) -> Result<[bool; 8], EvalError> {
let mut days = [false; 8];
match code {
1..=7 => {
let first = ((code + 4) % 7) + 1;
days[first as usize] = true;
days[(first % 7 + 1) as usize] = true;
}
11..=17 => {
days[(((code - 11 + 6) % 7) + 1) as usize] = true;
}
other => return Err(EvalError::new(format!("NETWORKDAYS weekend code {other} is not supported"))),
}
Ok(days)
}
fn holiday_days(table: &TableValue) -> Result<BTreeSet<i64>, EvalError> {
let mut days = BTreeSet::new();
if table.columns.is_empty() {
return Ok(days);
}
for row in &table.rows {
let Some(value) = row.first() else { continue };
if value.is_blank() {
continue;
}
let serial = coerce_date(value).ok_or_else(|| EvalError::new("NETWORKDAYS holidays must be dates"))?;
days.insert(serial.floor() as i64);
}
Ok(days)
}
// ---------------------------------------------------------------------------------------------
// Clock
// ---------------------------------------------------------------------------------------------
/// `NOW ()` — the current date and time. The clock is read once per evaluation and uses the
/// host's local timezone, as Excel does.
fn now() -> Result<Scalar, EvalError> {
Ok(Scalar::DateTime(support::now_serial()))
}
/// `TODAY ()` — the current local date at midnight.
fn today() -> Result<Scalar, EvalError> {
Ok(Scalar::DateTime(support::today_serial()))
}
/// `UTCNOW ()` — the current Coordinated Universal Time date and time.
fn utc_now() -> Result<Scalar, EvalError> {
Ok(Scalar::DateTime(support::utc_now_serial()))
}
/// `UTCTODAY ()` — the current UTC date at midnight.
fn utc_today() -> Result<Scalar, EvalError> {
Ok(Scalar::DateTime(support::utc_today_serial()))
}
// ---------------------------------------------------------------------------------------------
// Tables
// ---------------------------------------------------------------------------------------------
/// `CALENDAR ( <StartDate>, <EndDate> )` — one `Date` column with every day in the closed range.
fn calendar(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let start = date_arg("CALENDAR", &values, 0)?.floor();
let end = date_arg("CALENDAR", &values, 1)?.floor();
date_table(start, end, "CALENDAR")
}
/// `CALENDARAUTO ( [<FiscalYearEndMonth>] )` — a contiguous date table covering the whole fiscal
/// years spanned by the model's DateTime columns.
fn calendar_auto(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
let values = support::eval_all(ev, args, ctx)?;
let fiscal_end = optional_int("CALENDARAUTO", &values, 0, 12)?;
if !(1..=12).contains(&fiscal_end) {
return Err(EvalError::new("CALENDARAUTO FiscalYearEndMonth must be between 1 and 12"));
}
let mut bounds: Option<(f64, f64)> = None;
for table in &ev.model().tables {
for (index, column) in table.columns.iter().enumerate() {
let is_datetime = column.data_type.as_deref().is_some_and(is_date_type);
if !is_datetime {
continue;
}
for row in &table.rows {
let Some(value) = row.get(index) else { continue };
if value.is_blank() {
continue;
}
let Some(serial) = coerce_date(value) else { continue };
let serial = serial.floor();
bounds = Some(match bounds {
Some((min, max)) => (min.min(serial), max.max(serial)),
None => (serial, serial),
});
}
}
}
let Some((min, max)) = bounds else {
return Err(EvalError::new("CALENDARAUTO requires a model with at least one DateTime column"));
};
let start = fiscal_year_start(min, fiscal_end);
let end = fiscal_year_end(max, fiscal_end);
date_table(start, end, "CALENDARAUTO")
}
/// First day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
fn fiscal_year_start(serial: f64, end_month: i64) -> f64 {
let (year, month, _) = support::date_parts(serial);
let fiscal_year = if month <= end_month { year } else { year + 1 };
support::date_serial(fiscal_year - 1, end_month + 1, 1, 0, 0, 0)
}
/// Last day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
fn fiscal_year_end(serial: f64, end_month: i64) -> f64 {
let (year, month, _) = support::date_parts(serial);
let fiscal_year = if month <= end_month { year } else { year + 1 };
support::date_serial(fiscal_year, end_month, support::days_in_month(fiscal_year, end_month), 0, 0, 0)
}
/// Builds the one-column `Date` table shared by CALENDAR and CALENDARAUTO.
fn date_table(start: f64, end: f64, name: &str) -> Result<TableValue, EvalError> {
if end < start {
return Err(EvalError::new(format!("{name} requires the start date to be on or before the end date")));
}
if start < 0.0 || end > MAX_DATE_SERIAL {
return Err(EvalError::new(format!("{name} dates must be between 1899-12-30 and 9999-12-31")));
}
let count = (end - start) as i64 + 1;
if count > MAX_GENERATED_ROWS {
return Err(EvalError::new(format!("{name} result is too large")));
}
let rows = (0..count).map(|offset| vec![Scalar::DateTime(start + offset as f64)]).collect();
Ok(TableValue::new(vec![TableColumn { name: "Date".into() }], rows))
}
+331
View File
@@ -0,0 +1,331 @@
//! Math and trigonometry functions.
//!
//! The inverse trigonometric and hyperbolic families follow Excel's domains: a value outside the
//! documented range raises an error instead of returning NaN. `CONVERT` follows the catalog and
//! dax.guide, i.e. `CONVERT ( <Expression>, <DataType> )` with a bare type keyword.
//!
//! `RAND`/`RANDBETWEEN` use a local xorshift64* generator seeded from the clock (`js_sys::Date` on
//! wasm, where `SystemTime::now` traps) and a per-call salt; the catalog already flags both
//! functions as volatile.
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{SystemTime, UNIX_EPOCH};
use super::support::{args as arg_values, eval_all, parse_date_text, round_direction};
use super::*;
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
let name = name.to_ascii_uppercase();
match name.as_str() {
"ACOS" | "ACOSH" | "ACOT" | "ACOTH" | "ASIN" | "ASINH" | "ATAN" | "ATANH" | "CONVERT" | "COSH" | "COT" | "COTH" | "CURRENCY" | "EVEN"
| "MOD" | "MROUND" | "ODD" | "QUOTIENT" | "RAND" | "RANDBETWEEN" | "ROUNDDOWN" | "SINH" | "SQRTPI" | "TANH" => {}
_ => return None,
}
Some(evaluate(&name, ev, args, ctx))
}
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
None
}
fn evaluate(name: &str, ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = eval_all(ev, args, ctx)?;
let a = arg_values(name, &values);
match name {
"ACOS" => {
let x = domain_number(&a, -1.0, 1.0)?;
Ok(Scalar::Decimal(x.acos()))
}
"ACOSH" => {
let x = domain_number(&a, 1.0, f64::INFINITY)?;
Ok(Scalar::Decimal(x.acosh()))
}
"ACOT" => {
// Principal value in (0, pi), unlike ATAN's (-pi/2, pi/2).
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(std::f64::consts::FRAC_PI_2 - x.atan()))
}
"ACOTH" => {
let x = finite(a.number(0)?, name)?;
if x.abs() <= 1.0 {
return Err(EvalError::new("ACOTH argument must have an absolute value greater than 1"));
}
Ok(Scalar::Decimal(finite(0.5 * ((x + 1.0) / (x - 1.0)).ln(), name)?))
}
"ASIN" => {
let x = domain_number(&a, -1.0, 1.0)?;
Ok(Scalar::Decimal(x.asin()))
}
"ASINH" => {
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(x.asinh()))
}
"ATAN" => {
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(x.atan()))
}
"ATANH" => {
let x = finite(a.number(0)?, name)?;
if x <= -1.0 || x >= 1.0 {
return Err(EvalError::new("ATANH argument must be greater than -1 and less than 1"));
}
Ok(Scalar::Decimal(x.atanh()))
}
"CONVERT" => convert(&values),
"COSH" => {
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(finite(x.cosh(), name)?))
}
"COT" => {
let x = finite(a.number(0)?, name)?;
let tangent = x.tan();
if tangent == 0.0 {
return Err(EvalError::new("COT is undefined at multiples of pi"));
}
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
}
"COTH" => {
let x = finite(a.number(0)?, name)?;
let tangent = x.tanh();
if tangent == 0.0 {
return Err(EvalError::new("COTH is undefined at zero"));
}
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
}
"CURRENCY" => currency(a.arg(0)?),
"EVEN" => Ok(Scalar::Integer(round_away_to_even(finite(a.number(0)?, name)?)?)),
"MROUND" => {
let number = finite(a.number(0)?, name)?;
let multiple = finite(a.number(1)?, name)?;
Ok(Scalar::Decimal(mround(number, multiple)?))
}
"MOD" => modulo(a.arg(0)?, a.arg(1)?),
// ROUNDDOWN rounds toward zero (support::round_direction), so negatives go up.
"ROUNDDOWN" => Ok(Scalar::Decimal(round_direction(finite(a.number(0)?, name)?, a.number(1)? as i32, false))),
"ODD" => Ok(Scalar::Integer(round_away_to_odd(finite(a.number(0)?, name)?)?)),
"QUOTIENT" => {
let numerator = finite(a.number(0)?, name)?;
let denominator = finite(a.number(1)?, name)?;
if denominator == 0.0 {
return Err(EvalError::new("QUOTIENT denominator must not be zero"));
}
Ok(Scalar::Integer(truncate_i64(finite(numerator / denominator, name)?)?))
}
"RAND" => Ok(Scalar::Decimal(next_random_fraction())),
"RANDBETWEEN" => {
let bottom = truncate_i64(finite(a.number(0)?, name)?)?;
let top = truncate_i64(finite(a.number(1)?, name)?)?;
if bottom > top {
return Err(EvalError::new("RANDBETWEEN bottom must not be greater than top"));
}
let span = (top as i128) - (bottom as i128) + 1;
let offset = (next_random_u64() as u128 % span as u128) as i128;
Ok(Scalar::Integer((bottom as i128 + offset) as i64))
}
"SINH" => {
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(finite(x.sinh(), name)?))
}
"SQRTPI" => {
let x = finite(a.number(0)?, name)?;
if x < 0.0 {
return Err(EvalError::new("SQRTPI argument must not be negative"));
}
Ok(Scalar::Decimal(finite((x * std::f64::consts::PI).sqrt(), name)?))
}
"TANH" => {
let x = finite(a.number(0)?, name)?;
Ok(Scalar::Decimal(x.tanh()))
}
_ => Err(EvalError::new(format!("{name} is not a math function"))),
}
}
fn finite(value: f64, function: &str) -> Result<f64, EvalError> {
if value.is_finite() { Ok(value) } else { Err(EvalError::new(format!("{function} result is not a finite number"))) }
}
/// Reads the first argument as a finite number inside `[low, high]`.
fn domain_number(a: &super::support::Args<'_>, low: f64, high: f64) -> Result<f64, EvalError> {
let x = finite(a.number(0)?, a.name)?;
if x < low || x > high {
return Err(EvalError::new(format!("{} argument is outside the valid domain", a.name)));
}
Ok(x)
}
fn truncate_i64(value: f64) -> Result<i64, EvalError> {
if !value.is_finite() || value.trunc() < -9_223_372_036_854_775_808.0 || value.trunc() >= 9_223_372_036_854_775_808.0 {
return Err(EvalError::new("value is outside the 64-bit integer range"));
}
Ok(value.trunc() as i64)
}
/// CURRENCY rounds half away from zero to four decimals and stores the fixed-point integer.
fn currency(value: &Scalar) -> Result<Scalar, EvalError> {
let number = value.to_number().ok_or_else(|| EvalError::new("CURRENCY argument must be convertible to a number"))?;
let scaled = (number * 10_000.0).round();
if !scaled.is_finite() || scaled.abs() > i64::MAX as f64 {
return Err(EvalError::new("CURRENCY value is outside the representable range"));
}
Ok(Scalar::Currency(scaled as i64))
}
fn round_away_to_even(number: f64) -> Result<i64, EvalError> {
let magnitude = magnitude_i64(number)?;
let rounded = if magnitude % 2 == 0 {
magnitude
} else {
magnitude.checked_add(1).ok_or_else(|| EvalError::new("EVEN result is outside the 64-bit integer range"))?
};
Ok(with_sign(rounded, number))
}
fn round_away_to_odd(number: f64) -> Result<i64, EvalError> {
let magnitude = magnitude_i64(number)?;
let rounded = if magnitude % 2 == 1 {
magnitude
} else {
magnitude.checked_add(1).ok_or_else(|| EvalError::new("ODD result is outside the 64-bit integer range"))?
};
Ok(with_sign(rounded, number))
}
/// Absolute value rounded away from zero to an integer that still fits in an `i64`.
fn magnitude_i64(number: f64) -> Result<i64, EvalError> {
let magnitude = number.abs().ceil();
if !magnitude.is_finite() || magnitude >= 9_223_372_036_854_775_808.0 {
return Err(EvalError::new("number is outside the 64-bit integer range"));
}
Ok(magnitude as i64)
}
fn with_sign(magnitude: i64, number: f64) -> i64 {
if number < 0.0 { -magnitude } else { magnitude }
}
fn mround(number: f64, multiple: f64) -> Result<f64, EvalError> {
if multiple == 0.0 {
return Ok(0.0);
}
if (number > 0.0 && multiple < 0.0) || (number < 0.0 && multiple > 0.0) {
return Err(EvalError::new("MROUND number and multiple must have the same sign"));
}
finite((number / multiple).round() * multiple, "MROUND")
}
/// `MOD ( <Number>, <Divisor> )`: the remainder whose sign follows the *divisor*
/// (`number - divisor * FLOOR ( number / divisor )`), unlike Rust's `%`, which follows the
/// dividend. A zero divisor is a division-by-zero error in DAX, not BLANK. Two integer operands
/// keep the Integer type the catalog documents; anything else returns a Decimal.
fn modulo(number: &Scalar, divisor: &Scalar) -> Result<Scalar, EvalError> {
let divisor_number = finite(divisor.to_number().ok_or_else(|| EvalError::new("MOD argument 2 must be numeric"))?, "MOD")?;
if divisor_number == 0.0 {
return Err(EvalError::new("MOD divisor must not be zero"));
}
if let (Scalar::Integer(number), Scalar::Integer(divisor)) = (number, divisor) {
let divisor = *divisor;
let remainder = number.checked_rem(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?;
if remainder != 0 && (remainder < 0) != (divisor < 0) {
return Ok(Scalar::Integer(
remainder.checked_add(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?,
));
}
return Ok(Scalar::Integer(remainder));
}
let number = finite(number.to_number().ok_or_else(|| EvalError::new("MOD argument 1 must be numeric"))?, "MOD")?;
Ok(Scalar::Decimal(finite(number - divisor_number * (number / divisor_number).floor(), "MOD")?))
}
// ---------------------------------------------------------------------------------------------
// Random numbers
// ---------------------------------------------------------------------------------------------
/// Clock entropy for the PRNG seed. `SystemTime::now` traps on wasm, so it is only compiled for
/// native targets; wasm falls back to the counter that the caller mixes in.
#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::disallowed_methods)]
fn clock_nanos() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|duration| duration.as_nanos() as u64).unwrap_or(0)
}
/// The browser's wall clock in nanoseconds. `SystemTime::now` traps on wasm, and a fixed seed
/// would make every page load produce the same `RAND()` sequence, so the shared `js_sys::Date`
/// clock that `support.rs` already uses seeds the generator instead.
#[cfg(target_arch = "wasm32")]
fn clock_nanos() -> u64 {
(js_sys::Date::now() * 1_000_000.0) as u64
}
fn next_random_u64() -> u64 {
static STATE: AtomicU64 = AtomicU64::new(0);
static SALT: AtomicU64 = AtomicU64::new(0);
let mut state = STATE.load(Ordering::Relaxed);
if state == 0 {
let salt = SALT.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed);
state = clock_nanos() ^ salt;
if state == 0 {
state = 0x9E37_79B9_7F4A_7C15;
}
}
// xorshift64*: full-period, small and dependency-free.
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
STATE.store(state, Ordering::Relaxed);
state.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn next_random_fraction() -> f64 {
// 53 random mantissa bits give a uniform value in [0, 1).
(next_random_u64() >> 11) as f64 / 9_007_199_254_740_992.0
}
// ---------------------------------------------------------------------------------------------
// CONVERT
// ---------------------------------------------------------------------------------------------
fn convert(values: &[Scalar]) -> Result<Scalar, EvalError> {
match values {
[value, target] => convert_type(value, target),
_ => Err(EvalError::new("CONVERT expects an expression and a data type")),
}
}
fn convert_type(value: &Scalar, target: &Scalar) -> Result<Scalar, EvalError> {
let target = target.to_text().trim().to_ascii_uppercase();
match target.as_str() {
"BOOLEAN" | "LOGICAL" => {
let boolean = value.to_bool().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to BOOLEAN"))?;
Ok(Scalar::Boolean(boolean))
}
// "DECIMAL" is the DAX synonym for the fixed-decimal Currency type, not a double.
"CURRENCY" | "DECIMAL" | "FIXEDDECIMAL" => currency(value),
"DATETIME" => convert_datetime(value),
"DOUBLE" => {
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DOUBLE"))?;
Ok(Scalar::Decimal(finite(number, "CONVERT")?))
}
"INTEGER" | "INT64" => {
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to INTEGER"))?;
Ok(Scalar::Integer(truncate_i64(number)?))
}
"STRING" | "TEXT" => Ok(Scalar::String(value.to_dax_text())),
other => Err(EvalError::new(format!("CONVERT does not recognize the data type `{other}`"))),
}
}
fn convert_datetime(value: &Scalar) -> Result<Scalar, EvalError> {
match value {
Scalar::DateTime(_) => Ok(value.clone()),
Scalar::String(text) => {
let serial = parse_date_text(text).ok_or_else(|| EvalError::new("CONVERT cannot parse the text as DATETIME"))?;
Ok(Scalar::DateTime(serial))
}
other => {
let number = other.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DATETIME"))?;
Ok(Scalar::DateTime(finite(number, "CONVERT")?))
}
}
}
+79
View File
@@ -0,0 +1,79 @@
//! Time-intelligence functions.
#![allow(unused_imports)]
mod ranges;
mod totals;
use super::*;
/// Whether `data_type` names one of the two date types. `CALENDARAUTO`, the range functions and
/// the total functions share this test, so a column the model declares as `Date` counts as a date
/// everywhere instead of only in some of them.
pub(super) fn is_date_type(data_type: &str) -> bool {
data_type.eq_ignore_ascii_case("DateTime") || data_type.eq_ignore_ascii_case("Date")
}
/// [`is_date_type`] for a column's optional declared type: an undeclared type is not judged.
pub(super) fn is_date_column(data_type: Option<&str>) -> bool {
data_type.is_none_or(is_date_type)
}
/// The month and day a `YearEndDate` argument names. The range functions (`DATESYTD`, ...) and the
/// total functions (`TOTALYTD`, ...) both parse that argument here, so the documented `"6/30/2008"`
/// and `"6/30"` forms behave the same in both families and an impossible day (`"2/30"`) is rejected
/// by both instead of being clamped in one and rejected in the other. A month/day-only form is
/// checked against a leap year, so `"2/29"` stays valid.
pub(super) fn year_end_parts(value: &Scalar) -> Option<(i64, i64)> {
let (year, month, day) = match value {
Scalar::String(text) => {
let parts: Vec<&str> = text.trim().split(['/', '-']).map(str::trim).collect();
// An empty component (`"6/-30"`, `"6/"`) is not a date: reject it instead of letting
// the remaining parts parse as a valid month and day.
if parts.iter().any(|part| part.is_empty()) {
return None;
}
let numbers: Vec<i64> = parts.iter().map(|part| part.parse::<i64>().ok()).collect::<Option<Vec<i64>>>()?;
match numbers.as_slice() {
// `M/D`: only the month and day matter, and the year is never read back.
[month, day] => (2000, *month, *day),
// `Y/M/D` and `M/D/Y` are both documented shapes; a two-digit year is ignored.
[first, second, third] if *first > 31 => (*first, *second, *third),
[month, day, year] => (if *year > 99 { *year } else { 2000 }, *month, *day),
_ => return None,
}
}
other => {
let (year, month, day) = super::support::date_parts(super::support::date_value(other)?);
(year, month, day)
}
};
((1..=12).contains(&month) && day >= 1 && day <= super::support::days_in_month(year, month)).then_some((month, day))
}
/// The column a table argument contributes to the range and total functions, chosen by one rule so
/// `DATESWTD(Calendar)` and `TOTALWTD(…, Calendar)` never disagree: a column whose declared type is
/// a date type, then a column named `Date` that is not declared as another type, then — only when it
/// cannot be ambiguous — the table's single untyped column.
pub(super) fn table_date_column(table: &crate::model::ModelTable) -> Option<usize> {
if let Some(index) = table.columns.iter().position(|column| column.data_type.as_deref().is_some_and(is_date_type)) {
return Some(index);
}
if let Some(index) =
table.columns.iter().position(|column| column.name.eq_ignore_ascii_case("Date") && is_date_column(column.data_type.as_deref()))
{
return Some(index);
}
let untyped: Vec<usize> = table.columns.iter().enumerate().filter(|(_, column)| column.data_type.is_none()).map(|(index, _)| index).collect();
match untyped.as_slice() {
[index] => Some(*index),
_ => None,
}
}
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
totals::call(ev, name, args, ctx).or_else(|| ranges::call(ev, name, args, ctx))
}
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
totals::call_table(ev, name, args, ctx).or_else(|| ranges::call_table(ev, name, args, ctx))
}
@@ -0,0 +1,804 @@
//! Time-intelligence range functions (period tables).
//!
//! Every function here works the same way: it reads the dates visible in the current filter
//! context for a DateTime column, derives a calendar window from them, and materializes the
//! window as a one-column table whose rows are the *model's own* date values (so the result keeps
//! the date table's lineage and `CALCULATE` can use it as a filter).
//!
//! * The visible range comes from the filter context when the date column (or the date table) is
//! filtered, otherwise from the whole table. The window is anchored on the first visible date
//! (`PREVIOUS*`), the last visible date (`NEXT*`, `START*`, `END*`, `DATES*TD`), or both
//! (`DATEADD`, `DATESBETWEEN`, ...).
//! * The window is intersected with the dates that exist in the column, so a non-contiguous date
//! table only loses the missing days.
//! * The table forms replace any filter on the date column, per the documented time-intelligence
//! contract; the scalar conveniences (`FIRSTDATE` used as a value, ...) only accept a
//! single-row result.
//!
//! Week-based functions (`DATESWTD`, `STARTOFWEEK`, `ENDOFWEEK`, `NEXTWEEK`, `PREVIOUSWEEK`) take
//! a calendar reference in the catalog. GridCraft has no calendar objects, so the reference is
//! resolved to the calendar table's date column and weeks are Sunday-based, which is the Excel /
//! `WEEKDAY` default.
//!
//! https://dax.guide/datesinperiod/ (boundary date excluded), https://dax.guide/dateadd/
#![allow(unused_imports)]
use std::collections::BTreeSet;
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, derived_row_frame, edate};
use super::*;
/// Every function that this module answers for.
const FUNCTIONS: &[&str] = &[
"DATEADD",
"DATESBETWEEN",
"DATESINPERIOD",
"DATESMTD",
"DATESQTD",
"DATESWTD",
"DATESYTD",
"ENDOFMONTH",
"ENDOFQUARTER",
"ENDOFWEEK",
"ENDOFYEAR",
"FIRSTDATE",
"FIRSTNONBLANK",
"LASTDATE",
"LASTNONBLANK",
"NEXTDAY",
"NEXTMONTH",
"NEXTQUARTER",
"NEXTWEEK",
"NEXTYEAR",
"PARALLELPERIOD",
"PREVIOUSDAY",
"PREVIOUSMONTH",
"PREVIOUSQUARTER",
"PREVIOUSWEEK",
"PREVIOUSYEAR",
"SAMEPERIODLASTYEAR",
"STARTOFMONTH",
"STARTOFQUARTER",
"STARTOFWEEK",
"STARTOFYEAR",
];
/// Sanity bound for interval counts: the arithmetic stays exact and the loops over the date
/// table stay bounded by the model, so only absurd inputs need rejecting.
const MAX_INTERVALS: f64 = 1_000_000.0;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Interval {
Day,
Week,
Month,
Quarter,
Year,
}
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
let name = name.to_ascii_uppercase();
if !FUNCTIONS.contains(&name.as_str()) {
return None;
}
let result = match name.as_str() {
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true).and_then(|table| scalar_result(&name, table)),
"LASTNONBLANK" => nonblank(ev, args, ctx, false).and_then(|table| scalar_result(&name, table)),
_ => compute_table(ev, &name, args, ctx).and_then(|table| scalar_result(&name, table)),
};
Some(result)
}
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
let name = name.to_ascii_uppercase();
if !FUNCTIONS.contains(&name.as_str()) {
return None;
}
Some(match name.as_str() {
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true),
"LASTNONBLANK" => nonblank(ev, args, ctx, false),
_ => compute_table(ev, &name, args, ctx),
})
}
/// Converts a one-row, one-column result to its value; anything else cannot be used as a scalar.
fn scalar_result(name: &str, table: TableValue) -> Result<Scalar, EvalError> {
match table.rows.as_slice() {
[] => Ok(Scalar::Blank),
[row] => Ok(row.first().cloned().unwrap_or(Scalar::Blank)),
rows => Err(EvalError::new(format!("{name} returns a table with {} rows; use it as a CALCULATE filter instead of a scalar", rows.len()))),
}
}
/// The date column a time-intelligence call is anchored on.
struct DateAxis {
table: usize,
name: String,
/// Every date that exists in the column, ascending, as (day serial, original value).
dates: Vec<(f64, Scalar)>,
/// First and last visible date, absent when the filter context selects no date.
min: Option<f64>,
max: Option<f64>,
/// The distinct visible dates, ascending. Used to tell a selection that actually contains the
/// month's last two days from one that merely ends near its boundary.
visible_dates: Vec<f64>,
/// The visible cells themselves, as (day serial, original value): `FIRSTDATE`/`LASTDATE` pick
/// an exact cell, so they must choose among the values the filter context selects, not among
/// every timestamp the day happens to hold.
visible_values: Vec<(f64, Scalar)>,
}
impl DateAxis {
fn empty(&self) -> TableValue {
TableValue::new(vec![TableColumn { name: self.name.clone() }], Vec::new()).with_lineage(self.table)
}
/// The dates of the column between two inclusive boundaries.
fn table(&self, start: f64, end: f64) -> TableValue {
let start = start.floor();
let end = end.floor();
let rows = if start > end {
Vec::new()
} else {
self.dates.iter().filter(|(serial, _)| (start..=end).contains(serial)).map(|(_, value)| vec![value.clone()]).collect()
};
TableValue::new(vec![TableColumn { name: self.name.clone() }], rows).with_lineage(self.table)
}
/// `DATEADD` documents a contiguous dates argument: shifting a selection with a missing day
/// would sweep in the blocked date, so it is an error rather than a silently wider result.
fn require_contiguous(&self, name: &str) -> Result<(), EvalError> {
let Some(pair) = self.visible_dates.windows(2).find(|pair| pair[1] != pair[0] + 1.0) else {
return Ok(());
};
// Report the gap by calendar day: a serial alone does not tell the reader which day the
// selection skipped.
let day = |serial: f64| Scalar::DateTime(serial).to_dax_text().split(' ').next().unwrap_or_default().to_owned();
Err(EvalError::new(format!(
"{name} needs a contiguous range of visible dates; the selection skips from {} to {}",
day(pair[0]),
day(pair[1])
)))
}
/// One cell of `date` as a one-row table: the earliest cell of the day, or the latest when
/// `last` is set. Single-date operations (`FIRSTDATE`, `LASTDATE`, `PREVIOUSDAY`, ...) must stay
/// scalar, so they pick one exact cell value even when the day holds several timestamps; the
/// range tables keep every cell.
fn single(&self, date: f64, last: bool) -> TableValue {
let day = date.floor();
let visible: Vec<&Scalar> = self.visible_values.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect();
// A day the filter context selects contributes its visible cells; a day outside the
// selection (a `NEXTDAY` probe, say) falls back to every cell the column holds.
let cells =
if visible.is_empty() { self.dates.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect() } else { visible };
let ordering = |value: &&Scalar| date_value(value).unwrap_or(f64::NEG_INFINITY);
let picked = if last {
cells.into_iter().max_by(|a, b| ordering(a).total_cmp(&ordering(b)))
} else {
cells.into_iter().min_by(|a, b| ordering(a).total_cmp(&ordering(b)))
};
match picked {
Some(value) => TableValue::new(vec![TableColumn { name: self.name.clone() }], vec![vec![value.clone()]]).with_lineage(self.table),
None => self.empty(),
}
}
/// The first date that exists in `[start, end]`, as a one-row table.
fn first_in(&self, start: f64, end: f64) -> TableValue {
let mut table = self.table(start, end);
table.rows.truncate(1);
table
}
/// The last date that exists in `[start, end]`, as a one-row table.
fn last_in(&self, start: f64, end: f64) -> TableValue {
let mut table = self.table(start, end);
let last = table.rows.pop();
table.rows = last.into_iter().collect();
table
}
fn first(&self) -> TableValue {
match self.min {
Some(min) => self.single(min, false),
None => self.empty(),
}
}
fn last(&self) -> TableValue {
match self.max {
Some(max) => self.single(max, true),
None => self.empty(),
}
}
fn visible(&self) -> Option<(f64, f64)> {
Some((self.min?, self.max?))
}
/// Whether the selection contains both of the last two days of `max`'s month. `max` is the
/// selection's last visible date; the two days have to be on the axis itself, so a selection
/// that stops on the month-end date alone (or on its penultimate day) does not qualify.
fn includes_last_two_days(&self, max: f64) -> bool {
let last = month_end(max);
let penultimate = last - 1.0;
let contains = |date: f64| self.visible_dates.binary_search_by(|visible| visible.total_cmp(&date)).is_ok();
contains(penultimate) && contains(last)
}
}
/// Resolves the `Dates` argument (a DateTime column, or a calendar table for the week-based
/// functions) and reads the dates visible in the current filter context.
fn date_axis(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &Context, name: &str) -> Result<DateAxis, EvalError> {
let model = ev.model();
let (table, column) = match expr {
BoundExpr::Column { table, column } => (*table, *column),
BoundExpr::UnqualifiedColumn { name: column } => {
let tables = model.tables_with_column(column);
let table = match tables.as_slice() {
[table] => *table,
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column}]`"))),
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column}]` is ambiguous"))),
};
let index = model.column_index(table, column).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column}]`")))?;
(table, index)
}
BoundExpr::Table(table) => {
let model_table = model.tables.get(*table).ok_or_else(|| EvalError::new(format!("{name} needs a date table")))?;
let index = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("{name} needs a calendar with a date column")))?;
(*table, index)
}
_ => return Err(EvalError::new(format!("{name} needs a date column reference"))),
};
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid date table")))?;
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid date column")))?;
if let Some(data_type) = &model_column.data_type
&& !is_date_type(data_type)
{
return Err(EvalError::new(format!("{name} needs a DateTime column; `{}[{}]` is {data_type}", model_table.name, model_column.name)));
}
// `date_value` rather than `to_number`: BLANK is not the serial 0 (1899-12-30), and a
// non-finite number is not a date, so neither may enter the axis.
let mut dates: Vec<(f64, Scalar)> = model_table
.rows
.iter()
.filter_map(|row| row.get(column))
.filter_map(|value| date_value(value).filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
.collect();
dates.sort_by(|left, right| {
left.0
.total_cmp(&right.0)
.then_with(|| date_value(&left.1).unwrap_or(f64::NEG_INFINITY).total_cmp(&date_value(&right.1).unwrap_or(f64::NEG_INFINITY)))
});
// Deduplicate exact cell values, never whole days: a column can hold several timestamps that
// share a day, and the window's filter keys are those exact values, so dropping one would
// silently exclude its row from every range table.
let mut seen = BTreeSet::new();
dates.retain(|(_, value)| seen.insert(ScalarKey::from(value)));
// The visible dates honour the filter context. Only filters on the date table itself count:
// a filter on a fact table does not restrict the dimension it points at.
let mut min: Option<f64> = None;
let mut max: Option<f64> = None;
let mut visible_dates: Vec<f64> = Vec::new();
let mut visible_values: Vec<(f64, Scalar)> = Vec::new();
for row in visible_rows(ev, table, ctx) {
if let Some(value) = row.get(column)
&& let Some(serial) = date_value(value).filter(|serial| serial.is_finite())
{
let serial = serial.floor();
min = Some(min.map_or(serial, |value| value.min(serial)));
max = Some(max.map_or(serial, |value| value.max(serial)));
visible_dates.push(serial);
visible_values.push((serial, value.clone()));
}
}
visible_dates.sort_by(|left, right| left.total_cmp(right));
visible_dates.dedup_by(|left, right| left.total_cmp(right).is_eq());
Ok(DateAxis { table, name: model_column.name.clone(), dates, min, max, visible_dates, visible_values })
}
/// The model rows of a table that survive the filters currently in effect, in model column order.
///
/// Filtering goes through [`Evaluator::table`] so filters that reach the table through an active
/// relationship (a snowflaked dimension on the one side, or a bidirectional relationship) apply
/// too, not just filters set on the table's own columns.
fn visible_rows(ev: &Evaluator<'_>, table: usize, ctx: &Context) -> Vec<Vec<Scalar>> {
// A range function's column argument takes the current row: the row context transitions to
// filters, exactly as `CALCULATE` does, instead of the whole date column being visible.
ev.table(table, &ev.transitioned_filters(ctx)).rows
}
/// Resolves a `ColumnName` argument to (table, column, column name).
fn column_target(ev: &Evaluator<'_>, expr: &BoundExpr, name: &str) -> Result<(usize, usize, String), EvalError> {
let model = ev.model();
let (table, column) = match expr {
BoundExpr::Column { table, column } => (*table, *column),
BoundExpr::UnqualifiedColumn { name: column_name } => {
let tables = model.tables_with_column(column_name);
let table = match tables.as_slice() {
[table] => *table,
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column_name}]`"))),
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column_name}]` is ambiguous"))),
};
let index =
model.column_index(table, column_name).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column_name}]`")))?;
(table, index)
}
_ => return Err(EvalError::new(format!("{name} needs a column reference"))),
};
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid table")))?;
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid column")))?;
Ok((table, column, model_column.name.clone()))
}
fn number_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<f64, EvalError> {
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
let value = ev.eval(expr, ctx)?;
value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))
}
fn interval_count(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<i64, EvalError> {
let value = number_arg(ev, args, index, ctx, name)?;
if !value.is_finite() || value.abs() > MAX_INTERVALS {
return Err(EvalError::new(format!("{name} interval count is out of range")));
}
Ok(value.trunc() as i64)
}
fn interval_arg(
ev: &Evaluator<'_>,
args: &[BoundExpr],
index: usize,
ctx: &mut Context,
name: &str,
allow_day: bool,
allow_week: bool,
) -> Result<Interval, EvalError> {
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
let value = ev.eval(expr, ctx)?;
let text = value.to_text();
match text.trim().to_ascii_uppercase().as_str() {
"DAY" if allow_day => Ok(Interval::Day),
"WEEK" if allow_week => Ok(Interval::Week),
"MONTH" => Ok(Interval::Month),
"QUARTER" => Ok(Interval::Quarter),
"YEAR" => Ok(Interval::Year),
other => Err(EvalError::new(format!("{name} does not support the interval `{other}`"))),
}
}
/// A date argument that accepts BLANK (meaning "use the visible boundary").
fn optional_date(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<f64>, EvalError> {
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
let value = ev.eval(expr, ctx)?;
if value.is_blank() {
return Ok(None);
}
date_value(&value).map(|serial| Some(serial.floor())).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))
}
fn year_end_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<(i64, i64)>, EvalError> {
let Some(expr) = args.get(index) else {
return Ok(None);
};
let value = ev.eval(expr, ctx)?;
if value.is_blank() {
return Ok(None);
}
year_end_parts(&value).map(Some).ok_or_else(|| EvalError::new(format!("{name} YearEndDate must be a date such as \"6/30/2024\"")))
}
fn month_start(serial: f64) -> f64 {
let (year, month, _) = date_parts(serial);
date_serial(year, month, 1, 0, 0, 0)
}
fn month_end(serial: f64) -> f64 {
let (year, month, _) = date_parts(serial);
date_serial(year, month, days_in_month(year, month), 0, 0, 0)
}
fn quarter_start(serial: f64) -> f64 {
let (year, month, _) = date_parts(serial);
let first = (month - 1).div_euclid(3) * 3 + 1;
date_serial(year, first, 1, 0, 0, 0)
}
fn quarter_end(serial: f64) -> f64 {
let (year, month, _) = date_parts(serial);
let last = (month - 1).div_euclid(3) * 3 + 3;
date_serial(year, last, days_in_month(year, last), 0, 0, 0)
}
fn year_start(serial: f64) -> f64 {
date_serial(date_parts(serial).0, 1, 1, 0, 0, 0)
}
fn week_start(serial: f64) -> f64 {
// `date_weekday` uses the Excel WEEKDAY convention: Sunday = 1 ... Saturday = 7.
serial.floor() - (date_weekday(serial) - 1) as f64
}
fn week_end(serial: f64) -> f64 {
week_start(serial) + 6.0
}
/// End of the period (month/quarter/year) containing a date; day and week intervals are whole
/// numbers of days, so their aligned end is the date itself.
fn align_end(serial: f64, interval: Interval) -> f64 {
match interval {
Interval::Day | Interval::Week => serial.floor(),
Interval::Month => month_end(serial),
Interval::Quarter => quarter_end(serial),
Interval::Year => year_end_default(serial),
}
}
/// Start of the period (month/quarter/year) containing a date.
fn align_start(serial: f64, interval: Interval) -> f64 {
match interval {
Interval::Day | Interval::Week => serial.floor(),
Interval::Month => month_start(serial),
Interval::Quarter => quarter_start(serial),
Interval::Year => year_start(serial),
}
}
fn year_end_default(serial: f64) -> f64 {
date_serial(date_parts(serial).0, 12, 31, 0, 0, 0)
}
fn shift(serial: f64, count: i64, interval: Interval) -> f64 {
match interval {
Interval::Day => serial + count as f64,
Interval::Week => serial + 7.0 * count as f64,
Interval::Month => edate(serial, count),
Interval::Quarter => edate(serial, count.saturating_mul(3)),
Interval::Year => edate(serial, count.saturating_mul(12)),
}
}
/// The last day of a fiscal year that starts the day after the previous year's end date.
fn fiscal_end(year: i64, month: i64, day: i64) -> f64 {
date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0)
}
/// The (start, end) of the fiscal year containing `serial`; the default year ends December 31.
fn fiscal_bounds(serial: f64, year_end: Option<(i64, i64)>) -> (f64, f64) {
let (month, day) = year_end.unwrap_or((12, 31));
let (year, _, _) = date_parts(serial);
let end_this_year = fiscal_end(year, month, day);
let end_year = if serial.floor() <= end_this_year { year } else { year + 1 };
let end = fiscal_end(end_year, month, day);
let start = fiscal_end(end_year - 1, month, day) + 1.0;
(start, end)
}
/// The previous calendar month's window.
fn previous_month(serial: f64) -> (f64, f64) {
let last = month_start(serial) - 1.0;
(month_start(last), last)
}
fn next_month(serial: f64) -> (f64, f64) {
let first = month_end(serial) + 1.0;
(first, month_end(first))
}
fn previous_quarter(serial: f64) -> (f64, f64) {
let last = quarter_start(serial) - 1.0;
(quarter_start(last), last)
}
fn next_quarter(serial: f64) -> (f64, f64) {
let first = quarter_end(serial) + 1.0;
(first, quarter_end(first))
}
fn previous_week(serial: f64) -> (f64, f64) {
let last = week_start(serial) - 1.0;
(week_start(last), last)
}
fn next_week(serial: f64) -> (f64, f64) {
let first = week_end(serial) + 1.0;
(first, week_end(first))
}
fn compute_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
let dates_expr = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a date column")))?;
let axis = date_axis(ev, dates_expr, ctx, name)?;
match name {
"FIRSTDATE" => Ok(axis.first()),
"LASTDATE" => Ok(axis.last()),
"DATEADD" => {
// Arguments 4/5 (Extension/Truncation) exist only for model calendars. GridCraft has
// no calendar objects, so the date-column rules always apply: a selection that ends on
// the last day of a period extends to the end of the shifted period, and day positions
// that do not exist in the target month move to its last day (dax.guide/DATEADD).
let count = interval_count(ev, args, 1, ctx, name)?;
let interval = interval_arg(ev, args, 2, ctx, name, true, false)?;
let Some((min, max)) = axis.visible() else {
return Ok(axis.empty());
};
axis.require_contiguous(name)?;
let start = shift(min, count, interval);
let mut end = shift(max, count, interval);
// A selection that covers a whole period selects the whole target period. A selection
// that contains both of the last two days of its month (but not the whole period)
// still reaches the end of the shifted month, so a full February shifted by a year
// keeps February 29: "if the Dates argument includes all the days in April (30 rows),
// the result for the previous month includes all the days in March (31 days)"
// (dax.guide/DATEADD).
let month_edge = axis.includes_last_two_days(max);
if align_start(min, interval) == min && align_end(max, interval).floor() == max {
// The selection covers a whole period: the shift covers the whole target period.
end = align_end(end, interval);
} else if month_edge && matches!(interval, Interval::Month | Interval::Quarter | Interval::Year) {
// It runs to the end of its month instead: the shift reaches the end of the
// target month (a full February shifted by a year keeps February 29).
end = month_end(end);
}
Ok(axis.table(start.min(end), start.max(end)))
}
"DATESBETWEEN" => {
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
let end = optional_date(ev, args, 2, ctx, name)?.or(axis.max);
match (start, end) {
(Some(start), Some(end)) => Ok(axis.table(start, end)),
_ => Ok(axis.empty()),
}
}
"DATESINPERIOD" => {
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
let count = interval_count(ev, args, 2, ctx, name)?;
let interval = interval_arg(ev, args, 3, ctx, name, true, true)?;
let aligned = match args.get(4) {
Some(expr) => {
let value = ev.eval(expr, ctx)?;
match value.to_text().trim().to_ascii_uppercase().as_str() {
"ENDALIGNED" => true,
"" | "PRECISE" => false,
other => return Err(EvalError::new(format!("{name} does not support the EndBehavior `{other}`"))),
}
}
None => false,
};
let Some(start) = start else {
return Ok(axis.empty());
};
if count == 0 {
return Ok(axis.empty());
}
let mut boundary = shift(start, count, interval);
if aligned && align_end(start, interval).floor() == start.floor() {
boundary = align_end(boundary, interval);
}
let (low, high) = if count > 0 { (start, boundary - 1.0) } else { (boundary + 1.0, start) };
Ok(axis.table(low, high))
}
"DATESMTD" => match axis.max {
Some(max) => Ok(axis.table(month_start(max), max)),
None => Ok(axis.empty()),
},
"DATESQTD" => match axis.max {
Some(max) => Ok(axis.table(quarter_start(max), max)),
None => Ok(axis.empty()),
},
"DATESWTD" => match axis.max {
Some(max) => Ok(axis.table(week_start(max), max)),
None => Ok(axis.empty()),
},
"DATESYTD" => {
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
match axis.max {
Some(max) => {
let (start, _) = fiscal_bounds(max, year_end);
Ok(axis.table(start, max))
}
None => Ok(axis.empty()),
}
}
"ENDOFMONTH" => match axis.max {
Some(max) => Ok(axis.last_in(month_start(max), month_end(max))),
None => Ok(axis.empty()),
},
"ENDOFQUARTER" => match axis.max {
Some(max) => Ok(axis.last_in(quarter_start(max), quarter_end(max))),
None => Ok(axis.empty()),
},
"ENDOFWEEK" => match axis.max {
Some(max) => Ok(axis.last_in(week_start(max), week_end(max))),
None => Ok(axis.empty()),
},
"ENDOFYEAR" => {
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
match axis.max {
Some(max) => {
let (start, end) = fiscal_bounds(max, year_end);
Ok(axis.last_in(start, end))
}
None => Ok(axis.empty()),
}
}
"NEXTDAY" => match axis.max {
Some(max) => Ok(axis.single(max + 1.0, true)),
None => Ok(axis.empty()),
},
"PREVIOUSDAY" => match axis.min {
Some(min) => Ok(axis.single(min - 1.0, true)),
None => Ok(axis.empty()),
},
"NEXTMONTH" => match axis.max {
Some(max) => {
let (start, end) = next_month(max);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"PREVIOUSMONTH" => match axis.min {
Some(min) => {
let (start, end) = previous_month(min);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"NEXTQUARTER" => match axis.max {
Some(max) => {
let (start, end) = next_quarter(max);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"PREVIOUSQUARTER" => match axis.min {
Some(min) => {
let (start, end) = previous_quarter(min);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"NEXTWEEK" => match axis.max {
Some(max) => {
let (start, end) = next_week(max);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"PREVIOUSWEEK" => match axis.min {
Some(min) => {
let (start, end) = previous_week(min);
Ok(axis.table(start, end))
}
None => Ok(axis.empty()),
},
"NEXTYEAR" => {
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
match axis.max {
Some(max) => {
let (_, end) = fiscal_bounds(max, year_end);
let (start, next_end) = fiscal_bounds(end + 1.0, year_end);
Ok(axis.table(start, next_end))
}
None => Ok(axis.empty()),
}
}
"PREVIOUSYEAR" => {
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
match axis.min {
Some(min) => {
let (start, _) = fiscal_bounds(min, year_end);
let (previous_start, previous_end) = fiscal_bounds(start - 1.0, year_end);
Ok(axis.table(previous_start, previous_end))
}
None => Ok(axis.empty()),
}
}
"PARALLELPERIOD" => {
let count = interval_count(ev, args, 1, ctx, name)?;
let interval = interval_arg(ev, args, 2, ctx, name, false, false)?;
let Some((min, max)) = axis.visible() else {
return Ok(axis.empty());
};
let start = align_start(shift(min, count, interval), interval);
let end = align_end(shift(max, count, interval), interval);
Ok(axis.table(start, end))
}
"SAMEPERIODLASTYEAR" => {
let Some((min, max)) = axis.visible() else {
return Ok(axis.empty());
};
let start = edate(min, -12);
let mut end = edate(max, -12);
// It is `DATEADD(Dates, -1, YEAR)`: a selection containing the last two days of its
// month reaches the end of the shifted month, leap day included.
if axis.includes_last_two_days(max) {
end = month_end(end);
}
Ok(axis.table(start.min(end), start.max(end)))
}
"STARTOFMONTH" => match axis.max {
Some(max) => Ok(axis.first_in(month_start(max), month_end(max))),
None => Ok(axis.empty()),
},
"STARTOFQUARTER" => match axis.max {
Some(max) => Ok(axis.first_in(quarter_start(max), quarter_end(max))),
None => Ok(axis.empty()),
},
"STARTOFWEEK" => match axis.max {
Some(max) => Ok(axis.first_in(week_start(max), week_end(max))),
None => Ok(axis.empty()),
},
"STARTOFYEAR" => {
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
match axis.max {
Some(max) => {
let (start, end) = fiscal_bounds(max, year_end);
Ok(axis.first_in(start, end))
}
None => Ok(axis.empty()),
}
}
_ => Err(EvalError::new(format!("DAX function `{name}` is not implemented by this evaluator"))),
}
}
fn is_blank_scalar(value: &Scalar) -> bool {
value.is_blank() || matches!(value, Scalar::String(text) if text.is_empty())
}
/// `FIRSTNONBLANK`/`LASTNONBLANK`: walk the visible values of the column in sort order and return
/// the value whose accompanying expression is not blank.
fn nonblank(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<TableValue, EvalError> {
let name = if first { "FIRSTNONBLANK" } else { "LASTNONBLANK" };
let target = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
let expression = args.get(1).ok_or_else(|| EvalError::new(format!("{name} needs a value expression")))?;
let (table, column, column_name) = column_target(ev, target, name)?;
let visible = visible_rows(ev, table, ctx);
let mut entries: Vec<(ScalarKey, Scalar)> = Vec::new();
let mut seen: BTreeSet<ScalarKey> = BTreeSet::new();
for row in &visible {
if let Some(value) = row.get(column) {
let key = ScalarKey::from(value);
if seen.insert(key.clone()) {
entries.push((key, value.clone()));
}
}
}
entries.sort_by(|left, right| left.0.cmp(&right.0));
if !first {
entries.reverse();
}
for (key, value) in entries {
let previous = ctx.filters.filters.get(&(table, column)).cloned();
// `FilterContext::set` folds the key the same way the filter's `matches` does, so a
// mixed-case text candidate still selects its rows.
ctx.filters.set(table, column, [key]);
// The row context is `VALUES(column)`, not one model row: a measure's context transition
// must keep every row that shares the candidate value.
ctx.rows.push(derived_row_frame(Some(table), vec![column_name.clone()], vec![value.clone()], vec![Some(column)]));
let evaluated = ev.eval(expression, ctx);
ctx.rows.pop();
match previous {
Some(values) => {
ctx.filters.set(table, column, values);
}
None => {
ctx.filters.filters.remove(&(table, column));
}
}
if !is_blank_scalar(&evaluated?) {
return Ok(TableValue::new(vec![TableColumn { name: column_name }], vec![vec![value]]).with_lineage(table));
}
}
Ok(TableValue::new(vec![TableColumn { name: column_name }], Vec::new()).with_lineage(table))
}
@@ -0,0 +1,450 @@
//! Time-intelligence scalar totals and balance functions.
//!
//! `TOTAL*` are CALCULATE sugar: the expression is evaluated over a period-to-date window
//! derived from the last date visible on the date column. `OPENINGBALANCE*`/`CLOSINGBALANCE*`
//! evaluate the expression on the period's boundary date (the last date, or the day before the
//! first), matching Excel's `CALCULATE(<expr>, ENDOF.../PREVIOUSDAY(STARTOF...))` definitions.
//!
//! The window is applied as a filter on the date column. Like the table filter produced by
//! `DATESMTD`/`ENDOFMONTH` inside CALCULATE, it replaces the existing filters on the date table
//! (otherwise a matrix row filtered by month could never accumulate a quarter or a year) while
//! filters on other tables keep applying. When the date column is a fact table's own date rather
//! than a date dimension key, only that column's filter is replaced and the fact table's other
//! filters keep applying — the same rows `CALCULATE (<expr>, DATESYTD (<date>))` would see.
//!
//! Week periods follow DAX's Sunday-first convention (`STARTOFWEEK`); the optional
//! `YearEndDate` argument only contributes its month and day, as documented for `TOTALYTD`.
use std::collections::BTreeSet;
use crate::ast::BinaryOp;
use crate::value::ScalarKey;
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, eomonth};
use super::*;
/// The calendar period a total or a balance slice is anchored to.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Period {
Month,
Quarter,
Week,
Year,
}
/// A resolved date column: the table it belongs to and its column index.
#[derive(Clone, Copy)]
struct DateColumn {
table: usize,
column: usize,
}
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
let result = match name.to_ascii_uppercase().as_str() {
"TOTALMTD" => total(ev, name, args, ctx, Period::Month),
"TOTALQTD" => total(ev, name, args, ctx, Period::Quarter),
"TOTALWTD" => total(ev, name, args, ctx, Period::Week),
"TOTALYTD" => total(ev, name, args, ctx, Period::Year),
"OPENINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, true),
"OPENINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, true),
"OPENINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, true),
"OPENINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, true),
"CLOSINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, false),
"CLOSINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, false),
"CLOSINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, false),
"CLOSINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, false),
"FIRSTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, true),
"LASTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, false),
_ => return None,
};
Some(result)
}
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
None
}
/// `TOTALMTD`/`TOTALQTD`/`TOTALWTD`/`TOTALYTD`.
fn total(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period) -> Result<Scalar, EvalError> {
let max = if period == Period::Year { 4 } else { 3 };
if args.len() < 2 || args.len() > max {
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
}
// These functions are CALCULATE sugar: the row context transitions to filters first, and the
// expression then runs without row frames, so a measure argument cannot re-transition the
// window away.
let base = ev.transitioned_filters(ctx);
let dates = date_column(ev, &args[1])?;
let visible = visible_dates(ev, dates, &base);
let Some(last) = visible.last().copied() else {
return Ok(Scalar::Blank);
};
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
let (start, _) = period_bounds(period, last, year_end);
let mut filters = date_table_filters(ev, &base, dates);
if let Some(filter) = args.get(2) {
apply_filter_arg(ev, filter, &mut filters, ctx)?;
}
// The window only keeps dates that exist in the date column, exactly like DATESMTD/YTD; the
// keys use the column's own values so an untyped date column still matches its rows.
let window = dates_between(ev, dates, start, last);
// `TOTALYTD` is `CALCULATE(expr, DATESYTD(dates), filter)`: a filter argument on the date
// column intersects the window instead of being replaced by it.
let window: BTreeSet<ScalarKey> = window.iter().map(|(_, value)| ScalarKey::from(value)).collect();
let keys = match filters.filters.get(&(dates.table, dates.column)) {
Some(existing) => existing.intersection(&window).cloned().collect(),
None => window,
};
filters.set(dates.table, dates.column, keys);
let mut inner = nested_context(filters, ctx);
ev.eval(&args[0], &mut inner)
}
/// `OPENINGBALANCE*`/`CLOSINGBALANCE*`: `CALCULATE(<expression>, <boundary date>)`.
///
/// Excel defines the closing balance on the last date of the period and the opening balance on
/// the day before the first date (`PREVIOUSDAY(STARTOF...)`). The expression is evaluated with a
/// single-date filter, so a boundary date without data yields BLANK — including on sparse fact
/// tables, where a "last date with a value" scan would invent a value Excel does not return.
fn balance(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period, opening: bool) -> Result<Scalar, EvalError> {
let max = if period == Period::Year { 4 } else { 3 };
if args.len() < 2 || args.len() > max {
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
}
let base = ev.transitioned_filters(ctx);
let dates = date_column(ev, &args[1])?;
let visible = visible_dates(ev, dates, &base);
let Some(last) = visible.last().copied() else {
return Ok(Scalar::Blank);
};
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
let (start, end) = period_bounds(period, last, year_end);
// Every cell of the boundary day, not one per day: a fact date column can hold several
// timestamps that share a day, and all of them belong to the period's boundary.
let boundary = if opening {
// PREVIOUSDAY(STARTOF...): the stored cells of the day before the period, when they exist.
let day = start.floor() - 1.0;
dates_between(ev, dates, day, day)
} else {
// `ENDOF*` is the last day that exists in the column, not the calendar end of the period.
let window = dates_between(ev, dates, start, end);
let Some(boundary_day) = window.last().map(|(date, _)| *date) else {
return Ok(Scalar::Blank);
};
window.into_iter().filter(|(date, _)| *date == boundary_day).collect()
};
if boundary.is_empty() {
return Ok(Scalar::Blank);
}
let boundary_keys: BTreeSet<ScalarKey> = boundary.iter().map(|(_, value)| ScalarKey::from(value)).collect();
let mut filters = date_table_filters(ev, &base, dates);
if let Some(filter) = args.get(2) {
apply_filter_arg(ev, filter, &mut filters, ctx)?;
}
let keys = match filters.filters.get(&(dates.table, dates.column)) {
Some(existing) => existing.intersection(&boundary_keys).cloned().collect(),
None => boundary_keys,
};
filters.set(dates.table, dates.column, keys);
let mut inner = nested_context(filters, ctx);
ev.eval(&args[0], &mut inner)
}
/// `FIRSTNONBLANKVALUE`/`LASTNONBLANKVALUE`: the expression value at the first (last) visible
/// value of the column whose expression result is not blank.
fn non_blank_value(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<Scalar, EvalError> {
if args.len() != 2 {
return Err(EvalError::new(format!("{name} expects 2 arguments")));
}
// CALCULATE sugar, like `TOTAL*`: the row context transitions to filters first, and the
// expression runs with no row frames so a measure argument cannot re-transition the candidate
// filter away.
let base = ev.transitioned_filters(ctx);
let (table, column) = column_reference(ev, &args[0])?;
let source = ev.table(table, &base);
let values = source.column(column);
let keys: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(ScalarKey::from).collect();
let ordered: Vec<ScalarKey> = if first { keys.into_iter().collect() } else { keys.into_iter().rev().collect() };
let mut inner = nested_context(base, ctx);
for key in ordered {
inner.filters.set(table, column, [key]);
let value = ev.eval(&args[1], &mut inner)?;
if !value.is_blank() {
return Ok(value);
}
}
Ok(Scalar::Blank)
}
/// Resolves a date-column argument. The week functions in the catalog take a calendar/table
/// reference, so a table argument is accepted too and its date column is chosen the same way
/// `ranges::date_axis` chooses one: a column whose declared type is a date type first, a column
/// named `Date` only as the fallback. An untyped column is never preferred over a typed one.
fn date_column(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<DateColumn, EvalError> {
if let BoundExpr::Table(table) = expr {
let Some(model_table) = ev.model().tables.get(*table) else {
return Err(EvalError::new("the date table is out of range"));
};
let column = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("table `{}` has no date column", model_table.name)))?;
return Ok(DateColumn { table: *table, column });
}
let (table, column) = column_reference(ev, expr)?;
let Some(model_table) = ev.model().tables.get(table) else {
return Err(EvalError::new("the date table is out of range"));
};
let Some(model_column) = model_table.columns.get(column) else {
return Err(EvalError::new("the date column is out of range"));
};
if !is_date_column(model_column.data_type.as_deref()) {
return Err(EvalError::new(format!("`{}`[{}] is not a date column", model_table.name, model_column.name)));
}
Ok(DateColumn { table, column })
}
/// Resolves a plain column argument without a type restriction.
fn column_reference(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<(usize, usize), EvalError> {
match expr {
BoundExpr::Column { table, column } => {
let Some(model_table) = ev.model().tables.get(*table) else {
return Err(EvalError::new("the column's table is out of range"));
};
if model_table.columns.get(*column).is_none() {
return Err(EvalError::new("the column is out of range"));
}
Ok((*table, *column))
}
BoundExpr::UnqualifiedColumn { name } => {
let tables = ev.model().tables_with_column(name);
let [table] = tables.as_slice() else {
return Err(EvalError::new(format!("column `[{name}]` is ambiguous or not in the model")));
};
let column = ev.model().column_index(*table, name).ok_or_else(|| EvalError::new(format!("column `[{name}]` is not in the model")))?;
Ok((*table, column))
}
_ => Err(EvalError::new("this function needs a column reference")),
}
}
/// The date values visible in the current filter context. Filters propagate to the date table
/// only along bidirectional relationships, which `Evaluator::table` already models; filters on
/// the fact table of a single-direction date relationship must not shrink the calendar.
fn visible_dates(ev: &Evaluator<'_>, dates: DateColumn, filters: &FilterContext) -> Vec<f64> {
let table = ev.table(dates.table, filters);
let values: Vec<f64> = table.column(dates.column).iter().filter_map(date_value).collect();
normalized(values)
}
/// The dates of the column in `[start, end]`, each with the column's own value so a filter built
/// from them matches the stored cells even when the column has no declared date type. Serials are
/// rounded down to their day, so a DateTime cell that carries a time of day still matches the
/// whole-day bounds; every cell of a day is kept, because the filter keys are the exact cell
/// values and a day may hold more than one timestamp.
fn dates_between(ev: &Evaluator<'_>, dates: DateColumn, start: f64, end: f64) -> Vec<(f64, Scalar)> {
let Some(model_table) = ev.model().tables.get(dates.table) else {
return Vec::new();
};
let mut values: Vec<(f64, Scalar)> = model_table
.rows
.iter()
.filter_map(|row| row.get(dates.column).map(|value| (value, date_value(value))))
.filter_map(|(value, serial)| serial.filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
.filter(|(date, _)| *date >= start - 1e-9 && *date <= end + 1e-9)
.collect();
values.sort_by(|left, right| left.0.total_cmp(&right.0));
values
}
/// Sorts ascending and drops duplicate days.
fn normalized(mut dates: Vec<f64>) -> Vec<f64> {
dates.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
dates.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
dates
}
/// The context a `TOTAL*`/`BALANCE*`/`NONBLANKVALUE` expression runs in: the window's filters with
/// no row frames, carrying the caller's variables and grouping scope. A measure evaluated inside a
/// `SUMMARIZE`/`SUMMARIZECOLUMNS` group must still see the group's scope (`ISINSCOPE`), so the scope
/// is propagated rather than reset.
fn nested_context(filters: FilterContext, ctx: &Context) -> Context {
Context { filters, rows: Vec::new(), vars: ctx.vars.clone(), grouping_scope: ctx.grouping_scope.clone() }
}
/// Removes the filters the computed window replaces. A date dimension key replaces every filter on
/// the whole date table; any other date column (a fact table's own date) replaces only that
/// column's filter, so the fact table keeps its other slices.
fn date_table_filters(ev: &Evaluator<'_>, filters: &FilterContext, dates: DateColumn) -> FilterContext {
let model = ev.model();
let is_dimension_key = model.relationships.iter().any(|relationship| {
model.table_index(&relationship.to_table) == Some(dates.table)
&& model.column_index(dates.table, &relationship.to_column) == Some(dates.column)
});
let mut filters = filters.clone();
if is_dimension_key {
filters.filters.retain(|(table, _), _| *table != dates.table);
} else {
filters.filters.remove(&(dates.table, dates.column));
}
filters
}
/// The first and last day of the period containing `anchor`.
fn period_bounds(period: Period, anchor: f64, year_end: Option<f64>) -> (f64, f64) {
let anchor = anchor.floor();
let (year, month, _) = date_parts(anchor);
match period {
Period::Month => (date_serial(year, month, 1, 0, 0, 0), eomonth(anchor, 0)),
Period::Quarter => {
let first_month = (month - 1) / 3 * 3 + 1;
let start = date_serial(year, first_month, 1, 0, 0, 0);
(start, eomonth(start, 2))
}
Period::Week => {
// WEEKDAY numbers are Sunday = 1 ... Saturday = 7.
let start = anchor - (date_weekday(anchor) - 1) as f64;
(start, start + 6.0)
}
Period::Year => match year_end {
Some(year_end) => fiscal_bounds(anchor, year_end),
None => (date_serial(year, 1, 1, 0, 0, 0), date_serial(year, 12, 31, 0, 0, 0)),
},
}
}
/// The fiscal year containing `anchor` for a year-end month/day. The year-end date itself
/// belongs to the fiscal year that ends on it.
fn fiscal_bounds(anchor: f64, year_end: f64) -> (f64, f64) {
let (_, end_month, end_day) = date_parts(year_end);
let (year, _, _) = date_parts(anchor);
let year_end_in = |year: i64| date_serial(year, end_month, end_day.min(days_in_month(year, end_month)), 0, 0, 0);
let end_this_year = year_end_in(year);
if anchor <= end_this_year + 1e-9 { (year_end_in(year - 1) + 1.0, end_this_year) } else { (end_this_year + 1.0, year_end_in(year + 1)) }
}
/// Evaluates the optional `YearEndDate` argument. Only its month and day matter.
fn year_end_serial(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<f64, EvalError> {
let value = ev.eval(expr, ctx)?;
let serial = parse_year_end(&value).ok_or_else(|| EvalError::new("YearEndDate must be a date"))?;
if !serial.is_finite() {
return Err(EvalError::new("YearEndDate must be a date"));
}
Ok(serial.floor())
}
/// Parses a year-end date. Unlike `parse_date_text`, this accepts the `M/D/YYYY` form used in
/// Parses a year-end date through the shared parser, then pins it to a leap year: only the month
/// and day are used, so `"6/30/2008"` and `"6/30"` name the same fiscal year end.
fn parse_year_end(value: &Scalar) -> Option<f64> {
let (month, day) = super::year_end_parts(value)?;
Some(date_serial(2000, month, day, 0, 0, 0))
}
/// Applies one CALCULATE-style filter argument to `filters`, the way the core CALCULATE does:
/// column predicate, `ALL`/`REMOVEFILTERS` (no argument, column or table), or a table expression
/// over a model table. Removal runs before the period window is applied, so the window still
/// lands even when the modifier cleared the date table's own filters.
fn apply_filter_arg(ev: &Evaluator<'_>, expr: &BoundExpr, filters: &mut FilterContext, ctx: &mut Context) -> Result<(), EvalError> {
match expr {
BoundExpr::Binary { op, left, right }
if matches!(op, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge)
&& matches!(**left, BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) =>
{
let (table, column) = column_reference(ev, left)?;
let value = ev.eval(right, ctx)?;
// `col <op> v` is FILTER(ALL(col), …): the candidates come from the whole column and
// compare with DAX semantics (numeric across types, text ignoring case).
use std::cmp::Ordering::{Equal, Greater, Less};
let keep = |candidate: &Scalar| {
let order = candidate.compare(&value);
match op {
BinaryOp::Eq => order == Some(Equal),
BinaryOp::Ne => order != Some(Equal),
BinaryOp::Lt => order == Some(Less),
BinaryOp::Le => matches!(order, Some(Less | Equal)),
BinaryOp::Gt => order == Some(Greater),
_ => matches!(order, Some(Greater | Equal)),
}
};
let keys = ev
.table(table, &FilterContext::default())
.column(column)
.into_iter()
.filter(|candidate| keep(candidate))
.map(|candidate| ScalarKey::from(&candidate));
filters.set(table, column, keys);
Ok(())
}
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("ALL") || spec.name.eq_ignore_ascii_case("REMOVEFILTERS") => {
match args.first() {
// No argument removes every filter: `ALL ()` is `ALL(<every table>)`.
None => filters.clear(),
// A column argument clears only that column; a table argument clears the table.
// Unqualified columns resolve to the single model column with that name.
Some(BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) => {
for arg in args {
let (table, column) = column_reference(ev, arg)?;
filters.filters.remove(&(table, column));
}
}
Some(BoundExpr::Table(table)) => filters.remove_table(*table),
Some(_) => {}
}
Ok(())
}
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("KEEPFILTERS") => {
// KEEPFILTERS applies its inner filter and intersects it with what is already there.
let inner = args.first().ok_or_else(|| EvalError::new("KEEPFILTERS needs a filter"))?;
let mut applied = filters.clone();
apply_filter_arg(ev, inner, &mut applied, ctx)?;
for (key, values) in applied.filters {
let merged = match filters.filters.get(&key) {
Some(existing) => existing.intersection(&values).cloned().collect(),
None => values,
};
filters.filters.insert(key, merged);
}
Ok(())
}
_ => {
let table = ev.eval_table(expr, ctx)?;
let Some(index) = table.lineage else {
return Err(EvalError::new("a filter table needs a source table"));
};
for (position, column) in table.columns.iter().enumerate() {
let Some(model_column) = ev.model().column_index(index, &column.name) else { continue };
let keys: BTreeSet<ScalarKey> = table.rows.iter().filter_map(|row| row.get(position)).map(ScalarKey::from).collect();
filters.set(index, model_column, keys);
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_context_keeps_the_grouping_scope() {
// A date total called from inside a `SUMMARIZE` group runs its expression in a nested
// context; the group's scope has to survive so `ISINSCOPE` still sees the group.
let ctx = Context {
filters: FilterContext::default(),
rows: Vec::new(),
vars: vec![Scalar::Integer(7)],
grouping_scope: Some(vec![(0, 1), (0, 2)]),
};
let inner = nested_context(FilterContext::default(), &ctx);
assert_eq!(inner.grouping_scope, Some(vec![(0, 1), (0, 2)]));
assert_eq!(inner.vars, vec![Scalar::Integer(7)]);
assert!(inner.rows.is_empty());
}
#[test]
fn nested_context_starts_outside_any_group() {
// The same call outside a grouping has no scope to carry.
let ctx = Context { filters: FilterContext::default(), rows: Vec::new(), vars: Vec::new(), grouping_scope: None };
assert_eq!(nested_context(FilterContext::default(), &ctx).grouping_scope, None);
}
}
+44
View File
@@ -242,11 +242,55 @@ fn an_interval_keyword_is_not_shadowed_by_a_variable() {
let bound = bind(&model, "VAR YEAR = 1 RETURN DATEDIFF ( Sales[Amount], Sales[Amount], YEAR )");
let debug = format!("{bound:?}");
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
// `DATEADD`'s interval is catalogued as text, but it is the same documented enumeration: a
// variable holding another interval must not replace it.
let bound = bind(&model, "VAR MONTH = \"DAY\" RETURN DATEADD ( Sales[Amount], 1, MONTH )");
let debug = format!("{bound:?}");
assert!(debug.contains("Keyword(\"MONTH\")"), "{debug}");
// `DATESINPERIOD`'s fourth argument is the same documented enumeration, including `WEEK`,
// which `DATEADD` does not accept.
for interval in ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"] {
let formula = format!("VAR {interval} = \"DAY\" RETURN DATESINPERIOD ( Date[Date], Date[Date], -1, {interval} )");
let bound = bind(&model, &formula);
let debug = format!("{bound:?}");
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
}
// `PARALLELPERIOD`'s third argument is the month-boundary enumeration: a variable holding
// `YEAR` must not turn `-1, MONTH` into a year shift.
for interval in ["MONTH", "QUARTER", "YEAR"] {
let formula = format!("VAR {interval} = \"YEAR\" RETURN PARALLELPERIOD ( Date[Date], -1, {interval} )");
let bound = bind(&model, &formula);
let debug = format!("{bound:?}");
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
}
// A variable still wins where the parameter is documented as text: RANKX's Ties argument.
let bound = bind(&model, "VAR DENSE = 1 RETURN RANKX ( Sales, Sales[Amount], 42, DENSE )");
assert!(format!("{bound:?}").contains("Variable"), "{bound:?}");
}
#[test]
fn an_interval_keyword_is_not_shadowed_by_a_model_name() {
let mut model = sample_model();
model.tables.push(ModelTable {
name: "YEAR".into(),
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
rows: vec![],
});
// A model table called `YEAR` is not the interval: `DATEADD` must still bind the keyword.
let bound = bind(&model, "DATEADD ( Sales[Amount], 1, YEAR )");
let debug = format!("{bound:?}");
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
// A position that does not take an interval keyword still resolves names: `YEAR` in RANKX's
// Order slot is not an order word, so the model table wins and must bind as that table.
let year_table = model.tables.len() - 1;
match bind(&model, "RANKX ( Sales, Sales[Amount], 42, YEAR )") {
BoundExpr::Call { args, .. } => {
assert!(matches!(args.get(3), Some(BoundExpr::Table(table)) if *table == year_table), "{args:?}");
}
other => panic!("expected a call, got {other:?}"),
}
}
#[test]
fn documented_order_keywords_bind_at_their_argument_positions() {
let model = sample_model();
+565
View File
@@ -0,0 +1,565 @@
//! Evaluation tests for the date/time function family.
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
use gridcraft_dax::value::{Scalar, TableColumn, TableValue};
use gridcraft_dax::{Binder, Evaluator, parse_expression};
// ---------------------------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------------------------
/// The OLE Automation serial of a date, built with `chrono` (a normal dependency of the crate,
/// independent of the evaluator under test) from the 1899-12-30 epoch.
fn serial(year: i32, month: u32, day: u32) -> f64 {
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
let date = chrono::NaiveDate::from_ymd_opt(year, month, day).expect("the fixture date is valid");
(date - epoch).num_days() as f64
}
fn model() -> DataModel {
DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Order Date".into(), data_type: Some("DateTime".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: vec![
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
vec![Scalar::DateTime(serial(2024, 1, 15)), Scalar::Decimal(20.0)],
vec![Scalar::DateTime(serial(2024, 3, 10)), Scalar::Decimal(30.0)],
],
},
ModelTable {
name: "Date".into(),
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
// No rows: CALENDARAUTO must take its bounds from the Sales date column.
rows: Vec::new(),
},
],
relationships: Vec::new(),
measures: Vec::new(),
}
}
/// A model whose only column is numeric: CALENDARAUTO has nothing to scan.
fn model_without_dates() -> DataModel {
DataModel {
tables: vec![
ModelTable {
name: "Numbers".into(),
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
rows: vec![vec![Scalar::Integer(1)]],
},
ModelTable {
name: "Empty".into(),
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
rows: Vec::new(),
},
],
relationships: Vec::new(),
measures: Vec::new(),
}
}
/// A model whose date column is declared `Date` rather than `DateTime`: DAX has both date types,
/// so the fiscal calendar has to be built from either.
fn model_with_date_typed_columns() -> DataModel {
DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Order Date".into(), data_type: Some("Date".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: vec![
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
vec![Scalar::DateTime(serial(2023, 3, 31)), Scalar::Decimal(20.0)],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
}
}
fn eval_in(model: &DataModel, src: &str) -> Result<Scalar, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
let expr = parse_expression(src).map_err(|error| error.to_string())?;
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate(&bound).map_err(|error| error.to_string())
}
fn eval_table_in(model: &DataModel, src: &str) -> Result<TableValue, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
let expr = parse_expression(src).map_err(|error| error.to_string())?;
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
}
fn eval(src: &str) -> Result<Scalar, String> {
eval_in(&model(), src)
}
fn eval_table(src: &str) -> Result<TableValue, String> {
eval_table_in(&model(), src)
}
fn value(src: &str) -> Scalar {
eval(src).unwrap_or_else(|error| panic!("{src}: {error}"))
}
fn assert_close(actual: Scalar, expected: f64, label: &str) {
match actual {
Scalar::Decimal(value) if (value - expected).abs() <= 1e-12 => {}
other => panic!("{label}: expected {expected}, got {other:?}"),
}
}
// ---------------------------------------------------------------------------------------------
// Text conversion
// ---------------------------------------------------------------------------------------------
#[test]
fn datevalue_reads_the_common_text_dates() {
assert_eq!(value("DATEVALUE(\"2024-01-15\")"), Scalar::DateTime(45_306.0));
assert_eq!(value("DATEVALUE(\"2024/1/15\")"), Scalar::DateTime(45_306.0));
// The documented en-US form, month first.
assert_eq!(value("DATEVALUE(\"1/8/2009\")"), Scalar::DateTime(39_821.0));
// A time portion is ignored: DATEVALUE returns the date.
assert_eq!(value("DATEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(45_306.0));
// A 12-hour clock suffix is accepted in both date orders.
let expected = Scalar::DateTime(serial(2024, 1, 15));
assert_eq!(value("DATEVALUE(\"2024-01-15 4:48 PM\")"), expected);
assert_eq!(value("DATEVALUE(\"1/15/2024 4:48 PM\")"), expected);
assert_eq!(value("DATEVALUE(DATE(2024,1,15))"), Scalar::DateTime(45_306.0));
assert_eq!(value("DATEVALUE(\"2024-02-29\")"), Scalar::DateTime(45_351.0));
}
#[test]
fn datevalue_rejects_invalid_text() {
assert!(eval("DATEVALUE(\"not a date\")").is_err());
// Impossible days and month-first days above 12 are errors, not serial rollover.
assert!(eval("DATEVALUE(\"2024-02-30\")").is_err());
assert!(eval("DATEVALUE(\"31/12/2024\")").is_err());
assert!(eval("DATEVALUE(\"2024-13-01\")").is_err());
assert!(eval("DATEVALUE(\"\")").is_err());
}
#[test]
fn timevalue_reads_the_common_text_times() {
let clock = (16.0 * 3600.0 + 48.0 * 60.0 + 23.0) / 86_400.0;
assert_eq!(value("TIMEVALUE(\"16:48:23\")"), Scalar::DateTime(clock));
assert_eq!(value("TIMEVALUE(\"4:48:23 PM\")"), Scalar::DateTime(clock));
assert_eq!(value("TIMEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(clock));
assert_eq!(value("TIMEVALUE(\"12:00 AM\")"), Scalar::DateTime(0.0));
assert_eq!(value("TIMEVALUE(\"12:30 PM\")"), Scalar::DateTime((12.0 * 3600.0 + 30.0 * 60.0) / 86_400.0));
assert_eq!(value("TIMEVALUE(\"6:00\")"), Scalar::DateTime(0.25));
assert_eq!(value("TIMEVALUE(\"2024-01-15\")"), Scalar::DateTime(0.0));
}
#[test]
fn timevalue_rejects_invalid_text() {
assert!(eval("TIMEVALUE(\"25:00\")").is_err());
assert!(eval("TIMEVALUE(\"12:61\")").is_err());
assert!(eval("TIMEVALUE(\"lunch\")").is_err());
assert!(eval("TIMEVALUE(\"13:00 PM\")").is_err());
}
// ---------------------------------------------------------------------------------------------
// Scalar date parts
// ---------------------------------------------------------------------------------------------
#[test]
fn quarter_maps_month_to_calendar_quarter() {
assert_eq!(value("QUARTER(DATE(2024,1,15))"), Scalar::Integer(1));
assert_eq!(value("QUARTER(DATE(2024,3,31))"), Scalar::Integer(1));
assert_eq!(value("QUARTER(DATE(2024,4,1))"), Scalar::Integer(2));
assert_eq!(value("QUARTER(DATE(2024,7,1))"), Scalar::Integer(3));
assert_eq!(value("QUARTER(DATE(2024,10,5))"), Scalar::Integer(4));
assert_eq!(value("QUARTER(DATE(2024,12,31))"), Scalar::Integer(4));
assert_eq!(value("QUARTER(\"2024-05-15\")"), Scalar::Integer(2));
}
#[test]
fn weeknum_matches_excel_week_systems() {
// System 1: the week containing January 1 is week 1, weeks start on Sunday by default.
assert_eq!(value("WEEKNUM(DATE(2024,1,1))"), Scalar::Integer(1));
assert_eq!(value("WEEKNUM(DATE(2024,1,15))"), Scalar::Integer(3));
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), Scalar::Integer(3));
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), value("WEEKNUM(DATE(2024,1,15), 11)"));
// Monday start: Sunday 2024-01-07 still belongs to week 1.
assert_eq!(value("WEEKNUM(DATE(2024,1,7), 2)"), Scalar::Integer(1));
// Sunday start: the same Sunday begins week 2.
assert_eq!(value("WEEKNUM(DATE(2024,1,7))"), Scalar::Integer(2));
assert_eq!(value("WEEKNUM(DATE(2024,1,8), 2)"), Scalar::Integer(2));
// A year can end in week 53 when January 1 falls late in the week.
assert_eq!(value("WEEKNUM(DATE(2023,12,31))"), Scalar::Integer(53));
assert_eq!(value("WEEKNUM(\"2024-01-15\")"), Scalar::Integer(3));
}
#[test]
fn weeknum_iso_weeks_cross_year_boundaries() {
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 21)"), Scalar::Integer(3));
// 2021-01-01 (Friday) belongs to ISO week 53 of 2020.
assert_eq!(value("WEEKNUM(DATE(2021,1,1), 21)"), Scalar::Integer(53));
// 2018-12-31 (Monday) and 2024-12-30 (Monday) are week 1 of the next year.
assert_eq!(value("WEEKNUM(DATE(2018,12,31), 21)"), Scalar::Integer(1));
assert_eq!(value("WEEKNUM(DATE(2024,12,30), 21)"), Scalar::Integer(1));
assert_eq!(value("WEEKNUM(DATE(2024,12,29), 21)"), Scalar::Integer(52));
assert_eq!(value("WEEKNUM(DATE(2020,12,31), 21)"), Scalar::Integer(53));
assert!(eval("WEEKNUM(DATE(2024,1,1), 3)").is_err());
assert!(eval("WEEKNUM(DATE(2024,1,1), 10)").is_err());
}
// ---------------------------------------------------------------------------------------------
// YEARFRAC
// ---------------------------------------------------------------------------------------------
#[test]
fn yearfrac_supports_every_basis() {
let start = "DATE(2024,1,1)";
let end = "DATE(2024,7,1)";
// Leap year 2024: Jan 1 to Jul 1 is 182 actual days.
assert_close(value(&format!("YEARFRAC({start}, {end})")), 0.5, "basis 0 default");
assert_close(value(&format!("YEARFRAC({start}, {end}, 0)")), 180.0 / 360.0, "basis 0");
assert_close(value(&format!("YEARFRAC({start}, {end}, 1)")), 182.0 / 366.0, "basis 1");
assert_close(value(&format!("YEARFRAC({start}, {end}, 2)")), 182.0 / 360.0, "basis 2");
assert_close(value(&format!("YEARFRAC({start}, {end}, 3)")), 182.0 / 365.0, "basis 3");
assert_close(value(&format!("YEARFRAC({start}, {end}, 4)")), 180.0 / 360.0, "basis 4");
}
#[test]
fn yearfrac_handles_calendar_boundaries_and_reversed_ranges() {
// A whole leap year is 1 for the 30/360 convention and 365/366 for actual/actual.
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 0)"), 1.0, "30/360 whole year");
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 1)"), 365.0 / 366.0, "actual/actual whole year");
// Excel's US 30/360 February rule: the end of February counts as day 30 but March 31 keeps 31.
assert_close(value("YEARFRAC(DATE(2019,2,28), DATE(2019,3,31), 0)"), 31.0 / 360.0, "February rule");
// Two end-of-February dates collapse to 30/30, which is a full year.
assert_close(value("YEARFRAC(DATE(2011,2,28), DATE(2012,2,29), 0)"), 1.0, "February to February");
// actual/actual uses 366 when the period contains a February 29.
assert_close(value("YEARFRAC(DATE(2011,3,1), DATE(2012,2,29), 1)"), 365.0 / 366.0, "leap day between");
// Multi-year actual/actual divides by the average calendar year length.
assert_close(value("YEARFRAC(DATE(2000,1,1), DATE(2003,1,1), 1)"), 1096.0 / (1461.0 / 4.0), "average year");
// Excel ignores the argument order: the reversed pair returns the positive fraction.
assert_close(value("YEARFRAC(DATE(2024,7,1), DATE(2024,1,1), 2)"), 182.0 / 360.0, "reversed");
assert_close(value("YEARFRAC(\"2024-01-01\", \"2024-07-01\", 2)"), 182.0 / 360.0, "text dates");
// dax.guide's documented example: 2011-01-01 .. 2011-12-15.
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 0)"), 344.0 / 360.0, "dax.guide 30/360");
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 1)"), 348.0 / 365.0, "dax.guide actual/actual");
}
#[test]
fn yearfrac_rejects_unknown_bases() {
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 5)").is_err());
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), -1)").is_err());
}
// ---------------------------------------------------------------------------------------------
// NETWORKDAYS
// ---------------------------------------------------------------------------------------------
#[test]
fn networkdays_counts_working_days_with_weekends_and_holidays() {
// January 2024 has 31 days, starting on a Monday, with 8 weekend days.
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31))"), Scalar::Integer(23));
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1)"), Scalar::Integer(23));
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,15) })"), Scalar::Integer(22));
// A holiday already on a weekend does not count twice.
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,6) })"), Scalar::Integer(23));
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,1), DATE(2024,1,15) })"), Scalar::Integer(21));
// Weekend code 2 is Sunday/Monday, 11 is Sunday only.
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 2)"), Scalar::Integer(22));
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 11)"), Scalar::Integer(27));
// A reversed range returns the negative count.
assert_eq!(value("NETWORKDAYS(DATE(2024,1,31), DATE(2024,1,1))"), Scalar::Integer(-23));
// A single working day and a single weekend day.
assert_eq!(value("NETWORKDAYS(DATE(2024,1,2), DATE(2024,1,2))"), Scalar::Integer(1));
assert_eq!(value("NETWORKDAYS(DATE(2024,1,6), DATE(2024,1,6))"), Scalar::Integer(0));
}
#[test]
fn networkdays_rejects_bad_weekend_codes() {
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 0)").is_err());
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 8)").is_err());
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 18)").is_err());
}
// ---------------------------------------------------------------------------------------------
// CALENDAR / CALENDARAUTO
// ---------------------------------------------------------------------------------------------
#[test]
fn calendar_builds_the_inclusive_date_column() {
let table = eval_table("CALENDAR(DATE(2024,2,27), DATE(2024,3,1))").expect("calendar table");
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
// 2024 is a leap year, so February 29 is included.
assert_eq!(
table.rows,
vec![
vec![Scalar::DateTime(serial(2024, 2, 27))],
vec![Scalar::DateTime(serial(2024, 2, 28))],
vec![Scalar::DateTime(serial(2024, 2, 29))],
vec![Scalar::DateTime(serial(2024, 3, 1))],
]
);
assert_eq!(eval_table("CALENDAR(DATE(2024,1,1), DATE(2024,1,31))").expect("january").rows.len(), 31);
assert_eq!(value("COUNTROWS(CALENDAR(DATE(2024,1,1), DATE(2024,1,31)))"), Scalar::Integer(31));
// Table functions are not scalars.
assert!(eval("CALENDAR(DATE(2024,1,1), DATE(2024,1,2))").is_err());
}
#[test]
fn calendar_rejects_reversed_bounds() {
assert!(eval_table("CALENDAR(DATE(2024,2,1), DATE(2024,1,1))").is_err());
}
#[test]
fn calendar_rejects_oversized_spans() {
// The whole in-range span is 2,958,466 days, above the 1,000,000-row generation ceiling, so
// it must fail instead of allocating the table.
let error = eval_table("CALENDAR(DATE(1899,12,30), DATE(9999,12,31))").expect_err("oversized calendar");
assert!(error.contains("too large"), "{error}");
// 1900-01-01 is serial 2, so exactly 1,000,000 days end on 4637-11-27; the cap is inclusive
// there and one day further fails.
let largest = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,27))").expect("largest calendar");
assert_eq!(largest.rows.len(), 1_000_000);
assert_eq!(largest.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(4637, 11, 27))));
let error = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,28))").expect_err("one day over the cap");
assert!(error.contains("too large"), "{error}");
}
#[test]
fn calendarauto_covers_whole_fiscal_years() {
// Sales spans 2023-06-15 .. 2024-03-10 and Date spans 2023-01-01 .. 2024-12-31.
let table = eval_table("CALENDARAUTO()").expect("calendar auto");
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 12, 31))));
assert_eq!(table.rows.len(), 731);
assert_eq!(value("COUNTROWS(CALENDARAUTO())"), Scalar::Integer(731));
// Fiscal years ending in March: 2023-04-01 .. 2024-03-31, including leap day 2024-02-29.
let fiscal = eval_table("CALENDARAUTO(3)").expect("fiscal calendar");
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 4, 1))));
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
assert_eq!(fiscal.rows.len(), 366);
assert!(fiscal.rows.iter().any(|row| row[0] == Scalar::DateTime(serial(2024, 2, 29))));
}
#[test]
fn calendarauto_reads_date_typed_columns() {
// 2023-03-31 .. 2023-06-15, in a column declared `Date`: the whole 2023 calendar year.
let table = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO()").expect("calendar auto over Date columns");
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 12, 31))));
assert_eq!(table.rows.len(), 365);
// A fiscal year ending in March: two fiscal years, since June 2023 falls in FY2024.
let fiscal = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO(3)").expect("fiscal calendar over Date columns");
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2022, 4, 1))));
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
}
#[test]
fn calendarauto_validates_arguments_and_model() {
assert!(eval_table("CALENDARAUTO(0)").is_err());
assert!(eval_table("CALENDARAUTO(13)").is_err());
assert!(eval_table_in(&model_without_dates(), "CALENDARAUTO()").is_err());
// Table functions are not scalars.
assert!(eval("CALENDARAUTO()").is_err());
}
// ---------------------------------------------------------------------------------------------
// Clock
// ---------------------------------------------------------------------------------------------
#[test]
// The test runs natively and needs an independent clock reference for the date serials.
#[allow(clippy::disallowed_methods)]
fn clock_functions_track_the_system_clock() {
let clock = || {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_secs_f64() / 86_400.0 + 25_569.0)
.expect("system clock")
};
let serial_of = |src: &str| match value(src) {
Scalar::DateTime(serial) => serial,
other => panic!("{src} produced {other:?}"),
};
// Each function is a separate evaluation; retry if a local or UTC day boundary falls inside
// the sampling window, so the floor comparisons cannot race midnight.
let mut attempts = 0;
let (today, now, utc_today, utc_now) = loop {
let before = clock();
let (today, now) = (serial_of("TODAY()"), serial_of("NOW()"));
let (utc_today, utc_now) = (serial_of("UTCTODAY()"), serial_of("UTCNOW()"));
let after = clock();
if before.floor() == after.floor() && today == now.floor() && utc_today == utc_now.floor() {
break (today, now, utc_today, utc_now);
}
attempts += 1;
assert!(attempts < 5, "clock functions disagree: TODAY {today}, NOW {now}, UTCTODAY {utc_today}, UTCNOW {utc_now}");
};
let expected = clock();
assert!((utc_now - expected).abs() < 1.0 / 86_400.0, "UTCNOW follows the system clock");
assert!((0.0..1.0).contains(&now.fract()));
// The host supplies one wall clock, so the local and UTC variants never differ by a day.
assert!((now - utc_now).abs() < 1.0);
assert!((today - utc_today).abs() <= 1.0);
// Volatile functions take no arguments.
assert!(eval("NOW(1)").is_err());
assert!(eval("TODAY(1)").is_err());
}
#[test]
fn edate_and_eomonth_survive_extreme_month_offsets() {
// `months` is arbitrary input: the month arithmetic must saturate instead of overflowing.
let model = model();
for (formula, name) in [("EDATE(DATE(2024,1,15), 1E18)", "EDATE"), ("EOMONTH(DATE(2024,1,15), -1E18)", "EOMONTH")] {
match eval_in(&model, formula) {
// Out-of-range serials are reported, but the month arithmetic itself must not overflow.
Ok(value) => assert!(matches!(value, Scalar::DateTime(serial) if serial.is_finite() || serial.is_nan()), "{name}: {value:?}"),
Err(error) => assert!(!error.is_empty(), "{name} reported an empty error"),
}
}
}
// ---------------------------------------------------------------------------------------------
// Relocated regressions
//
// These pin documented results that the evaluator used to get wrong; they moved here from
// `eval_audit_semantics.rs` and `eval_text.rs` because their functions live in this family.
// ---------------------------------------------------------------------------------------------
/// The single numeric value of an expression; panics when it is not numeric.
fn number(src: &str) -> f64 {
let evaluated = value(src);
evaluated.to_number().unwrap_or_else(|| panic!("{src} is not numeric: {evaluated:?}"))
}
/// The message of the error an expression raises.
fn error(src: &str) -> String {
match eval(src) {
Err(message) => message,
Ok(evaluated) => panic!("{src}: expected an error, got {evaluated:?}"),
}
}
/// The text form of an expression, as produced by `& ""`.
fn text(src: &str) -> String {
match value(src) {
Scalar::String(text) => text,
other => panic!("{src} should return text, got {other:?}"),
}
}
#[test]
fn mod_follows_the_divisor_sign() {
// Microsoft Learn, MOD: "The result has the same sign as the divisor."
assert_eq!(value("MOD(7, 3)"), Scalar::Integer(1));
assert_eq!(value("MOD(-3, 2)"), Scalar::Integer(1));
assert_eq!(value("MOD(3, -2)"), Scalar::Integer(-1));
assert_eq!(value("MOD(-3, -2)"), Scalar::Integer(-1));
assert_eq!(value("MOD(10, 5)"), Scalar::Integer(0));
// A fractional operand keeps the Decimal result.
assert_eq!(number("MOD(5.5, 2)"), 1.5);
assert_eq!(number("MOD(-5.5, 2)"), 0.5);
// A zero divisor is a division-by-zero error, not BLANK.
assert!(error("MOD(1, 0)").contains("MOD divisor must not be zero"));
}
#[test]
fn roundup_and_rounddown_follow_the_sign() {
// Microsoft Learn: ROUNDDOWN rounds toward zero, ROUNDUP away from zero.
assert_eq!(number("ROUNDDOWN(-2.9, 0)"), -2.0);
assert_eq!(number("ROUNDDOWN(2.9, 0)"), 2.0);
assert_eq!(number("ROUNDDOWN(-2.345, 2)"), -2.34);
assert_eq!(number("ROUNDUP(-2.1, 0)"), -3.0);
assert_eq!(number("ROUNDUP(2.1, 0)"), 3.0);
assert_eq!(number("ROUNDUP(2.341, 2)"), 2.35);
// ROUND still rounds half away from zero.
assert_eq!(number("ROUND(2.5, 0)"), 3.0);
assert_eq!(number("ROUND(-2.5, 0)"), -3.0);
}
#[test]
fn datediff_counts_interval_boundaries() {
// The catalog: DATEDIFF counts the Interval boundaries crossed between two dates.
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), DAY)"), Scalar::Integer(60));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), MONTH)"), Scalar::Integer(2));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2025, 3, 1), YEAR)"), Scalar::Integer(1));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 7, 1), QUARTER)"), Scalar::Integer(2));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), WEEK)"), Scalar::Integer(8));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), HOUR)"), Scalar::Integer(24));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), MINUTE)"), Scalar::Integer(1_440));
// A month boundary is crossed even by a single day.
assert_eq!(value("DATEDIFF(DATE(2024, 1, 31), DATE(2024, 2, 1), MONTH)"), Scalar::Integer(1));
// The sign follows Date2 - Date1.
assert_eq!(value("DATEDIFF(DATE(2024, 3, 1), DATE(2024, 1, 1), MONTH)"), Scalar::Integer(-2));
// A text argument keeps the time of day, exactly like a DateTime one: the sub-day intervals
// must not be read as midnight on both sides.
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", MINUTE)"), Scalar::Integer(120));
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", SECOND)"), Scalar::Integer(7_200));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1) + 10/24, \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
assert!(error("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), FORTNIGHT)").contains("DATEDIFF interval"));
}
#[test]
fn time_wraps_inside_one_day() {
// The catalog: "Overflowing arguments wrap inside the same day instead of raising an error
// (TIME ( 10, 90, 0 ) is 11:30 and TIME ( 50, 0, 0 ) is 02:00)".
assert_eq!(number("TIME(10, 90, 0)"), 11.5 / 24.0);
assert_eq!(number("TIME(50, 0, 0)"), 2.0 / 24.0);
assert_eq!(number("TIME(25, 0, 0)"), 1.0 / 24.0);
assert_eq!(number("TIME(0, 0, 0)"), 0.0);
assert_eq!(number("TIME(1, 2, 3)"), (3_723.0) / 86_400.0);
assert!(error("TIME(-1, 0, 0)").contains("TIME argument 1"));
assert!(error("TIME(32768, 0, 0)").contains("TIME argument 1"));
}
#[test]
fn weekday_honours_the_return_type() {
// 2024-01-01 is a Monday. Return type 1 numbers Sunday 1, 2 numbers Monday 1, 3 numbers
// Monday 0, and 11-17 start the week on Monday through Sunday.
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1))"), Scalar::Integer(2));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 1)"), Scalar::Integer(2));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 2)"), Scalar::Integer(1));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 3)"), Scalar::Integer(0));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 11)"), Scalar::Integer(1));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 12)"), Scalar::Integer(7));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 17)"), Scalar::Integer(2));
// 2024-01-07 is a Sunday.
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 2)"), Scalar::Integer(7));
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 3)"), Scalar::Integer(6));
assert!(error("WEEKDAY(DATE(2024, 1, 1), 5)").contains("WEEKDAY return type"));
}
#[test]
fn datediff_counts_boundaries_for_sub_day_and_week_intervals() {
// 10:59:59 to 11:00:01 crosses the 11:00 hour boundary even though two seconds passed.
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 1), HOUR)"), Scalar::Integer(1));
assert_eq!(value("DATEDIFF(TIME(10, 59, 58), TIME(10, 59, 59), SECOND)"), Scalar::Integer(1));
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 0), MINUTE)"), Scalar::Integer(1));
// Exactly one elapsed hour is still one boundary; 59 minutes is none.
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(11, 0, 0), HOUR)"), Scalar::Integer(1));
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(10, 59, 59), HOUR)"), Scalar::Integer(0));
// Weeks are Sunday-based: 2024-01-01 is a Monday, so the week boundary is the Sunday before it.
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 6), WEEK)"), Scalar::Integer(0));
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 7), WEEK)"), Scalar::Integer(1));
// The sign follows Date2 - Date1.
assert_eq!(value("DATEDIFF(TIME(11, 0, 1), TIME(10, 59, 59), HOUR)"), Scalar::Integer(-1));
}
#[test]
fn currency_and_large_numbers_concatenate_in_dax_form() {
assert_eq!(text("CURRENCY(10) & \"\""), "10");
assert_eq!(text("CURRENCY(10.5) & \"\""), "10.5");
assert_eq!(text("CONVERT(1, CURRENCY) & \"\""), "1");
// Very large whole numbers use Excel's exponent text with the explicit sign.
assert_eq!(text("1e15 & \"\""), "1E+15");
// DAX prints 15 significant digits, so a floating-point residue does not surface.
assert_eq!(text("0.1 + 0.2 & \"\""), "0.3");
}
+196
View File
@@ -0,0 +1,196 @@
//! Evaluator tests for math and trigonometry functions.
use gridcraft_dax::model::DataModel;
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
fn model() -> DataModel {
DataModel { tables: vec![], relationships: vec![], measures: vec![] }
}
fn eval_result(source: &str) -> Result<Scalar, String> {
let model = model();
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
let expr = parse_expression(source).map_err(|error| error.to_string())?;
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate(&bound).map_err(|error| error.to_string())
}
fn eval(source: &str) -> Scalar {
eval_result(source).expect("expression evaluates")
}
fn assert_close(actual: Scalar, expected: f64) {
match actual {
Scalar::Decimal(value) => {
let tolerance = 1e-9 * expected.abs().max(1.0);
assert!((value - expected).abs() <= tolerance, "expected {expected}, got {value}");
}
other => panic!("expected Decimal({expected}), got {other:?}"),
}
}
#[test]
fn inverse_trigonometry() {
assert_close(eval("ACOS(0.5)"), std::f64::consts::FRAC_PI_3);
assert_close(eval("ACOS(-1)"), std::f64::consts::PI);
assert!(eval_result("ACOS(2)").is_err());
assert!(eval_result("ACOS(-1.0001)").is_err());
assert_close(eval("ASIN(0.5)"), std::f64::consts::FRAC_PI_6);
assert_close(eval("ASIN(-1)"), -std::f64::consts::FRAC_PI_2);
assert!(eval_result("ASIN(1.5)").is_err());
assert_close(eval("ATAN(1)"), std::f64::consts::FRAC_PI_4);
assert_close(eval("ATAN(0)"), 0.0);
assert_close(eval("ACOT(1)"), std::f64::consts::FRAC_PI_4);
assert_close(eval("ACOT(-1)"), 3.0 * std::f64::consts::FRAC_PI_4);
assert_close(eval("ACOT(0)"), std::f64::consts::FRAC_PI_2);
}
#[test]
fn hyperbolic_and_inverse_hyperbolic() {
assert_close(eval("ACOSH(2)"), 1.316_957_896_924_816_6);
assert!(eval_result("ACOSH(0.5)").is_err());
assert_close(eval("ASINH(1)"), 0.881_373_587_019_543);
assert_close(eval("ATANH(0.5)"), 0.549_306_144_334_054_9);
assert!(eval_result("ATANH(1)").is_err());
assert!(eval_result("ATANH(-1)").is_err());
assert_close(eval("ACOTH(2)"), 0.549_306_144_334_054_9);
assert_close(eval("ACOTH(-2)"), -0.549_306_144_334_054_9);
assert!(eval_result("ACOTH(1)").is_err());
assert!(eval_result("ACOTH(-0.5)").is_err());
assert_close(eval("COSH(1)"), 1.543_080_634_815_243_7);
assert_close(eval("SINH(1)"), 1.175_201_193_643_801_4);
assert_close(eval("TANH(1)"), 0.761_594_155_955_764_9);
assert!(eval_result("SINH(1000)").is_err(), "overflow must be an error, not infinity");
}
#[test]
fn cotangent_family() {
assert_close(eval("COT(PI() / 4)"), 1.0);
assert_close(eval("COTH(1)"), 1.313_035_285_499_331_2);
assert!(eval_result("COT(0)").is_err());
assert!(eval_result("COTH(0)").is_err());
}
#[test]
fn even_and_odd_round_away_from_zero() {
assert_eq!(eval("EVEN(3.2)"), Scalar::Integer(4));
assert_eq!(eval("EVEN(-3.2)"), Scalar::Integer(-4));
assert_eq!(eval("EVEN(2)"), Scalar::Integer(2));
assert_eq!(eval("EVEN(-2)"), Scalar::Integer(-2));
assert_eq!(eval("EVEN(0)"), Scalar::Integer(0));
assert_eq!(eval("ODD(2.1)"), Scalar::Integer(3));
assert_eq!(eval("ODD(-2.1)"), Scalar::Integer(-3));
assert_eq!(eval("ODD(2)"), Scalar::Integer(3));
assert_eq!(eval("ODD(0)"), Scalar::Integer(1));
assert_eq!(eval("ODD(-2)"), Scalar::Integer(-3));
}
#[test]
fn mround_sign_and_multiples() {
assert_close(eval("MROUND(7.3, 0.5)"), 7.5);
assert_close(eval("MROUND(10, 3)"), 9.0);
assert_close(eval("MROUND(-7.3, -0.5)"), -7.5);
// dax.guide documents the binary floating-point midpoints 6.0 and 7.1.
assert_close(eval("MROUND(6.05, 0.1)"), 6.0);
assert_close(eval("MROUND(7.05, 0.1)"), 7.1);
// A digit count whose scale factor would overflow leaves the value unchanged.
assert_close(eval("ROUND(1.5, 400)"), 1.5);
assert_close(eval("MROUND(10, 0)"), 0.0);
assert!(eval_result("MROUND(7, -2)").is_err());
assert!(eval_result("MROUND(-7, 2)").is_err());
}
#[test]
fn quotient_truncates_toward_zero() {
assert_eq!(eval("QUOTIENT(7, 2)"), Scalar::Integer(3));
assert_eq!(eval("QUOTIENT(-7, 2)"), Scalar::Integer(-3));
assert_eq!(eval("QUOTIENT(7, -2)"), Scalar::Integer(-3));
assert_eq!(eval("QUOTIENT(0, 2)"), Scalar::Integer(0));
assert!(eval_result("QUOTIENT(7, 0)").is_err());
}
#[test]
fn sqrtpi_domain() {
assert_close(eval("SQRTPI(2)"), 2.506_628_274_631_000_2);
assert_close(eval("SQRTPI(0)"), 0.0);
assert!(eval_result("SQRTPI(-1)").is_err());
}
#[test]
fn currency_rounds_to_four_decimals() {
assert_eq!(eval("CURRENCY(10.5)"), Scalar::Currency(105_000));
assert_eq!(eval("CURRENCY(3.66666)"), Scalar::Currency(36_667));
assert_eq!(eval("CURRENCY(-3.66666)"), Scalar::Currency(-36_667));
assert_eq!(eval("CURRENCY(3.0123456789)"), Scalar::Currency(30_123));
assert_eq!(eval("CURRENCY(\"3.66666\")"), Scalar::Currency(36_667));
assert_eq!(eval("CURRENCY(TRUE)"), Scalar::Currency(10_000));
assert_eq!(eval("CURRENCY(FALSE)"), Scalar::Currency(0));
assert!(eval_result("CURRENCY(\"not a number\")").is_err());
}
#[test]
fn random_functions_stay_in_range() {
for _ in 0..64 {
match eval("RAND()") {
Scalar::Decimal(value) => assert!((0.0..1.0).contains(&value), "RAND out of range: {value}"),
other => panic!("RAND returned {other:?}"),
}
match eval("RANDBETWEEN(1, 10)") {
Scalar::Integer(value) => assert!((1..=10).contains(&value), "RANDBETWEEN out of range: {value}"),
other => panic!("RANDBETWEEN returned {other:?}"),
}
}
assert_eq!(eval("RANDBETWEEN(5, 5)"), Scalar::Integer(5));
assert_eq!(eval("RANDBETWEEN(-3, -3)"), Scalar::Integer(-3));
assert!(eval_result("RANDBETWEEN(10, 1)").is_err());
}
#[test]
fn convert_data_types() {
assert_eq!(eval("CONVERT(32.34, INTEGER)"), Scalar::Integer(32));
assert_eq!(eval("CONVERT(-32.34, INT64)"), Scalar::Integer(-32));
assert_eq!(eval("CONVERT(\"123\", INTEGER)"), Scalar::Integer(123));
assert_eq!(eval("CONVERT(1, DOUBLE)"), Scalar::Decimal(1.0));
assert_eq!(eval("CONVERT(3.66666, CURRENCY)"), Scalar::Currency(36_667));
assert_eq!(eval("CONVERT(3.66666, DECIMAL)"), Scalar::Currency(36_667));
assert_eq!(eval("CONVERT(12345, DATETIME)"), Scalar::DateTime(12_345.0));
assert_eq!(eval("CONVERT(\"1966-12-25\", DATETIME)"), Scalar::DateTime(24_466.0));
assert_eq!(eval("CONVERT(TRUE, STRING)"), Scalar::String("TRUE".into()));
assert_eq!(eval("CONVERT(\"TRUE\", BOOLEAN)"), Scalar::Boolean(true));
assert_eq!(eval("CONVERT(0, LOGICAL)"), Scalar::Boolean(false));
assert!(eval_result("CONVERT(\"abc\", INTEGER)").is_err());
assert!(eval_result("CONVERT(1, NONSENSE)").is_err());
}
#[test]
fn ceiling_floor_and_trunc_use_their_second_argument() {
// The catalog's documented semantics: CEILING/FLOOR take a required Significance, TRUNC an
// optional NumberOfDigits.
assert_close(eval("CEILING(4.42, 0.05)"), 4.45);
assert_close(eval("CEILING(10.2, 1)"), 11.0);
assert_close(eval("CEILING(10.7, 0.5)"), 11.0);
// A negative number with a negative significance rounds away from zero.
assert_close(eval("CEILING(-2.5, -2)"), -4.0);
// ISO.CEILING takes the significance's magnitude and always rounds up.
assert_close(eval("ISO.CEILING(-2.5, 2)"), -2.0);
assert!(eval_result("CEILING(2.5, -2)").is_err());
assert_close(eval("FLOOR(27, 5)"), 25.0);
assert_close(eval("FLOOR(2.7, 1)"), 2.0);
assert_close(eval("FLOOR(-2.7, -1)"), -2.0);
assert!(eval_result("FLOOR(-2.7, 1)").is_err());
assert!(eval_result("FLOOR(1, 0)").is_err());
assert_close(eval("TRUNC(1.239, 2)"), 1.23);
assert_close(eval("TRUNC(2.71828)"), 2.0);
assert_close(eval("TRUNC(-2.71828, 2)"), -2.71);
assert_close(eval("TRUNC(1234.5, -2)"), 1200.0);
}
+632
View File
@@ -0,0 +1,632 @@
//! Time-intelligence range functions over an in-memory model.
//!
//! The fixture date table runs from 2022-01-01 to 2025-12-31 so that previous/next year windows
//! always have a full calendar to draw from. `Date` is table 0 and `Sales` is table 1; the
//! `Sales[Date]` -> `Date[Date]` relationship is the only cross-filtering path.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::value::{Scalar, TableValue};
use gridcraft_dax::{Binder, BoundExpr, Evaluator, FilterContext, Literal, ScalarKey, parse_expression};
const DATE_TABLE: usize = 0;
const DATE_COLUMN: usize = 0;
const YEAR_COLUMN: usize = 1;
const SALES_TABLE: usize = 1;
const AMOUNT_COLUMN: usize = 1;
/// Excel/OLE date serial, computed with `chrono` independently of the evaluator.
fn serial(year: i64, month: i64, day: i64) -> f64 {
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
(date - epoch).num_days() as f64
}
fn date_rows() -> Vec<Vec<Scalar>> {
use chrono::Datelike;
let start = chrono::NaiveDate::from_ymd_opt(2022, 1, 1).expect("the fixture start is a valid date");
let end = chrono::NaiveDate::from_ymd_opt(2025, 12, 31).expect("the fixture end is a valid date");
start
.iter_days()
.take_while(|date| *date <= end)
.map(|date| {
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
vec![
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
Scalar::Integer(year),
Scalar::Integer((month - 1) / 3 + 1),
Scalar::Integer(month),
]
})
.collect()
}
/// (year, month, day, amount) for every sales row.
const SALES: &[(i64, i64, i64, f64)] = &[
(2023, 1, 10, 10.0),
(2023, 3, 5, 20.0),
(2023, 6, 15, 30.0),
(2023, 9, 20, 40.0),
(2023, 12, 31, 50.0),
(2024, 1, 5, 100.0),
(2024, 1, 31, 200.0),
(2024, 2, 29, 300.0),
(2024, 3, 15, 400.0),
(2024, 4, 1, 500.0),
(2024, 6, 30, 600.0),
(2024, 9, 30, 700.0),
(2024, 11, 11, 800.0),
(2024, 12, 25, 900.0),
(2024, 12, 31, 1000.0),
];
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Date".into(),
columns: vec![
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
],
rows: date_rows(),
},
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: SALES
.iter()
.map(|(year, month, day, amount)| vec![Scalar::DateTime(serial(*year, *month, *day)), Scalar::Decimal(*amount)])
.collect(),
},
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "Date".into(),
to_table: "Date".into(),
to_column: "Date".into(),
bidirectional: false,
inactive: false,
}],
measures: vec![Measure {
name: "Sales Amount".into(),
formula: "SUM(Sales[Amount])".into(),
table: Some("Sales".into()),
format: None,
expr: None,
}],
};
model.parse_formulas().expect("model parses");
model
}
/// A three-day date table whose last row's date cell is BLANK: the axis must drop that row instead
/// of reading BLANK as serial 0 (1899-12-30).
fn model_with_blank_date() -> DataModel {
DataModel {
tables: vec![ModelTable {
name: "Day".into(),
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
rows: vec![
vec![Scalar::DateTime(serial(2024, 1, 1))],
vec![Scalar::DateTime(serial(2024, 1, 2))],
vec![Scalar::DateTime(serial(2024, 1, 3))],
vec![Scalar::Blank],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
}
}
fn evaluate(source: &str, filters: FilterContext) -> Result<Scalar, String> {
evaluate_in(&model(), source, filters)
}
fn evaluate_in(model: &DataModel, source: &str, filters: FilterContext) -> Result<Scalar, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
let expr = parse_expression(source).map_err(|error| error.to_string())?;
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate_with(&bound, filters).map_err(|error| error.to_string())
}
fn eval_with(source: &str, filters: FilterContext) -> Scalar {
evaluate(source, filters).expect("expression evaluates")
}
fn eval_error(source: &str, filters: FilterContext) -> String {
evaluate(source, filters).expect_err("expression must fail")
}
fn evaluate_table(source: &str) -> Result<TableValue, String> {
evaluate_table_in(&model(), source)
}
fn evaluate_table_in(model: &DataModel, source: &str) -> Result<TableValue, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
let expr = parse_expression(source).map_err(|error| error.to_string())?;
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
}
fn table(source: &str) -> TableValue {
evaluate_table(source).expect("table evaluates")
}
/// Filter context selecting the date column between two inclusive calendar days.
fn dates(from: (i64, i64, i64), to: (i64, i64, i64)) -> FilterContext {
let mut filters = FilterContext::default();
let mut keys = Vec::new();
let start = serial(from.0, from.1, from.2) as i64;
let end = serial(to.0, to.1, to.2) as i64;
for day in start..=end {
keys.push(ScalarKey::from(&Scalar::DateTime(day as f64)));
}
filters.set(DATE_TABLE, DATE_COLUMN, keys);
filters
}
fn year(year: i64) -> FilterContext {
let mut filters = FilterContext::default();
filters.set(DATE_TABLE, YEAR_COLUMN, [ScalarKey::from(&Scalar::Integer(year))]);
filters
}
/// Number of rows of a table expression evaluated under a filter context.
fn row_count(source: &str, filters: FilterContext) -> i64 {
let count = eval_with(&format!("COUNTROWS({source})"), filters);
match count {
Scalar::Blank => 0,
other => other.to_number().expect("COUNTROWS is numeric") as i64,
}
}
/// (first, last) date of a table expression evaluated under a filter context.
fn bounds(source: &str, filters: FilterContext) -> (f64, f64) {
let first = eval_with(&format!("MINX({source}, 'Date'[Date])"), filters.clone());
let last = eval_with(&format!("MAXX({source}, 'Date'[Date])"), filters);
(first.to_number().expect("first date"), last.to_number().expect("last date"))
}
#[test]
fn dateadd_shifts_the_visible_period() {
let march = dates((2024, 3, 1), (2024, 3, 31));
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), 29);
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
// A partial period keeps its day span.
assert_eq!(bounds("DATEADD('Date'[Date], 10, \"DAY\")", dates((2024, 3, 25), (2024, 3, 31))), (serial(2024, 4, 4), serial(2024, 4, 10)));
// A selection ending on the last day of its period extends to the whole target period.
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"QUARTER\")", dates((2024, 4, 1), (2024, 6, 30))), 91);
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", dates((2024, 2, 25), (2024, 2, 29))), (serial(2024, 3, 25), serial(2024, 3, 31)));
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2024, 3, 1), (2024, 3, 31))), 31);
let error = eval_error("DATEADD('Date'[Date], 1, \"DECADE\")", FilterContext::default());
assert!(error.contains("interval"), "{error}");
let error = eval_error("DATEADD(Sales[Amount], 1, \"DAY\")", FilterContext::default());
assert!(error.contains("DateTime"), "{error}");
}
#[test]
fn dateadd_rejects_a_non_contiguous_selection() {
// A complete date column filtered to May 1 and May 3 has a gap at May 2. Shifting the window
// would sweep in May 3's source day (and any blocked day inside the range), which Microsoft's
// date-column DATEADD contract forbids: the visible dates must be contiguous.
let mut filters = FilterContext::default();
filters.set(
DATE_TABLE,
DATE_COLUMN,
[ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 1))), ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 3)))],
);
let error = eval_error("DATEADD('Date'[Date], 1, \"DAY\")", filters.clone());
assert!(error.contains("contiguous"), "{error}");
assert!(error.contains("5/1/2024") && error.contains("5/3/2024"), "{error}");
// The contract covers every interval, not just days.
for interval in ["MONTH", "QUARTER", "YEAR"] {
let source = format!("DATEADD('Date'[Date], 1, \"{interval}\")");
let error = eval_error(&source, filters.clone());
assert!(error.contains("contiguous"), "{error}");
}
// A contiguous selection still shifts: May 1-2 to May 2-3, and a single day to its neighbour.
let contiguous = dates((2024, 5, 1), (2024, 5, 2));
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", contiguous.clone()), (serial(2024, 5, 2), serial(2024, 5, 3)));
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"DAY\")", contiguous), 2);
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", dates((2024, 5, 1), (2024, 5, 1))), (serial(2024, 5, 2), serial(2024, 5, 2)));
}
#[test]
fn blank_date_cells_are_not_axis_dates() {
let model = model_with_blank_date();
// BLANK is not serial 0, so it must not become the first visible date (1899-12-30) or an axis
// row that the range functions can select.
assert_eq!(evaluate_in(&model, "FIRSTDATE('Day'[Date])", FilterContext::default()).expect("first date"), Scalar::DateTime(serial(2024, 1, 1)));
assert_eq!(evaluate_in(&model, "LASTDATE('Day'[Date])", FilterContext::default()).expect("last date"), Scalar::DateTime(serial(2024, 1, 3)));
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(1899,12,30), DATE(1899,12,30))").expect("epoch day").rows.len(), 0);
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(2024,1,1), DATE(2024,1,3))").expect("window").rows.len(), 3);
}
#[test]
fn datesbetween_is_inclusive_and_accepts_blanks() {
let between = table("DATESBETWEEN('Date'[Date], DATE(2024, 1, 15), DATE(2024, 2, 10))");
assert_eq!(between.rows.len(), 27);
assert_eq!(between.columns.len(), 1);
assert_eq!(between.columns[0].name, "Date");
assert_eq!(between.lineage, Some(DATE_TABLE));
assert_eq!(between.rows[0][0], Scalar::DateTime(serial(2024, 1, 15)));
assert_eq!(between.rows[26][0], Scalar::DateTime(serial(2024, 2, 10)));
// BLANK boundaries fall back to the visible range.
assert_eq!(row_count("DATESBETWEEN('Date'[Date], BLANK(), DATE(2024, 1, 5))", FilterContext::default()), 735);
assert_eq!(row_count("DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), BLANK())", FilterContext::default()), 731);
assert_eq!(table("DATESBETWEEN('Date'[Date], DATE(2024, 2, 1), DATE(2024, 1, 1))").rows.len(), 0);
}
#[test]
fn datesinperiod_moves_backwards_from_the_start_date() {
let backwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -1, \"MONTH\")");
assert_eq!(backwards.rows.len(), 29);
assert_eq!(backwards.rows[0][0], Scalar::DateTime(serial(2024, 2, 16)));
assert_eq!(backwards.rows[28][0], Scalar::DateTime(serial(2024, 3, 15)));
let forwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 3, \"DAY\")");
assert_eq!(forwards.rows.len(), 3);
assert_eq!(forwards.rows[2][0], Scalar::DateTime(serial(2024, 3, 17)));
assert_eq!(table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 0, \"DAY\")").rows.len(), 0);
assert_eq!(
bounds("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -2, \"WEEK\")", FilterContext::default()),
(serial(2024, 3, 2), serial(2024, 3, 15))
);
}
#[test]
fn to_date_windows() {
assert_eq!(bounds("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), (serial(2024, 3, 1), serial(2024, 3, 20)));
assert_eq!(row_count("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), 20);
assert_eq!(row_count("DATESQTD('Date'[Date])", dates((2024, 5, 1), (2024, 5, 10))), 40);
assert_eq!(row_count("DATESWTD('Date')", dates((2024, 3, 13), (2024, 3, 15))), 6);
assert_eq!(row_count("DATESYTD('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), 75);
// A fiscal year ending June 30 starts on July 1.
assert_eq!(row_count("DATESYTD('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), 46);
}
#[test]
fn period_boundaries() {
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 5)));
assert_eq!(eval_with("LASTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 20)));
let first = table("FIRSTDATE('Date'[Date])");
assert_eq!(first.rows.len(), 1);
assert_eq!(first.lineage, Some(DATE_TABLE));
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 1)));
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", dates((2024, 2, 1), (2024, 2, 10))), Scalar::DateTime(serial(2024, 2, 29)));
assert_eq!(eval_with("STARTOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 4, 1)));
assert_eq!(eval_with("ENDOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 6, 30)));
assert_eq!(eval_with("STARTOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 10)));
assert_eq!(eval_with("ENDOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 16)));
assert_eq!(eval_with("STARTOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 1, 1)));
assert_eq!(eval_with("ENDOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 12, 31)));
assert_eq!(eval_with("STARTOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2023, 7, 1)));
assert_eq!(eval_with("ENDOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), Scalar::DateTime(serial(2025, 6, 30)));
}
#[test]
fn adjacent_periods() {
assert_eq!(eval_with("NEXTDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 16)));
assert_eq!(eval_with("PREVIOUSDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 14)));
assert_eq!(bounds("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 4, 1), serial(2024, 4, 30)));
assert_eq!(bounds("PREVIOUSMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 2, 1), serial(2024, 2, 29)));
assert_eq!(row_count("NEXTQUARTER('Date'[Date])", dates((2024, 2, 1), (2024, 2, 28))), 91);
assert_eq!(row_count("PREVIOUSQUARTER('Date'[Date])", dates((2024, 5, 1), (2024, 5, 31))), 91);
assert_eq!(bounds("NEXTWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 17), serial(2024, 3, 23)));
assert_eq!(bounds("PREVIOUSWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 3), serial(2024, 3, 9)));
assert_eq!(bounds("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2025, 1, 1), serial(2025, 12, 31)));
assert_eq!(row_count("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 365);
assert_eq!(bounds("PREVIOUSYEAR('Date'[Date])", dates((2024, 1, 10), (2024, 1, 20))), (serial(2023, 1, 1), serial(2023, 12, 31)));
// A partial period is expanded to the full parallel period.
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], -1, \"MONTH\")", dates((2024, 3, 15), (2024, 3, 20))), 29);
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], 0, \"YEAR\")", dates((2024, 3, 15), (2024, 3, 20))), 366);
assert_eq!(row_count("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 31);
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2023, 3, 1), serial(2023, 3, 31)));
}
#[test]
fn nonblank_scan_uses_the_value_expression() {
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 1, 10)));
assert_eq!(eval_with("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 12, 31)));
assert_eq!(row_count("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), 1);
// An aggregate expression works too: it is evaluated in the date row's context.
assert_eq!(
eval_with("LASTNONBLANK('Date'[Date], SUM(Sales[Amount]))", dates((2024, 1, 1), (2024, 6, 30))),
Scalar::DateTime(serial(2024, 6, 30))
);
// No sales at all in 2025: nothing is non-blank.
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), Scalar::Blank);
assert_eq!(row_count("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), 0);
}
#[test]
fn range_tables_drive_calculate() {
let march = dates((2024, 3, 1), (2024, 3, 31));
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), DATESMTD('Date'[Date]))", march.clone()), Scalar::Decimal(400.0));
assert_eq!(eval_with("CALCULATE([Sales Amount], SAMEPERIODLASTYEAR('Date'[Date]))", march), Scalar::Decimal(20.0));
assert_eq!(eval_with("CALCULATE([Sales Amount], PREVIOUSYEAR('Date'[Date]))", dates((2024, 1, 10), (2024, 1, 20))), Scalar::Decimal(150.0));
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), ENDOFMONTH('Date'[Date]))", dates((2024, 2, 1), (2024, 2, 10))), Scalar::Decimal(300.0));
assert_eq!(eval_with("CALCULATE(COUNTROWS('Date'), FIRSTDATE('Date'[Date]))", dates((2024, 3, 1), (2024, 3, 31))), Scalar::Integer(1));
// Rolling twelve months ending December 31, 2024.
assert_eq!(
eval_with("CALCULATE(SUM(Sales[Amount]), DATESINPERIOD('Date'[Date], DATE(2024, 12, 31), -12, \"MONTH\"))", FilterContext::default()),
Scalar::Decimal(5500.0)
);
assert_eq!(
eval_with("CALCULATE(SUM(Sales[Amount]), DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), DATE(2024, 3, 31)))", FilterContext::default()),
Scalar::Decimal(1000.0)
);
}
#[test]
fn multi_row_results_are_not_scalars() {
let error = eval_error("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
assert!(error.contains("rows"), "{error}");
let error = eval_error("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
assert!(error.contains("rows"), "{error}");
}
#[test]
fn single_date_results_are_scalars() {
let filters = dates((2024, 3, 15), (2024, 3, 15));
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 1)));
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 31)));
assert_eq!(eval_with("NEXTDAY('Date'[Date])", filters), Scalar::DateTime(serial(2024, 3, 16)));
}
#[test]
fn empty_filter_context_yields_empty_windows() {
// An empty date-column filter leaves nothing visible.
let mut filters = FilterContext::default();
filters.set(DATE_TABLE, DATE_COLUMN, Vec::<ScalarKey>::new());
assert_eq!(row_count("DATESMTD('Date'[Date])", filters.clone()), 0);
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::Blank);
assert_eq!(eval_with("LASTDATE('Date'[Date])", filters), Scalar::Blank);
}
#[test]
fn fact_filters_do_not_narrow_the_date_axis() {
let mut filters = FilterContext::default();
filters.set(SALES_TABLE, AMOUNT_COLUMN, [ScalarKey::from(&Scalar::Decimal(400.0))]);
// Only one sale matches, but the date table itself is unfiltered.
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2022, 1, 1)));
assert_eq!(row_count("DATESMTD('Date'[Date])", filters), 31);
}
#[test]
fn interval_keywords_reach_the_evaluator_as_keywords() {
// The binder turns a bare interval keyword (DATEADD(..., MONTH)) into `BoundExpr::Keyword`;
// build that shape directly so the evaluator path is covered independently of the binder.
let model = model();
let evaluator = Evaluator::new(&model).expect("evaluator");
let dateadd = BoundExpr::Call {
spec: gridcraft_dax::lookup("DATEADD").expect("DATEADD is catalogued"),
args: vec![
BoundExpr::Column { table: DATE_TABLE, column: DATE_COLUMN },
BoundExpr::Literal(Literal::Integer(-1)),
BoundExpr::Keyword("MONTH".into()),
],
};
let countrows = BoundExpr::Call { spec: gridcraft_dax::lookup("COUNTROWS").expect("COUNTROWS is catalogued"), args: vec![dateadd] };
let count = evaluator.evaluate_with(&countrows, dates((2024, 3, 1), (2024, 3, 31))).expect("count");
assert_eq!(count, Scalar::Integer(29));
}
#[test]
fn week_functions_accept_a_table_reference() {
let filters = dates((2024, 3, 13), (2024, 3, 13));
assert_eq!(row_count("DATESWTD('Date')", filters.clone()), 4);
assert_eq!(eval_with("STARTOFWEEK('Date')", filters), Scalar::DateTime(serial(2024, 3, 10)));
let error = eval_error("DATESWTD('Date'[Date])", FilterContext::default());
assert!(error.contains("table"), "{error}");
}
#[test]
fn dateadd_and_sameperiodlastyear_keep_the_leap_day_of_a_full_month() {
// A full February shifted back a year reaches 29 February 2024, not 28.
let february = dates((2025, 2, 1), (2025, 2, 28));
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", february.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", february), (serial(2024, 2, 1), serial(2024, 2, 29)));
// A selection ending mid-month keeps its day span.
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2025, 2, 1), (2025, 2, 15))), (serial(2024, 2, 1), serial(2024, 2, 15)));
}
#[test]
fn dateadd_does_not_extend_a_selection_ending_on_the_penultimate_day() {
// 29 April is its month's penultimate day, but the selection does not contain 30 April, so
// the shifted window keeps its day span instead of reaching 31 March.
let selection = dates((2024, 4, 1), (2024, 4, 29));
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", selection.clone()), (serial(2024, 3, 1), serial(2024, 3, 29)));
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", selection), 29);
}
#[test]
fn dateadd_does_not_extend_a_selection_ending_on_day_30_of_a_31_day_month() {
// 30 July is one day before its month end, but 31 July is not visible, so the shifted window
// stops on 30 August instead of extending to 31 August.
let selection = dates((2024, 7, 1), (2024, 7, 30));
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 8, 1), serial(2024, 8, 30)));
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 30);
}
#[test]
fn dateadd_does_not_expand_a_single_month_end_date_to_the_target_period() {
// Only 30 April 2024 is visible: the date shifts to 30 May and stays a single date instead of
// expanding to the end of May (or the whole target period).
let selection = dates((2024, 4, 30), (2024, 4, 30));
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 5, 30), serial(2024, 5, 30)));
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 1);
}
#[test]
fn same_day_timestamps_stay_in_the_date_axis() {
// Two timestamps sharing a day are distinct cells of the column, and the range tables key
// their filter on those exact values, so both rows have to survive the axis.
let model = DataModel {
tables: vec![ModelTable {
name: "Log".into(),
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
rows: vec![
vec![Scalar::DateTime(serial(2024, 1, 1))],
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
let table = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,2), DATE(2024,1,2))").expect("window");
assert_eq!(table.rows.len(), 2);
assert_eq!(table.rows[0][0], Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
assert_eq!(table.rows[1][0], Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0));
// The other days are untouched by the value-level deduplication.
let whole = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,1), DATE(2024,1,2))").expect("whole window");
assert_eq!(whole.rows.len(), 3);
}
#[test]
fn single_date_functions_pick_one_cell_of_a_day() {
// A day can hold several timestamps; `FIRSTDATE`/`LASTDATE` are scalar conveniences and must
// return one exact cell rather than every cell of the day.
let model = DataModel {
tables: vec![ModelTable {
name: "Log".into(),
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
rows: vec![
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
vec![Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
assert_eq!(
evaluate_in(&model, "LASTDATE('Log'[Stamp])", FilterContext::default()).expect("last date"),
Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)
);
// Filtered to the first day, which holds two timestamps: `FIRSTDATE` still returns one value.
let mut filters = FilterContext::default();
filters.set(
0,
0,
[Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0), Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]
.into_iter()
.map(|value| ScalarKey::from(&value)),
);
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters).expect("first date"), Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
}
#[test]
fn single_date_functions_stay_inside_the_visible_cells() {
// A filter that selects one timestamp of a two-timestamp day: `FIRSTDATE`/`LASTDATE` must pick
// from the selected cell, not from the other timestamp the same day holds.
let model = DataModel {
tables: vec![ModelTable {
name: "Log".into(),
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
rows: vec![vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
let early = Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0);
let late = Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0);
let mut filters = FilterContext::default();
filters.set(0, 0, [ScalarKey::from(&late)]);
// 14:00 is the only visible cell: the last date is it, even though 09:00 exists in the column.
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", filters.clone()).expect("last date"), late);
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters.clone()).expect("first date"), late);
let mut early_filters = FilterContext::default();
early_filters.set(0, 0, [ScalarKey::from(&early)]);
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", early_filters.clone()).expect("last date"), early);
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", early_filters).expect("first date"), early);
}
#[test]
fn nonblank_candidates_match_mixed_case_text_rows() {
// The candidate filter is written through `FilterContext::set`, which folds text the same way
// the filter's own comparison does: a candidate `"A"` has to select the `"A"` and `"a"` rows.
let mut model = DataModel {
tables: vec![ModelTable {
name: "T".into(),
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("a".into())], vec![Scalar::String("B".into())]],
}],
relationships: Vec::new(),
measures: vec![gridcraft_dax::model::Measure {
name: "Rows".into(),
formula: "COUNTROWS('T')".into(),
table: Some("T".into()),
format: None,
expr: None,
}],
};
model.parse_formulas().expect("model formulas parse");
// Only the folded candidate filter leaves rows for the expression; an unfolded key would match
// nothing and make every candidate blank.
assert_eq!(
evaluate_in(&model, "FIRSTNONBLANK('T'[Text], IF([Rows] = 0, BLANK(), 1))", FilterContext::default()).expect("first non blank"),
Scalar::String("A".into())
);
}
#[test]
fn period_ends_pick_the_latest_timestamp_of_a_day() {
// A day may hold several timestamps; the axis orders them by their full serial, so `ENDOFMONTH`
// returns the latest one even when the model stores it before or after its siblings.
let model = DataModel {
tables: vec![ModelTable {
name: "Log".into(),
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
rows: vec![vec![Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
let mut filters = FilterContext::default();
filters.set(
0,
0,
[Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0), Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]
.into_iter()
.map(|value| ScalarKey::from(&value)),
);
assert_eq!(
evaluate_in(&model, "ENDOFMONTH('Log'[Stamp])", filters.clone()).expect("end of month"),
Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)
);
assert_eq!(
evaluate_in(&model, "STARTOFMONTH('Log'[Stamp])", filters).expect("start of month"),
Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)
);
}
#[test]
fn an_impossible_year_end_date_is_rejected_by_the_range_functions() {
// The same validation the total functions use: `"2/30"` is not a date, while the documented
// `"6/30/2024"` and `"6/30"` forms are.
let model = model();
let count = |argument: &str| evaluate_in(&model, &format!("COUNTROWS(DATESYTD('Date'[Date], \"{argument}\"))"), FilterContext::default());
assert!(count("2/30").is_err());
// An empty component is not a date either.
assert!(count("6/-30").is_err());
assert!(count("6/").is_err());
assert!(count("6/30").is_ok());
assert!(count("6/30/2024").is_ok());
assert!(count("2/29").is_ok());
}
+564
View File
@@ -0,0 +1,564 @@
//! Integration tests for the time-intelligence totals and balance evaluator functions.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::value::{Scalar, ScalarKey};
use gridcraft_dax::{BoundExpr, Evaluator, FilterContext, Literal, lookup};
/// The calendar date of a whole-day Excel/OLE serial, via `chrono`.
fn date_of(value: f64) -> chrono::NaiveDate {
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
epoch + chrono::Duration::days(value.floor() as i64)
}
/// Excel/OLE date serial for a whole day, computed with `chrono`.
fn serial(year: i64, month: i64, day: i64) -> f64 {
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
(date - epoch).num_days() as f64
}
fn date(year: i64, month: i64, day: i64) -> Scalar {
Scalar::DateTime(serial(year, month, day))
}
/// The fixture shared with the worksheet/measure cases: Sales facts for 2023-2024 and a
/// contiguous Date table covering both years.
fn model() -> DataModel {
use chrono::Datelike;
let start = date_of(serial(2023, 1, 1));
let end = date_of(serial(2024, 12, 31));
let date_rows: Vec<Vec<Scalar>> = start
.iter_days()
.take_while(|date| *date <= end)
.map(|date| {
// Excel's weekday numbering is 1 = Sunday, matching the evaluator's WEEKDAY default.
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
vec![
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
Scalar::Integer(year),
Scalar::Integer((month - 1) / 3 + 1),
Scalar::Integer(month),
Scalar::Integer(i64::from(date.weekday().num_days_from_sunday()) + 1),
]
})
.collect();
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Integer(40), date(2024, 1, 3)],
vec![Scalar::String("East".into()), Scalar::Integer(100), date(2024, 1, 5)],
vec![Scalar::String("West".into()), Scalar::Integer(250), date(2024, 1, 12)],
vec![Scalar::String("North".into()), Scalar::Integer(75), date(2024, 2, 3)],
vec![Scalar::String("South".into()), Scalar::Integer(400), date(2024, 2, 20)],
vec![Scalar::String("East".into()), Scalar::Blank, date(2024, 3, 15)],
vec![Scalar::String("West".into()), Scalar::Integer(150), date(2024, 4, 1)],
vec![Scalar::String("North".into()), Scalar::Integer(300), date(2024, 6, 18)],
vec![Scalar::String("South".into()), Scalar::Integer(50), date(2024, 7, 7)],
vec![Scalar::String("East".into()), Scalar::Integer(220), date(2024, 9, 9)],
vec![Scalar::String("West".into()), Scalar::Integer(90), date(2024, 11, 11)],
vec![Scalar::String("North".into()), Scalar::Integer(180), date(2024, 12, 1)],
vec![Scalar::String("South".into()), Scalar::Integer(310), date(2024, 12, 25)],
vec![Scalar::String("East".into()), Scalar::Integer(60), date(2023, 3, 10)],
vec![Scalar::String("West".into()), Scalar::Integer(140), date(2023, 6, 15)],
vec![Scalar::String("North".into()), Scalar::Integer(200), date(2023, 9, 20)],
vec![Scalar::String("South".into()), Scalar::Integer(80), date(2023, 12, 5)],
],
},
ModelTable {
name: "Date".into(),
columns: vec![
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Weekday".into(), data_type: Some("Int64".into()) },
],
rows: date_rows,
},
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "Date".into(),
to_table: "Date".into(),
to_column: "Date".into(),
bidirectional: false,
inactive: false,
}],
measures: vec![
measure("Total Amount", "SUM(Sales[Amount])"),
measure("MTD", "TOTALMTD([Total Amount], 'Date'[Date])"),
measure("QTD", "TOTALQTD([Total Amount], 'Date'[Date])"),
measure("WTD", "TOTALWTD([Total Amount], Date)"),
measure("YTD", "TOTALYTD([Total Amount], 'Date'[Date])"),
measure("YTD June", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
measure("YTD All", "TOTALYTD([Total Amount], 'Date'[Date], ALL ())"),
measure("QTD Remove All", "TOTALQTD([Total Amount], 'Date'[Date], REMOVEFILTERS ())"),
measure("YTD Region All", "TOTALYTD([Total Amount], 'Date'[Date], ALL([Region]))"),
measure("YTD Over Ten", "TOTALYTD(SUM(Sales[Amount]), 'Date'[Date], Sales[Amount] > 100)"),
measure("YTD Unqualified", "TOTALYTD([Total Amount], 'Date'[Date], [Region] = \"East\")"),
measure("OB Month", "OPENINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
measure("CB Month", "CLOSINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
measure("OB Quarter", "OPENINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
measure("CB Quarter", "CLOSINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
measure("OB Week", "OPENINGBALANCEWEEK([Total Amount], Date)"),
measure("CB Week", "CLOSINGBALANCEWEEK([Total Amount], Date)"),
measure("OB Year", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
measure("CB Year", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
measure("OB Year June", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
measure("CB Year June", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
measure("First Non Blank", "FIRSTNONBLANKVALUE('Date'[Date], [Total Amount])"),
measure("Last Non Blank", "LASTNONBLANKVALUE('Date'[Date], [Total Amount])"),
measure("Bad Date Column", "TOTALMTD([Total Amount], Sales[Amount])"),
measure("Bad Filter", "TOTALMTD([Total Amount], 'Date'[Date], 1)"),
measure("Bad Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"not a date\")"),
measure("Impossible Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"2/30\")"),
],
};
model.parse_formulas().expect("model formulas parse");
model
}
fn measure(name: &str, formula: &str) -> Measure {
Measure { name: name.into(), formula: formula.into(), table: Some("Sales".into()), format: None, expr: None }
}
fn filters(model: &DataModel, pairs: &[(&str, &str, Scalar)]) -> FilterContext {
let mut context = FilterContext::default();
for (table, column, value) in pairs {
let table_index = model.table_index(table).expect("table exists");
let column_index = model.column_index(table_index, column).expect("column exists");
context.set(table_index, column_index, [ScalarKey::from(value)]);
}
context
}
fn date_filter(model: &DataModel, dates: &[Scalar]) -> FilterContext {
let table = model.table_index("Date").expect("Date table");
let column = model.column_index(table, "Date").expect("Date column");
let mut context = FilterContext::default();
context.set(table, column, dates.iter().map(ScalarKey::from));
context
}
fn eval_measure(model: &DataModel, name: &str, filters: FilterContext) -> Result<Scalar, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
evaluator.evaluate_measure(name, filters).map_err(|error| format!("{name}: {error}"))
}
fn assert_number(result: Result<Scalar, String>, expected: f64) {
match result {
Ok(value) => {
let actual = value.to_number().expect("numeric result");
assert!((actual - expected).abs() < 1e-9, "expected {expected}, got {actual} ({value:?})");
}
Err(error) => panic!("unexpected error: {error}"),
}
}
fn february_filter(model: &DataModel) -> FilterContext {
filters(model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))])
}
#[test]
fn period_to_date_totals() {
let model = model();
let february = february_filter(&model);
// February 2024: 2024-02-03 (75) + 2024-02-20 (400); January 2024: 40 + 100 + 250.
assert_number(eval_measure(&model, "MTD", february.clone()), 475.0);
assert_number(eval_measure(&model, "QTD", february.clone()), 865.0);
assert_number(eval_measure(&model, "YTD", february.clone()), 865.0);
// Fiscal year ending June 30: H2 2023 (200 + 80) plus the 2024 YTD window.
assert_number(eval_measure(&model, "YTD June", february), 1145.0);
let january = date_filter(&model, &[date(2024, 1, 5)]);
assert_number(eval_measure(&model, "MTD", january.clone()), 140.0);
assert_number(eval_measure(&model, "QTD", january.clone()), 140.0);
assert_number(eval_measure(&model, "YTD", january.clone()), 140.0);
// 2024-01-05 is a Friday: the DAX week starts on Sunday 2023-12-31.
assert_number(eval_measure(&model, "WTD", january), 140.0);
let second_friday = date_filter(&model, &[date(2024, 1, 12)]);
assert_number(eval_measure(&model, "WTD", second_friday), 250.0);
// The last visible date anchors the window: Feb 28 only, not the whole month.
let partial = date_filter(&model, &[date(2024, 1, 5), date(2024, 2, 28)]);
assert_number(eval_measure(&model, "MTD", partial.clone()), 475.0);
assert_number(eval_measure(&model, "QTD", partial.clone()), 865.0);
// No sale in the week of 2024-02-28 (Sunday 25th to Saturday 2nd), so the sum is blank.
assert_eq!(eval_measure(&model, "WTD", partial), Ok(Scalar::Blank));
}
#[test]
fn opening_and_closing_balances() {
// Boundary dates need facts: add one sale on every date the balance functions select.
let mut facts = model();
let boundaries = [
(2023, 6, 30, 900),
(2023, 12, 30, 450),
(2023, 12, 31, 500),
(2024, 1, 6, 550),
(2024, 1, 13, 650),
(2024, 1, 31, 600),
(2024, 2, 29, 700),
(2024, 3, 31, 800),
(2024, 6, 30, 950),
(2024, 12, 31, 1000),
];
let sales = &mut facts.tables[0].rows;
for (year, month, day, amount) in boundaries {
sales.push(vec![Scalar::String("Boundary".into()), Scalar::Integer(amount), date(year, month, day)]);
}
let february = february_filter(&facts);
// EXCEL: CLOSINGBALANCEMONTH = CALCULATE(expr, ENDOFMONTH(dates)), OPENING = previous day.
assert_number(eval_measure(&facts, "OB Month", february.clone()), 600.0);
assert_number(eval_measure(&facts, "CB Month", february.clone()), 700.0);
assert_number(eval_measure(&facts, "OB Quarter", february.clone()), 500.0);
assert_number(eval_measure(&facts, "CB Quarter", february.clone()), 800.0);
assert_number(eval_measure(&facts, "OB Year", february.clone()), 500.0);
assert_number(eval_measure(&facts, "CB Year", february.clone()), 1000.0);
// Fiscal year July 2023 - June 2024: opening is 2023-06-30, closing is 2024-06-30.
assert_number(eval_measure(&facts, "OB Year June", february.clone()), 900.0);
assert_number(eval_measure(&facts, "CB Year June", february), 950.0);
let january = date_filter(&facts, &[date(2024, 1, 5)]);
assert_number(eval_measure(&facts, "OB Month", january.clone()), 500.0);
assert_number(eval_measure(&facts, "CB Month", january.clone()), 600.0);
// The DAX week starts on Sunday 2023-12-31, so the opening date is 2023-12-30.
assert_number(eval_measure(&facts, "OB Week", january.clone()), 450.0);
assert_number(eval_measure(&facts, "CB Week", january), 550.0);
let second_week = date_filter(&facts, &[date(2024, 1, 12)]);
assert_number(eval_measure(&facts, "OB Week", second_week.clone()), 550.0);
assert_number(eval_measure(&facts, "CB Week", second_week), 650.0);
// March 31 carries a boundary fact, so the closing balance is that day's value.
let march = filters(&facts, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
assert_eq!(eval_measure(&facts, "CB Month", march), Ok(Scalar::Decimal(800.0)));
// Without a fact on the boundary date Excel returns BLANK, not a scan backwards.
let sparse = model();
let february = february_filter(&sparse);
assert_eq!(eval_measure(&sparse, "OB Month", february.clone()), Ok(Scalar::Blank));
assert_eq!(eval_measure(&sparse, "CB Month", february), Ok(Scalar::Blank));
}
#[test]
fn first_and_last_non_blank_values() {
let model = model();
let february = february_filter(&model);
assert_number(eval_measure(&model, "First Non Blank", february.clone()), 75.0);
assert_number(eval_measure(&model, "Last Non Blank", february.clone()), 400.0);
let january = date_filter(&model, &[date(2024, 1, 5)]);
assert_number(eval_measure(&model, "First Non Blank", january.clone()), 100.0);
assert_number(eval_measure(&model, "Last Non Blank", january), 100.0);
let march = filters(&model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
assert_eq!(eval_measure(&model, "First Non Blank", march.clone()), Ok(Scalar::Blank));
assert_eq!(eval_measure(&model, "Last Non Blank", march), Ok(Scalar::Blank));
}
#[test]
fn all_clears_the_outer_filter_context() {
let model = model();
// February 2024 restricted to the East region: the outer filter sits on the fact table, the
// date filters only anchor the window.
let east_february = filters(
&model,
&[("Sales", "Region", Scalar::String("East".into())), ("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))],
);
// Without a filter argument the region filter still applies: East only, January + February.
assert_number(eval_measure(&model, "YTD", east_february.clone()), 140.0);
assert_number(eval_measure(&model, "QTD", east_february.clone()), 140.0);
// `ALL ()` clears the whole filter context, so every region is visible again over the same
// year-to-date window (40 + 100 + 250 + 75 + 400 = 865).
assert_number(eval_measure(&model, "YTD All", east_february.clone()), 865.0);
// `REMOVEFILTERS ()` is the same modifier.
assert_number(eval_measure(&model, "QTD Remove All", east_february.clone()), 865.0);
// An unqualified column argument clears just that column: `[Region]` resolves to Sales[Region].
assert_number(eval_measure(&model, "YTD Region All", east_february), 865.0);
}
#[test]
fn empty_window_and_invalid_arguments() {
let model = model();
// A date filter outside the model's date range leaves nothing visible.
let outside = date_filter(&model, &[date(2030, 1, 1)]);
assert_eq!(eval_measure(&model, "MTD", outside.clone()), Ok(Scalar::Blank));
assert_eq!(eval_measure(&model, "CB Month", outside.clone()), Ok(Scalar::Blank));
assert_eq!(eval_measure(&model, "First Non Blank", outside), Ok(Scalar::Blank));
let error = eval_measure(&model, "Bad Date Column", FilterContext::default()).expect_err("amount is not a date");
assert!(error.contains("not a date column"), "{error}");
let error = eval_measure(&model, "Bad Filter", FilterContext::default()).expect_err("invalid filter");
assert!(error.contains("table expression"), "{error}");
let error = eval_measure(&model, "Bad Year End", FilterContext::default()).expect_err("invalid year end");
assert!(error.contains("YearEndDate"), "{error}");
// The range functions share the parser, so an impossible day is rejected here too.
let error = eval_measure(&model, "Impossible Year End", FilterContext::default()).expect_err("2/30 is not a date");
assert!(error.contains("YearEndDate"), "{error}");
let evaluator = Evaluator::new(&model).expect("evaluator");
let spec = lookup("TOTALMTD").expect("catalog entry");
let error = evaluator.evaluate(&BoundExpr::Call { spec, args: Vec::new() }).expect_err("arity");
assert!(error.message.contains("between 2 and 3"), "{}", error.message);
let spec = lookup("FIRSTNONBLANKVALUE").expect("catalog entry");
let measure_index = model.measure_index("Total Amount").expect("measure");
let expr = BoundExpr::Call { spec, args: vec![BoundExpr::Literal(Literal::Integer(1)), BoundExpr::Measure(measure_index)] };
let error = evaluator.evaluate(&expr).expect_err("non-column argument");
assert!(error.message.contains("column reference"), "{}", error.message);
}
#[test]
fn comparison_and_unqualified_column_filters_are_applied() {
// `TOTALYTD(expr, dates, filter)` is CALCULATE sugar: a comparison and an unqualified column
// are filter arguments too, not table expressions.
let model = model();
let february = date_filter(&model, &[Scalar::DateTime(serial(2024, 2, 1)), Scalar::DateTime(serial(2024, 2, 29))]);
let plain = eval_measure(&model, "YTD", february.clone()).expect("YTD");
let filtered = eval_measure(&model, "YTD Over Ten", february).expect("YTD Over Ten");
// Exact totals, so a filter argument the evaluator ignored could not pass: every 2024
// January-February amount is above 10 but only two are above 100.
assert_eq!(plain.to_number(), Some(865.0));
assert_eq!(filtered.to_number(), Some(650.0));
let east = eval_measure(&model, "YTD Unqualified", FilterContext::default()).expect("YTD Unqualified");
assert_eq!(east.to_number(), Some(360.0));
}
#[test]
fn related_dimension_filters_reach_the_visible_date_range() {
// Snowflaked calendar: `Date` is many-to-one against a `Year` dimension on its one side.
// Filtering `Year` propagates to `Date`, so the dates visible to the range functions narrow
// to the filtered year instead of spanning the whole model calendar.
let mut model = model();
model.tables.push(ModelTable {
name: "Year".into(),
columns: vec![ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) }],
rows: vec![vec![Scalar::Integer(2023)], vec![Scalar::Integer(2024)]],
});
model.relationships.push(Relationship {
from_table: "Date".into(),
from_column: "Year".into(),
to_table: "Year".into(),
to_column: "Year".into(),
bidirectional: false,
inactive: false,
});
model.measures.push(measure("Last Date", "LASTDATE('Date'[Date])"));
model.measures.push(measure("First Date", "FIRSTDATE('Date'[Date])"));
model.measures.push(measure("Dates YTD Rows", "COUNTROWS(DATESYTD('Date'[Date]))"));
model.parse_formulas().expect("model formulas parse");
let y2023 = filters(&model, &[("Year", "Year", Scalar::Integer(2023))]);
// The axis ends on the last date of the year the relationship selects, not on the model's
// overall last date (2024-12-31).
assert_eq!(eval_measure(&model, "Last Date", y2023.clone()), Ok(date(2023, 12, 31)));
assert_eq!(eval_measure(&model, "First Date", y2023.clone()), Ok(date(2023, 1, 1)));
// 2023 is not a leap year: 365 days in the year-to-date window, not the 366 of 2024.
assert_number(eval_measure(&model, "Dates YTD Rows", y2023.clone()), 365.0);
// The year-to-date total is 2023's own facts: 60 + 140 + 200 + 80.
assert_number(eval_measure(&model, "YTD", y2023.clone()), 480.0);
let y2024 = filters(&model, &[("Year", "Year", Scalar::Integer(2024))]);
assert_eq!(eval_measure(&model, "Last Date", y2024.clone()), Ok(date(2024, 12, 31)));
assert_number(eval_measure(&model, "Dates YTD Rows", y2024.clone()), 366.0);
// 2024's facts: 40 + 100 + 250 + 75 + 400 + 150 + 300 + 50 + 220 + 90 + 180 + 310.
assert_number(eval_measure(&model, "YTD", y2024), 2165.0);
}
/// Fixtures for the two fact-table cases: a model whose date column is a fact column, so there is
/// no date dimension whose filters the window may replace.
fn fact_date_model(mut measures: Vec<Measure>, rows: Vec<Vec<Scalar>>, amount_type: &str) -> DataModel {
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some(amount_type.into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows,
}],
relationships: Vec::new(),
measures: std::mem::take(&mut measures),
};
model.parse_formulas().expect("model formulas parse");
model
}
#[test]
fn fact_date_totals_keep_the_other_fact_filters() {
// The date column is a fact column, so the window replaces only that column's filter: the
// Region slice has to keep applying, as it would to `CALCULATE ( SUM (…), DATESYTD (…) )`.
let model = fact_date_model(
vec![measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"), measure("MTD Fact", "TOTALMTD(SUM(Sales[Amount]), Sales[Date])")],
vec![
vec![Scalar::String("East".into()), Scalar::Integer(10), date(2024, 1, 10)],
vec![Scalar::String("East".into()), Scalar::Integer(20), date(2024, 3, 10)],
vec![Scalar::String("West".into()), Scalar::Integer(100), date(2024, 1, 20)],
],
"Int64",
);
let east = filters(&model, &[("Sales", "Region", Scalar::String("East".into()))]);
// East's own year-to-date facts: 10 + 20. Dropping the Region filter would return 130.
assert_number(eval_measure(&model, "YTD Fact", east.clone()), 30.0);
assert_number(eval_measure(&model, "MTD Fact", east.clone()), 20.0);
// A filter on the fact date column itself is replaced by the window, not intersected with it:
// anchoring on 2024-03-10 makes the year-to-date window run from 2024-01-01, so both East rows
// count (30). Keeping and intersecting the filter would return only 2024-03-10's 20.
let east_march = filters(&model, &[("Sales", "Region", Scalar::String("East".into())), ("Sales", "Date", date(2024, 3, 10))]);
assert_number(eval_measure(&model, "YTD Fact", east_march), 30.0);
}
#[test]
fn fact_date_totals_match_cells_that_carry_a_time_of_day() {
// DateTime cells may store a time of day, and a day may hold more than one timestamp; every
// cell of the period still has to count, not just the first one found for its day.
let model = fact_date_model(
vec![
measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
measure("OB Month", "OPENINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"),
],
vec![
vec![Scalar::String("East".into()), Scalar::Integer(5), Scalar::DateTime(serial(2024, 1, 1))],
vec![Scalar::String("East".into()), Scalar::Integer(7), Scalar::DateTime(serial(2024, 2, 29) + 9.5 / 24.0)],
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
],
"Int64",
);
// March's closing balance covers both 2024-03-31 timestamps, not the earlier February date.
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
// March's opening balance is the day before its start: 2024-02-29 09:30.
assert_number(eval_measure(&model, "OB Month", FilterContext::default()), 7.0);
// The year-to-date window keeps every cell: 5 + 7 + 3 + 10, including both March 31 rows.
assert_number(eval_measure(&model, "YTD Fact", FilterContext::default()), 25.0);
}
#[test]
fn balance_filters_intersect_the_boundary_day() {
// The boundary day holds two timestamps; a filter argument that keeps only one of them has to
// intersect with the boundary keys, exactly like `TOTAL*`, instead of being dropped.
let mut model = fact_date_model(
vec![measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])")],
vec![
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
],
"Int64",
);
model.measures.push(measure("CB Month Filtered", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date], Sales[Date] > DATE(2024,3,31) + 10/24)"));
model.parse_formulas().expect("model formulas parse");
// Without a filter both same-day cells are the boundary.
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
// With a filter that keeps only the 14:00 cell the boundary is one cell: 10, not 13.
assert_number(eval_measure(&model, "CB Month Filtered", FilterContext::default()), 10.0);
}
#[test]
fn a_calendar_table_argument_uses_its_typed_date_column() {
// `TOTALWTD(…, Calendar)` must resolve the calendar's date column exactly like `DATESWTD`:
// the declared date type wins over an earlier untyped column.
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Calendar".into(),
columns: vec![
ModelColumn { name: "Label".into(), data_type: None },
ModelColumn { name: "Day".into(), data_type: Some("DateTime".into()) },
],
rows: vec![vec![Scalar::String("first".into()), date(2024, 1, 1)], vec![Scalar::String("second".into()), date(2024, 1, 2)]],
},
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
.into_iter()
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
.collect(),
},
],
relationships: Vec::new(),
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
};
model.parse_formulas().expect("model formulas parse");
// 2024-01-02 is a Tuesday, so the week starts on Sunday 2023-12-31: both calendar days are in
// the window and the sum is 30. Binding the untyped `Label` column would return BLANK.
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
}
#[test]
fn a_calendar_with_one_untyped_column_is_still_a_calendar() {
// A calendar whose only date column is untyped keeps working: the unambiguous untyped column
// is the fallback once no typed date column and no `Date` column exist.
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Calendar".into(),
columns: vec![ModelColumn { name: "Day".into(), data_type: None }],
rows: vec![vec![date(2024, 1, 1)], vec![date(2024, 1, 2)]],
},
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
.into_iter()
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
.collect(),
},
],
relationships: Vec::new(),
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
};
model.parse_formulas().expect("model formulas parse");
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
}
#[test]
fn a_calendar_date_column_declared_as_a_non_date_type_is_rejected() {
// An integer `Date` column (YYYYMMDD keys) is not a date axis: report the model, do not read
// its numbers as OLE serials.
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Calendar".into(),
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("Int64".into()) }],
rows: vec![vec![Scalar::Integer(20_240_101)]],
},
ModelTable {
name: "Sales".into(),
columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }],
rows: vec![vec![Scalar::Decimal(10.0)]],
},
],
relationships: Vec::new(),
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
};
model.parse_formulas().expect("model formulas parse");
let error = eval_measure(&model, "Week To Date", FilterContext::default()).expect_err("an Int64 Date column is not a date axis");
assert!(error.contains("has no date column"), "{error}");
}
+2
View File
@@ -210,6 +210,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"undone": label}))
@@ -232,6 +233,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"redone": label}))
+1 -1
View File
@@ -28,7 +28,7 @@ use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}
pub(crate) use scripts::has_scripts;
use scripts::{all_scripts, delete_script, new_script, record, run_script, stop_action, trust_scripts};
use window::{arrange_all, custom_views, hide_window, new_window, ruler, set_view, split, switch_windows, unhide_window, watch_window};
pub(crate) use window::{keep_view_modes, keep_watch_list, window_param};
pub(crate) use window::{keep_page_breaks, keep_view_modes, keep_watch_list, window_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
+12 -2
View File
@@ -72,9 +72,19 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
} else {
None
};
// Query field identity follows the surviving physical column, even if its header was renamed.
let query_field_id = c.checked_sub(old.start.col).and_then(|i| old_cols.get(i as usize)).and_then(|x| x.query_field_id);
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
Some(x) => TableColumn { name: name.clone(), query_field_id, ..x.clone() },
None => TableColumn {
name: name.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id,
xml: None,
},
});
}
let sheet = cx.sheet_mut(si)?;
+34 -1
View File
@@ -4,7 +4,8 @@ use super::{
};
/// 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.
/// neither records an undo step nor marks a clean workbook as changed. Page Break Preview also
/// turns on the sheet's page breaks, which Normal view then keeps showing (as in Excel).
pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
@@ -12,6 +13,9 @@ pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.view = mode;
if mode == SheetViewMode::PageBreakPreview {
sh.show_page_breaks = true;
}
}
if !dirty {
d.saved = d.wb.clone();
@@ -38,6 +42,35 @@ pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>
wb.names.extend(keep);
}
/// Show page breaks is a view setting: keep it on each surviving sheet across undo and redo.
/// Sheet identities persist through renames and moves; a restored sheet with no current identity
/// keeps its own snapshot value. A kept setting does not make a saved workbook dirty.
pub(crate) fn keep_page_breaks(d: &mut crate::DocState, from: &Workbook) {
let changed: Vec<_> =
d.wb.sheets
.iter()
.enumerate()
.filter_map(|(i, sh)| {
let on = from.sheets.iter().find(|f| f.uid.get() == sh.uid.get()).map_or(sh.show_page_breaks, |f| f.show_page_breaks);
(sh.show_page_breaks != on).then_some((i, on))
})
.collect();
if changed.is_empty() {
return;
}
let dirty = d.is_dirty();
let wb = std::sync::Arc::make_mut(&mut d.wb);
// Only the sheets that differ are copied (`sheet_mut` unshares the sheet).
for (i, on) in changed {
if let Some(sh) = wb.sheet_mut(i) {
sh.show_page_breaks = on;
}
}
if !dirty {
d.saved = d.wb.clone();
}
}
/// Normal, Page Layout and Page Break Preview belong to the window, not to the edits: Excel doesn't
/// undo a switch between them, and `set_view` is no undo step. So undo and redo keep each sheet's
/// current view when they swap in another snapshot of the workbook, and a view kept this way
+10 -1
View File
@@ -413,7 +413,15 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: headers
.iter()
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.map(|h| TableColumn {
name: h.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.collect(),
style: "TableStyleMedium2".into(),
banded_rows: true,
@@ -424,6 +432,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
let q = gridcraft_formula::quote_sheet(&sheet_name);
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Chart",
["Insert", "Charts"],
None,
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|pareto|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
+6 -1
View File
@@ -59,6 +59,7 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
("bubble", _) => ChartKind::Bubble,
("radar", _) => ChartKind::Radar,
("histogram", _) => ChartKind::Histogram,
("pareto", _) => ChartKind::Pareto,
("waterfall", _) => ChartKind::Waterfall,
("funnel", _) => ChartKind::Funnel,
("treemap", _) => ChartKind::Treemap,
@@ -285,7 +286,11 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
},
title,
series,
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
legend: match kind {
ChartKind::Pie | ChartKind::Doughnut => LegendPos::Right,
ChartKind::Pareto => LegendPos::None,
_ => LegendPos::Bottom,
},
data_labels: false,
data_table: None,
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
+10 -1
View File
@@ -112,7 +112,15 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: names
.into_iter()
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.map(|n| TableColumn {
name: n,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.collect(),
style,
banded_rows: true,
@@ -123,6 +131,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
cx.structural = true;
Ok(json!({"table": name, "range": r.a1()}))
+2 -2
View File
@@ -56,7 +56,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
#[cfg(test)]
use layout::bands;
pub(crate) use layout::split_bands;
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, page_break_bands, paper_size, print_range};
use layout::{seg_size, segments};
use objects::{PicCache, draw_objects};
#[cfg(test)]
@@ -96,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Page Setup…",
["Page Layout", "Page Setup"],
None,
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
has_doc,
page_setup
),
+19 -1
View File
@@ -353,7 +353,7 @@ pub(crate) fn page_sequence(rows: usize, cols: usize, order: PageOrder, cap: usi
}
/// Inclusive-start/end index spans of the pages along one axis.
pub(crate) type Bands = Vec<(u32, u32)>;
pub type Bands = Vec<(u32, u32)>;
/// 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
@@ -386,6 +386,24 @@ pub(crate) fn split_bands(sh: &Sheet, lay: &SheetLayout, cap: usize) -> (Bands,
(rows, cols)
}
/// Page bands for the grid's editing overlay, extending only the last printed bands to their
/// actual printable capacity. The original layout, print area, scale and page sequence stay intact.
pub fn page_break_bands(sh: &Sheet, lay: &SheetLayout) -> (Bands, Bands) {
let (Some(row), Some(col)) = (lay.row_bands.last(), lay.col_bands.last()) else { return (Vec::new(), Vec::new()) };
let mut tail = lay.clone();
tail.area = RangeRef::new(CellRef::new(row.0, col.0), CellRef::new(MAX_ROWS - 1, MAX_COLS - 1));
let (rows, cols) = split_bands(sh, &tail, 1);
let mut out_rows = lay.row_bands.clone();
let mut out_cols = lay.col_bands.clone();
if let (Some(last), Some(extended)) = (out_rows.last_mut(), rows.first()) {
*last = *extended;
}
if let (Some(last), Some(extended)) = (out_cols.last_mut(), cols.first()) {
*last = *extended;
}
(out_rows, out_cols)
}
/// Lays out every sheet a print command covers.
pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
let mut out = Vec::new();
+26
View File
@@ -22,6 +22,29 @@ fn arabic_face_available() -> bool {
!doc.missing_arabic_font()
}
#[test]
fn editing_page_boundaries_follow_paper_and_orientation_without_changing_print_range() {
let mut wb = Workbook::new();
wb.sheet_mut(0).unwrap().print.paper = "A4".into();
let overlay = |wb: &Workbook| {
let layout = layout_sheet(wb, 0, &PrintOptions::default(), None).unwrap();
let original = (layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone());
let (rows, cols) = page_break_bands(wb.sheet(0).unwrap(), &layout);
assert_eq!((layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone()), original);
assert_eq!(layout.row_bands.len(), 1);
assert_eq!(layout.col_bands.len(), 1);
(rows[0].1, cols[0].1)
};
let portrait = overlay(&wb);
assert!(portrait.0 > 0 && portrait.1 > 0, "an empty one-page sheet still shows its capacity");
wb.sheet_mut(0).unwrap().print.orientation = Orientation::Landscape;
let landscape = overlay(&wb);
assert!(landscape.1 > portrait.1 && landscape.0 < portrait.0);
wb.sheet_mut(0).unwrap().print.paper = "A3".into();
let larger = overlay(&wb);
assert!(larger.0 > landscape.0 && larger.1 > landscape.1);
}
#[test]
fn right_to_left_sheets_mirror_link_rectangles_and_targets() {
fn numbers_after(pdf: &[u8], key: &str, n: usize) -> Vec<f32> {
@@ -942,6 +965,9 @@ fn page_setup_edits_settings() {
fn japanese_paper_sizes_are_jis() {
for (name, w, h) in [
("A4", 595.28, 841.89), // unchanged
("A2", 1190.55, 1683.78),
("a1", 1683.78, 2383.94),
("A0", 2383.94, 3370.39),
("B4", 728.50, 1031.81),
("B5", 515.91, 728.50),
("B6", 362.83, 515.91),
+70 -6
View File
@@ -727,17 +727,80 @@ fn check_lines_protection(s: &Session, p: &Json, axis: Axis, at: u32, count: u32
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)) {
let lines = LockedLines::of(sh, axis, &locked);
if !(at..=end).all(|i| lines.unlocked(sh, i, &locked)) {
return Err(refuse());
}
Ok(())
}
/// Whether every cell of a row or column is unlocked, which Excel requires before it deletes the
/// line on a protected sheet ("You are trying to delete a row that contains a locked cell"),
/// however the Delete Rows or Delete Columns permission is set.
///
/// A cell the sheet does not store is judged by the style `Sheet::style_id` gives it: its row's
/// format, then its column's, then the default: the workbook's Normal style, locked unless the
/// file unlocked it (see `unlocked`). Reading a line with no format of
/// its own as the default refused every delete, even over a row the user had unlocked through
/// its columns; reading it as unlocked passed a blank row whose cells are all locked by default.
/// The cross lines' formats are summarised once here, since a delete can span a million rows.
struct LockedLines {
axis: Axis,
/// Cross lines (columns for a row, rows for a column) whose own format is locked.
locked_cross: Vec<u32>,
/// How many cross lines have no format of their own, and so no say over a cell they cross.
plain_count: u32,
}
impl LockedLines {
fn of(sh: &Sheet, axis: Axis, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> Self {
let (cross, cross_len) = if axis == Axis::Rows { (&sh.cols, MAX_COLS) } else { (&sh.rows, MAX_ROWS) };
let styled: Vec<_> = cross.iter().filter_map(|(k, x)| x.style.map(|st| (*k, st))).collect();
let locked_cross = styled.iter().filter(|(_, st)| locked(*st)).map(|(k, _)| *k).collect();
Self { axis, locked_cross, plain_count: cross_len - styled.len() as u32 }
}
fn unlocked(&self, sh: &Sheet, i: u32, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> bool {
let rows = self.axis == Axis::Rows;
let (line, cross_len) = if rows { (RangeRef::rows(i, i), MAX_COLS) } else { (RangeRef::cols(i, i), MAX_ROWS) };
let mut stored = std::collections::HashSet::new();
for (at, cell) in sh.cells.iter_range(line) {
if locked(cell.style) {
return false;
}
stored.insert(if rows { at.col } else { at.row });
}
if stored.len() as u32 == cross_len {
return true;
}
let (own_lines, cross) = if rows { (&sh.rows, &sh.cols) } else { (&sh.cols, &sh.rows) };
let own = own_lines.get(&i).and_then(|x| x.style);
// A row's own format is the first one its empty cells take, so it decides alone.
if rows && let Some(st) = own {
return !locked(st);
}
// Otherwise a cross line's locked format reaches every cell of this line it crosses
// (for a column, a row's format comes before the column's own).
if self.locked_cross.iter().any(|k| !stored.contains(k)) {
return false;
}
// The cells left are those under a cross line with no format. Deleting a column, they take
// the column's own format, which may unlock them all. Deleting a row, neither line has a
// format, so they take the default; when it is locked, each has to be a stored cell, and
// the stored ones were all checked above.
if !rows && own.is_some_and(|st| !locked(st)) {
return true;
}
// Neither line has a format, so the cells take the workbook's Normal style, which a file
// may have unlocked: then they all are.
if own.is_none() && !locked(gridcraft_model::StyleId::DEFAULT) {
return true;
}
let plain = stored.iter().filter(|k| !cross.get(k).is_some_and(|x| x.style.is_some())).count();
plain as u32 == self.plain_count
}
}
/// 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 {
@@ -895,6 +958,7 @@ fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, inse
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
t.columns.insert((idx + k).min(t.columns.len()), col);
+30 -1
View File
@@ -38,6 +38,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("view.gridlines", "Gridlines", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "gridlines")),
cmd!("view.headings", "Headings", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "headings")),
cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")),
cmd!(
noundo "view.showPageBreaks",
"Show Page Breaks",
[],
None,
"{sheet?, on?} → {on}: dashed page boundaries in Normal view (a display option, not saved with the file)",
has_doc,
show_page_breaks
),
cmd!("view.showOutlineSymbols", "Show Outline Symbols", [], Some("Ctrl+8"), "{on?}", has_doc, |s, p| sheet_flag(s, p, "outlineSymbols")),
cmd!("view.showObjects", "Show Objects", [], Some("Ctrl+6"), "{on?}", has_doc, show_objects),
cmd!(
@@ -84,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Size",
["Page Layout", "Page Setup"],
None,
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
"{paper: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
has_doc,
paper
),
@@ -225,6 +234,26 @@ fn workbook_view_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
})
}
/// Excel's Show page breaks: a display option of the sheet, so it neither records an undo step
/// nor marks a clean workbook as changed (like `set_view`).
fn show_page_breaks(s: &mut Session, p: &Json) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
let dirty = d.is_dirty();
let current = d.wb.sheet(si).is_some_and(|sh| sh.show_page_breaks);
let on = bool_param(p, "on").unwrap_or(!current);
if on != current {
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.show_page_breaks = on;
}
if !dirty {
d.saved = d.wb.clone();
}
}
Ok(json!({"on": on}))
}
/// Ctrl+6: hides every object, or shows them again. Placeholders (from a file) count as shown.
fn show_objects(s: &mut Session, p: &Json) -> Result<Json> {
use gridcraft_model::ShowObjects;
+1
View File
@@ -904,6 +904,7 @@ mod tests {
filter: Vec::new(),
table_type: None,
connection_id: None,
query_table: None,
});
let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)];
let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None };
+1
View File
@@ -695,6 +695,7 @@ fn grow_right(
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
});
cx.rebuild_deps = true;
+203
View File
@@ -3947,6 +3947,84 @@ fn show_outline_symbols_toggles() {
assert!(!on(&s));
}
/// Show page breaks (Excel: Options › Advanced, per worksheet): off on a new sheet, turned on by
/// Page Break Preview and kept in Normal view, switched without making the workbook dirty.
#[test]
fn page_break_preview_turns_on_show_page_breaks_for_its_sheet() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
let wb = s.doc().unwrap().wb.clone();
s.doc_mut().unwrap().saved = wb;
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|x| x.name == name).unwrap().show_page_breaks;
assert!(!on(&s, "Two"));
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
assert!(on(&s, "Two"), "Normal view keeps the page breaks Page Break Preview showed");
assert!(!on(&s, "Sheet1"), "only the previewed sheet");
assert_eq!(s.execute("view.showPageBreaks", json!({})).unwrap(), json!({"on": false}));
assert!(!on(&s, "Two"));
assert_eq!(s.execute("view.showPageBreaks", json!({"on": true})).unwrap(), json!({"on": true}));
assert!(on(&s, "Two"));
assert!(!s.doc().unwrap().is_dirty(), "a display option, not an edit");
}
/// Undo and redo swap in another snapshot of the workbook; the page breaks shown stay as they are
/// (a display option isn't undone), matched by sheet name.
#[test]
fn undo_and_redo_keep_show_page_breaks() {
let mut s = s();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
assert!(on(&s));
s.execute("edit.undo", json!({})).unwrap();
assert!(on(&s), "undoing the typing leaves the page breaks on");
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert!(!on(&s), "redo doesn't bring back the snapshot's page breaks either");
assert!(s.active().unwrap().wb.active().unwrap().cell(CellRef::new(0, 0)).is_some(), "the redo itself happened");
}
/// Undoing a rename brings back a sheet name the current workbook doesn't have: its page breaks
/// stay as the snapshot has them, not off.
#[test]
fn undoing_a_rename_keeps_show_page_breaks() {
let mut s = s();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
s.execute("sheet.rename", json!({"name": "Renamed"})).unwrap();
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
assert!(on(&s));
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_ne!(s.active().unwrap().wb.active().unwrap().name, "Renamed", "the rename was undone");
assert!(!on(&s), "the current setting survives the undone rename");
s.execute("edit.redo", json!({})).unwrap();
assert!(!on(&s), "the current setting survives the redone rename");
}
/// A grouped rename can reuse another sheet's name. View state follows identity, not that name.
#[test]
fn grouped_renames_keep_page_breaks_on_the_same_sheets() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.grouped("Rename sheets", |s| {
s.execute("sheet.rename", json!({"sheet": "Sheet1", "name": "Temp"}))?;
s.execute("sheet.rename", json!({"sheet": "Two", "name": "Sheet1"}))?;
Ok(())
})
.unwrap();
s.execute("view.showPageBreaks", json!({"sheet": "Temp", "on": true})).unwrap();
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|sh| sh.name == name).unwrap().show_page_breaks;
s.execute("edit.undo", json!({})).unwrap();
assert!(on(&s, "Sheet1"));
assert!(!on(&s, "Two"));
s.execute("edit.redo", json!({})).unwrap();
assert!(on(&s, "Temp"));
assert!(!on(&s, "Sheet1"));
}
fn reopen(s: &mut Session) {
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
let b64 = r["base64"].as_str().unwrap().to_string();
@@ -4042,6 +4120,7 @@ fn every_chart_kind_survives_xlsx() {
("combo", ChartKind::Combo),
("stock", ChartKind::Stock),
("histogram", ChartKind::Histogram),
("pareto", ChartKind::Pareto),
("boxWhisker", ChartKind::BoxWhisker),
("waterfall", ChartKind::Waterfall),
("funnel", ChartKind::Funnel),
@@ -4073,6 +4152,16 @@ fn every_chart_kind_survives_xlsx() {
}
}
#[test]
fn pareto_chart_has_no_legend() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [["Item", "Count"], ["A", 3], ["B", 2], ["C", 1]]})).unwrap();
s.execute("insert.chart", json!({"type": "pareto", "range": "A1:B4"})).unwrap();
let c = &s.doc().unwrap().wb.active().unwrap().charts[0];
assert_eq!(c.kind, gridcraft_model::ChartKind::Pareto);
assert_eq!(c.legend, gridcraft_model::LegendPos::None);
}
#[test]
fn chart_set_doughnut_hole_and_angle() {
let mut s = s();
@@ -7522,6 +7611,120 @@ fn unique_nonce() -> u64 {
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
/// Protect Sheet's Delete Rows and Delete Columns delete a line only when every cell in it is
/// unlocked, as Excel does ("You are trying to delete a row that contains a locked cell"). The
/// line-level check read a line without a format of its own as carrying the default style, which
/// is locked, so every delete was refused however the permission was set; a cell the sheet does
/// not store is judged by the format it shows, its row's, then its column's, then the default.
#[test]
fn a_protected_sheet_deletes_blank_lines_when_the_normal_style_is_unlocked() {
// A file whose Normal style is unlocked leaves every unformatted cell unlocked, stored or not.
let mut sess = s();
sess.execute("review.protectSheet", json!({})).unwrap();
{
let d = sess.doc_mut().unwrap();
let mut wb = (*d.wb).clone();
let mut normal = wb.styles.get(gridcraft_model::StyleId::DEFAULT).clone();
normal.protection.locked = false;
wb.styles = gridcraft_model::StyleTable::with_default(normal);
// The sheet must be protected, or the deletes below would pass without checking anything.
let p = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()).expect("review.protectSheet protected sheet 0");
p.delete_rows = true;
p.delete_columns = true;
d.wb = std::sync::Arc::new(wb);
}
sess.execute("selection.set", json!({"range": "A7:A7"})).unwrap();
assert!(sess.execute("home.deleteRows", json!({})).is_ok(), "a blank row of unlocked default cells");
sess.execute("selection.set", json!({"range": "F1:F1"})).unwrap();
assert!(sess.execute("home.deleteColumns", json!({})).is_ok(), "a blank column of unlocked default cells");
}
#[test]
fn a_protected_sheet_deletes_lines_when_it_says_so() {
fn grant(sess: &mut Session) {
let d = sess.doc_mut().unwrap();
let mut wb = (*d.wb).clone();
if let Some(p) = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()) {
p.delete_rows = true;
p.delete_columns = true;
}
d.wb = std::sync::Arc::new(wb);
}
// Values in A1:A3, the given ranges unlocked (or locked again) in order, then protected.
let book = |locks: &[(&str, bool)], granted: bool| {
let mut sess = s();
for (c, v) in [("A1", "1"), ("A2", "2"), ("A3", "3")] {
sess.execute("cell.set", json!({"cell": c, "input": v})).unwrap();
}
for (range, on) in locks {
sess.execute("home.lockCell", json!({"range": range, "on": on})).unwrap();
}
sess.execute("review.protectSheet", json!({})).unwrap();
if granted {
grant(&mut sess);
}
sess
};
let delete = |sess: &mut Session, what: &str, at: &str| {
sess.execute("selection.set", json!({"range": format!("{at}:{at}")})).unwrap();
sess.execute(what, json!({})).is_ok()
};
let (rows, cols) = ("home.deleteRows", "home.deleteColumns");
const SHEET: &str = "A1:XFD1048576";
// Granted, over whole rows the user unlocked: the row goes, and the rows below move up.
let mut sess = book(&[("A1:XFD10", false)], true);
assert!(delete(&mut sess, rows, "A1"), "an unlocked row is deleted");
assert_eq!((v(&sess, "A1"), v(&sess, "A2")), (Value::Number(2.0), Value::Number(3.0)));
// Its columns still have locked cells below row 10, so a column is not deleted.
assert!(!delete(&mut sess, cols, "A1"), "a column with locked cells stays");
// Granted, over a whole column the user unlocked: the column goes.
let mut sess = book(&[("A1:A1048576", false)], true);
assert!(delete(&mut sess, cols, "A1"), "an unlocked column is deleted");
assert_eq!(v(&sess, "A1"), Value::Empty);
// Granted, with the whole sheet unlocked: blank lines go too, judged by their columns' format.
let mut sess = book(&[(SHEET, false)], true);
assert!(delete(&mut sess, rows, "A7"), "a blank row under unlocked columns");
assert!(delete(&mut sess, cols, "F1"), "a blank unlocked column");
// Not granted: refused, and the rows stay.
let mut sess = book(&[(SHEET, false)], false);
assert!(!delete(&mut sess, rows, "A1"), "Delete rows is off");
assert!(!delete(&mut sess, cols, "A1"), "Delete columns is off");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, but only a block of cells is unlocked: the rest of each line is locked by default,
// so neither its rows nor its columns are deleted.
let mut sess = book(&[("A1:D10", false)], true);
assert!(!delete(&mut sess, rows, "A1"), "E1 onwards are locked");
assert!(!delete(&mut sess, cols, "A1"), "A11 onwards are locked");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, nothing unlocked: a blank line is locked by the default like any other, and a line
// with a locked value in it is refused by that cell.
let mut sess = book(&[], true);
assert!(!delete(&mut sess, rows, "A7"), "a blank row of default cells is locked");
assert!(!delete(&mut sess, cols, "F1"), "a blank column of default cells is locked");
assert!(!delete(&mut sess, rows, "A1"), "locked cells are not deleted");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, the sheet unlocked but row 5 locked again by a format of its own: row 5 is refused,
// and so is every column, since row 5's format comes before a column's in each cell it crosses.
// The format has to go on before the sheet is protected, since changing a format on a
// protected sheet is itself refused.
let mut sess = book(&[(SHEET, false), ("A5:XFD5", true)], true);
assert!(!delete(&mut sess, rows, "A5"), "a locked row format refuses");
assert!(!delete(&mut sess, cols, "B1"), "B5 is locked by its row");
assert!(delete(&mut sess, rows, "A6"), "the rows beside it are not");
// An unprotected sheet is untouched by any of this.
let mut sess = s();
sess.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
sess.execute("home.deleteRows", json!({})).unwrap();
}
/// Normal, Page Layout and Page Break Preview are not undo steps (as in Excel), so undoing or
/// redoing an edit keeps each sheet in the view it is in now, instead of putting back the view
/// of the snapshot it swaps in. Found through the command-sequence fuzz (seed 177).
+321
View File
@@ -317,6 +317,327 @@ fn a_python_cell_without_its_code_keeps_its_whole_cached_result_as_values() {
}
}
fn long_warning(n: u64) -> String {
format!("sheet \"Sheet1\": {n} cell text(s) longer than Excel's limit of 32767 UTF-16 units were read; they were not cut to that length")
}
#[test]
fn long_text_in_a_python_spill_is_kept_and_warned_about() {
// A Python cell's spilled values are its result, kept and saved, so text in them longer than
// Excel allows in a cell is kept whole with the warning a plain cell's gets; at the limit, no warning.
let most = gridcraft_core::MAX_CELL_CHARS as usize;
let book = |n: usize| {
let data = format!(
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A2\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
<row r=\"2\"><c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c></row></sheetData>",
"a".repeat(n)
);
crate::io::open_bytes("long.xlsx", &excel_shaped(&data, Some(&["[1, 'text']"]))).unwrap()
};
let long = |warnings: &[String]| warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>();
let (wb, warnings) = book(most);
assert!(long(&warnings).is_empty(), "{warnings:?}");
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most).into())));
let (wb, warnings) = book(most + 1);
assert_eq!(long(&warnings), [long_warning(1)], "{warnings:?}");
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most + 1).into())));
}
#[test]
fn a_repeated_address_in_a_python_spill_keeps_the_last_value_with_a_warning() {
// A2 lies in A1's spill and has the default style, so its value is kept only as part of the
// result, in the spill and not in a cell; a second A2, after B2, replaces it there, as on any
// cell, and is counted as a repeat, found by the column bitmap of row 2's element (the next
// test puts the second A2 in a later element, after another row's, where the spill finds it).
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c><c r=\"A2\"><v>9</v></c></row></sheetData>";
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(5.0));
assert!(
warnings
.iter()
.any(|w| w
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
"{warnings:?}"
);
assert!(!warnings.iter().any(|w| w.contains("out of column order")), "{warnings:?}");
}
#[test]
fn a_repeated_address_in_a_python_spill_in_a_later_row_element_is_found_in_the_spill() {
// As above, but the second A2 sits in a second row element for row 2, after row 3's: the
// column bitmap has been cleared and A2 is not the furthest cell, so only the spill finds the
// repeat.
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c></row><row r=\"3\"><c r=\"C3\"><v>7</v></c></row>\
<row r=\"2\"><c r=\"A2\"><v>9</v></c></row></sheetData>";
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
assert!(
warnings
.iter()
.any(|w| w
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
"{warnings:?}"
);
}
#[test]
fn a_long_spilled_text_is_counted_when_read_even_where_a_repeat_replaces_it() {
// A long A2 in A1's spill, then a second A2: the long text is counted as it is read, so a
// plain value replacing it leaves the count at one, and a second long one makes it two.
let long = format!("<c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c>", "a".repeat(gridcraft_core::MAX_CELL_CHARS as usize + 1));
let count = |second: &str| {
let data = format!(
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
<row r=\"2\">{long}{second}</row></sheetData>"
);
let (_, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(&data, Some(&["[1, 2, 3]"]))).unwrap();
assert!(warnings.iter().any(|w| w.contains("already read")), "{warnings:?}");
warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>()
};
assert_eq!(count("<c r=\"A2\"><v>9</v></c>"), [long_warning(1)]);
assert_eq!(count(&long), [long_warning(2)]);
}
#[test]
fn python_code_dropped_at_the_element_cap_leaves_its_cells_with_their_values() {
// The first script's code holds a million elements. With the `environmentDefinition` before
// the scripts in the tree, the last of them crosses the reader's element cap for a part, and
// the code element is dropped with the 999,999 it held: 1,000,001 elements. A script whose
// code was dropped is treated as missing, so A1, naming it, keeps its cached value and no
// Python code, through a save too. The second script is read whole, and the third, an empty
// `code` in the file, is empty code, as before.
let crowded = format!("x = 1{}", "<pad/>".repeat(1_000_000));
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c>\
<c r=\"C1\"><f>_xlfn._xlws.PY(2,0)</f><v>3</v></c></row></sheetData>";
let bytes = excel_shaped(data, Some(&[&crowded, "y = 2", ""]));
let (_, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
assert!(
warnings.iter().any(|w| w.starts_with("the Python part: dropped 1000001 element(s)")
&& w.ends_with("a script that lost its code and kept no code after it counts as missing")),
"{warnings:?}"
);
assert!(warnings.iter().any(|w| w.starts_with("1 Python cell(s) name code the file's Python part doesn't hold")), "{warnings:?}");
let mut s = s();
open(&mut s, "crowded.xlsx", &bytes);
let check = |s: &Session, when: &str| {
let sh = s.doc().unwrap().wb.active().unwrap();
let a1 = sh.cell(CellRef::parse("A1").unwrap()).unwrap_or_else(|| panic!("{when}: A1 is stored"));
assert_eq!(a1.value, Value::Number(1.0), "{when}");
assert!(a1.py.is_none() && a1.formula.is_none(), "{when}: A1 is a plain value");
assert_eq!(code(s, "B1").map(|p| p.code), Some("y = 2".to_string()), "{when}");
assert_eq!(code(s, "C1").map(|p| p.code), Some(String::new()), "{when}");
};
check(&s, "after open");
let saved = save(&mut s, "xlsx");
open(&mut s, "saved.xlsx", &saved);
check(&s, "after a save");
}
/// A1 naming the one script, `script` (a whole `pythonScript` element), read: A1's Python code, if
/// any, and the warnings.
fn a1_code_with_script(script: &str) -> (Option<String>, Vec<String>) {
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let good = excel_shaped(data, Some(&["MARKER"]));
let bytes = with_parts(
&good,
|name, text| {
if name == "xl/python/python1.xml" { text.replace("<pythonScript><code>MARKER</code></pythonScript>", script) } else { text.to_string() }
},
&[],
);
let (wb, warnings) = crate::io::open_bytes("script.xlsx", &bytes).unwrap();
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).cloned();
(a1.and_then(|c| c.py.map(|p| p.code.clone())), warnings)
}
#[test]
fn a_script_without_code_reads_as_empty_code_also_when_an_unknown_element_crosses_the_cap() {
// A script with no code reads as empty code. An unknown element in it that crosses the
// element cap is dropped and counted, but holds nothing the reader reads: the script still
// reads as empty code, not as missing.
for (script, dropped) in [
("<pythonScript><other/></pythonScript>".to_string(), false),
(format!("<pythonScript><other>{}</other></pythonScript>", "<pad/>".repeat(1_000_001)), true),
] {
let (code, warnings) = a1_code_with_script(&script);
assert_eq!(code.as_deref(), Some(""), "{warnings:?}");
assert_eq!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), dropped, "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
}
}
#[test]
fn a_script_whose_first_code_is_dropped_at_the_element_cap_takes_its_second_code() {
// The first code crosses the element cap and is dropped whole: it took no place in the
// script's allowance of one code, so the second code is read, and A1 takes it.
let (code, warnings) =
a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code>y = 2</code></pythonScript>", "<pad/>".repeat(1_000_001)));
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
}
#[test]
fn a_script_whose_code_is_dropped_at_the_element_cap_before_an_empty_code_counts_as_missing() {
// The first code crosses the element cap and is dropped whole, and the code after it is empty:
// the script lost its code and kept none, so A1 keeps only its value, as when no code follows.
let (code, warnings) = a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code/></pythonScript>", "<pad/>".repeat(1_000_001)));
assert_eq!(code, None, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
}
#[test]
fn a_script_that_keeps_its_code_and_loses_a_second_one_past_the_element_cap_keeps_its_code() {
// The second code crosses the element cap; it is one more than a script holds, so it is
// dropped for that, and the script, which lost no code it reads, keeps its first code, empty
// or not.
for kept in ["y = 2", ""] {
let (code, warnings) =
a1_code_with_script(&format!("<pythonScript><code>{kept}</code><code>x = 1{}</code></pythonScript>", "<pad/>".repeat(1_000_001)));
assert_eq!(code.as_deref(), Some(kept), "{warnings:?}");
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
}
}
#[test]
fn a_script_that_loses_an_unknown_element_at_the_element_cap_keeps_its_code() {
// The script's code comes first; an unknown element after it crosses the element cap and is
// dropped whole. The code was kept, so A1 keeps it.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let crowded = format!("</code><extra>{}</extra></pythonScript>", "<pad/>".repeat(1_000_001));
let good = excel_shaped(data, Some(&["y = 2"]));
let bytes = with_parts(
&good,
|name, text| if name == "xl/python/python1.xml" { text.replace("</code></pythonScript>", &crowded) } else { text.to_string() },
&[],
);
let (wb, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("y = 2"), "{warnings:?}");
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
}
#[test]
fn an_empty_script_with_the_element_cap_full_is_read_and_the_part_fails_when_its_scripts_close() {
// The `environmentDefinition` and the filler before `pythonScripts` fill the part's element
// cap of a million. An empty script holds no element, so it is handed out as on main and
// reads as empty code; `pythonScripts` itself is then one element past the cap, so the part
// fails as it closes, and the warning counts the empty script among those kept. A1, naming
// it, keeps the empty code. With one element less of filler the part is whole.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let good = excel_shaped(data, Some(&["MARKER"]));
for (filler, script, damaged) in
[(999_999, "<pythonScript/>", true), (999_999, "<pythonScript></pythonScript>", true), (999_998, "<pythonScript/>", false)]
{
let scripts = format!("{}<pythonScripts>{script}</pythonScripts>", "<pad/>".repeat(filler));
let bytes = with_parts(
&good,
|name, text| {
if name == "xl/python/python1.xml" {
text.replace("<pythonScripts><pythonScript><code>MARKER</code></pythonScript></pythonScripts>", &scripts)
} else {
text.to_string()
}
},
&[],
);
let (wb, warnings) = crate::io::open_bytes("full.xlsx", &bytes).unwrap();
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some(""), "{script} after {filler}: {warnings:?}");
let failed: Vec<&String> = warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).collect();
let expected = "the Python part is damaged (the file contains invalid XML: the part holds more than 1000000 elements); kept 1 scripts";
assert_eq!(failed, if damaged { vec![expected] } else { vec![] }, "{script} after {filler}");
assert!(!warnings.iter().any(|w| w.contains("doesn't hold") || w.starts_with("the Python part: dropped")), "{warnings:?}");
}
}
#[test]
fn a_damaged_python_part_still_reports_what_it_dropped_before_the_damage() {
// The script's second code is dropped, then the part ends in an unclosed comment: both the
// damage and the dropped element are warned about.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let good = excel_shaped(data, Some(&["x = 1</code><code>y = 2"]));
let bytes = with_parts(
&good,
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
&[],
);
let (_, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
}
#[test]
fn a_second_code_in_a_python_script_is_dropped_with_a_warning() {
// A script holds one code: the first is read, the second dropped and counted.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let (wb, warnings) = crate::io::open_bytes("twice.xlsx", &excel_shaped(data, Some(&["x = 1</code><code>y = 2"]))).unwrap();
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"));
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
}
fn unknown_warning(n: u64) -> String {
format!("the Python part: {n} element(s) GridCraft does not read (unknown elements) were left out and will not be saved")
}
fn unknown_warnings(warnings: &[String]) -> Vec<String> {
warnings.iter().filter(|w| w.contains("does not read")).cloned().collect()
}
#[test]
fn a_script_with_an_unknown_child_keeps_its_code_and_warns_that_it_will_not_be_saved() {
// The unknown child is small, so nothing reaches an allowance or the element cap and nothing
// is dropped: the code is read, and the child, which a save does not write, is warned about.
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code><extra>note</extra></pythonScript>");
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
assert!(!warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
}
#[test]
fn unknown_children_across_two_scripts_are_counted_in_one_warning() {
// Two unknown children in the first script and one in the second: one warning, counting three.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c></row></sheetData>";
let scripts = ["x = 1</code><extra/><other>text</other><code>unread", "y = 2</code><extra/><code>unread"];
let (wb, warnings) = crate::io::open_bytes("unknown.xlsx", &excel_shaped(data, Some(&scripts))).unwrap();
let sheet = wb.sheet(0).unwrap();
let code = |cell: &str| sheet.cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_ref().map(|p| p.code.clone()));
assert_eq!(code("A1").as_deref(), Some("x = 1"), "{warnings:?}");
assert_eq!(code("B1").as_deref(), Some("y = 2"), "{warnings:?}");
assert_eq!(unknown_warnings(&warnings), [unknown_warning(3)], "{warnings:?}");
}
#[test]
fn a_script_without_unknown_children_gives_no_unknown_element_warning() {
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code></pythonScript>");
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
assert!(unknown_warnings(&warnings).is_empty(), "{warnings:?}");
}
#[test]
fn a_damaged_python_part_still_reports_unknown_children_read_before_the_damage() {
// The script, with one unknown child, closes before the part ends in an unclosed comment: both
// the damage and the unknown child are warned about, and the script's code is kept.
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
let good = excel_shaped(data, Some(&["x = 1</code><extra/><code>unread"]));
let bytes = with_parts(
&good,
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
&[],
);
let (wb, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"), "{warnings:?}");
}
#[test]
fn a_python_spill_whose_blank_cells_have_no_records_is_still_a_spill() {
// A1's result spills over A1:A3, and the file holds no records for the blank A2 and A3.
@@ -530,7 +530,7 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
}
/// The workbook with view state (active sheet, scroll, active cell, zoom, Normal / Page Layout /
/// Page Break Preview) and the Watch Window list reset: undo restores view state as it was, but
/// Page Break Preview, Show page breaks) and the Watch Window list reset: undo restores view state as it was, but
/// switching sheets, zooming or switching views isn't an undoable edit.
fn canonical(wb: &Workbook) -> Workbook {
let mut wb = wb.clone();
@@ -542,6 +542,8 @@ fn canonical(wb: &Workbook) -> Workbook {
sh.view_top_left = CellRef::default();
sh.zoom = 100;
sh.view = SheetViewMode::Normal;
// Page Break Preview turns Show page breaks on, a display option that isn't an edit either.
sh.show_page_breaks = false;
}
wb
}
+11 -2
View File
@@ -600,8 +600,15 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
{
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
let col =
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
let col = |name: &str| TableColumn {
name: name.into(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
sh.tables.push(Table {
id: 1,
name: "LeftTable".into(),
@@ -618,6 +625,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.tables.push(Table {
id: 2,
@@ -635,6 +643,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(2).or_default().hidden = true;
@@ -55,6 +55,31 @@ fn resize_next_to_another_table_still_works() {
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
}
#[test]
fn resize_keeps_a_renamed_column_query_field() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns[1].query_field_id = Some(7);
s.execute("range.setValues", json!({"range":"B1", "values":[["Amount"]]})).unwrap();
s.execute("table.resize", json!({"table":"T", "range":"A1:B3"})).unwrap();
let col = &s.doc().unwrap().wb.active().unwrap().tables[0].columns[1];
assert_eq!((col.name.as_str(), col.query_field_id), ("Amount", Some(7)));
}
#[test]
fn resize_preserves_query_fields_only_for_surviving_addresses() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
let columns = &mut std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns;
columns[0].query_field_id = Some(3);
columns[1].query_field_id = Some(7);
s.execute("table.resize", json!({"table":"T", "range":"B1:C3"})).unwrap();
let cols = &s.doc().unwrap().wb.active().unwrap().tables[0].columns;
assert_eq!(cols.iter().map(|c| c.query_field_id).collect::<Vec<_>>(), [Some(7), None]);
}
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
s.doc().unwrap().wb.active().unwrap()
}
+72 -2
View File
@@ -23,6 +23,19 @@ fn needle(args: &[Arg], i: usize) -> R<Value> {
}
}
/// The lookup value of XLOOKUP and XMATCH. Unlike the older lookups, a reference to a blank cell is
/// blank rather than numeric zero: it matches a blank entry and nothing else (#4044). A written
/// blank argument (`XMATCH(, array)`) still becomes zero, as MATCH does.
fn xneedle(args: &[Arg], i: usize) -> R<Value> {
let a = arg(args, i)?;
match a.value.scalar() {
Value::Error(e) => Err(e),
Value::Empty if a.from_ref || a.blank_value => Ok(Value::Empty),
Value::Empty => Ok(Value::Number(0.0)),
v => Ok(v),
}
}
/// Order of two values for the approximate and binary searches: [`compare`], except that numbers
/// compare exactly. Excel's `=` treats numbers equal to 15 significant digits as equal, but its
/// lookups don't. Observed in Excel 365 with A1 holding
@@ -233,6 +246,12 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
}
if search_mode.abs() == 2 {
let desc = search_mode == -2;
// A blank needle only matches a blank entry. The coercing comparison would read it as
// numeric zero, so the exact result stands even when it finds nothing: the approximate
// probes must not fall through to a zero (#4044).
if matches!(x, Value::Empty) {
return Ok(bsearch_exact(x, hay, desc));
}
if match_mode == 2 {
// Wildcards are not supported with binary search: Excel falls back to exact.
return Ok(bsearch_exact(x, hay, desc));
@@ -292,13 +311,20 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
}
fn bsearch_exact(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
if matches!(x, Value::Empty) {
// A blank needle only matches a blank entry. The coercing comparison below would read it
// as numeric zero, so handle it here: blanks sort last in both directions, so the first
// blank entry is the only possible exact match.
let p = hay.partition_point(|v| !matches!(v, Value::Empty));
return matches!(hay.get(p)?, Value::Empty).then_some(p);
}
let p = bsearch_first(x, hay, desc)?;
let v = hay.get(p)?;
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
}
fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = needle(args, 0)?;
let x = xneedle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -344,7 +370,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
}
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = needle(args, 0)?;
let x = xneedle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -567,6 +593,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
mod tests {
use gridcraft_core::{CellError, Value};
use crate::Arg;
use crate::util::testutil::*;
fn table() -> Value {
@@ -759,6 +786,49 @@ mod tests {
assert_eq!(rows_of(&r), vec![vec![nv(3.0), nv(1.0)]]);
}
/// A reference to a blank cell is a blank lookup value, not numeric zero, for XMATCH and
/// XLOOKUP: it finds a blank entry and misses numbers. MATCH keeps Excel's zero coercion (#4044).
#[test]
fn xmatch_and_xlookup_treat_a_blank_reference_as_blank() {
let numbers = || av(row(&[0.0, 1.0, 3.0]));
let blank = || Arg::reference(Value::Empty);
is_err(ev("XMATCH", vec![blank(), numbers()]), CellError::NA);
close(ev("XMATCH", vec![blank(), rf(arr(vec![vec![Value::Empty], vec![nv(2.0)]]))]), 1.0);
let keys = || rf(col(&[0.0, 1.0, 3.0]));
let values = || av(col(&[10.0, 20.0, 30.0]));
close(ev("XLOOKUP", vec![blank(), keys(), values(), n(999.0), n(0.0)]), 999.0);
// Binary exact search (search mode 2 ascending, -2 descending) does not coerce the blank
// needle to zero either: {0} has no blank entry, {0;blank} has one last.
let zero = || rf(col(&[0.0]));
let zero_then_blank = || rf(arr(vec![vec![nv(0.0)], vec![Value::Empty]]));
let just_blank = || rf(arr(vec![vec![Value::Empty]]));
for mode in [2.0, -2.0] {
is_err(ev("XMATCH", vec![blank(), zero(), n(0.0), n(mode)]), CellError::NA);
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(0.0), n(mode)]), 2.0);
close(ev("XMATCH", vec![blank(), just_blank(), n(0.0), n(mode)]), 1.0);
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 999.0);
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 10.0);
// The approximate binary modes (-1 next smaller, 1 next larger) still take a present
// exact blank before their fallback, in both search directions.
for mm in [-1.0, 1.0] {
close(ev("XMATCH", vec![blank(), just_blank(), n(mm), n(mode)]), 1.0);
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(mm), n(mode)]), 2.0);
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 10.0);
close(ev("XLOOKUP", vec![blank(), zero_then_blank(), av(col(&[10.0, 20.0])), n(999.0), n(mm), n(mode)]), 20.0);
// Without a blank entry the approximate probes must not read the blank as zero.
is_err(ev("XMATCH", vec![blank(), zero(), n(mm), n(mode)]), CellError::NA);
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 999.0);
}
}
// Controls: numeric zero is still a key, and a written blank stays zero.
close(ev("XMATCH", vec![n(0.0), numbers()]), 1.0);
close(ev("XLOOKUP", vec![n(0.0), keys(), values(), n(999.0), n(0.0)]), 10.0);
is_err(ev("XMATCH", vec![n(0.0), just_blank(), n(0.0), n(2.0)]), CellError::NA);
close(ev("XMATCH", vec![empty(), zero(), n(0.0), n(2.0)]), 1.0);
close(ev("MATCH", vec![blank(), numbers(), n(0.0)]), 1.0);
close(ev("XMATCH", vec![empty(), numbers()]), 1.0);
}
/// Lookups compare numbers exactly, unlike `=` (15 significant digits). Observed in Excel 365.
#[test]
fn lookups_compare_numbers_exactly() {
+3 -3
View File
@@ -23,8 +23,8 @@ use descriptive::{
use distributions::{
beta_dist, beta_inv, betadist_legacy, binom_dist, binom_dist_range, binom_inv, chisq_dist, chisq_dist_rt, chisq_inv, chisq_inv_rt, chisq_test,
confidence_norm, confidence_t, expon_dist, f_dist, f_dist_rt, f_inv, f_inv_rt, f_test, fisher, gamma_dist, gamma_fn, gamma_inv, gammaln, gauss,
hypgeom_dist, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist, t_dist, t_dist_2t,
t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
hypgeom_dist, hypgeomdist_legacy, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist,
t_dist, t_dist_2t, t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
};
#[cfg(test)]
use regression::{MAX_REGRESSORS, check_regression_size};
@@ -649,7 +649,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
S,
"HYPGEOMDIST(sample_s, number_sample, population_s, number_pop)",
"Hypergeometric probability of an exact count.",
hypgeom_dist
hypgeomdist_legacy
),
f!(
"NEGBINOM.DIST",
+22 -2
View File
@@ -804,15 +804,27 @@ pub(super) fn weibull_dist(a: &[Arg], _: C) -> R<Value> {
num_val(if cum { -(-t).exp_m1() } else { al / be.powf(al) * x.powf(al - 1.0) * (-t).exp() })
}
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
fn hypgeom_common(a: &[Arg], strict: bool) -> R<Value> {
let k = num(a, 0)?.trunc();
let n = num(a, 1)?.trunc();
let kk = num(a, 2)?.trunc();
let nn = num(a, 3)?.trunc();
let cum = if a.len() > 4 { boolean(a, 4)? } else { false };
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn || k > n.min(kk) || k < (n - nn + kk).max(0.0) {
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn {
return Err(CellError::Num);
}
let lo = (n - nn + kk).max(0.0);
let hi = n.min(kk);
if k < lo || k > hi {
// Above the support the mass is zero and the cumulative form is 1, as
// Excel returns (#4032). Below the support Excel returns #NUM!, so both
// forms stay strict there. The legacy compatibility form is strict on
// both sides.
if strict || k < lo {
return Err(CellError::Num);
}
return num_val(if cum { 1.0 } else { 0.0 });
}
let pmf = |i: f64| (ln_comb(kk, i) + ln_comb(nn - kk, n - i) - ln_comb(nn, n)).exp();
if !cum {
return num_val(pmf(k));
@@ -829,6 +841,14 @@ pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
num_val(s.min(1.0))
}
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
hypgeom_common(a, false)
}
pub(super) fn hypgeomdist_legacy(a: &[Arg], _: C) -> R<Value> {
hypgeom_common(a, true)
}
pub(super) fn negbinom_dist(a: &[Arg], _: C) -> R<Value> {
let f = num(a, 0)?.trunc();
let s = num(a, 1)?.trunc();
+19
View File
@@ -821,6 +821,25 @@ fn discrete() {
close_tol(ev("NEGBINOMDIST", vec![n(10.0), n(5.0), n(0.25)]), 0.0550487, D7);
}
#[test]
fn hypgeom_dist_out_of_support_clamps() {
// Support is [max(0, n - nn + kk), min(n, kk)].
// Above support: k=2, n=1, kk=1, nn=3 -> high = min(1, 1) = 1, so 2 is above.
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(false)]), Value::Number(0.0));
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(true)]), Value::Number(1.0));
// Controls inside the support (low = max(0, 1 - 3 + 1) = 0, high = 1).
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(false)]), 1.0 / 3.0);
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(true)]), 1.0);
// Below support stays #NUM!, as Excel documents: k=0, n=4, kk=8, nn=10
// -> low = max(0, 4 - 10 + 8) = 2, so 0 is below.
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(false)]), CellError::Num);
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(true)]), CellError::Num);
// Legacy compatibility form stays strict outside the support.
is_err(ev("HYPGEOMDIST", vec![n(5.0), n(4.0), n(8.0), n(20.0)]), CellError::Num);
// Invalid population arguments stay #NUM! (number_sample > number_pop here).
is_err(ev("HYPGEOM.DIST", vec![n(1.0), n(5.0), n(2.0), n(3.0), b(false)]), CellError::Num);
}
#[test]
fn continuous() {
close_tol(ev("EXPON.DIST", vec![n(0.2), n(10.0), b(true)]), 0.86466472, D7);
+9
View File
@@ -60,6 +60,10 @@ pub struct TableColumn {
/// `uniqueName`: the name XML maps know the column by.
#[serde(default)]
pub unique_name: Option<String>,
/// `queryTableFieldId`: the field of the table's query table this column shows. It moves with
/// the column; inserted columns have none.
#[serde(default)]
pub query_field_id: Option<u32>,
/// Binding to an element of an XML map. It moves with the column and goes when the column is
/// deleted; inserted columns are unmapped.
#[serde(default)]
@@ -102,6 +106,10 @@ pub struct Table {
/// The connection (`xl/connections.xml`) an XML table is bound through.
#[serde(default)]
pub connection_id: Option<u32>,
/// The XML of the table's query table part (`xl/queryTables/…`), kept as read so the table
/// stays attached to its data connection. Never refreshed.
#[serde(default)]
pub query_table: Option<String>,
}
impl Table {
@@ -513,6 +521,7 @@ pub enum ChartKind {
Bubble,
Radar,
Histogram,
Pareto,
Waterfall,
Funnel,
Treemap,
+4 -1
View File
@@ -6,11 +6,14 @@
/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and
/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and
/// envelopes are the JIS ones too.
pub const PAPERS: [(&str, f32, f32); 24] = [
pub const PAPERS: [(&str, f32, f32); 27] = [
("Letter", 612.0, 792.0),
("Legal", 612.0, 1008.0),
("A4", 595.28, 841.89),
("A3", 841.89, 1190.55),
("A2", 1190.55, 1683.78),
("A1", 1683.78, 2383.94),
("A0", 2383.94, 3370.39),
("A5", 419.53, 595.28),
("A6", 297.64, 419.53),
("Tabloid", 792.0, 1224.0),
+5
View File
@@ -131,6 +131,10 @@ pub struct Sheet {
#[serde(default = "yes")]
pub summary_right: bool,
pub right_to_left: bool,
/// Excel's Show page breaks (Options › Advanced, "Display options for this worksheet"): dashed
/// page boundaries in Normal view. Page Break Preview turns it on; not saved with the file.
#[serde(skip)]
pub show_page_breaks: bool,
pub zoom: u16,
pub cond_formats: Vec<CondFormat>,
pub validations: Vec<Validation>,
@@ -211,6 +215,7 @@ impl Sheet {
show_formulas: false,
show_zeros: true,
right_to_left: false,
show_page_breaks: false,
zoom: 100,
cond_formats: vec![],
validations: vec![],
+1
View File
@@ -16,6 +16,7 @@ craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-print = { workspace = true }
craft-quit = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
gridcraft-engine = { workspace = true }
+21 -2
View File
@@ -93,6 +93,7 @@ impl SheetApp {
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
unsaved_prompt: None,
framework_host: crate::framework::host(),
}
}
@@ -205,6 +206,9 @@ impl SheetApp {
let t0 = now_ms();
// A script may have switched windows since the last frame.
self.follow_active_window();
// The window this pass draws: a command run in it may switch to another window, which draws
// in its own pass.
let drawn = self.ui_window();
// This window's key tip request that waited for this frame (its tab or ribbon was just
// shown); any other window's request was dropped before it.
self.ui.keytip_invoke = self.ui.keytip_invoke_next.take();
@@ -267,10 +271,13 @@ impl SheetApp {
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
// The update flow and the framework dialogs run once per frame, in the root window.
// The update flow runs once per frame, in the root window; the framework dialogs too, unless
// the unsaved-changes question asks about a workbook in another window: they show there.
#[cfg(not(target_arch = "wasm32"))]
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
}
if self.framework_dialogs_here(&ctx, drawn) {
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
@@ -302,6 +309,18 @@ impl SheetApp {
}
}
/// Whether a modal question is up and owns the keyboard: a GridCraft dialog or the shared
/// unsaved-changes question.
pub fn modal_open(&self) -> bool {
self.dialog.is_some() || self.unsaved_prompt.is_some()
}
/// The name of the open dialog, for automation: a GridCraft dialog's, or `saveChanges` while
/// the shared unsaved-changes question is up.
pub fn open_dialog_name(&self) -> Option<&str> {
self.dialog.as_ref().map(|d| d.name()).or_else(|| self.unsaved_prompt.as_ref().map(|_| "saveChanges"))
}
/// Current selection's top-left cell text as A1 (for the Name Box).
pub fn name_box_text(&self) -> String {
let Some(d) = self.session.active() else { return String::new() };
+6 -1
View File
@@ -298,6 +298,8 @@ impl SheetApp {
match i18n::Language::parse(code) {
Some(l) => {
self.ui.language = l;
// Chart text is translated: cached primitives hold the old language.
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
Ok(json!({"language": l}))
}
None => Err(format!("unknown language {code:?} (use one of {})", i18n::Language::code_list(", "))),
@@ -305,10 +307,12 @@ impl SheetApp {
}
"app.language.english" => {
self.ui.language = i18n::Language::En;
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
Ok(json!({"language": i18n::Language::En}))
}
"app.language.japanese" => {
self.ui.language = i18n::Language::Ja;
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
Ok(json!({"language": i18n::Language::Ja}))
}
"ui.quickAnalysis" => crate::quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)),
@@ -331,7 +335,7 @@ impl SheetApp {
"ui.dialog" => {
let name = p.get("name").and_then(Json::as_str).unwrap_or("");
self.open_dialog(name, p.clone());
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
Ok(json!({"dialog": self.open_dialog_name()}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
@@ -477,6 +481,7 @@ impl SheetApp {
}
// The notice AutoSave holds back with: Save asks what the notice says.
"saveLoss" => self.run_or_alert("file.save", json!({})),
"saveChanges" => self.open_unsaved_changes(&params),
// File › Options (`file.options`) and the File tab itself open the Backstage view.
"options" => self.open_backstage(backstage::Page::Options),
"backstage" => {
+1 -1
View File
@@ -4,7 +4,7 @@ impl SheetApp {
pub(super) fn ribbon_keys(&mut self, ctx: &egui::Context) {
let before = self.keytips.prefix().map(str::to_string);
let enabled = self.editor.is_none()
&& self.dialog.is_none()
&& !self.modal_open()
&& self.message.is_none()
&& self.name_box.is_none()
&& !ctx.text_edit_focused()
+1 -1
View File
@@ -58,7 +58,7 @@ impl SheetApp {
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
self.print_feedback_seen = None;
} else if let Some(print) = &self.services.print {
print(&bytes)?;
print(&bytes);
} else {
return Err("Printing is unavailable here; export a PDF instead.".into());
}
+82 -7
View File
@@ -1,7 +1,10 @@
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::{DialogResult, UnsavedAnswer, UnsavedChangesDialog};
use craft_ui::shell::embed::CloseDecision;
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
use crate::state::UnsavedPrompt;
impl SheetApp {
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
@@ -31,12 +34,11 @@ impl SheetApp {
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
match self.dialog.as_mut() {
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
Some(d) if d.name() == "saveChanges" => {
d.values.insert("quit".into(), json!(true));
}
_ => self.continue_quit(ctx),
self.promote_unsaved_to_quit();
} else {
self.continue_quit(ctx);
}
CloseDecision::Hold
}
@@ -233,13 +235,86 @@ impl SheetApp {
crate::macro_editor::request_close(self, true);
return;
}
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
// Already asking about a workbook (File › Close): answering it goes on to quit.
d.values.insert("quit".into(), json!(true));
self.promote_unsaved_to_quit();
return;
}
self.continue_quit(ctx);
}
/// Opens the shared unsaved-changes dialog on `framework_dialogs` for the active workbook.
pub(crate) fn open_unsaved_changes(&mut self, params: &Json) {
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
self.message = Some((
"Macro".into(),
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
));
return;
}
if let Some(mut old) = self.dialog.take() {
let _ = old.end_pick(self);
}
let Some(doc) = self.session.active().map(|d| d.uid) else { return };
let title = params
.get("title")
.and_then(Json::as_str)
.map(str::to_owned)
.or_else(|| self.session.active().map(|d| d.display_title()))
.unwrap_or_else(|| "this workbook".into());
let quitting = params.get("quit").and_then(Json::as_bool) == Some(true);
let scope = if quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(UnsavedPrompt { doc, window: self.ui_window(), quitting });
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
// A replaced question leaves a Cancel result; it is not the new question's answer.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
fn promote_unsaved_to_quit(&mut self) {
if let Some(prompt) = self.unsaved_prompt.as_mut()
&& !prompt.quitting
{
prompt.quitting = true;
let title =
self.session.documents().iter().find(|d| d.uid == prompt.doc).map(|d| d.display_title()).unwrap_or_else(|| "this workbook".into());
self.framework_dialogs.open(UnsavedChangesDialog::new(CloseScope::Quit, title).document_wording(true));
// The question it replaced left a Cancel as its result; it was not answered, and the
// quit's question asks on.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
}
/// Reads the answer from an open [`UnsavedChangesDialog`] and continues closing or quitting.
pub(crate) fn take_unsaved_changes_dialog(&mut self, ctx: &egui::Context) {
let Some(result) = self.framework_dialogs.take::<UnsavedChangesDialog>() else {
return;
};
let Some(prompt) = self.unsaved_prompt.take() else {
return;
};
let answer = match result {
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::DontSave, .. }) => SaveAnswer::DontSave,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Save, .. }) => SaveAnswer::Save,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Cancel, .. }) | DialogResult::Cancel | _ => SaveAnswer::Cancel,
};
if answer == SaveAnswer::Cancel {
return;
}
if let Some(w) = prompt.window.filter(|w| self.session.window(*w).is_some())
&& self.ui_window() != Some(w)
{
self.enter_window(w);
}
if self.session.active().map(|d| d.uid) != Some(prompt.doc) {
return;
}
if !self.answer_save_changes(answer, prompt.quitting, ctx) {
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
let scope = if prompt.quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(prompt);
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
}
}
}
#[cfg(test)]
+1 -1
View File
@@ -258,7 +258,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
+6
View File
@@ -46,6 +46,12 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
}
}
ui.add_space(18.0);
section(ui, lang, "Display options for this worksheet");
let mut page_breaks = app.session.active().and_then(|d| d.wb.active().map(|s| s.show_page_breaks)).unwrap_or(false);
if ui.checkbox(&mut page_breaks, lang.tr("Show page breaks")).changed() {
app.run_or_alert("view.showPageBreaks", json!({"on": page_breaks}));
}
ui.add_space(18.0);
section(ui, lang, "Formulas");
ui.label(lang.tr("Workbook calculation"));
calc_options(app, ui, lang, &calc);
+2 -4
View File
@@ -39,10 +39,8 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
&& app.commit_edit(0, 0, false, false)
{
match app.run("ui.printSubmit", params.clone()) {
Ok(_) => out.close = app.services.print_native.is_none(),
Err(error) => app.alert(error),
}
app.print_now(params.clone());
out.close = app.services.print_native.is_none();
}
ui.add_space(16.0);
egui::ComboBox::from_id_salt("backstage_print_scope")
+5 -3
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use egui::epaint::{PathShape, PathStroke};
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
use gridcraft_chart::{HAlign, Prim, VAlign};
use gridcraft_chart::{ChartLabels, HAlign, Prim, VAlign};
use gridcraft_engine::model::{Anchor, ObjKind, ObjRef, ShapeKind, Sheet, Workbook};
use crate::SheetApp;
@@ -39,7 +39,8 @@ pub fn paint_chart(p: &Painter, rect: Rect, wb: &Workbook, sheet: usize, chart:
let origin = rect.center() - vec2(w * z, h * z) / 2.0;
let data = gridcraft_chart::resolve(wb, sheet, chart);
let m = EguiMeasure { painter: p, z };
let prims = gridcraft_chart::render(chart, &data, w, h, &m);
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
let prims = gridcraft_chart::render_with_labels(chart, &data, w, h, &m, &labels);
paint_prims(&p.with_clip_rect(rect.intersect(p.clip_rect())), origin, &prims, z);
}
@@ -254,7 +255,8 @@ fn render_chart(p: &Painter, z: f32, wb: &Workbook, si: usize, ch: &gridcraft_en
tests::RENDERS.with(|c| c.set(c.get() + 1));
let data = gridcraft_chart::resolve(wb, si, ch);
let m = EguiMeasure { painter: p, z };
gridcraft_chart::render(ch, &data, ch.anchor.width, ch.anchor.height, &m)
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
gridcraft_chart::render_with_labels(ch, &data, ch.anchor.width, ch.anchor.height, &m, &labels)
}
/// The primitives of chart `ci` of sheet `si`: from the frame cache when the workbook, zoom and
+3 -2
View File
@@ -147,7 +147,8 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
"grid": app.grid.cells_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
"scroll": [v.scroll.x, v.scroll.y],
"editor": app.editor.as_ref().map(|e| editor_json(app, e)),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab})),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab}))
.or_else(|| app.unsaved_prompt.as_ref().map(|p| json!({"name": "saveChanges", "values": {"quit": p.quitting}}))),
"backstage": app.backstage.as_ref().map(|b| b.page.id()),
"message": app.message.as_ref().map(|(t, m)| json!({"title": t, "text": m})),
"selectedObject": app.selected_object,
@@ -339,7 +340,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
}
"ui.dialog" => {
app.open_dialog(s("name").unwrap_or(""), p.clone());
ok(json!({"dialog": app.dialog.as_ref().map(|d| d.name.clone())}))
ok(json!({"dialog": app.open_dialog_name()}))
}
"ui.dialog.set" => match app.dialog.as_mut() {
Some(d) => {
-1
View File
@@ -1166,7 +1166,6 @@ impl Dialog {
"formatControl" => return crate::control_ui::open_format(app, &params),
"controlQuestion" => return crate::control_ui::open_question(&params),
"saveCopy" => Dialog::custom("saveCopy", "Save a Copy", json!({"format": p("format")})),
"saveChanges" => Dialog::custom("saveChanges", "Save Changes?", json!({"title": p("title"), "quit": p("quit")})),
"start" => Dialog::custom("start", "GridCraft", json!({})),
"comments" => {
app.grid.pane = None;
+3 -2
View File
@@ -2,7 +2,7 @@ use super::show::ok_cancel;
use super::{Color32, Dialog, Icon, Json, Sense, SheetApp, Stroke, StrokeKind, icons, json, vec2};
/// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`.
const ALL_CHARTS: [(&str, &str, &str); 23] = [
const ALL_CHARTS: [(&str, &str, &str); 24] = [
("column", "", "Clustered Column"),
("column", "stacked", "Stacked Column"),
("column", "stacked100", "100% Stacked Column"),
@@ -23,6 +23,7 @@ const ALL_CHARTS: [(&str, &str, &str); 23] = [
("scatter", "lines", "Scatter with Lines"),
("radar", "", "Radar"),
("histogram", "", "Histogram"),
("pareto", "", "Pareto"),
("waterfall", "", "Waterfall"),
("funnel", "", "Funnel"),
("combo", "", "Combo"),
@@ -51,7 +52,7 @@ pub(super) fn select_chart(d: &mut Dialog, i: usize) {
fn chart_icon(t: &str) -> Icon {
match t {
"column" | "bar" | "histogram" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"column" | "bar" | "histogram" | "pareto" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"line" | "area" | "radar" => Icon::ChartLine,
"pie" | "doughnut" => Icon::ChartPie,
"scatter" | "bubble" => Icon::ChartScatter,
-13
View File
@@ -374,19 +374,6 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
}
}
}
"saveChanges" => {
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
ui.horizontal(|ui| {
for (label, answer) in
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
{
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
open = false;
}
}
});
}
"saveLoss" => {
let lang = app.ui.language;
let pending = d.pending_save();
+3 -3
View File
@@ -529,7 +529,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
let chars_before = ed.text.chars().count();
// A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the
// editor takes it back afterwards.
let dialog_open = app.dialog.is_some();
let dialog_open = app.modal_open();
if dialog_open && mine {
ed.request_focus = true;
ed.keep_selection = true;
@@ -671,7 +671,7 @@ fn editor_shortcuts(
) -> EditorKeyOutcome {
let mut outcome = EditorKeyOutcome { action: None, arrow: false, cancel: false, to_python: false };
// A message or dialog owns Enter and Escape until it closes.
if !has_focus || !mine || app.message.is_some() || app.dialog.is_some() {
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
return outcome;
}
// Ctrl+Alt+Shift+P turns the edit into Python code.
@@ -864,7 +864,7 @@ fn python_editor(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, width: f32
let Some(mut ed) = app.editor.take() else { return EditorInfo::default() };
// A message box (the code was refused) or a dialog over the edit has the keyboard; the
// editor takes it back when it closes.
let blocked = app.message.is_some() || app.dialog.is_some();
let blocked = app.message.is_some() || app.modal_open();
let mut caret = None;
if blocked {
ed.request_focus = true;
+13
View File
@@ -112,9 +112,22 @@ impl SheetApp {
embed::logic(ctx, || self.close_decision(ctx));
}
/// Whether this pass draws [`SheetApp::framework_dialogs`]: the pass of the window the unsaved-changes
/// question asks about (the window that keeps it, as a GridCraft dialog stays in its window), else the root's.
/// `drawn` is the window the pass began drawing: a question a command in it opened for another window (a quit
/// moving on to the next unsaved workbook) shows in that window's own pass, not for a frame in this one.
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context, drawn: Option<u64>) -> bool {
let shown = |w: &u64| self.session.window(*w).is_some_and(|w| !w.hidden);
match self.unsaved_prompt.as_ref().and_then(|p| p.window).filter(shown) {
Some(w) => drawn == Some(w),
None => ctx.viewport_id() == egui::ViewportId::ROOT,
}
}
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
self.take_unsaved_changes_dialog(ui.ctx());
}
}
+4
View File
@@ -19,6 +19,8 @@ use crate::theme::{self, Tokens};
pub(crate) type PaneQuad = ((u32, u32), (u32, u32), Rect);
/// Cached Page Break Preview ranges, keyed by (doc uid, revision, sheet).
type PagesCache = ((u64, u64, usize), Vec<(RangeRef, u32)>);
/// Cached Normal-view page breaks (row and column page bands), keyed by (doc uid, revision, sheet).
type PageBreaksCache = ((u64, u64, usize), Vec<(u32, u32)>, Vec<(u32, u32)>);
/// Cached Show Details cells, keyed by (doc uid, revision, sheet, pivot).
type DetailsCache = ((u64, u64, usize, usize), Option<std::collections::HashSet<(u32, u32)>>);
/// Cached fill-menu trend entries (label, mode), keyed by (doc uid, revision, sheet, source, dragged range).
@@ -378,6 +380,8 @@ pub struct GridState {
pub quick_analysis: crate::quick_analysis::State,
/// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns).
pub paper: Option<crate::paper_view::PaperCache>,
/// Normal view's page breaks: row and column page bands, cached per (doc uid, revision, sheet).
pub page_breaks: Option<PageBreaksCache>,
/// Header or footer being edited in place (Page Layout view).
pub hf_edit: Option<crate::paper_view::HfEdit>,
/// A page margin being dragged on a ruler (Page Layout view); committed on release.
+1 -1
View File
@@ -19,7 +19,7 @@ fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
// arrow key would move the selection the menu fills from), and a macro's question.
editing
|| app.dialog.is_some()
|| app.modal_open()
|| other_focus
|| app.message.is_some()
|| app.grid.filter_menu.is_some()
+2 -2
View File
@@ -328,7 +328,7 @@ pub(super) fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo,
app.grid.fill_tag = None;
return;
}
if app.editor.is_some() || app.dialog.is_some() || app.grid.drag != Drag::None {
if app.editor.is_some() || app.modal_open() || app.grid.drag != Drag::None {
return;
}
let size = vec2(18.0, 18.0);
@@ -471,7 +471,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
/// The warning button beside an active cell holding a number stored as text, as in Excel: its
/// menu names the problem and offers Convert to Number for the selection (#1994).
pub(super) fn error_check_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
if app.editor.is_some() || app.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
if app.editor.is_some() || app.modal_open() || sh.show_formulas || app.grid.drag != Drag::None {
return;
}
let Some(active) = app.session.active().map(|d| d.selection.active) else { return };
+157
View File
@@ -200,6 +200,8 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
)
};
app.grid.cf = cf_sheet.map(|s| (s, cf));
// Page breaks sit on the cells, under objects and the selection, as in Excel.
paint_page_breaks(app, &painter.with_clip_rect(geo.cells), &geo, &wb, si, sh, &t);
// Objects above cells. A hidden object can't stay selected: Delete or the Format pane would act
// on something the user can't see.
if crate::chartview::objects_hidden(&wb) {
@@ -824,6 +826,66 @@ pub(crate) fn paint_overlays(input: OverlayInput<'_>) {
let _ = (wb, si);
}
/// Normal view with Show page breaks on: Excel's dashed lines where each page ends. The
/// pagination is the printing one (`layout_sheet`, no PDF), cached per (doc uid, revision, sheet)
/// and computed only while the lines are shown. Other views draw nothing here.
fn paint_page_breaks(app: &mut SheetApp, p: &Painter, geo: &Geo, wb: &Workbook, si: usize, sh: &Sheet, t: &Tokens) {
if sh.view != gridcraft_engine::model::SheetViewMode::Normal || !sh.show_page_breaks || geo.paper.is_some() {
return;
}
let Some(d) = app.session.active() else { return };
let key = (d.uid, d.revision, si);
if app.grid.page_breaks.as_ref().is_none_or(|(k, ..)| *k != key) {
use gridcraft_engine::cmd::print::{PrintOptions, layout_sheet, page_break_bands};
let bands = layout_sheet(wb, si, &PrintOptions::default(), None).map(|l| page_break_bands(sh, &l)).unwrap_or_default();
app.grid.page_breaks = Some((key, bands.0, bands.1));
}
let Some((_, rows, cols)) = &app.grid.page_breaks else { return };
let stroke = Stroke::new(1.0, t.page_break);
for seg in page_break_lines(sh, geo, rows, cols, p.clip_rect()) {
p.extend(egui::Shape::dashed_line(&seg, stroke, BREAK_DASH, BREAK_GAP));
}
}
const BREAK_DASH: f32 = 3.0;
const BREAK_GAP: f32 = 2.0;
/// The dashed lines of `paint_page_breaks`, in grid coordinates: one after the last column of
/// each page column and one after the last row of each page row, across the printed extent.
/// The final band has been extended to its page capacity for the editing overlay. A
/// line scrolled under a frozen pane is left out, and the extent starts below / right of the
/// frozen panes when the printed cells do. Lines are cut to `clip` (a dashed line costs a shape
/// per dash, and the extent of a long list is far taller than the screen); a cut start moves to
/// the next dash boundary of the whole line, so the dashes don't crawl while scrolling.
fn page_break_lines(sh: &Sheet, geo: &Geo, rows: &[(u32, u32)], cols: &[(u32, u32)], clip: Rect) -> Vec<[egui::Pos2; 2]> {
let (Some(r0), Some(r1), Some(c0), Some(c1)) = (rows.first(), rows.last(), cols.first(), cols.last()) else { return vec![] };
let pane_top = geo.cells.top() + geo.frozen_h;
let pane_left = geo.cells.left() + geo.frozen_w;
let period = BREAK_DASH + BREAK_GAP;
// The first dash boundary of the whole line at or past `edge`.
let cut = |start: f32, edge: f32| if start < edge { start + ((edge - start) / period).ceil() * period } else { start };
let top = cut(geo.y(sh, r0.0), if r0.0 >= geo.fr { pane_top.max(clip.top()) } else { clip.top() });
let left = cut(geo.x(sh, c0.0), if c0.0 >= geo.fc { pane_left.max(clip.left()) } else { clip.left() });
let frozen_bottom = if r0.0 < geo.fr { geo.y_end(sh, r1.1.min(geo.fr - 1)) } else { f32::NEG_INFINITY };
let frozen_right = if c0.0 < geo.fc { geo.x_end(sh, c1.1.min(geo.fc - 1)) } else { f32::NEG_INFINITY };
let bottom = geo.y_end(sh, r1.1).max(frozen_bottom).min(clip.bottom());
let right = geo.x_end(sh, c1.1).max(frozen_right).min(clip.right());
let mut out = Vec::new();
for &(_, last) in cols {
let x = geo.x_end(sh, last);
if (last < geo.fc || x >= pane_left) && (clip.left()..=clip.right()).contains(&x) && bottom > top {
out.push([pos2(x, top), pos2(x, bottom)]);
}
}
for &(_, last) in rows {
let y = geo.y_end(sh, last);
if (last < geo.fr || y >= pane_top) && (clip.top()..=clip.bottom()).contains(&y) && right > left {
out.push([pos2(left, y), pos2(right, y)]);
}
}
out
}
fn paint_pages(app: &mut SheetApp, p: &Painter, geo: &Geo, sh: &Sheet) {
let Some(d) = app.session.active() else { return };
let key = (d.uid, d.revision, d.wb.active_sheet());
@@ -1158,3 +1220,98 @@ mod trace_arrow_tests {
assert!((30..=60).contains(&further.len()), "{}", further.len());
}
}
#[cfg(test)]
mod page_break_tests {
use super::*;
use gridcraft_engine::model::{DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT};
/// Two pages across and two down, with a hidden row inside the first page row: the lines sit
/// after columns E and J and after rows 10 and 20, and the hidden row takes no height.
#[test]
fn page_breaks_follow_the_page_bands_in_both_directions() {
let mut sh = Sheet::new("S");
sh.rows.entry(4).or_default().hidden = true;
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 0.0));
let (x0, y0, z) = (geo.cells.left(), geo.cells.top(), geo.z);
let (w, h) = (DEFAULT_COL_WIDTH * z, DEFAULT_ROW_HEIGHT * z);
let lines = page_break_lines(&sh, &geo, &[(0, 9), (10, 19)], &[(0, 4), (5, 9)], geo.cells);
let (bottom, right) = (y0 + 19.0 * h, x0 + 10.0 * w);
let expect = [
[pos2(x0 + 5.0 * w, y0), pos2(x0 + 5.0 * w, bottom)],
[pos2(right, y0), pos2(right, bottom)],
[pos2(x0, y0 + 9.0 * h), pos2(right, y0 + 9.0 * h)],
[pos2(x0, bottom), pos2(right, bottom)],
];
assert_eq!(lines.len(), expect.len(), "{lines:?}");
for (got, want) in lines.iter().zip(expect) {
for (g, w) in got.iter().zip(want) {
assert!((g.x - w.x).abs() < 0.01 && (g.y - w.y).abs() < 0.01, "{lines:?}");
}
}
assert!(page_break_lines(&sh, &geo, &[], &[(0, 4)], geo.cells).is_empty(), "no pages, no lines");
}
/// Frozen rows: a page break scrolled up under them is not drawn over the frozen rows, and the
/// vertical lines start below them.
#[test]
fn page_breaks_scrolled_under_frozen_rows_are_hidden() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 0));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 10.0 * DEFAULT_ROW_HEIGHT));
let pane_top = geo.cells.top() + geo.frozen_h;
let lines = page_break_lines(&sh, &geo, &[(5, 9), (10, 40)], &[(5, 9)], geo.cells);
let horizontal: Vec<_> = lines.iter().filter(|l| l[0].y == l[1].y).collect();
assert_eq!(horizontal.len(), 1, "the break after row 10 is under the frozen rows: {lines:?}");
assert!(horizontal[0][0].y > pane_top);
let vertical: Vec<_> = lines.iter().filter(|l| l[0].x == l[1].x).collect();
assert_eq!(vertical.len(), 1);
let start = vertical[0][0].y;
assert!(start >= pane_top && start < pane_top + BREAK_DASH + BREAK_GAP, "starts below the frozen rows: {start} vs {pane_top}");
}
#[test]
fn page_break_at_freeze_boundary_stays_on_frozen_edge() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(200.0, 200.0));
let lines = page_break_lines(&sh, &geo, &[(0, 2)], &[(0, 1)], geo.cells);
assert!(lines.iter().any(|line| line[0].y == geo.cells.top() + geo.frozen_h && line[1].y == line[0].y));
assert!(lines.iter().any(|line| line[0].x == geo.cells.left() + geo.frozen_w && line[1].x == line[0].x));
}
#[test]
fn scrolled_past_print_extent_keeps_frozen_portion_of_breaks() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 1000.0)), vec2(2000.0, 2000.0));
let lines = page_break_lines(&sh, &geo, &[(0, 1), (2, 9)], &[(0, 0), (1, 9)], geo.cells);
assert!(lines.iter().any(|line| line[0].x == line[1].x && line[1].y >= geo.cells.top() + geo.frozen_h));
assert!(lines.iter().any(|line| line[0].y == line[1].y && line[1].x >= geo.cells.left() + geo.frozen_w));
}
/// A 100,000-row print extent scrolled to its middle: every line is cut to the visible cells
/// (a dashed line is one shape per dash), and the cut keeps the dash phase of the whole line.
#[test]
fn page_breaks_are_cut_to_the_visible_cells() {
let sh = Sheet::new("S");
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 50_001.0 * DEFAULT_ROW_HEIGHT));
let rows: Vec<(u32, u32)> = (0..2000).map(|i| (i * 50, i * 50 + 49)).collect();
let lines = page_break_lines(&sh, &geo, &rows, &[(0, 4), (5, 9)], geo.cells);
let horizontal = lines.iter().filter(|l| l[0].y == l[1].y).count();
assert!(horizontal > 0 && horizontal < 10, "only the breaks on screen: {horizontal}");
assert_eq!(lines.len() - horizontal, 2);
for l in &lines {
for pt in l {
assert!(geo.cells.expand(BREAK_DASH + BREAK_GAP).contains(*pt), "{pt:?} outside {:?}", geo.cells);
}
}
let full_top = geo.y(&sh, 0);
let vertical = lines.iter().find(|l| l[0].x == l[1].x).unwrap();
// 50,001 rows above at 16 px each put the view's top 1 px past a dash boundary of the whole
// line: the cut line starts at the next boundary, 4 px down (`max` would start it at the top).
assert!((vertical[0].y - (geo.cells.top() + 4.0)).abs() < 0.15, "{:?} vs {}", vertical[0], geo.cells.top());
let phase = (vertical[0].y - full_top) % (BREAK_DASH + BREAK_GAP);
assert!(phase.abs() < 0.15 || (BREAK_DASH + BREAK_GAP - phase).abs() < 0.15, "phase {phase}");
}
}
+1
View File
@@ -171,6 +171,7 @@ fn filter_menu_uses_the_table_whose_header_was_clicked() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut sh = Sheet::new("S");
sh.tables.push(table(1, 0, 2));
+2
View File
@@ -430,6 +430,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatizace",
"Table Design" => "Návrh tabulky",
"Chart Design" => "Návrh grafu",
"Pareto" => "Pareto",
"Cumulative %" => "Kumulativní %",
"Ready" => "Připraveno",
"Enter" => "Zadat",
"Edit" => "Úpravy",
+2
View File
@@ -447,6 +447,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatisieren",
"Table Design" => "Tabellenentwurf",
"Chart Design" => "Diagrammentwurf",
"Pareto" => "Pareto",
"Cumulative %" => "Kumuliert %",
"Ready" => "Bereit",
"Enter" => "Eingeben",
"Edit" => "Bearbeiten",
+2 -3
View File
@@ -393,6 +393,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Αυτοματισμός",
"Table Design" => "Σχεδίαση πίνακα",
"Chart Design" => "Σχεδίαση γραφήματος",
"Pareto" => "Παρέτο",
"Cumulative %" => "Αθροιστικό %",
"Ready" => "Έτοιμο",
"Enter" => "Εισαγωγή",
"Edit" => "Επεξεργασία",
@@ -572,7 +574,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Zoom Out" => "Σμίκρυνση",
"Dismiss" => "Κλείσιμο",
"OK" => "Εντάξει",
"Don't Save" => "Χωρίς αποθήκευση",
"Open…" => "Άνοιγμα…",
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
@@ -581,7 +582,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Βαθμολόγιο",
"this workbook" => "αυτό το βιβλίο εργασίας",
"This workbook" => "Αυτό το βιβλίο εργασίας",
"Do you want to save the changes you made to {title}?" => "Θέλετε να αποθηκεύσετε τις αλλαγές που κάνατε στο {title};",
"Save a copy as .{format}" => "Αποθήκευση αντιγράφου ως .{format}",
"Select a chart first." => "Επιλέξτε πρώτα ένα γράφημα.",
"Row Height" => "Ύψος γραμμής",
@@ -622,7 +622,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Τοποθέτηση εικόνας πάνω από κελιά",
"Pick From List" => "Επιλογή από λίστα",
"Save a Copy" => "Αποθήκευση αντιγράφου",
"Save Changes?" => "Αποθήκευση αλλαγών;",
"Shift cells right" => "Μετατόπιση κελιών προς τα δεξιά",
"Shift cells down" => "Μετατόπιση κελιών προς τα κάτω",
"Shift cells left" => "Μετατόπιση κελιών προς τα αριστερά",
+2
View File
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatizar",
"Table Design" => "Diseño de tabla",
"Chart Design" => "Diseño de gráfico",
"Pareto" => "Pareto",
"Cumulative %" => "% acumulado",
"Ready" => "Listo",
"Enter" => "Introducir",
"Edit" => "Modificar",
+2
View File
@@ -308,6 +308,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatiser",
"Table Design" => "Création de tableau",
"Chart Design" => "Création de graphique",
"Pareto" => "Pareto",
"Cumulative %" => "% cumulé",
"Ready" => "Prêt",
"Enter" => "Entrée",
"Edit" => "Modifier",
+2 -3
View File
@@ -292,6 +292,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatizza",
"Table Design" => "Progettazione tabella",
"Chart Design" => "Progettazione grafico",
"Pareto" => "Pareto",
"Cumulative %" => "% cumulativo",
"Ready" => "Pronto",
"Enter" => "Immetti",
"Edit" => "Modifica",
@@ -443,7 +445,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Le impostazioni di calcolo vengono salvate con la cartella di lavoro.",
"OK" => "OK",
"Cancel" => "Annulla",
"Don't Save" => "Non salvare",
"Open…" => "Apri…",
"Show password" => "Mostra password",
"Start a new workbook" => "Crea una nuova cartella di lavoro",
@@ -452,7 +453,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Registro dei voti",
"this workbook" => "questa cartella di lavoro",
"This workbook" => "Questa cartella di lavoro",
"Do you want to save the changes you made to {title}?" => "Vuoi salvare le modifiche apportate a {title}?",
"Save a copy as .{format}" => "Salva una copia come .{format}",
"Select a chart first." => "Seleziona prima un grafico.",
"Text Box" => "Casella di testo",
@@ -503,7 +503,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Inserisci immagine sopra le celle",
"Pick From List" => "Scegli dall'elenco",
"Save a Copy" => "Salva una copia",
"Save Changes?" => "Salvare le modifiche?",
"Shift cells right" => "Sposta celle a destra",
"Shift cells down" => "Sposta celle in basso",
"Shift cells left" => "Sposta celle a sinistra",
+2 -3
View File
@@ -299,6 +299,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Automate", "自動化"),
("Table Design", "テーブル デザイン"),
("Chart Design", "グラフ デザイン"),
("Pareto", "パレート図"),
("Cumulative %", "累積 %"),
("Ready", "準備完了"),
("Enter", "入力"),
("Edit", "編集"),
@@ -460,7 +462,6 @@ pub(super) const CORE: &[(&str, &str)] = &[
pub(super) const DIALOGS: &[(&str, &str)] = &[
("OK", "OK"),
("Cancel", "キャンセル"),
("Don't Save", "保存しない"),
("Open…", "開く…"),
("Show password", "パスワードの表示"),
("Start a new workbook", "新しいブックの作成"),
@@ -469,7 +470,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Gradebook", "成績表"),
("this workbook", "このブック"),
("This workbook", "このブック"),
("Do you want to save the changes you made to {title}?", "{title} への変更を保存しますか?"),
("Save a copy as .{format}", ".{format} としてコピーを保存"),
("Select a chart first.", "先にグラフを選択してください。"),
("Text Box", "テキスト ボックス"),
@@ -520,7 +520,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Place Picture over Cells", "セルの上に画像を配置"),
("Pick From List", "リストから選択"),
("Save a Copy", "コピーを保存"),
("Save Changes?", "変更を保存しますか?"),
("Shift cells right", "セルを右に移動"),
("Shift cells down", "セルを下に移動"),
("Shift cells left", "セルを左に移動"),
+2
View File
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "자동화",
"Table Design" => "표 디자인",
"Chart Design" => "차트 디자인",
"Pareto" => "파레토",
"Cumulative %" => "누적 %",
"Ready" => "준비",
"Enter" => "입력",
"Edit" => "편집",
+2
View File
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatiseren",
"Table Design" => "Tabelontwerp",
"Chart Design" => "Grafiekontwerp",
"Pareto" => "Pareto",
"Cumulative %" => "Cumulatief %",
"Ready" => "Gereed",
"Enter" => "Invoeren",
"Edit" => "Bewerken",
+2 -3
View File
@@ -286,6 +286,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatyzacja",
"Table Design" => "Projekt tabeli",
"Chart Design" => "Projekt wykresu",
"Pareto" => "Pareto",
"Cumulative %" => "Skumulowany %",
"Ready" => "Gotowy",
"Enter" => "Wprowadź",
"Edit" => "Edytuj",
@@ -434,7 +436,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Ustawienia obliczeń są zapisywane razem ze skoroszytem.",
"OK" => "OK",
"Cancel" => "Anuluj",
"Don't Save" => "Nie zapisuj",
"Open…" => "Otwórz…",
"Show password" => "Pokaż hasło",
"Start a new workbook" => "Utwórz nowy skoroszyt",
@@ -443,7 +444,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Dziennik ocen",
"this workbook" => "ten skoroszyt",
"This workbook" => "Ten skoroszyt",
"Do you want to save the changes you made to {title}?" => "Czy chcesz zapisać zmiany wprowadzone w pliku {title}?",
"Save a copy as .{format}" => "Zapisz kopię jako .{format}",
"Select a chart first." => "Najpierw zaznacz wykres.",
"Text Box" => "Pole tekstowe",
@@ -494,7 +494,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Umieść obraz na komórkach",
"Pick From List" => "Wybierz z listy",
"Save a Copy" => "Zapisz kopię",
"Save Changes?" => "Zapisać zmiany?",
"Shift cells right" => "Przesuń komórki w prawo",
"Shift cells down" => "Przesuń komórki w dół",
"Shift cells left" => "Przesuń komórki w lewo",
+2 -3
View File
@@ -464,7 +464,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.",
"OK" => "OK",
"Cancel" => "Cancelar",
"Don't Save" => "Não Salvar",
"Open…" => "Abrir…",
"Show password" => "Mostrar senha",
"Start a new workbook" => "Criar uma pasta de trabalho",
@@ -473,7 +472,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Boletim de Notas",
"this workbook" => "esta pasta de trabalho",
"This workbook" => "Esta pasta de trabalho",
"Do you want to save the changes you made to {title}?" => "Deseja salvar as alterações feitas em {title}?",
"Save a copy as .{format}" => "Salvar uma cópia como .{format}",
"Select a chart first." => "Selecione um gráfico primeiro.",
"Text Box" => "Caixa de Texto",
@@ -530,7 +528,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Colocar Imagem sobre as Células",
"Pick From List" => "Escolher na Lista",
"Save a Copy" => "Salvar uma Cópia",
"Save Changes?" => "Salvar Alterações?",
"Shift cells right" => "Deslocar células para a direita",
"Shift cells down" => "Deslocar células para baixo",
"Shift cells left" => "Deslocar células para a esquerda",
@@ -851,6 +848,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Scatter with Lines" => "Dispersão com Linhas",
"Radar" => "Radar",
"Histogram" => "Histograma",
"Pareto" => "Pareto",
"Cumulative %" => "% Acumulado",
"Waterfall" => "Cascata",
"Funnel" => "Funil",
"Combo" => "Combinação",
+2 -3
View File
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatizare",
"Table Design" => "Design tabel",
"Chart Design" => "Proiectare diagramă",
"Pareto" => "Pareto",
"Cumulative %" => "% cumulat",
"Ready" => "Gata",
"Enter" => "Enter",
"Edit" => "Editare",
@@ -440,7 +442,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Setările de calcul se salvează împreună cu registrul.",
"OK" => "OK",
"Cancel" => "Anulare",
"Don't Save" => "Nu salva",
"Open…" => "Deschidere…",
"Show password" => "Afișare parolă",
"Start a new workbook" => "Începeți un registru nou",
@@ -449,7 +450,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Catalog de note",
"this workbook" => "acest registru",
"This workbook" => "Acest registru",
"Do you want to save the changes you made to {title}?" => "Doriți să salvați modificările făcute în {title}?",
"Save a copy as .{format}" => "Salvare copie ca .{format}",
"Select a chart first." => "Selectați mai întâi o diagramă.",
"Text Box" => "Casetă de text",
@@ -500,7 +500,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Plasare imagine peste celule",
"Pick From List" => "Alegere din listă",
"Save a Copy" => "Salvare copie",
"Save Changes?" => "Salvați modificările?",
"Shift cells right" => "Deplasare celule la dreapta",
"Shift cells down" => "Deplasare celule în jos",
"Shift cells left" => "Deplasare celule la stânga",
+2 -3
View File
@@ -295,6 +295,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Автоматизация",
"Table Design" => "Конструктор таблиц",
"Chart Design" => "Конструктор диаграмм",
"Pareto" => "Парето",
"Cumulative %" => "Накопленный %",
"Ready" => "Готово",
"Enter" => "Ввод",
"Edit" => "Изменение",
@@ -597,8 +599,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Display:" => "Отображать:",
"Distributed" => "Распределённый",
"Divide" => "Разделить",
"Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?",
"Don't Save" => "Не сохранять",
"Double" => "Двойное",
"Double Accounting" => "Двойное бухгалтерское",
"Doughnut" => "Кольцевая",
@@ -844,7 +844,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Rows" => "Строки",
"Sample" => "Выборка",
"Save (⌘S)" => "Сохранить (⌘S)",
"Save Changes?" => "Сохранить изменения?",
"Save a Copy" => "Сохранить копию",
"Save a copy as .{format}" => "Сохранить копию как .{format}",
"Scatter" => "Точечная",
+2
View File
@@ -298,6 +298,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Automatizacija",
"Table Design" => "Dizajn tabele",
"Chart Design" => "Dizajn grafikona",
"Pareto" => "Pareto",
"Cumulative %" => "Kumulativno %",
"Ready" => "Spremno",
"Enter" => "Unos",
"Edit" => "Uređivanje",
+2
View File
@@ -407,6 +407,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Otomatikleştir",
"Table Design" => "Tablo Tasarımı",
"Chart Design" => "Grafik Tasarımı",
"Pareto" => "Pareto",
"Cumulative %" => "Kümülatif %",
"Ready" => "Hazır",
"Enter" => "Giriş",
"Edit" => "Düzenle",
+2 -3
View File
@@ -288,6 +288,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Автоматизація",
"Table Design" => "Конструктор таблиць",
"Chart Design" => "Конструктор діаграм",
"Pareto" => "Парето",
"Cumulative %" => "Накопичений %",
"Ready" => "Готово",
"Enter" => "Ввід",
"Edit" => "Редагування",
@@ -438,7 +440,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Параметри обчислень зберігаються разом із книгою.",
"OK" => "OK",
"Cancel" => "Cancel",
"Don't Save" => "Don't Save",
"Open…" => "Open…",
"Show password" => "Show password",
"Start a new workbook" => "Start a new workbook",
@@ -447,7 +448,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Gradebook",
"this workbook" => "this workbook",
"This workbook" => "This workbook",
"Do you want to save the changes you made to {title}?" => "Do you want to save the changes you made to {title}?",
"Save a copy as .{format}" => "Save a copy as .{format}",
"Select a chart first." => "Спочатку виділіть діаграму.",
"Text Box" => "Напис",
@@ -498,7 +498,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Place Picture over Cells",
"Pick From List" => "Pick From List",
"Save a Copy" => "Save a Copy",
"Save Changes?" => "Save Changes?",
"Shift cells right" => "Shift cells right",
"Shift cells down" => "Shift cells down",
"Shift cells left" => "Shift cells left",
+2 -3
View File
@@ -301,6 +301,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Tự động hóa",
"Table Design" => "Thiết kế bảng",
"Chart Design" => "Thiết kế biểu đồ",
"Pareto" => "Pareto",
"Cumulative %" => "% tích lũy",
"Ready" => "Sẵn sàng",
"Enter" => "Nhập",
"Edit" => "Sửa",
@@ -448,7 +450,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
// Dialogs, menus, context menus and tooltips.
"OK" => "OK",
"Cancel" => "Hủy",
"Don't Save" => "Không lưu",
"Open…" => "Mở…",
"Show password" => "Hiện mật khẩu",
"Start a new workbook" => "Bắt đầu sổ làm việc mới",
@@ -457,7 +458,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Sổ điểm",
"this workbook" => "sổ làm việc này",
"This workbook" => "Sổ làm việc này",
"Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?",
"Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}",
"Select a chart first." => "Hãy chọn một biểu đồ trước.",
"Text Box" => "Hộp văn bản",
@@ -508,7 +508,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Đặt ảnh đè lên các ô",
"Pick From List" => "Chọn từ danh sách",
"Save a Copy" => "Lưu bản sao",
"Save Changes?" => "Lưu thay đổi?",
"Shift cells right" => "Dịch các ô sang phải",
"Shift cells down" => "Dịch các ô xuống dưới",
"Shift cells left" => "Dịch các ô sang trái",
+2
View File
@@ -293,6 +293,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "自动化",
"Table Design" => "表格设计",
"Chart Design" => "图表设计",
"Pareto" => "排列图",
"Cumulative %" => "累积百分比",
"Ready" => "就绪",
"Enter" => "输入",
"Edit" => "编辑",
+4 -2
View File
@@ -362,9 +362,11 @@ pub struct SheetApp {
/// The update check, the startup prompt and a running self-update (desktop only).
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime,
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
/// after GridCraft's own UI in the root window's pass.
/// The framework dialogs GridCraft keeps as values (the update dialogs and the unsaved-changes
/// prompt), run once per frame after GridCraft's own UI in the root window's pass.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Which workbook and window the open `UnsavedChangesDialog` is asking about.
pub unsaved_prompt: Option<state::UnsavedPrompt>,
/// Who GridCraft is to the framework's dialogs.
framework_host: std::sync::Arc<craft_host::Host>,
}
+18 -21
View File
@@ -18,6 +18,8 @@
use std::collections::BTreeMap;
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::UnsavedChangesDialog;
use egui::{Color32, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::macros::policy::{Policy, macro_policy};
@@ -1100,7 +1102,7 @@ fn ref_edit(app: &SheetApp, ui: &mut Ui, d: &mut Dialog, refs: &mut RefPick, key
d.values.insert(key.into(), json!(s));
}
/// Keep changes? (stopping a debugged run) and Save changes? (closing with unsaved edits).
/// Keep changes? (stopping a debugged run) and the unsaved-changes question (closing with unsaved edits).
fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut bool) {
if ed.ask_stop {
let mut answer: Option<Option<bool>> = None;
@@ -1141,25 +1143,20 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
return;
}
if ed.ask_close {
let mut answer: Option<Option<bool>> = None;
egui::Modal::new(Id::unique("gridcraft.macro_editor.close")).show(ctx, |ui| {
ui.set_width(360.0);
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
answer = Some(None);
}
if ui.button("Don't Save").clicked() {
answer = Some(Some(false));
}
if ui.button("Save").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
answer = Some(Some(true));
}
});
});
// The shared unsaved-changes question, named for the macro. Each asking gets its own area,
// so the question's own open state starts open every time it is asked.
let scope = if ed.quit { CloseScope::Quit } else { CloseScope::Close };
let asked = Id::unique("gridcraft.macro_editor.close");
let opening = ctx.data(|d| d.get_temp::<u64>(asked)).unwrap_or_default();
let shown = egui::Area::new(asked.with(opening))
.order(egui::Order::Foreground)
.show(ctx, |ui| UnsavedChangesDialog::new(scope, ed.draft.name.clone()).document_wording(true).show(ui));
let answer = shown.inner.answer.map(|a| a.answer);
if answer.is_some() {
ctx.data_mut(|d| d.insert_temp(asked, opening + 1));
}
match answer {
Some(Some(true)) => {
Some(CloseAnswer::Save) => {
ed.ask_close = false;
if save(app, ed) {
*open = false;
@@ -1170,11 +1167,11 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
ed.quit = false;
}
}
Some(Some(false)) => {
Some(CloseAnswer::DontSave) => {
ed.ask_close = false;
*open = false;
}
Some(None) => {
Some(CloseAnswer::Cancel) => {
ed.ask_close = false;
ed.quit = false;
ed.then_close = None;
+1
View File
@@ -205,6 +205,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
("Doughnut", "doughnut", ""),
("Scatter", "scatter", ""),
("Radar", "radar", ""),
("Pareto", "pareto", ""),
] {
let cur = chart.kind == gridcraft_engine::cmd::insert::chart_kind(k, s);
if ui.selectable_label(cur, l).clicked() {

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