Compare commits

..
Author SHA1 Message Date
FredApps e6bba235af Lock the shared workbook page range dependencies 2026-12-03 00:28:31 +01:00
FredApps 91a7e1b533 Return the workbook preview to the first sheet when its page range changes
(cherry picked from commit 7f6a69b126)
2026-12-03 00:26:53 +01:00
FredApps 897158c43c Restore the print scope import for ranged workbook previews 2026-12-03 00:26:53 +01:00
FredApps 860be81832 Use current queue fixtures and inspect the selected worksheet PDF page
(cherry picked from commit a52182d431)
2026-12-03 00:26:52 +01:00
FredApps 79c0836f34 Use shared page bounds for workbook print, preview and PDF output 2026-12-02 23:25:58 +01:00
FredApps 894bb14be2 Integrate the contributor page-range controls with current GridCraft printing 2026-12-02 23:21:15 +01:00
Ingmar Lübbe c50fa8d3e1 Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-13 14:08:55 +01:00
Ingmar Lübbe 30bfcac0d1 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-05 09:47:47 +01:00
Ingmar Lübbe 078ef5f7cc Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-04 07:44:45 +01:00
Ingmar LübbeandClaude Opus 5.5 1bfd0f0cf0 Print: a call to another window uses that window's page range (#3016)
`engine.execute` with `window` or `doc` made the target window active in the engine, but a UI
command such as `ui.printSettings` or `ui.printSubmit` still read and changed the interface state
of the window that was active: it set that window's page range, and printed the target workbook
with it. `run_in` now brings in the target window's interface state before the command and the
active window's after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-04 00:12:27 +01:00
Ingmar LübbeandClaude Opus 5.5 6376c5ddb2 Print: each window keeps its own page range (#3016)
File › Print's page range was one for the whole app: with two workbooks in their Print views, a
range set in one applied to the other, and one starting after its last page disabled its Print
button. `print_pages` is now part of the interface state each window parks and swaps in, like its
Backstage view; a new window starts with every page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-03 20:21:36 +01:00
Ingmar Lübbe 3f935e0461 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-03 19:59:49 +01:00
Ingmar Lübbe 455d11bd5a Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-02 17:51:54 +01:00
Ingmar Lübbe 9f5919dd87 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	crates/engine/src/cmd/print/tests.rs
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 16:11:26 +01:00
Ingmar Lübbe b1ecd718af Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 15:41:14 +01:00
Ingmar Lübbe 0ba908412c Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/gaps.md
2026-11-02 07:34:17 +01:00
Ingmar LübbeandClaude Opus 5.5 adbcd14233 Print: a page range counts the pages in the sheet's page order (#3016)
With main's page order merged in, a test holds `from`/`to` to the pages as they print: over,
then down, page 2 of a 2×2 sheet is the top right one and page 3 the bottom left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-11-02 07:26:37 +01:00
Ingmar Lübbe 145c253a60 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	crates/engine/src/cmd/print.rs
#	docs/file-format-parity.md
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-02 07:08:41 +01:00
Ingmar LübbeandClaude Opus 5.5 4f7f73cd4b Print: a page range (Pages … to …) in File › Print and Export as PDF (#3016)
file.print, file.exportPdf and file.printPreview take `from` and `to`,
page numbers counted over the whole job in sheet order. Only those pages
print, and their headers and footers keep the job's &P and &N. As Excel
measures it, a range after the last page is an error, `to` past the last
page stops there and `from` greater than `to` prints the pages between.
The preview lists only the pages that print, under their own numbers.

File › Print has Pages … to … below the scope, set through
ui.printSettings, which takes `from`/`to` (null clears one);
ui.printSubmit prints that range. Export › Create PDF has the same
fields. Labels in all interface languages; docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-10-31 10:15:30 +01:00
142 changed files with 1412 additions and 9284 deletions
Generated
+19 -1
View File
@@ -1281,6 +1281,16 @@ 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"
@@ -1406,6 +1416,14 @@ 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"
@@ -2941,6 +2959,7 @@ version = "0.20.0"
dependencies = [
"craft-csv",
"craft-gridcraft-format",
"craft-pages",
"gridcraft-calc",
"gridcraft-chart",
"gridcraft-core",
@@ -3050,7 +3069,6 @@ dependencies = [
"craft-host",
"craft-keymap",
"craft-print",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
+1 -1
View File
@@ -44,6 +44,7 @@ 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" }
@@ -105,7 +106,6 @@ craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
[workspace.lints.rust]
unsafe_code = "forbid"
-29
View File
@@ -275,37 +275,8 @@ handling again for troubleshooting.
| Fedora/RHEL/openSUSE | `gridcraft-<ver>-linux-x86_64.rpm` | `gridcraft-<ver>-linux-aarch64.rpm` | |
| Tarball | `gridcraft-<ver>-linux-x86_64.tar.gz` | `gridcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
#### Community packages
These packages are maintained by community members, not by the GridCraft team, and the project
does not review them. An overlay's ebuilds run as root when you install a package, so read the
ebuild before you emerge it.
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the
Linux release as `app-office/gridcraft-bin` (prebuilt) and `app-office/gridcraft` (built from source).
`gridcraft-bin` downloads `gridcraft-<ver>-linux-x86_64.tar.gz` from this repository's releases, and
Portage refuses the file unless it matches the overlay's `Manifest`. To check that it is the
release's own file before installing it, fetch it first with `emerge --fetchonly`, run `sha256sum`
on it in your `DISTDIR` and compare with the release's `SHA256SUMS.txt`.
```sh
emerge --ask --noreplace app-eselect/eselect-repository
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
emaint sync -r snakebyte
# package.accept_keywords can be a directory or a single file
if [ -d /etc/portage/package.accept_keywords ]; then
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/gridcraft
else
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords
fi
emerge --fetchonly app-office/gridcraft-bin # then check the file in DISTDIR as above
emerge --ask app-office/gridcraft-bin
```
### FreeBSD
Current prebuilt FreeBSD downloads require FreeBSD 15.1 or later; they are not compatible with FreeBSD 14.x.
| Build | File |
|---|---|
| x86_64 | `gridcraft-<ver>-freebsd-x86_64.tar.gz` |
-5
View File
@@ -119,11 +119,6 @@ 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,11 +141,6 @@ 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,70 +915,6 @@ 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>) {
+12 -55
View File
@@ -57,9 +57,6 @@ 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
@@ -117,8 +114,6 @@ 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(),
@@ -243,25 +238,6 @@ 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).
@@ -633,10 +609,6 @@ 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
@@ -726,7 +698,18 @@ 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`.
if self.range_has_spill(sheet, range) {
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 {
return false;
}
for (c, cell) in sh.cells.iter_range(range) {
@@ -737,32 +720,6 @@ impl Host for PassHost<'_> {
}
true
}
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
if self.iterate || self.range_has_spill(sheet, range) {
return None;
}
let sh = self.wb.sheet(sheet)?;
// When fewer calculations are in play than cells to inspect, check their coordinates
// first. A formula near the bottom of a dense range would otherwise cost two walks.
let pass_cells = self.pending.len() + self.results.len();
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
return None;
}
let mut bounds: Option<RangeRef> = None;
for (c, cell) in sh.cells.iter_range(range) {
// With no pending or computed results in the block, formula and Python readers
// see the stored values as well. Otherwise leave their evaluation to range_values.
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
return None;
}
if !cell.value.is_empty() {
let cell_range = RangeRef::cell(c);
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
}
}
Some(bounds)
}
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
// Constants can't change during a pass, so a block's result stays valid for it. Spills
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
-19
View File
@@ -810,7 +810,6 @@ fn arrays_do_not_spill_in_tables() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
t.set("C4", "=SEQUENCE(2)");
t.set("E1", "=SEQUENCE(4)");
@@ -840,7 +839,6 @@ fn one_value_array_in_a_table_is_not_a_spill() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
@@ -1571,7 +1569,6 @@ fn subtotal_skips_filtered_rows() {
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
}],
style: String::new(),
@@ -1583,7 +1580,6 @@ fn subtotal_skips_filtered_rows() {
filter: crit(),
table_type: None,
connection_id: None,
query_table: None,
});
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
@@ -2501,21 +2497,6 @@ 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
+2 -9
View File
@@ -95,15 +95,8 @@ impl Evaluator<'_> {
if (h as u64) * (w as u64) > MAX_CELLS {
return Err(CellError::Num);
}
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 values = self.host.range_values(a.sheet, part);
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
+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::{ChartLabels, Swatch, legend_entries, legend_entries_with, render, render_with_labels, supports_trendline};
pub use render::{Swatch, legend_entries, render, supports_trendline};
pub use resolve::{default_palette, has_volatile_series, resolve, series_color};
pub use sparkline::render_sparkline;
+5 -11
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, pareto, pie, radar, stock, treemap, waterfall};
use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall};
use legend::draw_legend;
pub use legend::{ChartLabels, Swatch, legend_entries, legend_entries_with};
pub use legend::{Swatch, legend_entries};
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).
pub(crate) const MAX_LINE_PTS: usize = 2000;
const MAX_LINE_PTS: usize = 2000;
/// Most markers per series (after de-duplicating by pixel).
pub(crate) const MAX_MARKERS: usize = 5000;
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,11 +217,6 @@ 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![];
}
@@ -238,7 +233,7 @@ pub fn render_with_labels(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &d
area.y += used;
area.h -= used;
}
let entries = legend_entries_with(chart, &data, labels);
let entries = legend_entries(chart, &data);
if !entries.is_empty() && area.ok() {
area = draw_legend(&mut ctx, &entries, chart.legend, area);
}
@@ -266,7 +261,6 @@ 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),
+9 -125
View File
@@ -1,19 +1,16 @@
use std::collections::HashMap;
use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range};
use super::legend::{cat_label, pareto_line_color, point_color};
use super::lines::decimate;
use super::legend::{cat_label, point_color};
use super::{
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,
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,
};
// ---------------------------------------------------------------- histogram
/// 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())?;
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 };
let n = vals.len();
let span = hi - lo;
let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100);
@@ -25,12 +22,13 @@ fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
// 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;
@@ -39,15 +37,6 @@ fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
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");
@@ -66,111 +55,6 @@ 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,32 +31,8 @@ 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![];
}
@@ -68,10 +44,6 @@ pub fn legend_entries_with(chart: &Chart, data: &ChartData, labels: &ChartLabels
(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![];
+1 -196
View File
@@ -3,13 +3,12 @@ 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; 29] = [
const ALL_KINDS: [ChartKind; 28] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -31,7 +30,6 @@ const ALL_KINDS: [ChartKind; 29] = [
ChartKind::Bubble,
ChartKind::Radar,
ChartKind::Histogram,
ChartKind::Pareto,
ChartKind::Waterfall,
ChartKind::Funnel,
ChartKind::Treemap,
@@ -156,198 +154,6 @@ 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);
@@ -666,7 +472,6 @@ 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,32 +2,13 @@
//!
//! 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_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,
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,
};
pub use date::DateSystem;
pub use region::Region;
+2 -3
View File
@@ -522,9 +522,8 @@ 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: 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;
/// Longest text a cell can hold, in UTF-16 code units.
pub const MAX_TEXT_CHARS: usize = 32_767;
/// `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,20 +326,6 @@ 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;
mod date_time;
// date_time
// filter
// financial
mod information;
mod logical;
mod math_trig;
// math_trig
mod model_info;
// other
// parent_child
// statistical
// table_manipulation
// text
mod time_intelligence;
// 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 },
Family { name: "date_time", scalar: date_time::call, table: date_time::call_table },
// date_time
// filter
// financial
Family { name: "information", scalar: information::call, table: information::call_table },
Family { name: "logical", scalar: logical::call, table: logical::call_table },
Family { name: "math_trig", scalar: math_trig::call, table: math_trig::call_table },
// math_trig
Family { name: "model_info", scalar: model_info::call, table: model_info::call_table },
// other
// parent_child
// statistical
// table_manipulation
// text
Family { name: "time_intelligence", scalar: time_intelligence::call, table: time_intelligence::call_table },
// time_intelligence
// visual
];
-613
View File
@@ -1,613 +0,0 @@
//! 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
@@ -1,331 +0,0 @@
//! 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
@@ -1,79 +0,0 @@
//! 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))
}
@@ -1,804 +0,0 @@
//! 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))
}
@@ -1,450 +0,0 @@
//! 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,55 +242,11 @@ 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
@@ -1,565 +0,0 @@
//! 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
@@ -1,196 +0,0 @@
//! 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
@@ -1,632 +0,0 @@
//! 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
@@ -1,564 +0,0 @@
//! 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,6 +22,7 @@ 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,7 +210,6 @@ 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}))
@@ -233,7 +232,6 @@ 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_page_breaks, keep_view_modes, keep_watch_list, window_param};
pub(crate) use window::{keep_view_modes, keep_watch_list, window_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
+2 -12
View File
@@ -72,19 +72,9 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
} else {
None
};
// Query field identity follows the surviving physical column, even if its header was renamed.
let query_field_id = c.checked_sub(old.start.col).and_then(|i| old_cols.get(i as usize)).and_then(|x| x.query_field_id);
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), query_field_id, ..x.clone() },
None => TableColumn {
name: name.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id,
xml: None,
},
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
});
}
let sheet = cx.sheet_mut(si)?;
+1 -34
View File
@@ -4,8 +4,7 @@ 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. Page Break Preview also
/// turns on the sheet's page breaks, which Normal view then keeps showing (as in Excel).
/// neither records an undo step nor marks a clean workbook as changed.
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()?;
@@ -13,9 +12,6 @@ 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();
@@ -42,35 +38,6 @@ 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 -10
View File
@@ -413,15 +413,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: headers
.iter()
.map(|h| TableColumn {
name: h.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.collect(),
style: "TableStyleMedium2".into(),
banded_rows: true,
@@ -432,7 +424,6 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
let q = gridcraft_formula::quote_sheet(&sheet_name);
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Chart",
["Insert", "Charts"],
None,
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|pareto|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|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
+1 -6
View File
@@ -59,7 +59,6 @@ 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,
@@ -286,11 +285,7 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
},
title,
series,
legend: match kind {
ChartKind::Pie | ChartKind::Doughnut => LegendPos::Right,
ChartKind::Pareto => LegendPos::None,
_ => LegendPos::Bottom,
},
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
data_labels: false,
data_table: None,
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
+1 -10
View File
@@ -112,15 +112,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: names
.into_iter()
.map(|n| TableColumn {
name: n,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.collect(),
style,
banded_rows: true,
@@ -131,7 +123,6 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
cx.structural = true;
Ok(json!({"table": name, "range": r.a1()}))
+42 -14
View File
@@ -7,7 +7,9 @@
//! 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.
//! 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.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
#[cfg(test)]
@@ -56,7 +58,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
#[cfg(test)]
use layout::bands;
pub(crate) use layout::split_bands;
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, page_break_bands, paper_size, print_range};
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
use layout::{seg_size, segments};
use objects::{PicCache, draw_objects};
#[cfg(test)]
@@ -69,7 +71,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\", 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.",
"{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.",
has_doc,
export_pdf
),
@@ -78,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print…",
["File"],
Some("Cmd+P"),
"{path?, sheets?: active|all, range?, fitToPage?: bool} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
"{path?, sheets?: active|all, range?, fitToPage?: bool, 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",
has_doc,
print
),
@@ -87,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
["File"],
None,
"{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
"{page? (1-based), sheets?: active|all, range?, fitToPage?, 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",
has_doc,
print_preview
),
@@ -96,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Page Setup…",
["Page Layout", "Page Setup"],
None,
"{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",
"{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",
has_doc,
page_setup
),
@@ -119,12 +121,19 @@ 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)
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, 1..=usize::MAX)
}
/// [`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) -> Result<RenderedPdf> {
fn render_pdf_with_image_budget(
wb: &Workbook,
layouts: &[SheetLayout],
file: &str,
path: &str,
image_bytes: u64,
pages: std::ops::RangeInclusive<usize>,
) -> 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() };
@@ -145,6 +154,9 @@ fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &s
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);
@@ -223,8 +235,9 @@ 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(&d.wb, &lays, &d.display_title(), &path)?;
let pdf = render_pdf_with_image_budget(&d.wb, &lays, &d.display_title(), &path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, first..=last)?;
if pdf.missing_arabic_font {
s.ui_requests.push(crate::UiRequest::Message(MISSING_ARABIC_FONT.into()));
}
@@ -252,16 +265,24 @@ 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> {
let opts = PrintOptions::from_params(p, "file.printPreview")?;
const CMD: &str = "file.printPreview";
let opts = PrintOptions::from_params(p, CMD)?;
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!({
@@ -280,11 +301,18 @@ fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some(page) = u32_param(p, "page") {
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}));
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}));
}
Ok(json!({"pages": n, "pageList": list}))
Ok(json!({"pages": list.len(), "total": total, "pageList": list}))
}
fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
+36 -20
View File
@@ -75,6 +75,10 @@ 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>,
}
impl PrintOptions {
@@ -90,7 +94,37 @@ impl PrintOptions {
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
}
}
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
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 })
}
/// 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()))),
}
}
@@ -353,7 +387,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 type Bands = Vec<(u32, u32)>;
pub(crate) type Bands = Vec<(u32, u32)>;
/// Splits a layout's area into row and column bands that fit its pages (at most `cap` of each),
/// honouring manual breaks (when `lay.manual_breaks`), print headings and repeated titles. The
@@ -386,24 +420,6 @@ 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();
+192 -27
View File
@@ -1,4 +1,6 @@
use gridcraft_model::{Sparkline, SparklineKind};
use std::collections::BTreeSet;
use serde_json::json;
use super::*;
@@ -22,29 +24,6 @@ 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> {
@@ -922,7 +901,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).unwrap();
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget, 1..=usize::MAX).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");
@@ -965,9 +944,6 @@ 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),
@@ -1314,6 +1290,186 @@ 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};
@@ -1593,6 +1749,15 @@ 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);
+6 -70
View File
@@ -727,80 +727,17 @@ 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 lines = LockedLines::of(sh, axis, &locked);
if !(at..=end).all(|i| lines.unlocked(sh, i, &locked)) {
let infos = if axis == Axis::Rows { &sh.rows } else { &sh.cols };
if (at..=end).any(|i| locked(infos.get(&i).and_then(|x| x.style).unwrap_or_default())) {
return Err(refuse());
}
let block = if axis == Axis::Rows { RangeRef::rows(at, end) } else { RangeRef::cols(at, end) };
if sh.cells.iter_range(block).any(|(_, cell)| locked(cell.style)) {
return Err(refuse());
}
Ok(())
}
/// 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 {
@@ -958,7 +895,6 @@ fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, inse
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
t.columns.insert((idx + k).min(t.columns.len()), col);
+1 -30
View File
@@ -38,15 +38,6 @@ 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!(
@@ -93,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Size",
["Page Layout", "Page Setup"],
None,
"{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)}",
"{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)}",
has_doc,
paper
),
@@ -234,26 +225,6 @@ fn workbook_view_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
})
}
/// Excel's Show page breaks: a display option of the sheet, so it neither records an undo step
/// nor marks a clean workbook as changed (like `set_view`).
fn show_page_breaks(s: &mut Session, p: &Json) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
let dirty = d.is_dirty();
let current = d.wb.sheet(si).is_some_and(|sh| sh.show_page_breaks);
let on = bool_param(p, "on").unwrap_or(!current);
if on != current {
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.show_page_breaks = on;
}
if !dirty {
d.saved = d.wb.clone();
}
}
Ok(json!({"on": on}))
}
/// Ctrl+6: hides every object, or shows them again. Placeholders (from a file) count as shown.
fn show_objects(s: &mut Session, p: &Json) -> Result<Json> {
use gridcraft_model::ShowObjects;
-1
View File
@@ -904,7 +904,6 @@ mod tests {
filter: Vec::new(),
table_type: None,
connection_id: None,
query_table: None,
});
let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)];
let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None };
-1
View File
@@ -695,7 +695,6 @@ fn grow_right(
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
});
cx.rebuild_deps = true;
-203
View File
@@ -3947,84 +3947,6 @@ 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();
@@ -4120,7 +4042,6 @@ 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),
@@ -4152,16 +4073,6 @@ 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();
@@ -7611,120 +7522,6 @@ 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,327 +317,6 @@ 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, Show page breaks) and the Watch Window list reset: undo restores view state as it was, but
/// Page Break Preview) 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,8 +542,6 @@ 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
}
+2 -11
View File
@@ -600,15 +600,8 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
{
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
let col = |name: &str| TableColumn {
name: name.into(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
let col =
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
sh.tables.push(Table {
id: 1,
name: "LeftTable".into(),
@@ -625,7 +618,6 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.tables.push(Table {
id: 2,
@@ -643,7 +635,6 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(2).or_default().hidden = true;
@@ -55,31 +55,6 @@ fn resize_next_to_another_table_still_works() {
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
}
#[test]
fn resize_keeps_a_renamed_column_query_field() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns[1].query_field_id = Some(7);
s.execute("range.setValues", json!({"range":"B1", "values":[["Amount"]]})).unwrap();
s.execute("table.resize", json!({"table":"T", "range":"A1:B3"})).unwrap();
let col = &s.doc().unwrap().wb.active().unwrap().tables[0].columns[1];
assert_eq!((col.name.as_str(), col.query_field_id), ("Amount", Some(7)));
}
#[test]
fn resize_preserves_query_fields_only_for_surviving_addresses() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
let columns = &mut std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns;
columns[0].query_field_id = Some(3);
columns[1].query_field_id = Some(7);
s.execute("table.resize", json!({"table":"T", "range":"B1:C3"})).unwrap();
let cols = &s.doc().unwrap().wb.active().unwrap().tables[0].columns;
assert_eq!(cols.iter().map(|c| c.query_field_id).collect::<Vec<_>>(), [Some(7), None]);
}
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
s.doc().unwrap().wb.active().unwrap()
}
+2 -72
View File
@@ -23,19 +23,6 @@ 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
@@ -246,12 +233,6 @@ 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));
@@ -311,20 +292,13 @@ 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 = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -370,7 +344,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
}
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -593,7 +567,6 @@ pub(crate) fn specs() -> Vec<FnSpec> {
mod tests {
use gridcraft_core::{CellError, Value};
use crate::Arg;
use crate::util::testutil::*;
fn table() -> Value {
@@ -786,49 +759,6 @@ 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, 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,
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,
};
#[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.",
hypgeomdist_legacy
hypgeom_dist
),
f!(
"NEGBINOM.DIST",
+2 -22
View File
@@ -804,27 +804,15 @@ 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() })
}
fn hypgeom_common(a: &[Arg], strict: bool) -> R<Value> {
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> 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 {
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) {
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));
@@ -841,14 +829,6 @@ fn hypgeom_common(a: &[Arg], strict: bool) -> 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,25 +821,6 @@ fn discrete() {
close_tol(ev("NEGBINOMDIST", vec![n(10.0), n(5.0), n(0.25)]), 0.0550487, D7);
}
#[test]
fn hypgeom_dist_out_of_support_clamps() {
// Support is [max(0, n - nn + kk), min(n, kk)].
// Above support: k=2, n=1, kk=1, nn=3 -> high = min(1, 1) = 1, so 2 is above.
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(false)]), Value::Number(0.0));
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(true)]), Value::Number(1.0));
// Controls inside the support (low = max(0, 1 - 3 + 1) = 0, high = 1).
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(false)]), 1.0 / 3.0);
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(true)]), 1.0);
// Below support stays #NUM!, as Excel documents: k=0, n=4, kk=8, nn=10
// -> low = max(0, 4 - 10 + 8) = 2, so 0 is below.
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(false)]), CellError::Num);
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(true)]), CellError::Num);
// Legacy compatibility form stays strict outside the support.
is_err(ev("HYPGEOMDIST", vec![n(5.0), n(4.0), n(8.0), n(20.0)]), CellError::Num);
// Invalid population arguments stay #NUM! (number_sample > number_pop here).
is_err(ev("HYPGEOM.DIST", vec![n(1.0), n(5.0), n(2.0), n(3.0), b(false)]), CellError::Num);
}
#[test]
fn continuous() {
close_tol(ev("EXPON.DIST", vec![n(0.2), n(10.0), b(true)]), 0.86466472, D7);
-9
View File
@@ -60,10 +60,6 @@ pub struct TableColumn {
/// `uniqueName`: the name XML maps know the column by.
#[serde(default)]
pub unique_name: Option<String>,
/// `queryTableFieldId`: the field of the table's query table this column shows. It moves with
/// the column; inserted columns have none.
#[serde(default)]
pub query_field_id: Option<u32>,
/// Binding to an element of an XML map. It moves with the column and goes when the column is
/// deleted; inserted columns are unmapped.
#[serde(default)]
@@ -106,10 +102,6 @@ pub struct Table {
/// The connection (`xl/connections.xml`) an XML table is bound through.
#[serde(default)]
pub connection_id: Option<u32>,
/// The XML of the table's query table part (`xl/queryTables/…`), kept as read so the table
/// stays attached to its data connection. Never refreshed.
#[serde(default)]
pub query_table: Option<String>,
}
impl Table {
@@ -521,7 +513,6 @@ pub enum ChartKind {
Bubble,
Radar,
Histogram,
Pareto,
Waterfall,
Funnel,
Treemap,
+1 -4
View File
@@ -6,14 +6,11 @@
/// 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); 27] = [
pub const PAPERS: [(&str, f32, f32); 24] = [
("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,10 +131,6 @@ 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>,
@@ -215,7 +211,6 @@ impl Sheet {
show_formulas: false,
show_zeros: true,
right_to_left: false,
show_page_breaks: false,
zoom: 100,
cond_formats: vec![],
validations: vec![],
-1
View File
@@ -16,7 +16,6 @@ craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-print = { workspace = true }
craft-quit = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
gridcraft-engine = { workspace = true }
+3 -21
View File
@@ -42,6 +42,7 @@ impl SheetApp {
notice: None,
services,
printing: Default::default(),
print_pages: Default::default(),
print_feedback_seen: None,
synthetic: Default::default(),
ctrl_wheel: false,
@@ -93,7 +94,6 @@ impl SheetApp {
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
unsaved_prompt: None,
framework_host: crate::framework::host(),
}
}
@@ -206,9 +206,6 @@ impl SheetApp {
let t0 = now_ms();
// A script may have switched windows since the last frame.
self.follow_active_window();
// The window this pass draws: a command run in it may switch to another window, which draws
// in its own pass.
let drawn = self.ui_window();
// This window's key tip request that waited for this frame (its tab or ribbon was just
// shown); any other window's request was dropped before it.
self.ui.keytip_invoke = self.ui.keytip_invoke_next.take();
@@ -271,13 +268,10 @@ impl SheetApp {
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
// The update flow runs once per frame, in the root window; the framework dialogs too, unless
// the unsaved-changes question asks about a workbook in another window: they show there.
#[cfg(not(target_arch = "wasm32"))]
// The update flow and the framework dialogs run once per frame, in the root window.
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
}
if self.framework_dialogs_here(&ctx, drawn) {
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
@@ -309,18 +303,6 @@ impl SheetApp {
}
}
/// Whether a modal question is up and owns the keyboard: a GridCraft dialog or the shared
/// unsaved-changes question.
pub fn modal_open(&self) -> bool {
self.dialog.is_some() || self.unsaved_prompt.is_some()
}
/// The name of the open dialog, for automation: a GridCraft dialog's, or `saveChanges` while
/// the shared unsaved-changes question is up.
pub fn open_dialog_name(&self) -> Option<&str> {
self.dialog.as_ref().map(|d| d.name()).or_else(|| self.unsaved_prompt.as_ref().map(|_| "saveChanges"))
}
/// Current selection's top-left cell text as A1 (for the Name Box).
pub fn name_box_text(&self) -> String {
let Some(d) = self.session.active() else { return String::new() };
+8 -8
View File
@@ -223,8 +223,13 @@ impl SheetApp {
Ok(Json::Null)
}
"data.fromClipboard" => self.import_clipboard_text(p),
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
"ui.printSubmit" => self.submit_print(p.clone()),
"ui.printSettings" => printing::settings(&mut self.printing, &mut self.print_pages, p, self.services.printers.as_ref()),
"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.ribbonTab" => {
self.ui.ribbon_tab = p.get("tab").and_then(Json::as_str).unwrap_or("Home").to_string();
Ok(Json::Null)
@@ -298,8 +303,6 @@ 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(", "))),
@@ -307,12 +310,10 @@ 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)),
@@ -335,7 +336,7 @@ impl SheetApp {
"ui.dialog" => {
let name = p.get("name").and_then(Json::as_str).unwrap_or("");
self.open_dialog(name, p.clone());
Ok(json!({"dialog": self.open_dialog_name()}))
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
@@ -481,7 +482,6 @@ impl SheetApp {
}
// The notice AutoSave holds back with: Save asks what the notice says.
"saveLoss" => self.run_or_alert("file.save", json!({})),
"saveChanges" => self.open_unsaved_changes(&params),
// File › Options (`file.options`) and the File tab itself open the Backstage view.
"options" => self.open_backstage(backstage::Page::Options),
"backstage" => {
+1 -1
View File
@@ -4,7 +4,7 @@ impl SheetApp {
pub(super) fn ribbon_keys(&mut self, ctx: &egui::Context) {
let before = self.keytips.prefix().map(str::to_string);
let enabled = self.editor.is_none()
&& !self.modal_open()
&& self.dialog.is_none()
&& self.message.is_none()
&& self.name_box.is_none()
&& !ctx.text_edit_focused()
+7 -82
View File
@@ -1,10 +1,7 @@
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::{DialogResult, UnsavedAnswer, UnsavedChangesDialog};
use craft_ui::shell::embed::CloseDecision;
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
use crate::state::UnsavedPrompt;
impl SheetApp {
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
@@ -34,11 +31,12 @@ impl SheetApp {
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
match self.dialog.as_mut() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
self.promote_unsaved_to_quit();
} else {
self.continue_quit(ctx);
Some(d) if d.name() == "saveChanges" => {
d.values.insert("quit".into(), json!(true));
}
_ => self.continue_quit(ctx),
}
CloseDecision::Hold
}
@@ -235,86 +233,13 @@ impl SheetApp {
crate::macro_editor::request_close(self, true);
return;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
// Already asking about a workbook (File › Close): answering it goes on to quit.
self.promote_unsaved_to_quit();
d.values.insert("quit".into(), json!(true));
return;
}
self.continue_quit(ctx);
}
/// Opens the shared unsaved-changes dialog on `framework_dialogs` for the active workbook.
pub(crate) fn open_unsaved_changes(&mut self, params: &Json) {
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
self.message = Some((
"Macro".into(),
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
));
return;
}
if let Some(mut old) = self.dialog.take() {
let _ = old.end_pick(self);
}
let Some(doc) = self.session.active().map(|d| d.uid) else { return };
let title = params
.get("title")
.and_then(Json::as_str)
.map(str::to_owned)
.or_else(|| self.session.active().map(|d| d.display_title()))
.unwrap_or_else(|| "this workbook".into());
let quitting = params.get("quit").and_then(Json::as_bool) == Some(true);
let scope = if quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(UnsavedPrompt { doc, window: self.ui_window(), quitting });
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
// A replaced question leaves a Cancel result; it is not the new question's answer.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
fn promote_unsaved_to_quit(&mut self) {
if let Some(prompt) = self.unsaved_prompt.as_mut()
&& !prompt.quitting
{
prompt.quitting = true;
let title =
self.session.documents().iter().find(|d| d.uid == prompt.doc).map(|d| d.display_title()).unwrap_or_else(|| "this workbook".into());
self.framework_dialogs.open(UnsavedChangesDialog::new(CloseScope::Quit, title).document_wording(true));
// The question it replaced left a Cancel as its result; it was not answered, and the
// quit's question asks on.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
}
/// Reads the answer from an open [`UnsavedChangesDialog`] and continues closing or quitting.
pub(crate) fn take_unsaved_changes_dialog(&mut self, ctx: &egui::Context) {
let Some(result) = self.framework_dialogs.take::<UnsavedChangesDialog>() else {
return;
};
let Some(prompt) = self.unsaved_prompt.take() else {
return;
};
let answer = match result {
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::DontSave, .. }) => SaveAnswer::DontSave,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Save, .. }) => SaveAnswer::Save,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Cancel, .. }) | DialogResult::Cancel | _ => SaveAnswer::Cancel,
};
if answer == SaveAnswer::Cancel {
return;
}
if let Some(w) = prompt.window.filter(|w| self.session.window(*w).is_some())
&& self.ui_window() != Some(w)
{
self.enter_window(w);
}
if self.session.active().map(|d| d.uid) != Some(prompt.doc) {
return;
}
if !self.answer_save_changes(answer, prompt.quitting, ctx) {
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
let scope = if prompt.quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(prompt);
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
}
}
}
#[cfg(test)]
+49 -18
View File
@@ -18,13 +18,14 @@ 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::print;
use print::{page_range_fields, print};
/// Width of the navigation column.
const NAV_W: f32 = 196.0;
@@ -99,8 +100,16 @@ impl Page {
}
/// What a print preview was built for: document, revision, scope, the selection when it is
/// the scope, and fit to page.
type PreviewKey = (u64, u64, PrintScope, String, bool);
/// the scope, fit to page, and the requested page range.
#[derive(Clone, Debug, PartialEq, Eq)]
struct PreviewKey {
document: u64,
revision: u64,
scope: PrintScope,
selection: String,
fit_to_page: bool,
pages: PageRange,
}
/// What File › Print › Settings prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -145,10 +154,15 @@ 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).
/// Print: the previewed page (0-based, among the pages that print).
preview_page: usize,
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
/// Print: the preview and what it was made for.
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.
@@ -170,6 +184,9 @@ 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(),
}
@@ -250,7 +267,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 out),
Page::Export => export(app, ui, &mut bs, &mut out),
Page::Options => options(app, ui),
Page::Account => account(app, ui),
}
@@ -258,7 +275,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
@@ -728,7 +745,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) {
} else if export_as(app, fmt, json!({})) {
out.close = true;
}
}
@@ -736,12 +753,23 @@ 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, out: &mut Outcome) {
fn export(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let lang = app.ui.language;
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;
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;
}
}
ui.add_space(14.0);
section(ui, lang, "Change File Type");
@@ -749,15 +777,16 @@ fn export(app: &mut SheetApp, ui: &mut Ui, 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) {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt, json!({})) {
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. Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
/// 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 {
if !app.commit_edit(0, 0, false, false) {
return false;
}
@@ -767,13 +796,15 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> 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();
return match app.run(id, json!({"path": path})) {
params["path"] = json!(path);
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
@@ -787,7 +818,7 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> 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, json!({})) {
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
-6
View File
@@ -46,12 +46,6 @@ 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);
+49 -10
View File
@@ -1,9 +1,9 @@
use super::{
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
vec2,
Align2, Backstage, Icon, Json, Language, Outcome, PageRange, PreviewKey, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim,
json, pos2, square_button, theme, vec2,
};
/// 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.
/// 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.
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,19 +23,27 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if bs.fit_to_page {
params["fitToPage"] = json!(true);
}
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
app.print_pages.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 };
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
if bs.preview.as_ref().is_some_and(|(k, _)| k.pages != key.pages) {
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 pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
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);
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());
}
let can_print = app.services.print_native.is_none() || app.printing.ready();
let can_print = (app.services.print_native.is_none() || app.printing.ready()) && !pages.is_empty();
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)
{
@@ -57,6 +65,16 @@ 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;
}
@@ -95,10 +113,9 @@ 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);
}
let text = lang
.tr("Page {page} of {pages}")
.replace("{page}", &(bs.preview_page + 1).to_string())
.replace("{pages}", &pages.len().to_string());
// 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());
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);
@@ -108,6 +125,28 @@ 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;
+3 -5
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::{ChartLabels, HAlign, Prim, VAlign};
use gridcraft_chart::{HAlign, Prim, VAlign};
use gridcraft_engine::model::{Anchor, ObjKind, ObjRef, ShapeKind, Sheet, Workbook};
use crate::SheetApp;
@@ -39,8 +39,7 @@ 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 labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
let prims = gridcraft_chart::render_with_labels(chart, &data, w, h, &m, &labels);
let prims = gridcraft_chart::render(chart, &data, w, h, &m);
paint_prims(&p.with_clip_rect(rect.intersect(p.clip_rect())), origin, &prims, z);
}
@@ -255,8 +254,7 @@ 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 };
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)
gridcraft_chart::render(ch, &data, ch.anchor.width, ch.anchor.height, &m)
}
/// The primitives of chart `ci` of sheet `si`: from the frame cache when the workbook, zoom and
+8 -5
View File
@@ -110,8 +110,12 @@ 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
}
@@ -147,8 +151,7 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
"grid": app.grid.cells_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
"scroll": [v.scroll.x, v.scroll.y],
"editor": app.editor.as_ref().map(|e| editor_json(app, e)),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab}))
.or_else(|| app.unsaved_prompt.as_ref().map(|p| json!({"name": "saveChanges", "values": {"quit": p.quitting}}))),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab})),
"backstage": app.backstage.as_ref().map(|b| b.page.id()),
"message": app.message.as_ref().map(|(t, m)| json!({"title": t, "text": m})),
"selectedObject": app.selected_object,
@@ -295,12 +298,12 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
(
"ui.printSettings",
"Print Settings",
"{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",
"{printer?: discovered name, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, from?: page (1-based)|null, to?: page|null, refresh?: bool} → {printer,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",
),
(
"ui.printSubmit",
"Submit Print Job",
"existing file.print sheet/pagination params → {printing,bytes,pending}; submits without opening a dialog",
"existing file.print sheet/pagination params; without from/to, the page range of ui.printSettings → {printing,bytes,pending}; submits without opening a dialog",
),
("app.language.set", "Interface Language", language_params.as_str()),
("app.language.english", "Interface Language: English", ""),
@@ -340,7 +343,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
}
"ui.dialog" => {
app.open_dialog(s("name").unwrap_or(""), p.clone());
ok(json!({"dialog": app.open_dialog_name()}))
ok(json!({"dialog": app.dialog.as_ref().map(|d| d.name.clone())}))
}
"ui.dialog.set" => match app.dialog.as_mut() {
Some(d) => {
+1
View File
@@ -1166,6 +1166,7 @@ impl Dialog {
"formatControl" => return crate::control_ui::open_format(app, &params),
"controlQuestion" => return crate::control_ui::open_question(&params),
"saveCopy" => Dialog::custom("saveCopy", "Save a Copy", json!({"format": p("format")})),
"saveChanges" => Dialog::custom("saveChanges", "Save Changes?", json!({"title": p("title"), "quit": p("quit")})),
"start" => Dialog::custom("start", "GridCraft", json!({})),
"comments" => {
app.grid.pane = None;
+2 -3
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); 24] = [
const ALL_CHARTS: [(&str, &str, &str); 23] = [
("column", "", "Clustered Column"),
("column", "stacked", "Stacked Column"),
("column", "stacked100", "100% Stacked Column"),
@@ -23,7 +23,6 @@ const ALL_CHARTS: [(&str, &str, &str); 24] = [
("scatter", "lines", "Scatter with Lines"),
("radar", "", "Radar"),
("histogram", "", "Histogram"),
("pareto", "", "Pareto"),
("waterfall", "", "Waterfall"),
("funnel", "", "Funnel"),
("combo", "", "Combo"),
@@ -52,7 +51,7 @@ pub(super) fn select_chart(d: &mut Dialog, i: usize) {
fn chart_icon(t: &str) -> Icon {
match t {
"column" | "bar" | "histogram" | "pareto" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"column" | "bar" | "histogram" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"line" | "area" | "radar" => Icon::ChartLine,
"pie" | "doughnut" => Icon::ChartPie,
"scatter" | "bubble" => Icon::ChartScatter,
+13
View File
@@ -374,6 +374,19 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
}
}
}
"saveChanges" => {
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
ui.horizontal(|ui| {
for (label, answer) in
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
{
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
open = false;
}
}
});
}
"saveLoss" => {
let lang = app.ui.language;
let pending = d.pending_save();
+3 -3
View File
@@ -529,7 +529,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
let chars_before = ed.text.chars().count();
// A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the
// editor takes it back afterwards.
let dialog_open = app.modal_open();
let dialog_open = app.dialog.is_some();
if dialog_open && mine {
ed.request_focus = true;
ed.keep_selection = true;
@@ -671,7 +671,7 @@ fn editor_shortcuts(
) -> EditorKeyOutcome {
let mut outcome = EditorKeyOutcome { action: None, arrow: false, cancel: false, to_python: false };
// A message or dialog owns Enter and Escape until it closes.
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
if !has_focus || !mine || app.message.is_some() || app.dialog.is_some() {
return outcome;
}
// Ctrl+Alt+Shift+P turns the edit into Python code.
@@ -864,7 +864,7 @@ fn python_editor(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, width: f32
let Some(mut ed) = app.editor.take() else { return EditorInfo::default() };
// A message box (the code was refused) or a dialog over the edit has the keyboard; the
// editor takes it back when it closes.
let blocked = app.message.is_some() || app.modal_open();
let blocked = app.message.is_some() || app.dialog.is_some();
let mut caret = None;
if blocked {
ed.request_focus = true;
-13
View File
@@ -112,22 +112,9 @@ impl SheetApp {
embed::logic(ctx, || self.close_decision(ctx));
}
/// Whether this pass draws [`SheetApp::framework_dialogs`]: the pass of the window the unsaved-changes
/// question asks about (the window that keeps it, as a GridCraft dialog stays in its window), else the root's.
/// `drawn` is the window the pass began drawing: a question a command in it opened for another window (a quit
/// moving on to the next unsaved workbook) shows in that window's own pass, not for a frame in this one.
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context, drawn: Option<u64>) -> bool {
let shown = |w: &u64| self.session.window(*w).is_some_and(|w| !w.hidden);
match self.unsaved_prompt.as_ref().and_then(|p| p.window).filter(shown) {
Some(w) => drawn == Some(w),
None => ctx.viewport_id() == egui::ViewportId::ROOT,
}
}
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
self.take_unsaved_changes_dialog(ui.ctx());
}
}
-4
View File
@@ -19,8 +19,6 @@ 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).
@@ -380,8 +378,6 @@ pub struct GridState {
pub quick_analysis: crate::quick_analysis::State,
/// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns).
pub paper: Option<crate::paper_view::PaperCache>,
/// Normal view's page breaks: row and column page bands, cached per (doc uid, revision, sheet).
pub page_breaks: Option<PageBreaksCache>,
/// Header or footer being edited in place (Page Layout view).
pub hf_edit: Option<crate::paper_view::HfEdit>,
/// A page margin being dragged on a ruler (Page Layout view); committed on release.
+1 -1
View File
@@ -19,7 +19,7 @@ fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
// arrow key would move the selection the menu fills from), and a macro's question.
editing
|| app.modal_open()
|| app.dialog.is_some()
|| other_focus
|| app.message.is_some()
|| app.grid.filter_menu.is_some()
+2 -2
View File
@@ -328,7 +328,7 @@ pub(super) fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo,
app.grid.fill_tag = None;
return;
}
if app.editor.is_some() || app.modal_open() || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || app.grid.drag != Drag::None {
return;
}
let size = vec2(18.0, 18.0);
@@ -471,7 +471,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
/// The warning button beside an active cell holding a number stored as text, as in Excel: its
/// menu names the problem and offers Convert to Number for the selection (#1994).
pub(super) fn error_check_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
if app.editor.is_some() || app.modal_open() || sh.show_formulas || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
return;
}
let Some(active) = app.session.active().map(|d| d.selection.active) else { return };
-157
View File
@@ -200,8 +200,6 @@ 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) {
@@ -826,66 +824,6 @@ 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());
@@ -1220,98 +1158,3 @@ mod trace_arrow_tests {
assert!((30..=60).contains(&further.len()), "{}", further.len());
}
}
#[cfg(test)]
mod page_break_tests {
use super::*;
use gridcraft_engine::model::{DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT};
/// Two pages across and two down, with a hidden row inside the first page row: the lines sit
/// after columns E and J and after rows 10 and 20, and the hidden row takes no height.
#[test]
fn page_breaks_follow_the_page_bands_in_both_directions() {
let mut sh = Sheet::new("S");
sh.rows.entry(4).or_default().hidden = true;
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 0.0));
let (x0, y0, z) = (geo.cells.left(), geo.cells.top(), geo.z);
let (w, h) = (DEFAULT_COL_WIDTH * z, DEFAULT_ROW_HEIGHT * z);
let lines = page_break_lines(&sh, &geo, &[(0, 9), (10, 19)], &[(0, 4), (5, 9)], geo.cells);
let (bottom, right) = (y0 + 19.0 * h, x0 + 10.0 * w);
let expect = [
[pos2(x0 + 5.0 * w, y0), pos2(x0 + 5.0 * w, bottom)],
[pos2(right, y0), pos2(right, bottom)],
[pos2(x0, y0 + 9.0 * h), pos2(right, y0 + 9.0 * h)],
[pos2(x0, bottom), pos2(right, bottom)],
];
assert_eq!(lines.len(), expect.len(), "{lines:?}");
for (got, want) in lines.iter().zip(expect) {
for (g, w) in got.iter().zip(want) {
assert!((g.x - w.x).abs() < 0.01 && (g.y - w.y).abs() < 0.01, "{lines:?}");
}
}
assert!(page_break_lines(&sh, &geo, &[], &[(0, 4)], geo.cells).is_empty(), "no pages, no lines");
}
/// Frozen rows: a page break scrolled up under them is not drawn over the frozen rows, and the
/// vertical lines start below them.
#[test]
fn page_breaks_scrolled_under_frozen_rows_are_hidden() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 0));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 10.0 * DEFAULT_ROW_HEIGHT));
let pane_top = geo.cells.top() + geo.frozen_h;
let lines = page_break_lines(&sh, &geo, &[(5, 9), (10, 40)], &[(5, 9)], geo.cells);
let horizontal: Vec<_> = lines.iter().filter(|l| l[0].y == l[1].y).collect();
assert_eq!(horizontal.len(), 1, "the break after row 10 is under the frozen rows: {lines:?}");
assert!(horizontal[0][0].y > pane_top);
let vertical: Vec<_> = lines.iter().filter(|l| l[0].x == l[1].x).collect();
assert_eq!(vertical.len(), 1);
let start = vertical[0][0].y;
assert!(start >= pane_top && start < pane_top + BREAK_DASH + BREAK_GAP, "starts below the frozen rows: {start} vs {pane_top}");
}
#[test]
fn page_break_at_freeze_boundary_stays_on_frozen_edge() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(200.0, 200.0));
let lines = page_break_lines(&sh, &geo, &[(0, 2)], &[(0, 1)], geo.cells);
assert!(lines.iter().any(|line| line[0].y == geo.cells.top() + geo.frozen_h && line[1].y == line[0].y));
assert!(lines.iter().any(|line| line[0].x == geo.cells.left() + geo.frozen_w && line[1].x == line[0].x));
}
#[test]
fn scrolled_past_print_extent_keeps_frozen_portion_of_breaks() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 1000.0)), vec2(2000.0, 2000.0));
let lines = page_break_lines(&sh, &geo, &[(0, 1), (2, 9)], &[(0, 0), (1, 9)], geo.cells);
assert!(lines.iter().any(|line| line[0].x == line[1].x && line[1].y >= geo.cells.top() + geo.frozen_h));
assert!(lines.iter().any(|line| line[0].y == line[1].y && line[1].x >= geo.cells.left() + geo.frozen_w));
}
/// A 100,000-row print extent scrolled to its middle: every line is cut to the visible cells
/// (a dashed line is one shape per dash), and the cut keeps the dash phase of the whole line.
#[test]
fn page_breaks_are_cut_to_the_visible_cells() {
let sh = Sheet::new("S");
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 50_001.0 * DEFAULT_ROW_HEIGHT));
let rows: Vec<(u32, u32)> = (0..2000).map(|i| (i * 50, i * 50 + 49)).collect();
let lines = page_break_lines(&sh, &geo, &rows, &[(0, 4), (5, 9)], geo.cells);
let horizontal = lines.iter().filter(|l| l[0].y == l[1].y).count();
assert!(horizontal > 0 && horizontal < 10, "only the breaks on screen: {horizontal}");
assert_eq!(lines.len() - horizontal, 2);
for l in &lines {
for pt in l {
assert!(geo.cells.expand(BREAK_DASH + BREAK_GAP).contains(*pt), "{pt:?} outside {:?}", geo.cells);
}
}
let full_top = geo.y(&sh, 0);
let vertical = lines.iter().find(|l| l[0].x == l[1].x).unwrap();
// 50,001 rows above at 16 px each put the view's top 1 px past a dash boundary of the whole
// line: the cut line starts at the next boundary, 4 px down (`max` would start it at the top).
assert!((vertical[0].y - (geo.cells.top() + 4.0)).abs() < 0.15, "{:?} vs {}", vertical[0], geo.cells.top());
let phase = (vertical[0].y - full_top) % (BREAK_DASH + BREAK_GAP);
assert!(phase.abs() < 0.15 || (BREAK_DASH + BREAK_GAP - phase).abs() < 0.15, "phase {phase}");
}
}
-1
View File
@@ -171,7 +171,6 @@ fn filter_menu_uses_the_table_whose_header_was_clicked() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut sh = Sheet::new("S");
sh.tables.push(table(1, 0, 2));
+2 -2
View File
@@ -339,6 +339,8 @@ 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.",
@@ -430,8 +432,6 @@ 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,6 +358,8 @@ 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.",
@@ -447,8 +449,6 @@ 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",
+5 -2
View File
@@ -317,6 +317,8 @@ 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." => "Δεν υπάρχει περιεχόμενο για εκτύπωση.",
@@ -393,8 +395,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Αυτοματισμός",
"Table Design" => "Σχεδίαση πίνακα",
"Chart Design" => "Σχεδίαση γραφήματος",
"Pareto" => "Παρέτο",
"Cumulative %" => "Αθροιστικό %",
"Ready" => "Έτοιμο",
"Enter" => "Εισαγωγή",
"Edit" => "Επεξεργασία",
@@ -574,6 +574,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Zoom Out" => "Σμίκρυνση",
"Dismiss" => "Κλείσιμο",
"OK" => "Εντάξει",
"Don't Save" => "Χωρίς αποθήκευση",
"Open…" => "Άνοιγμα…",
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
@@ -582,6 +583,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Βαθμολόγιο",
"this workbook" => "αυτό το βιβλίο εργασίας",
"This workbook" => "Αυτό το βιβλίο εργασίας",
"Do you want to save the changes you made to {title}?" => "Θέλετε να αποθηκεύσετε τις αλλαγές που κάνατε στο {title};",
"Save a copy as .{format}" => "Αποθήκευση αντιγράφου ως .{format}",
"Select a chart first." => "Επιλέξτε πρώτα ένα γράφημα.",
"Row Height" => "Ύψος γραμμής",
@@ -622,6 +624,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Τοποθέτηση εικόνας πάνω από κελιά",
"Pick From List" => "Επιλογή από λίστα",
"Save a Copy" => "Αποθήκευση αντιγράφου",
"Save Changes?" => "Αποθήκευση αλλαγών;",
"Shift cells right" => "Μετατόπιση κελιών προς τα δεξιά",
"Shift cells down" => "Μετατόπιση κελιών προς τα κάτω",
"Shift cells left" => "Μετατόπιση κελιών προς τα αριστερά",
+2 -2
View File
@@ -345,6 +345,8 @@ 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.",
@@ -434,8 +436,6 @@ 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,8 +308,6 @@ 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",
@@ -436,6 +434,8 @@ 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.",
+5 -2
View File
@@ -292,8 +292,6 @@ 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",
@@ -421,6 +419,8 @@ 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.",
@@ -445,6 +445,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Le impostazioni di calcolo vengono salvate con la cartella di lavoro.",
"OK" => "OK",
"Cancel" => "Annulla",
"Don't Save" => "Non salvare",
"Open…" => "Apri…",
"Show password" => "Mostra password",
"Start a new workbook" => "Crea una nuova cartella di lavoro",
@@ -453,6 +454,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Registro dei voti",
"this workbook" => "questa cartella di lavoro",
"This workbook" => "Questa cartella di lavoro",
"Do you want to save the changes you made to {title}?" => "Vuoi salvare le modifiche apportate a {title}?",
"Save a copy as .{format}" => "Salva una copia come .{format}",
"Select a chart first." => "Seleziona prima un grafico.",
"Text Box" => "Casella di testo",
@@ -503,6 +505,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Inserisci immagine sopra le celle",
"Pick From List" => "Scegli dall'elenco",
"Save a Copy" => "Salva una copia",
"Save Changes?" => "Salvare le modifiche?",
"Shift cells right" => "Sposta celle a destra",
"Shift cells down" => "Sposta celle in basso",
"Shift cells left" => "Sposta celle a sinistra",
+5 -2
View File
@@ -299,8 +299,6 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Automate", "自動化"),
("Table Design", "テーブル デザイン"),
("Chart Design", "グラフ デザイン"),
("Pareto", "パレート図"),
("Cumulative %", "累積 %"),
("Ready", "準備完了"),
("Enter", "入力"),
("Edit", "編集"),
@@ -424,6 +422,8 @@ 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.", "印刷する内容がありません。"),
@@ -462,6 +462,7 @@ pub(super) const CORE: &[(&str, &str)] = &[
pub(super) const DIALOGS: &[(&str, &str)] = &[
("OK", "OK"),
("Cancel", "キャンセル"),
("Don't Save", "保存しない"),
("Open…", "開く…"),
("Show password", "パスワードの表示"),
("Start a new workbook", "新しいブックの作成"),
@@ -470,6 +471,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Gradebook", "成績表"),
("this workbook", "このブック"),
("This workbook", "このブック"),
("Do you want to save the changes you made to {title}?", "{title} への変更を保存しますか?"),
("Save a copy as .{format}", ".{format} としてコピーを保存"),
("Select a chart first.", "先にグラフを選択してください。"),
("Text Box", "テキスト ボックス"),
@@ -520,6 +522,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Place Picture over Cells", "セルの上に画像を配置"),
("Pick From List", "リストから選択"),
("Save a Copy", "コピーを保存"),
("Save Changes?", "変更を保存しますか?"),
("Shift cells right", "セルを右に移動"),
("Shift cells down", "セルを下に移動"),
("Shift cells left", "セルを左に移動"),
+2 -2
View File
@@ -293,8 +293,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "자동화",
"Table Design" => "표 디자인",
"Chart Design" => "차트 디자인",
"Pareto" => "파레토",
"Cumulative %" => "누적 %",
"Ready" => "준비",
"Enter" => "입력",
"Edit" => "편집",
@@ -436,6 +434,8 @@ 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,8 +299,6 @@ 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",
@@ -423,6 +421,8 @@ 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.",
+5 -2
View File
@@ -286,8 +286,6 @@ 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",
@@ -413,6 +411,8 @@ 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.",
@@ -436,6 +436,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Ustawienia obliczeń są zapisywane razem ze skoroszytem.",
"OK" => "OK",
"Cancel" => "Anuluj",
"Don't Save" => "Nie zapisuj",
"Open…" => "Otwórz…",
"Show password" => "Pokaż hasło",
"Start a new workbook" => "Utwórz nowy skoroszyt",
@@ -444,6 +445,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Dziennik ocen",
"this workbook" => "ten skoroszyt",
"This workbook" => "Ten skoroszyt",
"Do you want to save the changes you made to {title}?" => "Czy chcesz zapisać zmiany wprowadzone w pliku {title}?",
"Save a copy as .{format}" => "Zapisz kopię jako .{format}",
"Select a chart first." => "Najpierw zaznacz wykres.",
"Text Box" => "Pole tekstowe",
@@ -494,6 +496,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Umieść obraz na komórkach",
"Pick From List" => "Wybierz z listy",
"Save a Copy" => "Zapisz kopię",
"Save Changes?" => "Zapisać zmiany?",
"Shift cells right" => "Przesuń komórki w prawo",
"Shift cells down" => "Przesuń komórki w dół",
"Shift cells left" => "Przesuń komórki w lewo",
+5 -2
View File
@@ -428,6 +428,8 @@ 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.",
@@ -464,6 +466,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.",
"OK" => "OK",
"Cancel" => "Cancelar",
"Don't Save" => "Não Salvar",
"Open…" => "Abrir…",
"Show password" => "Mostrar senha",
"Start a new workbook" => "Criar uma pasta de trabalho",
@@ -472,6 +475,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Boletim de Notas",
"this workbook" => "esta pasta de trabalho",
"This workbook" => "Esta pasta de trabalho",
"Do you want to save the changes you made to {title}?" => "Deseja salvar as alterações feitas em {title}?",
"Save a copy as .{format}" => "Salvar uma cópia como .{format}",
"Select a chart first." => "Selecione um gráfico primeiro.",
"Text Box" => "Caixa de Texto",
@@ -528,6 +532,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Colocar Imagem sobre as Células",
"Pick From List" => "Escolher na Lista",
"Save a Copy" => "Salvar uma Cópia",
"Save Changes?" => "Salvar Alterações?",
"Shift cells right" => "Deslocar células para a direita",
"Shift cells down" => "Deslocar células para baixo",
"Shift cells left" => "Deslocar células para a esquerda",
@@ -848,8 +853,6 @@ 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",
+5 -2
View File
@@ -293,8 +293,6 @@ 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",
@@ -420,6 +418,8 @@ 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.",
@@ -442,6 +442,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Setările de calcul se salvează împreună cu registrul.",
"OK" => "OK",
"Cancel" => "Anulare",
"Don't Save" => "Nu salva",
"Open…" => "Deschidere…",
"Show password" => "Afișare parolă",
"Start a new workbook" => "Începeți un registru nou",
@@ -450,6 +451,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Catalog de note",
"this workbook" => "acest registru",
"This workbook" => "Acest registru",
"Do you want to save the changes you made to {title}?" => "Doriți să salvați modificările făcute în {title}?",
"Save a copy as .{format}" => "Salvare copie ca .{format}",
"Select a chart first." => "Selectați mai întâi o diagramă.",
"Text Box" => "Casetă de text",
@@ -500,6 +502,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Plasare imagine peste celule",
"Pick From List" => "Alegere din listă",
"Save a Copy" => "Salvare copie",
"Save Changes?" => "Salvați modificările?",
"Shift cells right" => "Deplasare celule la dreapta",
"Shift cells down" => "Deplasare celule în jos",
"Shift cells left" => "Deplasare celule la stânga",
+5 -2
View File
@@ -295,8 +295,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Автоматизация",
"Table Design" => "Конструктор таблиц",
"Chart Design" => "Конструктор диаграмм",
"Pareto" => "Парето",
"Cumulative %" => "Накопленный %",
"Ready" => "Готово",
"Enter" => "Ввод",
"Edit" => "Изменение",
@@ -435,6 +433,8 @@ 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." => "Нечего печатать.",
@@ -599,6 +599,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Display:" => "Отображать:",
"Distributed" => "Распределённый",
"Divide" => "Разделить",
"Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?",
"Don't Save" => "Не сохранять",
"Double" => "Двойное",
"Double Accounting" => "Двойное бухгалтерское",
"Doughnut" => "Кольцевая",
@@ -844,6 +846,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Rows" => "Строки",
"Sample" => "Выборка",
"Save (⌘S)" => "Сохранить (⌘S)",
"Save Changes?" => "Сохранить изменения?",
"Save a Copy" => "Сохранить копию",
"Save a copy as .{format}" => "Сохранить копию как .{format}",
"Scatter" => "Точечная",
+2 -2
View File
@@ -298,8 +298,6 @@ 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",
@@ -429,6 +427,8 @@ 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,6 +332,8 @@ 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.",
@@ -407,8 +409,6 @@ 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",
+5 -2
View File
@@ -288,8 +288,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Автоматизація",
"Table Design" => "Конструктор таблиць",
"Chart Design" => "Конструктор діаграм",
"Pareto" => "Парето",
"Cumulative %" => "Накопичений %",
"Ready" => "Готово",
"Enter" => "Ввід",
"Edit" => "Редагування",
@@ -418,6 +416,8 @@ 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." => "Немає що друкувати.",
@@ -440,6 +440,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Параметри обчислень зберігаються разом із книгою.",
"OK" => "OK",
"Cancel" => "Cancel",
"Don't Save" => "Don't Save",
"Open…" => "Open…",
"Show password" => "Show password",
"Start a new workbook" => "Start a new workbook",
@@ -448,6 +449,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Gradebook",
"this workbook" => "this workbook",
"This workbook" => "This workbook",
"Do you want to save the changes you made to {title}?" => "Do you want to save the changes you made to {title}?",
"Save a copy as .{format}" => "Save a copy as .{format}",
"Select a chart first." => "Спочатку виділіть діаграму.",
"Text Box" => "Напис",
@@ -498,6 +500,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Place Picture over Cells",
"Pick From List" => "Pick From List",
"Save a Copy" => "Save a Copy",
"Save Changes?" => "Save Changes?",
"Shift cells right" => "Shift cells right",
"Shift cells down" => "Shift cells down",
"Shift cells left" => "Shift cells left",
+5 -2
View File
@@ -301,8 +301,6 @@ 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",
@@ -423,6 +421,8 @@ 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.",
@@ -450,6 +450,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
// Dialogs, menus, context menus and tooltips.
"OK" => "OK",
"Cancel" => "Hủy",
"Don't Save" => "Không lưu",
"Open…" => "Mở…",
"Show password" => "Hiện mật khẩu",
"Start a new workbook" => "Bắt đầu sổ làm việc mới",
@@ -458,6 +459,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Sổ điểm",
"this workbook" => "sổ làm việc này",
"This workbook" => "Sổ làm việc này",
"Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?",
"Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}",
"Select a chart first." => "Hãy chọn một biểu đồ trước.",
"Text Box" => "Hộp văn bản",
@@ -508,6 +510,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Đặt ảnh đè lên các ô",
"Pick From List" => "Chọn từ danh sách",
"Save a Copy" => "Lưu bản sao",
"Save Changes?" => "Lưu thay đổi?",
"Shift cells right" => "Dịch các ô sang phải",
"Shift cells down" => "Dịch các ô xuống dưới",
"Shift cells left" => "Dịch các ô sang trái",
+2 -2
View File
@@ -293,8 +293,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "自动化",
"Table Design" => "表格设计",
"Chart Design" => "图表设计",
"Pareto" => "排列图",
"Cumulative %" => "累积百分比",
"Ready" => "就绪",
"Enter" => "输入",
"Edit" => "编辑",
@@ -428,6 +426,8 @@ 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." => "没有可打印的内容。",
+5 -4
View File
@@ -261,6 +261,9 @@ 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_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>>,
@@ -362,11 +365,9 @@ pub struct SheetApp {
/// The update check, the startup prompt and a running self-update (desktop only).
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime,
/// The framework dialogs GridCraft keeps as values (the update dialogs and the unsaved-changes
/// prompt), run once per frame after GridCraft's own UI in the root window's pass.
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
/// after GridCraft's own UI in the root window's pass.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Which workbook and window the open `UnsavedChangesDialog` is asking about.
pub unsaved_prompt: Option<state::UnsavedPrompt>,
/// Who GridCraft is to the framework's dialogs.
framework_host: std::sync::Arc<craft_host::Host>,
}
+21 -18
View File
@@ -18,8 +18,6 @@
use std::collections::BTreeMap;
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::UnsavedChangesDialog;
use egui::{Color32, Id, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::macros::policy::{Policy, macro_policy};
@@ -1102,7 +1100,7 @@ fn ref_edit(app: &SheetApp, ui: &mut Ui, d: &mut Dialog, refs: &mut RefPick, key
d.values.insert(key.into(), json!(s));
}
/// Keep changes? (stopping a debugged run) and the unsaved-changes question (closing with unsaved edits).
/// Keep changes? (stopping a debugged run) and Save changes? (closing with unsaved edits).
fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut bool) {
if ed.ask_stop {
let mut answer: Option<Option<bool>> = None;
@@ -1143,20 +1141,25 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
return;
}
if ed.ask_close {
// The shared unsaved-changes question, named for the macro. Each asking gets its own area,
// so the question's own open state starts open every time it is asked.
let scope = if ed.quit { CloseScope::Quit } else { CloseScope::Close };
let asked = Id::unique("gridcraft.macro_editor.close");
let opening = ctx.data(|d| d.get_temp::<u64>(asked)).unwrap_or_default();
let shown = egui::Area::new(asked.with(opening))
.order(egui::Order::Foreground)
.show(ctx, |ui| UnsavedChangesDialog::new(scope, ed.draft.name.clone()).document_wording(true).show(ui));
let answer = shown.inner.answer.map(|a| a.answer);
if answer.is_some() {
ctx.data_mut(|d| d.insert_temp(asked, opening + 1));
}
let mut answer: Option<Option<bool>> = None;
egui::Modal::new(Id::unique("gridcraft.macro_editor.close")).show(ctx, |ui| {
ui.set_width(360.0);
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
answer = Some(None);
}
if ui.button("Don't Save").clicked() {
answer = Some(Some(false));
}
if ui.button("Save").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
answer = Some(Some(true));
}
});
});
match answer {
Some(CloseAnswer::Save) => {
Some(Some(true)) => {
ed.ask_close = false;
if save(app, ed) {
*open = false;
@@ -1167,11 +1170,11 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
ed.quit = false;
}
}
Some(CloseAnswer::DontSave) => {
Some(Some(false)) => {
ed.ask_close = false;
*open = false;
}
Some(CloseAnswer::Cancel) => {
Some(None) => {
ed.ask_close = false;
ed.quit = false;
ed.then_close = None;
-1
View File
@@ -205,7 +205,6 @@ 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() {
+50 -4
View File
@@ -22,13 +22,43 @@ fn printer_name(settings: &Settings) -> &str {
}
}
/// 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.
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
/// `from` and `to` set the Print view's page range (`null` clears a bound).
pub fn settings(
state: &mut State,
pages: &mut PageRange,
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", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale or refresh".into());
if object.keys().any(|key| !["printer", "copies", "duplex", "grayscale", "from", "to", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale, from, to or refresh".into());
}
if state.busy() && !object.is_empty() {
return Err("wait for the active print submission before changing settings".into());
@@ -58,6 +88,21 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
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 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")?;
@@ -66,6 +111,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
}
}
state.settings = next;
*pages = range;
let (status, detail) = match state.message.as_ref() {
None => ("idle", ""),
Some(Feedback::FindingPrinters) => ("findingPrinters", ""),
@@ -80,7 +126,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
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,
"grayscale": state.settings.grayscale, "from": pages.from, "to": pages.to,
"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,
}))
+1 -1
View File
@@ -167,7 +167,7 @@ pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool {
d.selection.ranges.len() > 1
|| d.selection.current().is_single()
|| app.editor.is_some()
|| app.modal_open()
|| app.dialog.is_some()
|| app.text_box_editor.is_some()
|| app.grid.context_menu.is_some()
|| geo.paper.is_some()

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