Compare commits

..
Author SHA1 Message Date
dependabot[bot] 1e7026305a ci(deps): bump step-security/harden-runner
Bumps the actions group with 1 update in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/v2.22.4...v2.23.0)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-12-04 11:05:44 +00: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
FredApps 9b15f7b3d7 Merge main for Gentoo package documentation 2026-12-04 11:29:33 +01:00
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
126 changed files with 8327 additions and 2161 deletions
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
old=8fa4db64a9bb943520259ea95331a303ba788f21
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$GRID_FRAMEWORK/g"
cargo metadata --locked --format-version 1 > "$RUNNER_TEMP/gridcraft-queue-paper-graph.json"
python - "$RUNNER_TEMP/gridcraft-queue-paper-graph.json" "$GRID_FRAMEWORK" <<'PY'
import json
import sys
graph = json.load(open(sys.argv[1], encoding="utf-8-sig"))
for crate in ("craft-print", "craft-pages"):
package, = [p for p in graph["packages"] if p["name"] == crate]
assert package["source"].endswith("#" + sys.argv[2]), (crate, package["source"])
PY
-79
View File
@@ -1,79 +0,0 @@
param([Parameter(Mandatory)][string]$Binary)
$ErrorActionPreference = 'Stop'
if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_OS -ne 'Windows' -or $env:RUNNER_ENVIRONMENT -ne 'github-hosted') {
throw 'This capture uses the spooler of a disposable hosted Windows machine.'
}
$Binary = (Resolve-Path -LiteralPath $Binary).Path
$driver = 'Microsoft Print to PDF'
$feature = 'Printing-PrintToPDFServices-Features'
Set-Service Spooler -StartupType Manual
Start-Service Spooler
if (-not (Get-PrinterDriver -Name $driver -ErrorAction SilentlyContinue)) {
$current = Get-WindowsOptionalFeature -Online -FeatureName $feature
if ($current.State -ne 'Enabled') {
$change = Enable-WindowsOptionalFeature -Online -FeatureName $feature -NoRestart
if ($change.RestartNeeded) { throw 'The inbox Print to PDF feature requires a restart.' }
}
if (-not (Get-PrinterDriver -Name $driver -ErrorAction SilentlyContinue)) {
Add-PrinterDriver -Name $driver
}
}
$installed = Get-PrinterDriver -Name $driver
$installed | Select-Object Name, Manufacturer, MajorVersion |
ConvertTo-Json | Write-Output
$tag = [Guid]::NewGuid().ToString('N')
$env:GRIDCRAFT_WINDOWS_PRINT_TEST = $tag
$output = New-Item -ItemType Directory -Path (Join-Path $PWD 'gridcraft-windows-paper-output')
$queues = @{}
$ports = @{}
try {
foreach ($case in 'a4', 'legal') {
$name = "GridCraft QA $tag $case"
$port = Join-Path $output.FullName "$case.pdf"
if ((Test-Path -LiteralPath $port) -or (Get-Printer -Name $name -ErrorAction SilentlyContinue)) {
throw 'The private destination already exists.'
}
Add-PrinterPort -Name $port
$ports[$case] = $port
Add-Printer -Name $name -DriverName $driver -PortName $port
$queues[$case] = $name
$queue = Get-Printer -Name $name
if ($queue.PortName -ne $port -or $queue.Shared -or $queue.DriverName -ne $driver) {
throw 'The queue is not bound exclusively to the private file port and expected driver.'
}
Set-PrintConfiguration -PrinterName $name -PaperSize Letter
if ((Get-PrintConfiguration -PrinterName $name).PaperSize -ne 'Letter') {
throw 'Both private queues must start with Letter as their default.'
}
if (Get-PrintJob -PrinterName $name) { throw 'The new private queue is not empty.' }
}
$log = Join-Path $output.FullName 'gridcraft.log'
& $Binary --exact print::windows_paper_qa::file_print_switches_windows_stock_and_only_prints_the_visible_worksheet_selection --nocapture |
Tee-Object -FilePath $log
if ($LASTEXITCODE) { throw "GridCraft native test failed with status $LASTEXITCODE." }
foreach ($case in 'a4', 'legal') {
if (@(Select-String -LiteralPath $log -Pattern "^WINDOWS_GRIDCRAFT_RECEIPT $case ").Count -ne 1) {
throw "Expected exactly one successful native receipt for $case."
}
$deadline = (Get-Date).AddSeconds(60)
do {
$file = Get-Item -LiteralPath $ports[$case] -ErrorAction SilentlyContinue
if ($file.Length -gt 0 -and -not (Get-PrintJob -PrinterName $queues[$case])) { break }
if ((Get-Date) -gt $deadline) { throw "Timed out waiting for $case PDF output." }
Start-Sleep -Seconds 1
} while ($true)
Get-FileHash -LiteralPath $file.FullName | Format-List
}
} finally {
foreach ($name in $queues.Values) {
try { Remove-Printer -Name $name } catch { Write-Warning "Could not remove private queue: $_" }
}
foreach ($path in $ports.Values) {
try {
$port = Get-PrinterPort | Where-Object Name -eq $path
if ($port) { Remove-PrinterPort -InputObject $port }
} catch { Write-Warning "Could not remove private file port on disposable runner: $_" }
}
}
-29
View File
@@ -1,29 +0,0 @@
"""Verify the document printed by Windows, including rendered text."""
import pathlib
import re
import subprocess
import sys
root = pathlib.Path(sys.argv[1])
markers = {"AUTUMN LANTERN", "WINTER ANCHOR", "EXCLUDED ORCHARD"}
for case, width, height, expected in (
("a4", 595.28, 841.89, "AUTUMN LANTERN"),
("legal", 612, 1008, "WINTER ANCHOR"),
):
pdf = root / f"{case}.pdf"
info = subprocess.check_output(["pdfinfo", str(pdf)], text=True)
assert re.search(r"^Pages:\s+1$", info, re.M), info
size = re.search(r"^Page size:\s+([0-9.]+) x ([0-9.]+) pts", info, re.M)
assert size, info
actual_width, actual_height = map(float, size.groups())
assert abs(actual_width - width) < 1 and abs(actual_height - height) < 1, info
text_layer = subprocess.check_output(["pdftotext", "-layout", str(pdf), "-"], text=True)
assert " ".join(text_layer.split()) == expected, (case, text_layer)
prefix = root / case
subprocess.run(["pdftoppm", "-r", "300", "-gray", "-singlefile", "-png", str(pdf), str(prefix)], check=True)
text = subprocess.check_output(["tesseract", f"{prefix}.png", "stdout", "--psm", "6"], text=True)
(root / f"{case}.ocr.txt").write_text(text, encoding="utf-8")
recognized = " ".join(text.upper().split())
assert expected in recognized, (case, text)
assert not any(other in recognized for other in markers - {expected}), (case, text)
print(f"{case}: one {actual_width:g} x {actual_height:g} pt sheet with {expected!r} and no other marker")
-65
View File
@@ -1,65 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
shared=shared-print/crates/print/examples/print_acceptance/cups_capture.sh
anchor='timeout 20s "$harness" list | tee "$results/discovery.log"'
grep -Fxq "$anchor" "$shared"
awk -v anchor="$anchor" '$0 == anchor { exit } { print }' "$shared" >"$RUNNER_TEMP/gridcraft-cups-setup.sh"
source "$RUNNER_TEMP/gridcraft-cups-setup.sh" "$1" "$PWD/gridcraft-print-output"
timeout 20s lpadmin -h "$CUPS_SERVER" -d "$queue"
test -z "$(timeout 10s lpstat -W all -o "$queue")"
# Give the private printer distinct names with the same Legal geometry. The
# size suffix lets the shared catalog interpret lpoptions on a private socket,
# where it deliberately does not read the host system's PPD directory.
awk '
{ print }
/^\*(PageSize|PageRegion|ImageableArea|PaperDimension) Legal([/:])/ {
left = right = $0
sub(/ Legal[^:]*:/, " qa_left_8.5x14in/Legal left feed:", left)
sub(/ Legal[^:]*:/, " qa_right_8.5x14in/Legal right feed:", right)
print left
print right
}
' "$work/capture.ppd" >"$work/equal-forms.ppd"
for key in qa_left_8.5x14in qa_right_8.5x14in; do
grep -Eq "^\*PaperDimension $key[/:]" "$work/equal-forms.ppd"
done
timeout 20s lpadmin -h "$CUPS_SERVER" -p "$queue" -P "$work/equal-forms.ppd"
for key in qa_left_8.5x14in qa_right_8.5x14in; do
case_dir="$results/$key"
mkdir "$case_dir"
sudo -n test ! -e "$capture"
sudo -n install -m 0600 /dev/null "$capture"
offset=$(wc -l <"$results/scheduler.log")
GRIDCRAFT_PRIVATE_CUPS=1 GRIDCRAFT_TEST_PAPER="$key" timeout 90s "$harness" \
--test-threads=1 --nocapture selected_queue_legal_paper_and_page_range_reach_the_private_cups_file | tee "$case_dir/app.log"
mapfile -t receipts < <(sed -nE 's/^.*GRIDCRAFT_RECEIPT=.*(craft-print-capture-[0-9]+).*$/\1/p' "$case_dir/app.log")
[[ ${#receipts[@]} == 1 ]]
job_id=${receipts[0]}
echo "$job_id" >>"$results/receipts.txt"
for elapsed in {1..60}; do
timeout 10s lpstat -W completed -o "$queue" >"$case_dir/completed-jobs.log"
if awk -v id="$job_id" '$1 == id { seen=1 } END { exit !seen }' "$case_dir/completed-jobs.log" && sudo -n test -s "$capture"; then
sudo -n cat -- "$capture" >"$case_dir/captured.pdf"
sudo -n rm -- "$capture"
break
fi
sleep 1
done
tail -n "+$((offset + 1))" "$results/scheduler.log" >"$case_dir/ipp.log"
grep -F 'cupsdProcessIPPRequest: media ' "$case_dir/ipp.log" | grep -Fq "'$key'"
pdfinfo "$case_dir/captured.pdf" >"$case_dir/captured.pdfinfo"
pdftotext -layout "$case_dir/captured.pdf" "$case_dir/captured.txt"
grep -Eq '^Pages: +1$' "$case_dir/captured.pdfinfo"
grep -Eq '^Page size: +612 x 1008 pts' "$case_dir/captured.pdfinfo"
grep -Fq 'Paper form selected page' "$case_dir/captured.txt"
if grep -Fq 'Paper form first page' "$case_dir/captured.txt"; then
echo "The unselected worksheet page was printed" >&2
exit 1
fi
echo "Verified $key in the scheduler request, one Legal sheet and only the selected worksheet page from $job_id"
done
timeout 10s lpstat -W all -o "$queue" >"$results/all-jobs.log"
diff -u <(sort "$results/receipts.txt") <(awk '{print $1}' "$results/all-jobs.log" | sort)
+5 -5
View File
@@ -8,7 +8,7 @@ workflows:
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/nightly-dispatch.yml': []
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
@@ -16,7 +16,7 @@ workflows:
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
@@ -26,8 +26,8 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/[email protected]2.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
'step-security/[email protected]3.0':
ref: 'v2.23.0'
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
owner_id: 88700172
repo_id: 422287306
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+2 -2
View File
@@ -30,7 +30,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
@@ -47,7 +47,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
@@ -1,114 +0,0 @@
name: GridCraft Windows queue paper capture
on:
push:
branches: [verify/gridcraft-windows-queue-paper-4859]
workflow_dispatch:
inputs:
build_run:
description: Reuse the compiled test from this run ID
required: false
build_sha256:
description: Expected SHA-256 for a reused test binary
required: false
permissions:
actions: read
contents: read
env:
GRID_FRAMEWORK: 6992dba3069ff7342bb81efb40d657e81ee37ca8
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_INCREMENTAL: '0'
CRAFT_FONTS_REQUIRED: '1'
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
jobs:
build:
if: inputs.build_run == ''
runs-on: windows-2025
timeout-minutes: 90
outputs:
sha256: ${{ steps.binary.outputs.sha256 }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- name: Apply exact app framework baseline plus catalog and range code
shell: bash
run: bash .github/qa/queue-paper-overlay.sh
- name: Build the GridCraft Windows binary with the real File Print test
id: binary
shell: pwsh
run: |
$buildLog = Join-Path $env:RUNNER_TEMP 'gridcraft-build.jsonl'
cargo test --locked -p gridcraft --bin gridcraft --no-run --message-format json > $buildLog
if ($LASTEXITCODE) { exit $LASTEXITCODE }
$binary = Select-String -LiteralPath $buildLog -SimpleMatch '"executable":"' |
ForEach-Object { $_.Line | ConvertFrom-Json } |
Where-Object { $_.reason -eq 'compiler-artifact' -and $_.profile.test -and $_.target.name -eq 'gridcraft' } |
Select-Object -ExpandProperty executable
if (@($binary).Count -ne 1) { throw 'Expected one native GridCraft test binary.' }
Copy-Item -LiteralPath $binary -Destination gridcraft-paper-test.exe
$sha = (Get-FileHash -LiteralPath gridcraft-paper-test.exe).Hash
"sha256=$sha" >> $env:GITHUB_OUTPUT
"Native test SHA-256 $sha"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
name: gridcraft-windows-paper-test
path: gridcraft-paper-test.exe
if-no-files-found: error
capture:
if: always() && (needs.build.result == 'success' || (needs.build.result == 'skipped' && inputs.build_run != ''))
needs: build
runs-on: windows-2025
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
with:
name: gridcraft-windows-paper-test
path: native-test
github-token: ${{ github.token }}
run-id: ${{ inputs.build_run || github.run_id }}
- name: Submit from File Print to private Windows PDF queues
shell: pwsh
env:
BUILD_SHA256: ${{ inputs.build_sha256 || needs.build.outputs.sha256 }}
run: |
$binary = 'native-test/gridcraft-paper-test.exe'
if ((Get-FileHash -LiteralPath $binary).Hash -ne $env:BUILD_SHA256) {
throw 'The downloaded test binary does not match the recorded SHA-256.'
}
.github/qa/verify-queue-paper-windows.ps1 -Binary $binary
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: gridcraft-windows-paper-capture
path: gridcraft-windows-paper-output/
if-no-files-found: warn
verify:
needs: capture
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
with:
name: gridcraft-windows-paper-capture
path: gridcraft-windows-paper-output
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: poppler-utils tesseract-ocr
- name: Independently measure and render the Windows output
run: python3 .github/qa/verify-queue-paper-windows.py gridcraft-windows-paper-output
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: gridcraft-windows-paper-verified
path: gridcraft-windows-paper-output/
if-no-files-found: error
-82
View File
@@ -1,82 +0,0 @@
name: GridCraft queue paper and range
on:
push:
branches: [verify/gridcraft-queue-paper-4859]
permissions:
contents: read
env:
GRID_FRAMEWORK: 6992dba3069ff7342bb81efb40d657e81ee37ca8
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_INCREMENTAL: '0'
CRAFT_FONTS_REQUIRED: '1'
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
jobs:
linux:
runs-on: ubuntu-24.04
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: fa63a22393bb03f40e33accbffa67c51465ee327
path: shared-print
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev
libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev
xvfb xauth cups-daemon cups-client cups-filters poppler-utils
- name: Apply the exact app framework baseline plus the staged catalog and range code
run: bash .github/qa/queue-paper-overlay.sh
- name: Check that the selected paper reflows workbook layout
if: "!contains(github.event.head_commit.message, '[linux only]')"
run: cargo test --locked -p gridcraft-engine --lib job_paper_override
- name: Exercise the paper, preview, range and retry regressions
run: xvfb-run -a cargo test --locked -p gridcraft-ui-egui --test it --test print_selection -- queue_papers the_print_views_page_fields_set_the_range_and_the_preview_follows print_selection_previews refused_browser_handoff --test-threads=1
- name: Build the real native submit path and capture its output
run: |
set -euo pipefail
cargo test --locked -p gridcraft --bin gridcraft --no-run --message-format json > "$RUNNER_TEMP/gridcraft-build.jsonl"
binary=$(jq -er 'select(.reason == "compiler-artifact" and .profile.test and .target.name == "gridcraft" and .executable) | .executable' "$RUNNER_TEMP/gridcraft-build.jsonl")
echo "GRIDCRAFT_QA_BINARY=$binary" >> "$GITHUB_ENV"
bash .github/qa/verify-queue-paper.sh "$binary"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: failure() && env.GRIDCRAFT_QA_BINARY != ''
with:
name: gridcraft-compiled-cups-test
path: ${{ env.GRIDCRAFT_QA_BINARY }}
retention-days: 3
if-no-files-found: error
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: gridcraft-queue-paper-output
path: gridcraft-print-output/
if-no-files-found: warn
windows:
if: "!contains(github.event.head_commit.message, '[linux only]')"
runs-on: windows-2025
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- name: Apply the exact app framework baseline plus the staged catalog and range code
shell: bash
run: bash .github/qa/queue-paper-overlay.sh
- name: Check the real Windows adapter against the shared forms API
shell: bash
run: |
set -euo pipefail
cargo check --locked -p gridcraft --bin gridcraft
Generated
-20
View File
@@ -1281,16 +1281,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-text",
"kurbo",
"serde",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -1416,14 +1406,6 @@ dependencies = [
"vectorcraft-pathops",
]
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"serde",
]
[[package]]
name = "craft-theme"
version = "0.1.0"
@@ -2876,7 +2858,6 @@ dependencies = [
"craft-update",
"eframe",
"egui",
"egui_kittest",
"fmv-macos-events",
"getrandom 0.4.3",
"gridcraft-engine",
@@ -2960,7 +2941,6 @@ version = "0.20.0"
dependencies = [
"craft-csv",
"craft-gridcraft-format",
"craft-pages",
"gridcraft-calc",
"gridcraft-chart",
"gridcraft-core",
-1
View File
@@ -44,7 +44,6 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pages = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
+27
View File
@@ -275,6 +275,33 @@ 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
| Build | File |
-3
View File
@@ -21,9 +21,6 @@ log = { workspace = true }
image = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
egui_kittest = { workspace = true }
[build-dependencies]
# Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows.
winresource = "0.1"
-1
View File
@@ -231,7 +231,6 @@ fn services() -> Services {
})),
open_url: Some(Box::new(|url: &str| open_with_system(url))),
printers: Some(print::discover()),
printer_papers: Some(print::discover_papers()),
print_native: Some(print::submit()),
..Default::default()
}
+3 -120
View File
@@ -1,8 +1,5 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Destination, Discover, DiscoverPapers, Duplex, Paper, Printer, Settings, Submit};
#[cfg(all(test, windows))]
mod windows_paper_qa;
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
pub fn discover() -> Discover {
@@ -16,45 +13,6 @@ pub fn discover() -> Discover {
})
}
pub fn discover_papers() -> DiscoverPapers {
Box::new(|queue| {
let queue = queue.to_owned();
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-paper-discovery".into()).spawn(move || {
let _ = sender.send(papers(&queue));
});
receiver
})
}
#[cfg(windows)]
fn papers(queue: &str) -> Vec<Paper> {
craft_print::printer_papers(queue)
.into_iter()
.map(|form| Paper {
id: format!("{}x{}:{}", form.width, form.height, form.name),
name: form.name,
width: form.width,
height: form.height,
cups_media: None,
})
.collect()
}
#[cfg(unix)]
fn papers(queue: &str) -> Vec<Paper> {
craft_print::cups::media_catalog(queue)
.sizes
.into_iter()
.map(|size| Paper { id: size.key.clone(), name: size.label, width: size.width, height: size.height, cups_media: Some(size.key) })
.collect()
}
#[cfg(not(any(windows, unix)))]
fn papers(_queue: &str) -> Vec<Paper> {
Vec::new()
}
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
// let process exit kill PowerShell/CUPS before it hands the job to the spooler.
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
@@ -69,7 +27,7 @@ pub fn finish_pending_jobs() {
}
pub fn submit() -> Submit {
Box::new(|bytes, settings: Settings, paper| {
Box::new(|bytes, settings: Settings| {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
@@ -86,8 +44,7 @@ pub fn submit() -> Submit {
_ => None,
}),
grayscale: settings.grayscale,
scaling: if paper.is_some() { craft_print::Scaling::Exact } else { craft_print::Scaling::ShrinkToFit },
options: paper.and_then(|choice| choice.cups_media).into_iter().map(|key| ("media".into(), key)).collect(),
scaling: craft_print::Scaling::ShrinkToFit,
title: "GridCraft document".into(),
..Default::default()
};
@@ -122,77 +79,3 @@ mod tests {
assert!(JOBS.lock().unwrap().is_empty(), "workers were joined before shutdown returned");
}
}
#[cfg(all(test, target_os = "linux"))]
mod cups_paper_qa {
use super::*;
use std::{
os::unix::fs::FileTypeExt as _,
path::PathBuf,
thread::sleep,
time::{Duration, Instant},
};
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
#[test]
fn selected_queue_legal_paper_and_page_range_reach_the_private_cups_file() {
if std::env::var("GRIDCRAFT_PRIVATE_CUPS").as_deref() != Ok("1") {
return;
}
let socket = PathBuf::from(std::env::var_os("CUPS_SERVER").unwrap());
assert!(socket.starts_with("/run/cups") || socket.starts_with("/var/spool/cups"));
assert!(socket.ends_with("socket/cups.sock"));
assert!(socket.parent().unwrap().parent().unwrap().file_name().unwrap().to_string_lossy().starts_with("craft-print-acceptance."));
assert!(std::fs::metadata(socket).unwrap().file_type().is_socket());
let queue = "craft-print-capture";
let requested_paper = std::env::var("GRIDCRAFT_TEST_PAPER").unwrap();
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = SheetApp::new(
session,
Services { printers: Some(discover()), printer_papers: Some(discover_papers()), print_native: Some(submit()), ..Default::default() },
);
app.run("cell.set", json!({"cell":"A1","input":"Paper form first page"})).unwrap();
app.run("cell.set", json!({"cell":"A20","input":"Paper form selected page"})).unwrap();
app.run("pageLayout.pageSetup", json!({"paper":"Letter","rowBreaks":[10]})).unwrap();
app.run("ui.printSettings", json!({"refresh":true})).unwrap();
let ctx = egui::Context::default();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
app.poll_printing(&ctx);
let settings = app.run("ui.printSettings", json!({})).unwrap();
if settings["printer"] == queue && settings["papersLoading"] == false {
let papers = settings["papers"].as_array().unwrap();
let left = papers.iter().find(|paper| paper["id"] == "qa_left_8.5x14in").expect("left-feed form");
let right = papers.iter().find(|paper| paper["id"] == "qa_right_8.5x14in").expect("right-feed form");
assert_ne!(left["name"], right["name"]);
for paper in [left, right] {
assert!((paper["width"].as_f64().unwrap() - 612.0).abs() < 1.0);
assert!((paper["height"].as_f64().unwrap() - 1008.0).abs() < 1.0);
}
break;
}
assert!(Instant::now() < deadline, "Legal was not discovered on the private queue: {settings}");
sleep(Duration::from_millis(40));
}
let picked = app.run("ui.printSettings", json!({"printer":queue,"paper":requested_paper,"from":2,"to":2})).unwrap();
assert_eq!(picked["paper"], requested_paper);
app.run("ui.printSubmit", json!({})).unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
app.poll_printing(&ctx);
let settings = app.run("ui.printSettings", json!({})).unwrap();
if !app.printing.busy() {
assert_eq!(settings["status"], "submitted", "{settings}");
println!("GRIDCRAFT_RECEIPT={}", settings["detail"].as_str().unwrap());
break;
}
assert!(Instant::now() < deadline, "the print submission did not finish");
sleep(Duration::from_millis(40));
}
let preview = app.run("file.printPreview", json!({})).unwrap();
assert_eq!(preview["pageList"][0]["height"], 792.0);
}
}
@@ -1,92 +0,0 @@
//! QA-only native File > Print check using a synthetic workbook and two disposable file queues.
use egui::accesskit::Role;
use egui_kittest::{Harness, kittest::Queryable as _};
use gridcraft_engine::Session;
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::{Value, json};
use std::thread::sleep;
use std::time::{Duration, Instant};
fn until(harness: &mut Harness<'_, SheetApp>, ready: impl Fn(&Value) -> bool) -> Value {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
harness.run_steps(1);
let settings = harness.state_mut().run("ui.printSettings", json!({})).unwrap();
if ready(&settings) {
return settings;
}
assert!(Instant::now() < deadline, "Print did not reach the expected state: {settings}");
sleep(Duration::from_millis(40));
}
}
#[test]
fn file_print_switches_windows_stock_and_only_prints_the_visible_worksheet_selection() {
let Ok(tag) = std::env::var("GRIDCRAFT_WINDOWS_PRINT_TEST") else {
return;
};
assert_eq!(tag.len(), 32);
assert!(tag.bytes().all(|byte| byte.is_ascii_hexdigit()));
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(
session,
Services {
printers: Some(super::discover()),
printer_papers: Some(super::discover_papers()),
print_native: Some(super::submit()),
..Default::default()
},
);
for (cell, text) in [("A1", "AUTUMN LANTERN"), ("D4", "WINTER ANCHOR"), ("H20", "EXCLUDED ORCHARD")] {
app.run("cell.set", json!({"cell": cell, "input": text})).unwrap();
}
// Keep each marker inside its own cell. A print selection clips text at its range boundary.
for column in ["A:A", "D:D", "H:H"] {
app.run("home.columnWidth", json!({"cols":column,"width":200})).unwrap();
}
app.run("pageLayout.pageSetup", json!({"paper":"Letter","printArea":"F10:H20"})).unwrap();
app.run("ui.backstage", json!({"page":"print"})).unwrap();
app.run("ui.printSettings", json!({"refresh":true})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1280.0, 960.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
harness.run_steps(4);
assert!(harness.query_by_label("Sheet1 · F10:H20").is_some());
harness.query_by_label("Print What").or_else(|| harness.query_by_label("Print Active Sheets")).expect("print scope dropdown").click();
harness.run_steps(3);
harness.get_by_label("Print Selection").click();
harness.run_steps(4);
for (case, width, height, range) in [("a4", 595.28, 841.89, "A1:B2"), ("legal", 612.0, 1008.0, "D4:E5")] {
let queue = format!("GridCraft QA {tag} {case}");
until(&mut harness, |settings| settings["printers"].as_array().unwrap().iter().any(|printer| printer["name"] == queue));
let reset = harness.state_mut().run("ui.printSettings", json!({"printer":queue})).unwrap();
assert!(reset["paper"].is_null(), "switching queues resets the previous paper: {reset}");
let catalog = until(&mut harness, |settings| settings["papersLoading"] == false && !settings["papers"].as_array().unwrap().is_empty());
let paper = catalog["papers"]
.as_array()
.unwrap()
.iter()
.find(|paper| (paper["width"].as_f64().unwrap() - width).abs() < 1.0 && (paper["height"].as_f64().unwrap() - height).abs() < 1.0)
.expect("the private queue must advertise the stock in real PrintCapabilities");
let picked = harness.state_mut().run("ui.printSettings", json!({"paper":paper["id"]})).unwrap();
assert_eq!(picked["paper"], paper["id"]);
harness.state_mut().run("selection.set", json!({"range":range})).unwrap();
harness.run_steps(4);
assert!(harness.query_by_label(format!("Sheet1 · {range}").as_str()).is_some());
assert!(harness.query_by_label("Sheet1 · F10:H20").is_none());
harness.get_all_by_role_and_label(Role::Button, "Print").last().expect("File > Print button").click();
let result = until(&mut harness, |settings| matches!(settings["status"].as_str(), Some("submitted" | "failed" | "workerStopped")));
assert_eq!(result["status"], "submitted", "{case}: {result}");
assert_eq!(result["detail"], "spooled 1 sheet(s)", "{case}: {result}");
println!("WINDOWS_GRIDCRAFT_RECEIPT {case} {paper} {}", result["detail"].as_str().unwrap());
}
let preview = harness.state_mut().run("file.printPreview", json!({})).unwrap();
assert_eq!(preview["pageList"][0]["height"], 792.0, "the print overrides left the workbook's saved Letter stock intact");
}
+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.
+15
View File
@@ -2497,6 +2497,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}");
}
-1
View File
@@ -22,7 +22,6 @@ thiserror = { workspace = true }
log = { workspace = true }
gridcraft-xlsx = { workspace = true }
craft-csv = { workspace = true }
craft-pages = { workspace = true }
craft-gridcraft-format = { workspace = true }
gridcraft-chart = { workspace = true }
gridcraft-pdf = { workspace = true }
+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![
+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
+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),
+14 -42
View File
@@ -7,9 +7,7 @@
//! drawn into a PDF with `gridcraft-pdf`: fills, gridlines, borders, formatted text (fonts mapped
//! to the standard 14 PDF fonts), merged cells, wrapping, overflow into empty neighbours,
//! conditional formats, table styles, charts, images, shapes and sparklines. Headers and footers
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes. A page range
//! (`from`/`to`, File › Print's Pages … to …) prints some of the job's pages, each still numbered
//! as in the whole job.
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
#[cfg(test)]
@@ -58,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::{PaperOverride, 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)]
@@ -71,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export as PDF",
["File", "Export"],
None,
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\" (active sheet), fitToPage?: bool, from?: page (1-based, counted over the whole job in sheet order), to?: page} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup. A page range prints only its pages, and their headers and footers keep the whole job's &P and &N; `from` after the last page is an error, `to` past it stops at the last page, and `from` greater than `to` prints the pages between them.",
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
has_doc,
export_pdf
),
@@ -80,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print…",
["File"],
Some("Cmd+P"),
"{path?, sheets?: active|all, range?, fitToPage?: bool, paperOverride?: {name,width,height} (points), from?: page (1-based, over the whole job), to?: page} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog; a page range works as in file.exportPdf",
"{path?, sheets?: active|all, range?, fitToPage?: bool} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
has_doc,
print
),
@@ -89,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
["File"],
None,
"{page? (1-based), sheets?: active|all, range?, fitToPage?, paperOverride?: {name,width,height} (points), from?: page, to?: page} → {pages, total, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order; with a page range, pageList holds only the pages that print, under their numbers in the whole job of `total` pages",
"{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
has_doc,
print_preview
),
@@ -98,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
),
@@ -121,19 +119,12 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P
/// Renders laid-out sheets to a PDF.
pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result<RenderedPdf> {
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, 1..=usize::MAX)
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES)
}
/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it
/// to exercise the cap without building gigabytes of pictures).
fn render_pdf_with_image_budget(
wb: &Workbook,
layouts: &[SheetLayout],
file: &str,
path: &str,
image_bytes: u64,
pages: std::ops::RangeInclusive<usize>,
) -> Result<RenderedPdf> {
fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result<RenderedPdf> {
let mut doc = PdfDoc::new();
doc.set_image_budget(image_bytes);
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
@@ -154,9 +145,6 @@ fn render_pdf_with_image_budget(
let (aw, ah) = lay.avail();
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
page_no += 1;
if !pages.contains(&page_no) {
continue;
}
let (Some(rband), Some(cband)) = (lay.row_bands.get(*ri).copied(), lay.col_bands.get(*ci).copied()) else { continue };
let rsegs = segments(lay.title_rows, rband);
let csegs = segments(lay.title_cols, cband);
@@ -235,9 +223,8 @@ fn build_pdf(s: &mut Session, p: &Json, cmd: &str) -> Result<(Vec<u8>, usize)> {
let opts = PrintOptions::from_params(p, cmd)?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let (first, last) = opts.page_span(lays.iter().map(|l| l.pages.len()).sum(), cmd)?;
let path = d.path.clone().unwrap_or_default();
let pdf = render_pdf_with_image_budget(&d.wb, &lays, &d.display_title(), &path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, first..=last)?;
let pdf = render_pdf(&d.wb, &lays, &d.display_title(), &path)?;
if pdf.missing_arabic_font {
s.ui_requests.push(crate::UiRequest::Message(MISSING_ARABIC_FONT.into()));
}
@@ -265,24 +252,16 @@ fn print(s: &mut Session, p: &Json) -> Result<Json> {
Ok(out)
}
/// The pages a print would print, each with its number in the whole job: a page range lists only
/// the pages in it, under their own numbers.
fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
const CMD: &str = "file.printPreview";
let opts = PrintOptions::from_params(p, CMD)?;
let opts = PrintOptions::from_params(p, "file.printPreview")?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let total: usize = lays.iter().map(|l| l.pages.len()).sum();
let (first, last) = opts.page_span(total, CMD)?;
let mut list = Vec::new();
let mut n = 0usize;
for lay in &lays {
let name = d.wb.sheet(lay.sheet).map(|s| s.name.clone()).unwrap_or_default();
for (ri, ci) in &lay.pages {
n += 1;
if !(first..=last).contains(&n) {
continue;
}
let (Some(rb), Some(cb)) = (lay.row_bands.get(*ri), lay.col_bands.get(*ci)) else { continue };
let r = RangeRef::new(CellRef::new(rb.0, cb.0), CellRef::new(rb.1, cb.1));
list.push(json!({
@@ -301,18 +280,11 @@ fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some(page) = u32_param(p, "page") {
let page = (page as usize).max(1);
if page > total {
return Err(bad(CMD, format!("there are only {total} pages")));
}
let one = list
.iter()
.find(|pg| pg["page"].as_u64() == Some(page as u64))
.cloned()
.ok_or_else(|| bad(CMD, format!("page {page} is outside the pages to print ({first} to {last})")))?;
return Ok(json!({"pages": list.len(), "total": total, "page": one}));
let one =
list.get((page as usize).saturating_sub(1)).cloned().ok_or_else(|| bad("file.printPreview", format!("there are only {n} pages")))?;
return Ok(json!({"pages": n, "page": one}));
}
Ok(json!({"pages": list.len(), "total": total, "pageList": list}))
Ok(json!({"pages": n, "pageList": list}))
}
fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
+22 -63
View File
@@ -75,19 +75,6 @@ pub struct PrintOptions {
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
pub ranges: Vec<RangeRef>,
pub fit_to_page: Option<bool>,
/// The page range (File › Print's Pages … to …): 1-based page numbers counted over the
/// whole job in sheet order. `None` = from the first page, to the last.
pub from: Option<usize>,
pub to: Option<usize>,
/// One physical paper size for this print job, without editing any worksheet's Page Setup.
pub paper_override: Option<PaperOverride>,
}
#[derive(Clone, Debug)]
pub struct PaperOverride {
pub name: String,
pub width: f32,
pub height: f32,
}
impl PrintOptions {
@@ -103,48 +90,7 @@ impl PrintOptions {
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
}
}
let paper_override = p
.get("paperOverride")
.map(|paper| {
let size = |key| paper.get(key).and_then(Json::as_f64).filter(|value| (36.0..=14_400.0).contains(value)).map(|v| v as f32);
let name = paper.get("name").and_then(Json::as_str).filter(|name| !name.trim().is_empty());
match (name, size("width"), size("height")) {
(Some(name), Some(width), Some(height)) => Ok(PaperOverride { name: name.into(), width, height }),
_ => Err(bad(cmd, "`paperOverride` needs a name and a width and height from 36 to 14400 points")),
}
})
.transpose()?;
let (from, to) = (page_param(p, "from", cmd)?, page_param(p, "to", cmd)?);
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage"), from, to, paper_override })
}
/// The first and last page that print out of a job of `total` pages (1-based, inclusive),
/// as Excel measures them: `from` after the last page is an error (nothing to print), `to`
/// past the last page stops at the last page, and `from` greater than `to` prints the pages
/// between them (3 to 2 prints pages 2 and 3).
pub(super) fn page_span(&self, total: usize, cmd: &str) -> Result<(usize, usize)> {
let span = craft_pages::range::print_page_span(total, self.from, self.to).map_err(|first| {
let pages = if total == 1 { "1 page".to_string() } else { format!("{total} pages") };
bad(cmd, format!("nothing to print: the job has {pages} and the page range starts at page {first}"))
})?;
Ok((span.start + 1, span.end))
}
}
/// A page-number param (`from`, `to`): a whole number from 1, as a number or as text. Absent,
/// `null` or empty text means no bound.
fn page_param(p: &Json, key: &str, cmd: &str) -> Result<Option<usize>> {
let n = match p.get(key) {
None | Some(Json::Null) => return Ok(None),
Some(Json::String(t)) if t.trim().is_empty() => return Ok(None),
Some(Json::String(t)) => t.trim().parse::<u64>().ok(),
// 2.0 is a whole number; 2.5, -1 and 0 are not page numbers.
Some(Json::Number(n)) => n.as_u64().or_else(|| n.as_f64().filter(|v| v.fract() == 0.0 && *v >= 1.0).map(|v| v as u64)),
Some(_) => None,
};
match n {
Some(n) if n >= 1 => Ok(Some(usize::try_from(n).unwrap_or(usize::MAX))),
_ => Err(bad(cmd, format!("`{key}` must be a page number from 1, not {}", p.get(key).map(Json::to_string).unwrap_or_default()))),
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
}
}
@@ -303,13 +249,8 @@ fn title_span(t: Option<(u32, u32)>, max: u32) -> Option<(u32, u32)> {
/// Paginates one sheet.
pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_override: Option<RangeRef>) -> Option<SheetLayout> {
let sh = wb.sheet(si)?;
let mut st = sh.print.clone();
let (mut pw, mut ph) = if let Some(paper) = &opts.paper_override {
st.paper.clone_from(&paper.name);
(paper.width.min(paper.height), paper.width.max(paper.height))
} else {
paper_size(&st.paper)
};
let st = sh.print.clone();
let (mut pw, mut ph) = paper_size(&st.paper);
if st.orientation == Orientation::Landscape {
std::mem::swap(&mut pw, &mut ph);
}
@@ -412,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
@@ -445,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();
+27 -212
View File
@@ -1,6 +1,4 @@
use gridcraft_model::{Sparkline, SparklineKind};
use std::collections::BTreeSet;
use serde_json::json;
use super::*;
@@ -24,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> {
@@ -901,7 +922,7 @@ fn picture_copies_across_pages_stay_within_the_image_budget() {
// 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page.
let budget = 64 * 1024;
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget, 1..=usize::MAX).unwrap();
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap();
assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures");
let capped_draws = draws(&capped);
assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget");
@@ -944,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),
@@ -1013,26 +1037,6 @@ fn page_setup_paper_sizes_reach_the_pdf_page() {
assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err());
}
#[test]
fn job_paper_override_reflows_the_preview_and_keeps_saved_orientation() {
let mut s = s();
let rows: Vec<_> = (0..60).map(|row| [row]).collect();
s.execute("range.setValues", json!({"range":"A1:A60","values":rows})).unwrap();
s.execute("pageLayout.pageSetup", json!({"paper":"A4","orientation":"landscape"})).unwrap();
let original = s.execute("file.printPreview", json!({})).unwrap();
let params = json!({"paperOverride":{"name":"Short Form","width":288.0,"height":432.0}});
let show = s.execute("file.printPreview", params.clone()).unwrap();
assert_eq!(show["pageList"][0]["paper"], "Short Form");
assert_eq!(show["pageList"][0]["width"], 432.0);
assert_eq!(show["pageList"][0]["height"], 288.0);
assert!(show["pages"].as_u64().unwrap() > original["pages"].as_u64().unwrap());
let (pdf, pages) = pdf_of(&mut s, params);
assert_eq!(pages as u64, show["pages"].as_u64().unwrap());
assert!(contains(&pdf, "/MediaBox [0 0 432 288]"));
assert_eq!(s.execute("file.printPreview", json!({})).unwrap(), original);
assert!(s.execute("file.print", json!({"paperOverride":{"name":"Bad","width":0,"height":432}})).is_err());
}
/// An empty paper name means no paper is stated; it prints on Letter.
#[test]
fn an_unstated_paper_prints_on_letter() {
@@ -1310,186 +1314,6 @@ fn checkbox_cells_print_as_boxes_not_true_false() {
assert!(contains(&pdf, "0.431 0.431 0.431 RG"), "the unchecked box is not outlined");
}
/// #3016's workbook: Sheet1 holds A1:A50 with a page break every 10 rows (5 pages), sheet Two
/// A1:A30 (3 pages), both with the footer "Page &P of &N". Each cell names its sheet, page and
/// row (`S1P2R11`).
fn paged_book() -> Session {
let mut s = s();
let labels =
|sheet: u32, rows: u32| -> Vec<Vec<Json>> { (1..=rows).map(|r| vec![json!(format!("S{sheet}P{}R{r}", (r - 1) / 10 + 1))]).collect() };
s.execute("range.setValues", json!({"range": "A1", "values": labels(1, 50)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21, 31, 41], "footer": "&CPage &P of &N"})).unwrap();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Two"})).unwrap();
s.execute("range.setValues", json!({"range": "A1", "values": labels(2, 30)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21], "footer": "&CPage &P of &N"})).unwrap();
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
s
}
/// Each page of a PDF as (the sheet and page its cells name, its footer): `("S1P2", "Page 2 of
/// 5")`. Pages are the content streams in order (one per page; the workbook has no pictures).
fn printed_pages(pdf: &[u8]) -> Vec<(String, String)> {
let text = String::from_utf8_lossy(pdf);
let chunks: Vec<&str> = text.split("endstream").collect();
let streams = chunks.get(..chunks.len().saturating_sub(1)).unwrap_or_default();
streams
.iter()
.map(|page| {
let shown: Vec<&str> = page.lines().filter_map(|l| l.strip_prefix('(')?.strip_suffix(") Tj")).collect();
let cells: BTreeSet<&str> = shown.iter().filter(|t| t.starts_with('S')).filter_map(|t| t.split_once('R').map(|(sp, _)| sp)).collect();
assert_eq!(cells.len(), 1, "a page shows the cells of one printed page: {shown:?}");
let footer = shown.iter().find(|t| t.starts_with("Page ")).copied().unwrap_or_default();
(cells.into_iter().next().unwrap_or_default().to_string(), footer.to_string())
})
.collect()
}
fn pages_of(s: &mut Session, cmd: &str, p: Json) -> Vec<(String, String)> {
let r = s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
let pdf = crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap();
let pages = printed_pages(&pdf);
assert_eq!(r["pages"].as_u64(), Some(pages.len() as u64), "{cmd} {p}: `pages` counts the printed pages");
pages
}
#[test]
fn a_page_range_prints_its_pages_under_the_whole_jobs_numbers() {
// #3016: the cases measured in Excel (ExportAsFixedFormat with From and To).
let mut s = paged_book();
let page = |sp: &str, n: u32, of: u32| (sp.to_string(), format!("Page {n} of {of}"));
let sheet1 = |pages: &[u32]| pages.iter().map(|n| page(&format!("S1P{n}"), *n, 5)).collect::<Vec<_>>();
for (params, want) in [
(json!({}), sheet1(&[1, 2, 3, 4, 5])),
(json!({"from": 2, "to": 3}), sheet1(&[2, 3])),
(json!({"from": 5, "to": 5}), sheet1(&[5])),
// `to` past the last page stops at the last page.
(json!({"from": 4, "to": 99}), sheet1(&[4, 5])),
// `from` greater than `to` prints the pages between them.
(json!({"from": 3, "to": 2}), sheet1(&[2, 3])),
// Only `from`: to the last page; only `to`: from the first.
(json!({"from": 4}), sheet1(&[4, 5])),
(json!({"to": 2}), sheet1(&[1, 2])),
// Whole numbers as text or as 3.0, and `null` or empty text for no bound.
(json!({"from": "2", "to": 3.0}), sheet1(&[2, 3])),
(json!({"from": null, "to": ""}), sheet1(&[1, 2, 3, 4, 5])),
// The whole workbook counts its pages in sheet order: Two's first page is page 6 of 8.
(json!({"sheets": "all", "from": 5, "to": 6}), vec![page("S1P5", 5, 8), page("S2P1", 6, 8)]),
(json!({"sheets": "all", "from": 6, "to": 8}), vec![page("S2P1", 6, 8), page("S2P2", 7, 8), page("S2P3", 8, 8)]),
] {
assert_eq!(pages_of(&mut s, "file.exportPdf", params.clone()), want, "file.exportPdf {params}");
// The printer gets the same pages.
assert_eq!(pages_of(&mut s, "file.print", params.clone()), want, "file.print {params}");
}
// A range that starts after the last page prints nothing: an error, not an empty PDF.
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for params in [json!({"from": 6, "to": 7}), json!({"from": 6}), json!({"from": 9, "to": 9, "sheets": "all"})] {
let e = s.execute(cmd, params.clone()).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{cmd} {params}: {e}");
}
}
// A written file holds the same pages.
let dir = std::env::temp_dir().join(format!("gridcraft-print-range-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("p.pdf");
let r = s.execute("file.exportPdf", json!({"path": path.to_str().unwrap(), "from": 2, "to": 3})).unwrap();
assert_eq!(r["pages"], 2);
assert_eq!(printed_pages(&std::fs::read(&path).unwrap()), sheet1(&[2, 3]));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn print_preview_lists_the_pages_of_a_range_under_their_numbers() {
let mut s = paged_book();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64()), (Some(2), Some(5)));
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["rows"].as_str().unwrap())).collect();
assert_eq!(listed, [(2, "11:20"), (3, "21:30")]);
let pv = s.execute("file.printPreview", json!({"sheets": "all", "from": 5, "to": 6})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["sheet"].as_str().unwrap())).collect();
assert_eq!(listed, [(5, "Sheet1"), (6, "Two")]);
assert_eq!(pv["total"], 8);
// `page` picks a page by its number in the job; one outside the range is an error.
assert_eq!(s.execute("file.printPreview", json!({"page": 3, "from": 2, "to": 3})).unwrap()["page"]["rows"], "21:30");
assert!(s.execute("file.printPreview", json!({"page": 1, "from": 2, "to": 3})).is_err());
assert!(s.execute("file.printPreview", json!({"page": 6})).is_err());
// Without a range nothing changes: every page, `pages` and `total` alike.
let pv = s.execute("file.printPreview", json!({})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64(), pv["pageList"].as_array().map(Vec::len)), (Some(5), Some(5), Some(5)));
}
#[test]
fn a_page_range_counts_the_pages_in_the_sheets_page_order() {
let mut s = s();
let rows: Vec<Vec<Json>> = (0..60).map(|r| (0..15).map(|c| json!(r * 100 + c)).collect()).collect();
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["range"].as_str().unwrap())).collect();
// Over, then down: page 2 is the top right of the four, page 3 the bottom left.
assert_eq!(listed, [(2, "K1:O45"), (3, "A46:J60")]);
assert_eq!(pv["total"], 4);
}
#[test]
fn page_range_params_that_are_not_page_numbers_are_clear_errors() {
let mut s = paged_book();
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for bad_value in [json!(0), json!(-1), json!(2.5), json!("x"), json!("-2"), json!("1.5"), json!(true), json!([2]), json!({"page": 2})] {
for key in ["from", "to"] {
let params = json!({ key: bad_value.clone() });
let e = s.execute(cmd, params.clone()).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{cmd} {params}: {e:?}");
assert!(e.to_string().contains(&format!("`{key}` must be a page number from 1")), "{cmd} {params}: {e}");
}
}
}
}
#[test]
fn hostile_page_ranges_never_panic() {
// `every_command_survives_empty_params` for the page range: any value, alone or paired, on
// every print command gives a result or a clear error, never a caught panic.
let mut s = paged_book();
let values = [
json!(null),
json!(0),
json!(1),
json!(-1),
json!(2.5),
json!(1e300),
json!(-1e300),
json!(u64::MAX),
json!(i64::MIN),
json!(MAX_PAGES + 1),
json!(""),
json!(" 3 "),
json!("x"),
json!("99999999999999999999999999"),
json!(true),
json!([]),
json!({}),
];
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for from in &values {
for to in [json!(null), json!(2), json!(u64::MAX), json!("x")] {
for params in [json!({"from": from, "to": to}), json!({"to": from}), json!({"from": from, "to": to, "sheets": "all", "page": 7})] {
let r = s.execute(cmd, params.clone());
assert!(!matches!(r, Err(crate::EngineError::Internal(..))), "{cmd} {params}: {r:?}");
}
}
}
}
// Huge numbers are pages after the last one, not an overflow.
let e = s.execute("file.exportPdf", json!({"from": u64::MAX})).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{e}");
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": u64::MAX})).len(), 1);
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": 1e300})).len(), 1);
}
#[test]
fn an_equation_without_a_layout_prints_its_source_one_line_per_line() {
use super::objects::{MAX_FALLBACK_LINES, fallback_lines};
@@ -1769,15 +1593,6 @@ fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() {
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]);
// Several areas, like a multi-area selection: one run of pages each, in the order given.
assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]);
let second_area = json!({"range": "D4:E5,A1:B2", "from": 2, "to": 2});
let preview = s.execute("file.printPreview", second_area.clone()).unwrap();
assert_eq!(preview["pageList"].as_array().unwrap().len(), 1);
assert_eq!(preview["pageList"][0]["range"], "A1:B2");
assert_eq!(preview["pageList"][0]["page"], 2);
let (pdf, count) = pdf_of(&mut s, second_area);
assert_eq!(count, 1);
assert!(contains(&pdf, "/Count 1 >>"));
assert!(contains(&pdf, "(x) Tj"));
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]);
let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"}));
assert_eq!(pages, 2);
+69 -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 {
+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;
+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
}
+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);
+1
View File
@@ -513,6 +513,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 -3
View File
@@ -42,8 +42,6 @@ impl SheetApp {
notice: None,
services,
printing: Default::default(),
print_pages: Default::default(),
print_paper: Default::default(),
print_feedback_seen: None,
synthetic: Default::default(),
ctrl_wheel: false,
@@ -581,7 +579,7 @@ mod lifecycle_tests {
let mut app = app();
app.printing.printers.push(crate::printing::Printer::new("Queue").is_default(true));
app.run("ui.printSettings", serde_json::json!({"printer": "Queue"})).unwrap();
app.services.print_native = Some(Box::new(|_, _, _| {
app.services.print_native = Some(Box::new(|_, _| {
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Err("printer is offline".into())).unwrap();
receiver
+6 -14
View File
@@ -223,20 +223,8 @@ impl SheetApp {
Ok(Json::Null)
}
"data.fromClipboard" => self.import_clipboard_text(p),
"ui.printSettings" => printing::settings(
&mut self.printing,
&mut self.print_paper,
&mut self.print_pages,
p,
self.services.printers.as_ref(),
self.services.printer_papers.is_some(),
),
"ui.printSubmit" => {
// The Print view's page range applies unless the call names its own.
let mut params = p.clone();
self.print_pages.apply(&mut params);
self.submit_print(params)
}
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
"ui.printSubmit" => self.submit_print(p.clone()),
"ui.ribbonTab" => {
self.ui.ribbon_tab = p.get("tab").and_then(Json::as_str).unwrap_or("Home").to_string();
Ok(Json::Null)
@@ -310,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(", "))),
@@ -317,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)),
+2 -17
View File
@@ -46,28 +46,16 @@ impl SheetApp {
}
}
pub(super) fn submit_print(&mut self, mut params: Json) -> Result<Json, String> {
pub(super) fn submit_print(&mut self, params: Json) -> Result<Json, String> {
if self.services.print_native.is_some() && !self.printing.ready() {
return Err("Select an available printer in File > Print before submitting.".into());
}
let paper = self.print_paper.selected(printing::printer_name(&self.printing.settings)).cloned();
if self.services.print_native.is_some() {
// A native request may choose only a paper from the selected queue.
if let Some(fields) = params.as_object_mut() {
fields.remove("paperOverride");
}
if let Some(paper) = &paper {
paper.apply(&mut params);
}
}
let pdf = self.run("file.print", params)?;
let encoded = pdf.get("base64").and_then(Json::as_str).ok_or("The print command did not produce a PDF.")?;
let bytes = gridcraft_engine::io::base64_decode(encoded).ok_or("Couldn't decode the generated PDF.")?;
let len = bytes.len();
if let Some(submit) = &self.services.print_native {
self.printing
.begin(submit(bytes, self.printing.settings.clone(), paper))
.map_err(|_| "A print job is already being submitted.".to_owned())?;
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);
@@ -82,9 +70,6 @@ impl SheetApp {
/// `tests/native_print.rs` deliberately bypass the lifecycle to test this helper alone.
pub fn poll_printing(&mut self, ctx: &egui::Context) {
self.printing.poll(ctx);
if let Some(discover) = &self.services.printer_papers {
self.print_paper.poll(printing::printer_name(&self.printing.settings), discover, ctx);
}
if self.printing.message == self.print_feedback_seen {
return;
}
+17 -49
View File
@@ -18,14 +18,13 @@ use serde_json::{Value as Json, json};
use crate::SheetApp;
use crate::i18n::{self, Language};
use crate::icons::{self, Icon};
use crate::printing::PageRange;
use crate::theme::{self, Tokens};
mod options;
mod print;
use options::{options, platform};
use print::{page_range_fields, print};
use print::print;
/// Width of the navigation column.
const NAV_W: f32 = 196.0;
@@ -100,17 +99,8 @@ impl Page {
}
/// What a print preview was built for: document, revision, scope, the selection when it is
/// the scope, fit to page, and the requested page range.
#[derive(Clone, Debug, PartialEq)]
struct PreviewKey {
document: u64,
revision: u64,
scope: PrintScope,
selection: String,
fit_to_page: bool,
pages: PageRange,
paper: Option<crate::printing::Paper>,
}
/// the scope, and fit to page.
type PreviewKey = (u64, u64, PrintScope, String, bool);
/// What File › Print › Settings prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -155,15 +145,10 @@ pub struct Backstage {
pub print_scope: PrintScope,
/// Print: fit each sheet on one page.
pub fit_to_page: bool,
/// Print: the previewed page (0-based, among the pages that print).
/// Print: the previewed page (0-based).
preview_page: usize,
/// Print: the preview and what it was made for.
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
preview: Option<(PreviewKey, Json)>,
/// Print: the Pages … to … fields as typed.
print_drafts: [String; 2],
/// Export: the page range of Create PDF, and its fields as typed.
pdf_pages: PageRange,
pdf_drafts: [String; 2],
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
pub save_format: &'static str,
/// Home and Open: when the recent workbooks were last changed.
@@ -185,9 +170,6 @@ impl Backstage {
fit_to_page: false,
preview_page: 0,
preview: None,
print_drafts: Default::default(),
pdf_pages: PageRange::default(),
pdf_drafts: Default::default(),
save_format: "xlsx",
recent: RecentFiles::default(),
}
@@ -268,7 +250,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
Page::Info => info(app, ui, &mut bs),
Page::SaveAs => save_as(app, ui, &mut bs, &mut out),
Page::Print => print(app, ui, &mut bs, &mut out),
Page::Export => export(app, ui, &mut bs, &mut out),
Page::Export => export(app, ui, &mut out),
Page::Options => options(app, ui),
Page::Account => account(app, ui),
}
@@ -746,7 +728,7 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
if after != before || asking || app.services.pick_save.is_none() {
out.close = true;
}
} else if export_as(app, fmt, json!({})) {
} else if export_as(app, fmt) {
out.close = true;
}
}
@@ -754,23 +736,12 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
dim(ui, lang.tr("A CSV file, web page or PDF is a copy: the workbook keeps its own file."));
}
fn export(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
fn export(app: &mut SheetApp, ui: &mut Ui, out: &mut Outcome) {
let lang = app.ui.language;
let create_pdf =
action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked();
// Create PDF's page range, in line with its description; empty fields export every page.
ui.horizontal(|ui| {
ui.add_space(52.0);
if let Some(range) = page_range_fields(ui, lang, "backstage_pdf_pages", &mut bs.pdf_drafts, bs.pdf_pages) {
bs.pdf_pages = range;
}
});
if create_pdf {
let mut params = json!({});
bs.pdf_pages.apply(&mut params);
if export_as(app, "pdf", params) {
out.close = true;
}
if action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked()
&& export_as(app, "pdf")
{
out.close = true;
}
ui.add_space(14.0);
section(ui, lang, "Change File Type");
@@ -778,16 +749,15 @@ fn export(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome
("csv", Icon::TextColumns, "CSV (Comma delimited)", "Save the active sheet as comma-separated text."),
("html", Icon::Link, "Web Page (.html)", "Save the workbook as a web page."),
] {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt, json!({})) {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt) {
out.close = true;
}
}
}
/// Exports the active workbook as `pdf`, `csv` or `html`: through the save picker on the desktop,
/// as a browser download on the web. `params` go to the export command with the path (a PDF's
/// page range). Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str, params: Json) -> bool {
/// as a browser download on the web. Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
if !app.commit_edit(0, 0, false, false) {
return false;
}
@@ -797,15 +767,13 @@ pub fn export_as(app: &mut SheetApp, fmt: &str, params: Json) -> bool {
"html" => "file.exportHtml",
_ => return false,
};
let mut params = if params.is_object() { params } else { json!({}) };
let title = app.session.active().map(|d| d.display_title()).unwrap_or_else(|| "Book1".into());
let stem = std::path::Path::new(&title).file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
if let Some(pick) = &app.services.pick_save {
let Some(path) = pick(&format!("{stem}.{fmt}")) else { return false };
// The picker may suggest a workbook extension; the export writes the chosen format.
let path = std::path::Path::new(&path).with_extension(fmt).to_string_lossy().into_owned();
params["path"] = json!(path);
return match app.run(id, params) {
return match app.run(id, json!({"path": path})) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
@@ -819,7 +787,7 @@ pub fn export_as(app: &mut SheetApp, fmt: &str, params: Json) -> bool {
}
if fmt == "pdf" {
// Without a path the PDF comes back as bytes, which `SheetApp::run` hands to the browser.
return match app.run(id, params) {
return match app.run(id, json!({})) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
+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);
+10 -59
View File
@@ -1,9 +1,9 @@
use super::{
Align2, Backstage, Icon, Json, Language, Outcome, PageRange, PreviewKey, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim,
json, pos2, square_button, theme, vec2,
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
vec2,
};
/// Builds the print scope, page range and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
/// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let t = Tokens::get(ui.ctx());
let lang = app.ui.language;
@@ -23,37 +23,19 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if bs.fit_to_page {
params["fitToPage"] = json!(true);
}
app.print_pages.apply(&mut params);
let queue = crate::printing::printer_name(&app.printing.settings);
let paper = app.print_paper.selected(queue).cloned();
if let Some(paper) = &paper {
paper.apply(&mut params);
}
let key = PreviewKey { document: uid, revision, scope: bs.print_scope, selection, fit_to_page: bs.fit_to_page, pages: app.print_pages, paper };
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
if bs.preview.as_ref().is_some_and(|(k, _)| k.pages != key.pages || k.paper != key.paper) {
bs.preview_page = 0;
}
// A range that starts after the last page is an error: nothing to print.
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
bs.preview = Some((key, preview));
}
let preview = bs.preview.as_ref().map(|(_, p)| p);
let pages: Vec<Json> = preview.and_then(|p| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
// The whole job's page count: a page range previews only its pages, under their numbers in the job.
let total = preview.and_then(|p| p.get("total")).and_then(Json::as_u64).unwrap_or(pages.len() as u64);
let pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
}
if let Some(discover) = &app.services.printer_papers {
let queue = crate::printing::printer_name(&app.printing.settings);
app.print_paper.poll(queue, discover, ui.ctx());
app.print_paper.show(ui, queue, lang, !app.printing.busy());
}
let can_print = (app.services.print_native.is_none() || app.printing.ready()) && !pages.is_empty();
let can_print = app.services.print_native.is_none() || app.printing.ready();
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)
{
@@ -75,16 +57,6 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
.response
.accessible_name(lang.tr("Print What"));
ui.add_space(8.0);
// Pages … to …, counted over what the scope prints; empty fields print every page.
ui.horizontal(|ui| {
if let Some(range) = page_range_fields(ui, lang, "backstage_print_pages", &mut bs.print_drafts, app.print_pages) {
// Set through `ui.printSettings`, as a control client sets them. It refuses changes
// only while a job is being handed to the printer; a field left then shows the kept range.
let _ = app.run("ui.printSettings", json!({"from": range.from, "to": range.to}));
ui.ctx().request_repaint();
}
});
ui.add_space(8.0);
if ui.checkbox(&mut bs.fit_to_page, lang.tr("Fit Sheet on One Page")).changed() {
bs.preview_page = 0;
}
@@ -123,9 +95,10 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if ui.add_enabled(bs.preview_page > 0, egui::Button::new("◀")).on_hover_text(lang.tr("Previous page")).clicked() {
bs.preview_page = bs.preview_page.saturating_sub(1);
}
// The page's own number in the job, as its header and footer print it.
let number = page.get("page").and_then(Json::as_u64).unwrap_or(bs.preview_page as u64 + 1);
let text = lang.tr("Page {page} of {pages}").replace("{page}", &number.to_string()).replace("{pages}", &total.to_string());
let text = lang
.tr("Page {page} of {pages}")
.replace("{page}", &(bs.preview_page + 1).to_string())
.replace("{pages}", &pages.len().to_string());
ui.label(text);
if ui.add_enabled(bs.preview_page < last, egui::Button::new("▶")).on_hover_text(lang.tr("Next page")).clicked() {
bs.preview_page = (bs.preview_page + 1).min(last);
@@ -135,28 +108,6 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
});
}
/// Pages [from] to [to]: a page range as two small number fields, in a horizontal layout. Empty
/// fields mean the first and the last page. `drafts` hold the text as typed (a field that isn't
/// being edited shows `range`); returns the new range when a field changed it.
pub(super) fn page_range_fields(ui: &mut Ui, lang: Language, id: &str, drafts: &mut [String; 2], range: PageRange) -> Option<PageRange> {
let mut next = range;
for (i, (label, bound)) in [("Pages", &mut next.from), ("Print pages|to", &mut next.to)].into_iter().enumerate() {
let Some(draft) = drafts.get_mut(i) else { continue };
let label = ui.label(lang.tr(label));
let field = ui.make_persistent_id((id, i));
if !ui.ctx().memory(|m| m.has_focus(field)) {
*draft = bound.map(|page| page.to_string()).unwrap_or_default();
}
let edit = egui::TextEdit::singleline(draft).id(field).desired_width(44.0).char_limit(5);
if ui.add(edit).labelled_by(label.id).changed() {
draft.retain(|c| c.is_ascii_digit());
// 0 is no page: like an empty field, it prints from the first or to the last page.
*bound = draft.parse::<u32>().ok().filter(|page| *page >= 1);
}
}
(next != range).then_some(next)
}
/// Most rows and columns one preview page draws (a page holds far fewer at any readable scale).
const PREVIEW_ROWS: u32 = 200;
+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
+2 -6
View File
@@ -110,12 +110,8 @@ fn run(app: &mut SheetApp, id: &str, params: Json) -> Result<Json, String> {
/// window afterwards unless the command itself switched windows.
fn run_in(app: &mut SheetApp, target: gridcraft_engine::Target, id: &str, params: Json) -> Result<Json, String> {
let guard = app.session.enter_target(target).map_err(|e| e.to_string())?;
// A UI command reads and changes the target window's interface state (its page range…),
// and the active window's is back once the command is done.
app.follow_active_window();
let r = run(app, id, params);
app.session.leave_target(guard);
app.follow_active_window();
r
}
@@ -298,12 +294,12 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
(
"ui.printSettings",
"Print Settings",
"{printer?: discovered name, paper?: discovered paper id|null for workbook paper, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, from?: page (1-based)|null, to?: page|null, refresh?: bool} → {printer,paper,papers,papersLoading,copies,duplex,grayscale,from,to,printers,ready,busy,discovering,status,detail}; from/to are the Print view's page range (null clears a bound); {} inspects without submitting",
"{printer?: discovered name, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, refresh?: bool} → {printer,copies,duplex,grayscale,printers,ready,busy,discovering,status,detail}; {} inspects without submitting",
),
(
"ui.printSubmit",
"Submit Print Job",
"existing file.print sheet/pagination params; without from/to, the page range of ui.printSettings → {printing,bytes,pending}; submits without opening a dialog",
"existing file.print sheet/pagination params → {printing,bytes,pending}; submits without opening a dialog",
),
("app.language.set", "Interface Language", language_params.as_str()),
("app.language.english", "Interface Language: English", ""),
+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,
+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.
+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}");
}
}
+2 -2
View File
@@ -339,8 +339,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Vytisknout celý sešit",
"Print Selection" => "Vytisknout výběr",
"Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku",
"Pages" => "Stránky",
"Print pages|to" => "až",
"Page Setup…" => "Vzhled stránky…",
"Page {page} of {pages}" => "Stránka {page} z {pages}",
"Nothing to print." => "Není co tisknout.",
@@ -432,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 -2
View File
@@ -358,8 +358,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Gesamte Arbeitsmappe drucken",
"Print Selection" => "Auswahl drucken",
"Fit Sheet on One Page" => "Blatt auf einer Seite darstellen",
"Pages" => "Seiten",
"Print pages|to" => "bis",
"Page Setup…" => "Seite einrichten…",
"Page {page} of {pages}" => "Seite {page} von {pages}",
"Nothing to print." => "Nichts zu drucken.",
@@ -449,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 -2
View File
@@ -317,8 +317,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας",
"Print Selection" => "Εκτύπωση επιλογής",
"Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα",
"Pages" => "Σελίδες",
"Print pages|to" => "έως",
"Page Setup…" => "Διαμόρφωση σελίδας…",
"Page {page} of {pages}" => "Σελίδα {page} από {pages}",
"Nothing to print." => "Δεν υπάρχει περιεχόμενο για εκτύπωση.",
@@ -395,6 +393,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Αυτοματισμός",
"Table Design" => "Σχεδίαση πίνακα",
"Chart Design" => "Σχεδίαση γραφήματος",
"Pareto" => "Παρέτο",
"Cumulative %" => "Αθροιστικό %",
"Ready" => "Έτοιμο",
"Enter" => "Εισαγωγή",
"Edit" => "Επεξεργασία",
+2 -2
View File
@@ -345,8 +345,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir todo el libro",
"Print Selection" => "Imprimir selección",
"Fit Sheet on One Page" => "Ajustar hoja en una página",
"Pages" => "Páginas",
"Print pages|to" => "a",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "No hay nada que imprimir.",
@@ -436,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 -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",
@@ -434,8 +436,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimer tout le classeur",
"Print Selection" => "Imprimer la sélection",
"Fit Sheet on One Page" => "Ajuster la feuille sur une page",
"Pages" => "Pages",
"Print pages|to" => "à",
"Page Setup…" => "Mise en page…",
"Page {page} of {pages}" => "Page {page} sur {pages}",
"Nothing to print." => "Rien à imprimer.",
+2 -2
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",
@@ -419,8 +421,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Stampa intera cartella di lavoro",
"Print Selection" => "Stampa selezione",
"Fit Sheet on One Page" => "Adatta foglio a una pagina",
"Pages" => "Pagine",
"Print pages|to" => "a",
"Page Setup…" => "Imposta pagina…",
"Page {page} of {pages}" => "Pagina {page} di {pages}",
"Nothing to print." => "Niente da stampare.",
+2 -2
View File
@@ -299,6 +299,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Automate", "自動化"),
("Table Design", "テーブル デザイン"),
("Chart Design", "グラフ デザイン"),
("Pareto", "パレート図"),
("Cumulative %", "累積 %"),
("Ready", "準備完了"),
("Enter", "入力"),
("Edit", "編集"),
@@ -422,8 +424,6 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Print Entire Workbook", "ブック全体を印刷"),
("Print Selection", "選択した部分を印刷"),
("Fit Sheet on One Page", "シートを 1 ページに印刷"),
("Pages", "ページ指定"),
("Print pages|to", "~"),
("Page Setup…", "ページ設定…"),
("Page {page} of {pages}", "{page} / {pages} ページ"),
("Nothing to print.", "印刷する内容がありません。"),
+2 -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" => "편집",
@@ -434,8 +436,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "전체 통합 문서 인쇄",
"Print Selection" => "선택 영역 인쇄",
"Fit Sheet on One Page" => "한 페이지에 시트 맞추기",
"Pages" => "페이지",
"Print pages|to" => "~",
"Page Setup…" => "페이지 설정…",
"Page {page} of {pages}" => "{page}/{pages} 페이지",
"Nothing to print." => "인쇄할 내용이 없습니다.",
+2 -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",
@@ -421,8 +423,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Hele werkmap afdrukken",
"Print Selection" => "Selectie afdrukken",
"Fit Sheet on One Page" => "Blad op één pagina passen",
"Pages" => "Pagina's",
"Print pages|to" => "tot",
"Page Setup…" => "Pagina-instelling…",
"Page {page} of {pages}" => "Pagina {page} van {pages}",
"Nothing to print." => "Niets om af te drukken.",
+2 -2
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",
@@ -411,8 +413,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Drukuj cały skoroszyt",
"Print Selection" => "Drukuj zaznaczenie",
"Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony",
"Pages" => "Strony",
"Print pages|to" => "do",
"Page Setup…" => "Ustawienia strony…",
"Page {page} of {pages}" => "Strona {page} z {pages}",
"Nothing to print." => "Nie ma nic do wydrukowania.",
+2 -2
View File
@@ -428,8 +428,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir toda a pasta de trabalho",
"Print Selection" => "Imprimir seleção",
"Fit Sheet on One Page" => "Ajustar planilha em uma página",
"Pages" => "Páginas",
"Print pages|to" => "até",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "Nada para imprimir.",
@@ -853,6 +851,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 -2
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",
@@ -418,8 +420,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimare tot registrul",
"Print Selection" => "Imprimare selecție",
"Fit Sheet on One Page" => "Încadrare foaie pe o pagină",
"Pages" => "Pagini",
"Print pages|to" => "la",
"Page Setup…" => "Configurare pagină…",
"Page {page} of {pages}" => "Pagina {page} din {pages}",
"Nothing to print." => "Nimic de imprimat.",
+2 -2
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" => "Изменение",
@@ -433,8 +435,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Напечатать всю книгу",
"Print Selection" => "Напечатать выделенный диапазон",
"Fit Sheet on One Page" => "Вписать лист на одну страницу",
"Pages" => "Страницы",
"Print pages|to" => "по",
"Page Setup…" => "Параметры страницы…",
"Page {page} of {pages}" => "Страница {page} из {pages}",
"Nothing to print." => "Нечего печатать.",
+2 -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",
@@ -427,8 +429,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Štampaj celu radnu svesku",
"Print Selection" => "Štampaj izbor",
"Fit Sheet on One Page" => "Uklopi list na jednu stranicu",
"Pages" => "Stranice",
"Print pages|to" => "do",
"Page Setup…" => "Podešavanje stranice…",
"Page {page} of {pages}" => "Stranica {page} od {pages}",
"Nothing to print." => "Nema ničega za štampu.",
+2 -2
View File
@@ -332,8 +332,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır",
"Print Selection" => "Seçimi Yazdır",
"Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır",
"Pages" => "Sayfalar",
"Print pages|to" => "-",
"Page Setup…" => "Sayfa Yapısı…",
"Page {page} of {pages}" => "Sayfa {page} / {pages}",
"Nothing to print." => "Yazdırılacak bir şey yok.",
@@ -409,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 -2
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" => "Редагування",
@@ -416,8 +418,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Надрукувати всю книгу",
"Print Selection" => "Надрукувати виділений діапазон",
"Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку",
"Pages" => "Сторінки",
"Print pages|to" => "по",
"Page Setup…" => "Параметри сторінки…",
"Page {page} of {pages}" => "Сторінка {page} з {pages}",
"Nothing to print." => "Немає що друкувати.",
+2 -2
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",
@@ -421,8 +423,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "In toàn bộ sổ làm việc",
"Print Selection" => "In vùng chọn",
"Fit Sheet on One Page" => "Vừa trang tính trên một trang in",
"Pages" => "Trang",
"Print pages|to" => "đến",
"Page Setup…" => "Thiết lập trang…",
"Page {page} of {pages}" => "Trang {page} trên {pages}",
"Nothing to print." => "Không có nội dung để in.",
+2 -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" => "编辑",
@@ -426,8 +428,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "打印整个工作簿",
"Print Selection" => "打印选定区域",
"Fit Sheet on One Page" => "将工作表调整为一页",
"Pages" => "页数",
"Print pages|to" => "至",
"Page Setup…" => "页面设置…",
"Page {page} of {pages}" => "第 {page} 页,共 {pages} 页",
"Nothing to print." => "没有可打印的内容。",
-4
View File
@@ -261,10 +261,6 @@ pub struct SheetApp {
pub notice: Option<Notice>,
pub services: Services,
pub printing: printing::State,
/// File › Print's page range (Pages … to …), set there or by `ui.printSettings`. Each window
/// has its own, parked with its other interface state while another window is active.
pub print_pages: printing::PageRange,
print_paper: printing::PaperSelection,
print_feedback_seen: Option<printing::Feedback>,
/// Synthetic input from agents, one batch per step (drags need several steps).
pub synthetic: std::collections::VecDeque<Vec<egui::Event>>,
+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() {
+6 -80
View File
@@ -1,12 +1,6 @@
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
//! localized feedback. The panel's own words come from the framework host.
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State};
mod paper;
pub(crate) use paper::PaperSelection;
pub use paper::{DiscoverPapers, Paper};
pub type Submit = Box<dyn Fn(Vec<u8>, Settings, Option<Paper>) -> std::sync::mpsc::Receiver<Result<String, String>>>;
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
/// Draws the shared print controls and the feedback of the last discovery or job.
///
@@ -21,52 +15,20 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate
}
/// The printer queue the settings name; empty for none.
pub(crate) fn printer_name(settings: &Settings) -> &str {
fn printer_name(settings: &Settings) -> &str {
match &settings.destination {
Destination::Printer(name) => name,
_ => "",
}
}
/// File › Print's page range (Pages … to …): 1-based page numbers counted over the whole print
/// job. `None` prints from the first page or to the last.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageRange {
pub from: Option<u32>,
pub to: Option<u32>,
}
impl PageRange {
/// Adds the range to print-command params as `from` and `to`, unless they name a range of
/// their own (either bound, `null` included).
pub fn apply(&self, params: &mut serde_json::Value) {
let Some(map) = params.as_object_mut() else { return };
if map.contains_key("from") || map.contains_key("to") {
return;
}
for (key, page) in [("from", self.from), ("to", self.to)] {
if let Some(page) = page {
map.insert(key.into(), page.into());
}
}
}
}
/// Read print settings/status, or validate an explicit update before changing anything.
/// `refresh: true` starts discovery only; this command never submits a job or opens a dialog.
/// `from` and `to` set the Print view's page range (`null` clears a bound).
pub(crate) fn settings(
state: &mut State,
paper: &mut PaperSelection,
pages: &mut PageRange,
params: &serde_json::Value,
discover: Option<&Discover>,
has_catalog: bool,
) -> Result<serde_json::Value, String> {
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
use serde_json::{Value, json};
let object = params.as_object().ok_or("print settings must be an object")?;
if object.keys().any(|key| !["printer", "paper", "copies", "duplex", "grayscale", "from", "to", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, paper, copies, duplex, grayscale, from, to or refresh".into());
if object.keys().any(|key| !["printer", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale or refresh".into());
}
if state.busy() && !object.is_empty() {
return Err("wait for the active print submission before changing settings".into());
@@ -96,33 +58,6 @@ pub(crate) fn settings(
if let Some(value) = object.get("grayscale") {
next.grayscale = value.as_bool().ok_or("grayscale must be a boolean")?;
}
let mut range = *pages;
for (key, bound) in [("from", &mut range.from), ("to", &mut range.to)] {
if let Some(value) = object.get(key) {
*bound = match value {
Value::Null => None,
_ => Some(
value
.as_u64()
.and_then(|page| u32::try_from(page).ok())
.filter(|page| *page >= 1)
.ok_or_else(|| format!("{key} must be a page number from 1, or null for no limit"))?,
),
};
}
}
let queue = printer_name(&next);
let requested_paper = match object.get("paper") {
None => None,
Some(Value::Null) => Some(None),
Some(value) => {
let id = value.as_str().ok_or("paper must be an id from the selected printer or null for workbook paper")?;
if !paper.offered(queue).iter().any(|size| size.id == id) {
return Err("paper must be an id from the selected printer's available papers".into());
}
Some(Some(id.to_owned()))
}
};
let refresh = object.get("refresh").map(|value| value.as_bool().ok_or("refresh must be a boolean")).transpose()?.unwrap_or(false);
if refresh {
let discover = discover.ok_or("native printer discovery is unavailable here")?;
@@ -130,13 +65,7 @@ pub(crate) fn settings(
return Err("printer discovery or submission is already active".into());
}
}
paper.set_queue(queue);
if let Some(requested) = requested_paper {
paper.selected = requested;
}
state.settings = next;
*pages = range;
let queue = printer_name(&state.settings);
let (status, detail) = match state.message.as_ref() {
None => ("idle", ""),
Some(Feedback::FindingPrinters) => ("findingPrinters", ""),
@@ -151,10 +80,7 @@ pub(crate) fn settings(
Ok(json!({
"printer": printer_name(&state.settings), "copies": state.settings.copies,
"duplex": match state.settings.duplex { Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", _ => "printerDefault" },
"grayscale": state.settings.grayscale, "from": pages.from, "to": pages.to,
"paper": paper.selected(queue).map(|size| size.id.as_str()),
"papers": paper.offered(queue).iter().map(|size| json!({"id":size.id,"name":size.name,"width":size.width,"height":size.height})).collect::<Vec<_>>(),
"papersLoading": has_catalog && paper.loading(queue),
"grayscale": state.settings.grayscale,
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
"busy": state.busy(), "discovering": state.discovering(), "ready": state.ready(), "status": status, "detail": detail,
}))
-115
View File
@@ -1,115 +0,0 @@
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::Duration;
use serde_json::{Value, json};
/// A paper offered by a system printer. Dimensions are in points.
#[derive(Clone, Debug, PartialEq)]
pub struct Paper {
pub id: String,
pub name: String,
pub width: f64,
pub height: f64,
/// The exact CUPS choice, where the spooler takes one independently of the PDF geometry.
pub cups_media: Option<String>,
}
impl Paper {
pub(crate) fn apply(&self, params: &mut Value) {
if !params.is_object() {
*params = json!({});
}
if let Some(fields) = params.as_object_mut() {
fields.insert("paperOverride".into(), json!({"name":self.name,"width":self.width,"height":self.height}));
}
}
fn usable(&self) -> bool {
!self.name.trim().is_empty() && [self.width, self.height].iter().all(|side| (36.0..=14_400.0).contains(side))
}
}
pub type DiscoverPapers = Box<dyn Fn(&str) -> Receiver<Vec<Paper>>>;
/// Paper choices belong to the selected queue and window, never the workbook.
#[derive(Default)]
pub(crate) struct PaperSelection {
queue: String,
offered: Option<Vec<Paper>>,
pub(super) selected: Option<String>,
pending: Vec<(String, Receiver<Vec<Paper>>)>,
}
impl PaperSelection {
pub(super) fn set_queue(&mut self, queue: &str) {
if self.queue != queue {
self.queue = queue.into();
self.offered = None;
self.selected = None;
}
}
pub(crate) fn poll(&mut self, queue: &str, discover: &DiscoverPapers, ctx: &egui::Context) {
self.set_queue(queue);
self.pending.retain(|(requested, answer)| {
match answer.try_recv() {
Err(TryRecvError::Empty) => return true,
Ok(mut papers) if *requested == self.queue => {
papers.retain(Paper::usable);
self.offered = Some(papers);
}
Err(TryRecvError::Disconnected) if *requested == self.queue => self.offered = Some(Vec::new()),
_ => {}
}
false
});
if !queue.is_empty() && self.offered.is_none() && self.pending.len() < 2 && !self.pending.iter().any(|(requested, _)| requested == queue) {
self.pending.push((queue.into(), discover(queue)));
}
if !self.pending.is_empty() {
ctx.request_repaint_after(Duration::from_millis(100));
}
}
pub(super) fn offered(&self, queue: &str) -> &[Paper] {
if self.queue == queue { self.offered.as_deref().unwrap_or_default() } else { &[] }
}
pub(super) fn loading(&self, queue: &str) -> bool {
!queue.is_empty() && (self.queue != queue || self.offered.is_none())
}
pub(crate) fn selected(&self, queue: &str) -> Option<&Paper> {
self.offered(queue).iter().find(|paper| self.selected.as_deref() == Some(paper.id.as_str()))
}
pub(crate) fn show(&mut self, ui: &mut egui::Ui, queue: &str, language: crate::i18n::Language, enabled: bool) {
use egui::accesskit::Role;
let papers = self.offered(queue);
let default = language.tr("Use workbook paper");
let label = language.tr("Paper");
let value = self.selected(queue).map_or(default, |paper| paper.name.as_str());
let mut selected = self.selected.clone();
ui.horizontal(|ui| {
ui.label(label);
ui.add_enabled_ui(enabled && !papers.is_empty(), |ui| {
let response = egui::ComboBox::from_id_salt("gridcraft_queue_paper")
.width(200.0)
.selected_text(value)
.show_ui(ui, |ui| {
ui.selectable_value(&mut selected, None, default);
for paper in papers {
ui.selectable_value(&mut selected, Some(paper.id.clone()), &paper.name);
}
})
.response;
ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label));
});
});
self.selected = selected;
if self.loading(queue) {
let response = ui.label(language.tr("Looking for printer paper sizes…"));
response.ctx.accesskit_node_builder(response.id, |node| node.set_role(Role::Status));
}
}
}
+1
View File
@@ -160,6 +160,7 @@ pub(super) fn chart_design(app: &mut SheetApp, ui: &mut Ui) {
("Doughnut", "doughnut", ""),
("Scatter", "scatter", ""),
("Radar", "radar", ""),
("Pareto", "pareto", ""),
("Waterfall", "waterfall", ""),
("Funnel", "funnel", ""),
("Treemap", "treemap", ""),
+74 -2
View File
@@ -118,11 +118,15 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
("Number Format", &["Comma", "Comma [0]", "Currency", "Currency [0]", "Percent"]),
];
for (g, names) in groups {
ui.label(egui::RichText::new(*g).strong());
ui.label(egui::RichText::new(app.ui.language.tr(g)).strong());
egui::Grid::new(("csg", *g)).spacing(vec2(4.0, 4.0)).show(ui, |ui| {
for (i, n) in names.iter().enumerate() {
// The built-in style keeps its English name: it is stored in the workbook and sent
// by `home.cellStyle`, so only the painted label is translated.
let label = app.ui.language.tr(n);
let st = gridcraft_engine::cmd::format::builtin_cell_style(n, &wb.theme).unwrap_or_default();
let (r, resp) = ui.allocate_exact_size(vec2(82.0, 24.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
let fill = st
.fill
.fg
@@ -144,7 +148,7 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
ui.painter().text(
r.left_center() + vec2(4.0, 0.0),
Align2::LEFT_CENTER,
*n,
label,
egui::FontId::new((st.font.size).clamp(10.0, 15.0), fam),
col,
);
@@ -162,3 +166,71 @@ pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
});
}
}
#[cfg(test)]
mod tests {
use super::cell_style_gallery;
use crate::SheetApp;
use crate::i18n::Language;
use egui_kittest::kittest::{NodeT as _, Queryable};
use serde_json::json;
/// Every text a frame painted, at any depth.
fn painted_text(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => out.push(t.galley.text().to_owned()),
egui::Shape::Vec(shapes) => {
for s in shapes {
painted_text(s, out);
}
}
_ => {}
}
}
/// The gallery paints its group headings and style names through the interface language, while
/// the English built-in names stay what `home.cellStyle` receives.
#[test]
fn gallery_labels_are_translated() {
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("app.language.set", serde_json::json!({"language": "ja"})).unwrap();
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| cell_style_gallery(&mut app, ui));
output.textures_delta.clear();
let mut texts = Vec::new();
for clipped in &output.shapes {
painted_text(&clipped.shape, &mut texts);
}
for english in ["Good, Bad and Neutral", "Heading 1"] {
let translated = Language::Ja.tr(english);
assert_ne!(translated, english, "the Japanese catalog translates {english:?}");
assert!(texts.iter().any(|t| t == translated), "the gallery paints {translated:?}; painted: {texts:?}");
assert!(!texts.iter().any(|t| t == english), "the gallery no longer paints {english:?}");
}
}
/// Each swatch is a button named with its translated label, and activating it applies the
/// English built-in style (`home.cellStyle`'s key), not the painted translation (#4249).
#[test]
fn gallery_swatches_are_named_buttons_and_activate_their_builtin_style() {
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("app.language.set", json!({"language": "ja"})).unwrap();
let mut h = egui_kittest::Harness::builder()
.with_size(egui::vec2(600.0, 800.0))
.allow_missing_glyphs()
.build_ui_state(|ui, app: &mut SheetApp| cell_style_gallery(app, ui), app);
h.run_steps(2);
let label = Language::Ja.tr("Heading 1");
let swatch = h.get_by_label(label);
assert_eq!(swatch.accesskit_node().role(), egui::accesskit::Role::Button, "the swatch is a button");
swatch.click();
h.run_steps(2);
let cell = h.state_mut().session.execute("cell.get", json!({"cell": "A1"})).unwrap();
assert_eq!(cell["style"]["font"]["size"], json!(15.0), "Heading 1's size");
assert_eq!(cell["style"]["font"]["bold"], json!(true), "Heading 1's weight");
}
}
+6 -1
View File
@@ -125,7 +125,12 @@ pub(super) fn insert(app: &mut SheetApp, ui: &mut Ui) {
"insert.chart.scatter",
vec![("Scatter", "scatter", ""), ("Scatter with Lines", "scatter", "lines"), ("Bubble", "bubble", "")],
),
(Icon::Chart, "Statistic", "insert.chart.statistic", vec![("Histogram", "histogram", ""), ("Box & Whisker", "boxWhisker", "")]),
(
Icon::Chart,
"Statistic",
"insert.chart.statistic",
vec![("Histogram", "histogram", ""), ("Pareto", "pareto", ""), ("Box & Whisker", "boxWhisker", "")],
),
(
Icon::Theme,
"Hierarchy & more",
+3
View File
@@ -55,6 +55,9 @@ pub(super) fn page_layout(app: &mut SheetApp, ui: &mut Ui) {
"Legal",
"Tabloid",
"Executive",
"A0",
"A1",
"A2",
"A3",
"A4",
"A5",

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