mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-06 04:26:49 -06:00
Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f77d672f83 | ||
|
|
e2b2084eb2 | ||
|
|
44e40fd606 | ||
|
|
2ecd0cf70a | ||
|
|
4baabc6dd3 | ||
|
|
c26b7a975c | ||
|
|
abe329dabf | ||
|
|
acae69ffa9 | ||
|
|
d9bd8a8334 | ||
|
|
d4534b7ce4 | ||
|
|
fe6195d207 | ||
|
|
6ee8f4b6df | ||
|
|
3e080a17fd | ||
|
|
9e9e52b0e0 | ||
|
|
8bb34047aa | ||
|
|
e93be7cdbf | ||
|
|
31f1ad07f4 | ||
|
|
9558000414 | ||
|
|
d99ea8ca0f | ||
|
|
9b15f7b3d7 | ||
|
|
fb7ca98282 | ||
|
|
2da139915f | ||
|
|
86ba6b5138 | ||
|
|
5a850f6a72 | ||
|
|
0f2589bfef | ||
|
|
ba82b95ca0 | ||
|
|
41a5eb8a56 | ||
|
|
966b87337f | ||
|
|
2aa1ac4683 | ||
|
|
2c0d199321 | ||
|
|
623061303f | ||
|
|
c05683be93 | ||
|
|
d37c5a70ea | ||
|
|
0ab181731c | ||
|
|
f444f0c420 | ||
|
|
848e8e49d4 | ||
|
|
3b8d41c27f | ||
|
|
e4cdee3997 | ||
|
|
9622664cd5 | ||
|
|
1aef9a961d | ||
|
|
f528d1233f | ||
|
|
95d904dfe2 | ||
|
|
ed6f1852c6 | ||
|
|
1ce588b785 | ||
|
|
4a604e7a17 | ||
|
|
f4062709c4 | ||
|
|
391448abed | ||
|
|
8cc2732ca6 | ||
|
|
4efade7515 | ||
|
|
a672926c91 | ||
|
|
a621569d0f | ||
|
|
23e13497a7 | ||
|
|
53403bc2dd | ||
|
|
62260e6e4b | ||
|
|
e7f9d0008b | ||
|
|
a72b9287f2 | ||
|
|
5b19af3c89 | ||
|
|
2a0183e3d2 | ||
|
|
230bf2304f | ||
|
|
bb0d997cfd | ||
|
|
c824ae702e | ||
|
|
63a9c928a2 | ||
|
|
8cc7cc4e38 | ||
|
|
74014cc850 | ||
|
|
5647e98048 | ||
|
|
2c04e06499 |
@@ -1,14 +0,0 @@
|
||||
[package]
|
||||
name = "browser-print-probe"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
craft-print = { path = "../../shared/crates/print" }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
@@ -1,188 +0,0 @@
|
||||
"""Use real Chrome print preview on an isolated runner, then inspect the saved PDFs."""
|
||||
import functools
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageGrab
|
||||
from reportlab.pdfgen import canvas
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.firefox.service import Service as FirefoxService
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
|
||||
SITE = Path(__file__).resolve().parent
|
||||
RESULTS = Path("browser-capture").resolve()
|
||||
COLORS = {"first": [(220, 40, 50), (25, 55, 215)], "second": [(0, 160, 45)]}
|
||||
|
||||
|
||||
def fixture(name, colors):
|
||||
doc = canvas.Canvas(str(SITE / f"{name}.pdf"), pagesize=(612, 792))
|
||||
for index, rgb in enumerate(colors):
|
||||
doc.drawString(72, 690, f"{name} document page {index + 1}")
|
||||
doc.setFillColorRGB(*(v / 255 for v in rgb))
|
||||
doc.rect(145, 245, 322, 302, fill=1, stroke=0)
|
||||
doc.showPage()
|
||||
doc.save()
|
||||
|
||||
|
||||
def wait_for_pdf(before, name):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
found = set(RESULTS.glob("*.pdf")) - before
|
||||
if len(found) > 1:
|
||||
raise RuntimeError(f"multiple outputs for {name}: {found}")
|
||||
if found:
|
||||
path = next(iter(found))
|
||||
if path.read_bytes().rstrip().endswith(b"%%EOF"):
|
||||
return path.rename(RESULTS / f"{name}-captured.pdf")
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError(f"{name} produced no complete PDF")
|
||||
|
||||
|
||||
def inspect_pdf(path, colors):
|
||||
info = subprocess.check_output(["pdfinfo", path], text=True)
|
||||
pages = next(int(line.split()[1]) for line in info.splitlines() if line.startswith("Pages:"))
|
||||
assert pages == len(colors), (path, pages, colors)
|
||||
prefix = path.with_suffix("")
|
||||
subprocess.run(["pdftoppm", "-r", "36", "-png", path, prefix], check=True)
|
||||
for index, rgb in enumerate(colors, start=1):
|
||||
with Image.open(f"{prefix}-{index}.png") as image:
|
||||
actual = image.convert("RGB").getpixel((image.width // 2, image.height // 2))
|
||||
assert max(abs(a - b) for a, b in zip(actual, rgb)) < 20, (index, actual, rgb)
|
||||
print(f"{path.name} page {index}: {actual}", flush=True)
|
||||
|
||||
|
||||
def wait_preview(name, color, visible):
|
||||
"""Observe the actual X11 surface. The host page contains no colour marks."""
|
||||
deadline = time.monotonic() + 40
|
||||
while True:
|
||||
image = ImageGrab.grab().convert("RGB")
|
||||
# A half-page solid rectangle survives Chrome's print-preview scaling.
|
||||
pixels = image.resize((320, 240)).getdata()
|
||||
count = sum(max(abs(a - b) for a, b in zip(pixel, color)) < 18 for pixel in pixels)
|
||||
if (count > 300) == visible:
|
||||
image.save(RESULTS / f"{name}.png")
|
||||
print(f"{name}: {count} matching preview pixels", flush=True)
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
image.save(RESULTS / f"{name}-timeout.png")
|
||||
raise TimeoutError(f"{name}: matching preview pixels = {count}")
|
||||
time.sleep(0.35)
|
||||
|
||||
|
||||
def cancel_then_save(driver):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "first"))).click()
|
||||
wait_preview("before-cancel", COLORS["first"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("after-cancel", COLORS["first"][0], False)
|
||||
assert set(RESULTS.glob("*.pdf")) == before, "cancel created a PDF"
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "second"))).click()
|
||||
wait_preview("next-document", COLORS["second"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
# Chrome's Save as PDF destination opens the native Save File dialog.
|
||||
deadline = time.monotonic() + 25
|
||||
while time.monotonic() < deadline:
|
||||
if set(RESULTS.glob("*.pdf")) != before:
|
||||
break
|
||||
title = subprocess.run(["xdotool", "getwindowfocus", "getwindowname"], capture_output=True, text=True)
|
||||
# Firefox's GTK picker can be a transient without a separate window title.
|
||||
image = io.BytesIO()
|
||||
ImageGrab.grab().save(image, format="PNG")
|
||||
words = subprocess.run(["tesseract", "stdin", "stdout", "--psm", "6"], input=image.getvalue(), capture_output=True, check=True).stdout.decode()
|
||||
if "save" in title.stdout.lower() or ("Name:" in words and "Save" in words):
|
||||
print("Native Save File dialog is visible", flush=True)
|
||||
subprocess.run(["xdotool", "key", "ctrl+l"], check=True)
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
break
|
||||
time.sleep(0.25)
|
||||
pdf = wait_for_pdf(before, "after-cancel")
|
||||
inspect_pdf(pdf, COLORS["second"])
|
||||
assert set(RESULTS.glob("*.pdf")) == before | {pdf}
|
||||
|
||||
|
||||
def firefox_probe(url):
|
||||
options = webdriver.FirefoxOptions()
|
||||
options.set_preference("print_printer", "Mozilla Save to PDF")
|
||||
options.set_preference("print.save_print_settings", True)
|
||||
with webdriver.Firefox(options=options, service=FirefoxService(shutil.which("geckodriver"))) as driver:
|
||||
print("Firefox", driver.capabilities["browserVersion"], flush=True)
|
||||
driver.get(url)
|
||||
try:
|
||||
driver.find_element(By.ID, "control").click()
|
||||
yellow = (240, 185, 20)
|
||||
wait_preview("firefox-parent-preview", yellow, True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("firefox-parent-dismissed", yellow, False)
|
||||
cancel_then_save(driver)
|
||||
finally:
|
||||
ImageGrab.grab().save(RESULTS / "firefox-last-screen.png")
|
||||
|
||||
|
||||
def main():
|
||||
RESULTS.mkdir()
|
||||
for name, colors in COLORS.items():
|
||||
fixture(name, colors)
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=SITE)
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
url = f"http://127.0.0.1:{server.server_port}/"
|
||||
# This disposable browser cannot contact the system CUPS server.
|
||||
os.environ["CUPS_SERVER"] = str(RESULTS / "absent-cups.sock")
|
||||
if "--firefox" in sys.argv:
|
||||
firefox_probe(url)
|
||||
return
|
||||
options = webdriver.ChromeOptions()
|
||||
cancellation = "--cancel" in sys.argv
|
||||
if not cancellation:
|
||||
options.add_argument("--kiosk-printing")
|
||||
options.add_argument("--no-first-run")
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": str(RESULTS),
|
||||
"savefile.default_directory": str(RESULTS),
|
||||
"printing.print_preview_sticky_settings.appState": json.dumps({
|
||||
"version": 2, "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
|
||||
"selectedDestinationId": "Save as PDF",
|
||||
}),
|
||||
})
|
||||
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
|
||||
with webdriver.Chrome(options=options, service=Service(shutil.which("chromedriver"))) as driver:
|
||||
print("Chrome", driver.capabilities["browserVersion"], flush=True)
|
||||
matrix = "--matrix" in sys.argv
|
||||
driver.get(url + ("?matrix" if matrix else ""))
|
||||
try:
|
||||
if cancellation:
|
||||
cancel_then_save(driver)
|
||||
return
|
||||
for name in (("range", "large", "plotter") if matrix else ("control", "first", "second")):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, name))).click()
|
||||
pdf = wait_for_pdf(before, name)
|
||||
if matrix:
|
||||
verifier = Path("acceptance/crates/print/examples/print_acceptance/verify.py")
|
||||
args = {"range": ["2", "4"], "large": list(map(str, range(1, 105))), "plotter": ["--plotter", "1"]}
|
||||
subprocess.run([sys.executable, verifier, pdf, *args[name]], check=True)
|
||||
elif name == "control":
|
||||
text = subprocess.check_output(["pdftotext", pdf, "-"], text=True)
|
||||
assert "Parent page control only" in text, text
|
||||
else:
|
||||
inspect_pdf(pdf, COLORS[name])
|
||||
finally:
|
||||
(RESULTS / "browser-log.json").write_text(json.dumps(driver.get_log("browser"), indent=2))
|
||||
driver.save_screenshot(str(RESULTS / "last-view.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,30 +0,0 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>Parent page control</title>
|
||||
<style>
|
||||
#control-marker { display: none; }
|
||||
@media print { #control-marker { display: block; } }
|
||||
</style>
|
||||
<p>Parent page control only</p>
|
||||
<svg id="control-marker" width="360" height="340"><rect width="360" height="340" fill="rgb(240,185,20)"/></svg>
|
||||
<button id="control" onclick="setTimeout(() => window.print(), 0)">Print parent</button>
|
||||
<button id="first" disabled>Print first PDF</button>
|
||||
<button id="second" disabled>Print second PDF</button>
|
||||
<script type="module">
|
||||
import init, { print_document } from "./pkg/browser_print_probe.js";
|
||||
await init();
|
||||
const matrix = new URLSearchParams(location.search).has("matrix");
|
||||
for (const id of matrix ? ["range", "large", "plotter"] : ["first", "second"]) {
|
||||
if (matrix) {
|
||||
const button = document.createElement("button");
|
||||
button.id = id;
|
||||
button.disabled = true;
|
||||
button.textContent = "Print " + id;
|
||||
document.body.append(button);
|
||||
}
|
||||
const pdf = new Uint8Array(await (await fetch("./" + id + ".pdf")).arrayBuffer());
|
||||
const button = document.getElementById(id);
|
||||
button.addEventListener("click", () => print_document(pdf));
|
||||
button.disabled = false;
|
||||
}
|
||||
</script>
|
||||
@@ -1,11 +0,0 @@
|
||||
#[path = "../../acceptance/crates/print/examples/print_acceptance/fixture.rs"]
|
||||
mod fixture;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let dest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let large: Vec<_> = (1..=104).collect();
|
||||
for (name, pages, plotter) in [("range", &[2, 4][..], false), ("large", large.as_slice(), false), ("plotter", &[1][..], true)] {
|
||||
std::fs::write(dest.join(format!("{name}.pdf")), fixture::pdf(pages, plotter))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Exercise the same shared entry point as the GridCraft web print service.
|
||||
#[wasm_bindgen]
|
||||
pub fn print_document(bytes: &[u8]) -> Result<(), JsValue> {
|
||||
craft_print::browser::print_pdf(bytes).map_err(|error| JsValue::from_str(&error))
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
name: Verify browser print output
|
||||
on:
|
||||
push:
|
||||
branches: [verify/gridcraft-browser-print-matrix-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
browser-print:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: e0646e91ad432c43358137d0d894877216fa91ed
|
||||
path: shared
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: cd03603db5426352c127148014a3d8fa635ae76c
|
||||
path: acceptance
|
||||
sparse-checkout: crates/print/examples/print_acceptance
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: xvfb xauth xdotool tesseract-ocr poppler-utils python3-selenium python3-reportlab python3-pil
|
||||
- name: Build the shared browser entry point as WebAssembly
|
||||
working-directory: .github/print-probe
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: 0
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cp ../../shared/Cargo.lock Cargo.lock
|
||||
cargo build --target wasm32-unknown-unknown
|
||||
archive="$RUNNER_TEMP/wasm-bindgen.tar.gz"
|
||||
curl --fail --location --silent --show-error https://github.com/wasm-bindgen/wasm-bindgen/releases/download/0.2.129/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl.tar.gz -o "$archive"
|
||||
echo "82d12bb940e2d4e72e0d5605387fc1b8ca179044e012b620f0ce4e7440e8320e $archive" | sha256sum --check
|
||||
tar -xf "$archive" -C "$RUNNER_TEMP" wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen
|
||||
"$RUNNER_TEMP/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen" --target web --out-dir pkg target/wasm32-unknown-unknown/debug/browser_print_probe.wasm
|
||||
- name: Generate the shared numbered and large-image fixtures
|
||||
working-directory: .github/print-probe
|
||||
run: |
|
||||
CARGO_MANIFEST_DIR="$PWD" rustc --edition 2024 numbered.rs -o "$RUNNER_TEMP/numbered"
|
||||
"$RUNNER_TEMP/numbered"
|
||||
- name: Print selected pages, 104 pages, and a 24 by 36 inch image in Chrome
|
||||
run: xvfb-run -a /usr/bin/python3 .github/print-probe/capture.py --matrix
|
||||
- name: Preserve output and diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
with:
|
||||
name: chromium-print-matrix
|
||||
path: browser-capture
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
Generated
+196
-7
@@ -155,6 +155,12 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ambient-authority"
|
||||
version = "0.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
|
||||
|
||||
[[package]]
|
||||
name = "android-activity"
|
||||
version = "0.6.1"
|
||||
@@ -698,6 +704,36 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-primitives"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
|
||||
dependencies = [
|
||||
"ambient-authority",
|
||||
"fs-set-times",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.1",
|
||||
"ipnet",
|
||||
"maybe-owned",
|
||||
"rustix 1.1.6",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cap-std"
|
||||
version = "4.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"io-extras",
|
||||
"io-lifetimes 3.0.1",
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.6.0"
|
||||
@@ -1031,6 +1067,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1049,6 +1095,31 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"hmac 0.12.1",
|
||||
"log",
|
||||
"png 0.17.16",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
@@ -1085,6 +1156,21 @@ name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-flags",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
version = "0.1.0"
|
||||
@@ -1113,6 +1199,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
@@ -1235,7 +1331,7 @@ dependencies = [
|
||||
"craft-zip",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"hmac 0.13.0",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1263,7 +1359,7 @@ dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-xml",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"hmac 0.13.0",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1872,6 +1968,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2539,6 +2636,17 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-set-times"
|
||||
version = "0.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -2853,13 +2961,15 @@ version = "0.20.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"chrono",
|
||||
"craft-automation",
|
||||
"craft-control",
|
||||
"craft-nightly",
|
||||
"craft-print",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"getrandom 0.4.3",
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
"gridcraft-sandbox",
|
||||
@@ -2904,6 +3014,7 @@ dependencies = [
|
||||
name = "gridcraft-cli"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-control",
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
"gridcraft-sandbox",
|
||||
@@ -2939,8 +3050,10 @@ dependencies = [
|
||||
name = "gridcraft-engine"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"cap-std",
|
||||
"craft-csv",
|
||||
"craft-gridcraft-format",
|
||||
"getrandom 0.4.3",
|
||||
"gridcraft-calc",
|
||||
"gridcraft-chart",
|
||||
"gridcraft-core",
|
||||
@@ -2955,6 +3068,7 @@ dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-segmentation",
|
||||
"web-time",
|
||||
@@ -2992,7 +3106,11 @@ dependencies = [
|
||||
name = "gridcraft-mcp"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-control",
|
||||
"craft-mcp-server",
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"gridcraft-engine",
|
||||
"log",
|
||||
"serde_json",
|
||||
@@ -3046,7 +3164,9 @@ dependencies = [
|
||||
name = "gridcraft-ui-egui"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-print",
|
||||
@@ -3078,7 +3198,6 @@ dependencies = [
|
||||
name = "gridcraft-web"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
@@ -3245,6 +3364,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
@@ -3672,7 +3800,7 @@ dependencies = [
|
||||
"byteorder-lite",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -3712,6 +3840,28 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-extras"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "3.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -4062,6 +4212,12 @@ version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "maybe-owned"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -4162,7 +4318,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -5115,6 +5271,19 @@ dependencies = [
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.17.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"crc32fast",
|
||||
"fdeflate",
|
||||
"flate2",
|
||||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -5789,6 +5958,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix-linux-procfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
@@ -6786,7 +6965,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
@@ -8083,6 +8262,16 @@ version = "0.0.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
|
||||
@@ -54,6 +54,11 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
|
||||
# Agents in the open window: the ArtCraft Launcher's switch, the connection file and the CLI's live
|
||||
# client (`craft-control`, feature `agents`), and the app's link host, control server and Agents page
|
||||
# (`craft-automation`, features `agents` and `ui`).
|
||||
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
|
||||
@@ -172,8 +172,8 @@ so a Nightly run never touches the stable app's settings, prefs or logs.
|
||||
## For agents: MCP, CLI and the control channel
|
||||
|
||||
```sh
|
||||
claude mcp add gridcraft -- gridcraft-cli mcp # headless MCP server
|
||||
gridcraft-cli mcp --connect 7979 # MCP bridged to a running window
|
||||
gridcraft-cli mcp # MCP server: the open window while AI agents are on
|
||||
gridcraft-cli mcp --headless # MCP server without a window
|
||||
gridcraft-cli eval '=XLOOKUP("b",{"a","b"},{1,2})' # → 2
|
||||
gridcraft-cli run --sample budget --cmd 'home.bold={"range":"B4:F4"}' --out budget.xlsx
|
||||
gridcraft-cli cat budget.xlsx --range B4:F15 # aligned text table
|
||||
@@ -275,8 +275,37 @@ handling again for troubleshooting.
|
||||
| Fedora/RHEL/openSUSE | `gridcraft-<ver>-linux-x86_64.rpm` | `gridcraft-<ver>-linux-aarch64.rpm` | |
|
||||
| Tarball | `gridcraft-<ver>-linux-x86_64.tar.gz` | `gridcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
|
||||
|
||||
#### Community packages
|
||||
|
||||
These packages are maintained by community members, not by the GridCraft team, and the project
|
||||
does not review them. An overlay's ebuilds run as root when you install a package, so read the
|
||||
ebuild before you emerge it.
|
||||
|
||||
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the
|
||||
Linux release as `app-office/gridcraft-bin` (prebuilt) and `app-office/gridcraft` (built from source).
|
||||
`gridcraft-bin` downloads `gridcraft-<ver>-linux-x86_64.tar.gz` from this repository's releases, and
|
||||
Portage refuses the file unless it matches the overlay's `Manifest`. To check that it is the
|
||||
release's own file before installing it, fetch it first with `emerge --fetchonly`, run `sha256sum`
|
||||
on it in your `DISTDIR` and compare with the release's `SHA256SUMS.txt`.
|
||||
|
||||
```sh
|
||||
emerge --ask --noreplace app-eselect/eselect-repository
|
||||
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
|
||||
emaint sync -r snakebyte
|
||||
# package.accept_keywords can be a directory or a single file
|
||||
if [ -d /etc/portage/package.accept_keywords ]; then
|
||||
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/gridcraft
|
||||
else
|
||||
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords
|
||||
fi
|
||||
emerge --fetchonly app-office/gridcraft-bin # then check the file in DISTDIR as above
|
||||
emerge --ask app-office/gridcraft-bin
|
||||
```
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Current prebuilt FreeBSD downloads require FreeBSD 15.1 or later; they are not compatible with FreeBSD 14.x.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `gridcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
+21
@@ -136,6 +136,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-12-02 | Agents in the open window: while the ArtCraft Launcher's AI agents switch names GridCraft, plain `gridcraft-cli mcp` reaches the open window by itself (no port or token in the client's configuration; the window proves it holds the token first), confined to the agent folders; File › Options › Agents shows the link and the folders, the `agent_folders` tool names them, and `--headless` / `--when-closed` choose a session without a window; `--connect` is deprecated (#5012) |
|
||||
| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) |
|
||||
| 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) |
|
||||
| 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `<controls>` and VML), alongside the form controls GridCraft keeps unchanged |
|
||||
@@ -392,3 +393,23 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-10 | minor | Checked against the alpha gate (six core workflows pass): stays alpha |
|
||||
| 2026-10-10 | major | Re-measured against Excel for Mac 16.113.4: stage alpha, breadth ~75%, ready ~50%, ~160–240 h to beta, ~700–1,100 h to full parity; progress docs restructured; detail moved to `docs/` |
|
||||
| 2026-10-07 | major | First estimates: catalog 89%, functions ~93%, depth ~65%, ~35 h to alpha, ~215 h to full parity |
|
||||
|
||||
|
||||
## Contribution #2739 — scoped notes
|
||||
|
||||
> **Last updated:** 2026-11-15 · These notes describe this contribution. The mainline assessment and progress tables above are retained verbatim from `1d0b311b4a94`. The contribution does not revise the mainline readiness estimates.
|
||||
|
||||
The behavior described in these scoped notes applies to this branch and supersedes corresponding older baseline statements above. Dated rows below record the contribution history, rather than adding a new claim of general parity.
|
||||
|
||||
### Contribution progress
|
||||
|
||||
| Date | What changed |
|
||||
|---|---|
|
||||
| 2026-11-05 | Native file-I/O confinement: a new save requests mode 0644 and the process umask applies, rather than forcing owner-only access; over an existing file whose group can't be kept, the replacement keeps its owner-only temporary mode; the directory-handle confinement policy is unchanged. |
|
||||
| 2026-10-27 | MCP can confine file I/O to operator-selected read/write folders; initial `--in`, generic commands and atomic-save paths are covered (#445, #2172) |
|
||||
|
||||
### Contribution revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-05 | trivial | new native saves request mode 0644 before the umask; when an existing file's group can't be kept, the replacement keeps its owner-only temporary mode instead of restoring the old owner and other bits; synthetic regression, no readiness change |
|
||||
|
||||
@@ -17,6 +17,8 @@ path = "src/main.rs"
|
||||
gridcraft-sandbox = { workspace = true }
|
||||
gridcraft-engine = { workspace = true }
|
||||
gridcraft-mcp = { workspace = true }
|
||||
# `mcp`: the closed-app choice and starting the desktop app beside the CLI.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# `check`: validating the packages GridCraft writes (content types, relationships).
|
||||
|
||||
+145
-30
@@ -9,7 +9,8 @@
|
||||
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
|
||||
//! gridcraft-cli commands [--json] [--search X]
|
||||
//! gridcraft-cli functions [--json] [--search X] [--category C]
|
||||
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
|
||||
//! gridcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--in FILE | --sample NAME]
|
||||
//! [--automation-read-root DIR] [--automation-write-root DIR]
|
||||
//! gridcraft-cli send <port> <method> [json]
|
||||
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
|
||||
//! gridcraft-cli version | --version
|
||||
@@ -49,7 +50,11 @@ const USAGE: &str = "usage:
|
||||
blank lines and lines starting with # or // are skipped
|
||||
gridcraft-cli commands [--json] [--search X]
|
||||
gridcraft-cli functions [--json] [--search X] [--category C]
|
||||
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
|
||||
gridcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--in FILE | --sample NAME]
|
||||
[--automation-read-root DIR] [--automation-write-root DIR]
|
||||
the open GridCraft window while AI agents may use it (ArtCraft Launcher ›
|
||||
Settings › AI agents), otherwise a session without a window; --headless,
|
||||
--in and --sample always use one
|
||||
gridcraft-cli send <port> <method> [json]
|
||||
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
|
||||
whether this system confines programs (no program: a confined self-test)
|
||||
@@ -558,31 +563,100 @@ fn functions(args: &[String]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
|
||||
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
|
||||
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
|
||||
/// The stderr line `mcp --connect` prints: the flag works for one more release.
|
||||
const CONNECT_DEPRECATED: &str = "gridcraft-cli: --connect is deprecated and will be removed in a later release; plain `gridcraft-cli mcp` finds the open GridCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
|
||||
|
||||
/// Validate MCP arguments without opening files, connecting or starting a server.
|
||||
fn mcp_args(args: &[String]) -> Result<Args, String> {
|
||||
let a = Args::parse(args, &["connect", "in", "sample", "automation-read-root", "automation-write-root", "when-closed"], &["headless"])?;
|
||||
a.no_extra(0)?;
|
||||
let backend: Box<dyn Backend> = match a.opt("connect") {
|
||||
Some(c) => {
|
||||
let addr = control_addr(c);
|
||||
Box::new(
|
||||
Remote::connect(&addr)
|
||||
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
|
||||
)
|
||||
for option in ["automation-read-root", "automation-write-root"] {
|
||||
if a.opts.iter().filter(|(name, _)| name == option).count() > 1 {
|
||||
return Err(format!("--{option} may be given only once"));
|
||||
}
|
||||
None => {
|
||||
let session = match (a.opt("in"), a.opt("sample")) {
|
||||
(Some(p), _) => open(p)?,
|
||||
(None, Some(name)) => {
|
||||
let mut s = Session::new();
|
||||
exec(&mut s, "file.new", json!({"sample": name}))?;
|
||||
s
|
||||
}
|
||||
(None, None) => blank(),
|
||||
if a.opt(option) == Some("") {
|
||||
return Err(format!("--{option} must name an existing directory"));
|
||||
}
|
||||
}
|
||||
if a.opt("connect").is_some() && (a.opt("automation-read-root").is_some() || a.opt("automation-write-root").is_some()) {
|
||||
return Err("automation roots require headless MCP; --connect cannot enforce them in the desktop app".into());
|
||||
}
|
||||
if a.opt("connect").is_some() && (a.has("headless") || a.opt("when-closed").is_some()) {
|
||||
return Err("--connect names a `gridcraft --control` app itself; --headless and --when-closed are for plain `mcp`".into());
|
||||
}
|
||||
if let Some(choice) = a.opt("when-closed") {
|
||||
if craft_control::agents::WhenAppClosed::parse(choice).is_none() {
|
||||
return Err(format!("--when-closed must be launch, headless or error, not `{choice}`"));
|
||||
}
|
||||
if a.has("headless") || a.opt("in").is_some() || a.opt("sample").is_some() {
|
||||
return Err("--when-closed is for the open window; --headless, --in and --sample never reach it".into());
|
||||
}
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// `mcp`: the open GridCraft window while the person lets agents use it, found through its
|
||||
/// connection file on every tool call, otherwise a headless session (`gridcraft_mcp::agents`).
|
||||
/// `--headless` (or `--in`/`--sample`, which name a headless workbook) always runs headless.
|
||||
/// `--connect PORT|HOST:PORT` drives an app started with `gridcraft --control PORT` (deprecated).
|
||||
/// JSON-RPC on stdin/stdout; logs on stderr.
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
use gridcraft_mcp::agents::{LiveBackend, LiveConfig};
|
||||
use gridcraft_mcp::{Backend, Headless, Server};
|
||||
let a = mcp_args(args)?;
|
||||
let read_root = a.opt("automation-read-root");
|
||||
let write_root = a.opt("automation-write-root");
|
||||
let roots = gridcraft_engine::file_access::AutomationRoots::new(read_root.map(std::path::Path::new), write_root.map(std::path::Path::new))?;
|
||||
let headless_only = a.has("headless") || a.opt("in").is_some() || a.opt("sample").is_some();
|
||||
let settings_dir = gridcraft_mcp::agents::settings_dir();
|
||||
let backend: Box<dyn Backend> = match (a.opt("connect"), settings_dir) {
|
||||
(Some(c), _) => {
|
||||
eprintln!("{CONNECT_DEPRECATED}");
|
||||
Box::new(gridcraft_mcp::agents::control_window(c)?)
|
||||
}
|
||||
(None, Some(dir)) if !headless_only => {
|
||||
let mut cfg = LiveConfig::new(dir);
|
||||
cfg.when_closed = a.opt("when-closed").and_then(craft_control::agents::WhenAppClosed::parse);
|
||||
cfg.read_root = read_root.map(std::path::PathBuf::from);
|
||||
cfg.write_root = write_root.map(std::path::PathBuf::from);
|
||||
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft_control::agents::launcher(&cli, gridcraft_mcp::agents::APP_EXE));
|
||||
Box::new(LiveBackend::new(cfg))
|
||||
}
|
||||
(None, None) if !headless_only && a.opt("when-closed").is_some() => {
|
||||
return Err("no settings folder (APPDATA or HOME is not set), so the open GridCraft window can't be found; use --headless for a session without a window"
|
||||
.into());
|
||||
}
|
||||
(None, _) => {
|
||||
// As in every Craft app: each automation root grants that direction of file access and
|
||||
// an omitted one denies it, so with neither the session opens and saves nothing. With
|
||||
// roots, they apply before --in, and to worker threads as well as calls arriving over
|
||||
// MCP; without them, the --in file the command names is opened before that.
|
||||
let open_session = || -> Result<Session, String> {
|
||||
Ok(match (a.opt("in"), a.opt("sample")) {
|
||||
(Some(p), _) => open(p)?,
|
||||
(None, Some(name)) => {
|
||||
let mut s = Session::new();
|
||||
exec(&mut s, "file.new", json!({"sample": name}))?;
|
||||
s
|
||||
}
|
||||
(None, None) => blank(),
|
||||
})
|
||||
};
|
||||
Box::new(Headless::with_session(session))
|
||||
let (session, roots) = match roots {
|
||||
Some(roots) => {
|
||||
if !gridcraft_engine::file_access::confine_process(roots.clone()) {
|
||||
return Err("automation roots were already configured for this process".into());
|
||||
}
|
||||
(open_session()?, roots)
|
||||
}
|
||||
None => {
|
||||
let session = open_session()?;
|
||||
let none = gridcraft_engine::file_access::AutomationRoots::none();
|
||||
gridcraft_engine::file_access::confine_process(none.clone());
|
||||
(session, none)
|
||||
}
|
||||
};
|
||||
Box::new(Headless::with_session(session).with_automation_roots(Some(roots)))
|
||||
}
|
||||
};
|
||||
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
|
||||
@@ -591,9 +665,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
|
||||
/// `send PORT METHOD [JSON]`: one control-channel request to a running `gridcraft --control` app.
|
||||
fn send(args: &[String]) -> Result<(), String> {
|
||||
use gridcraft_mcp::{Backend, Remote, control_addr};
|
||||
use gridcraft_mcp::Backend;
|
||||
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
|
||||
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
|
||||
let params: Value = match args.get(2) {
|
||||
@@ -603,10 +677,7 @@ fn send(args: &[String]) -> Result<(), String> {
|
||||
if let Some(x) = args.get(3) {
|
||||
return Err(format!("unexpected argument `{x}`"));
|
||||
}
|
||||
let addr = control_addr(port);
|
||||
let mut r = Remote::connect(&addr)
|
||||
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
|
||||
let v = r.call(method, params)?;
|
||||
let v = gridcraft_mcp::agents::control_window(port)?.call(method, params)?;
|
||||
outln!("{}", pretty(&v));
|
||||
Ok(())
|
||||
}
|
||||
@@ -665,6 +736,50 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Root parsing is independent of the filesystem and never starts a server.
|
||||
#[test]
|
||||
fn mcp_root_arguments_are_independent() {
|
||||
for (flags, read, write) in [
|
||||
(vec![], None, None),
|
||||
(vec!["--automation-read-root", "/selected"], Some("/selected"), None),
|
||||
(vec!["--automation-write-root=/selected/out"], None, Some("/selected/out")),
|
||||
(vec!["--automation-read-root=/selected", "--automation-write-root", "/selected/out"], Some("/selected"), Some("/selected/out")),
|
||||
(vec!["--automation-read-root", "/selected", "--automation-write-root", "/selected"], Some("/selected"), Some("/selected")),
|
||||
] {
|
||||
let args: Vec<String> = flags.iter().map(|s| s.to_string()).collect();
|
||||
let parsed = mcp_args(&args).unwrap();
|
||||
assert_eq!(parsed.opt("automation-read-root"), read);
|
||||
assert_eq!(parsed.opt("automation-write-root"), write);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid policy options fail before a backend or process policy is installed.
|
||||
#[test]
|
||||
fn mcp_root_arguments_reject_alias_and_invalid_combinations() {
|
||||
for flags in [
|
||||
vec!["--root", "/selected"],
|
||||
vec!["--root=/selected"],
|
||||
vec!["--automation-read-root", "/selected", "--automation-read-root", "/other"],
|
||||
vec!["--automation-write-root=/selected/out", "--automation-write-root=/other"],
|
||||
vec!["--automation-read-root", ""],
|
||||
vec!["--automation-write-root="],
|
||||
vec!["--automation-read-root"],
|
||||
vec!["--automation-write-root"],
|
||||
vec!["--connect", "7979", "--automation-read-root", "/selected"],
|
||||
vec!["--connect", "7979", "--automation-write-root", "/selected/out"],
|
||||
// The closed-app choice names one of three, and only plain `mcp` reaches a window.
|
||||
vec!["--when-closed", "later"],
|
||||
vec!["--when-closed", "launch", "--headless"],
|
||||
vec!["--when-closed", "headless", "--in", "book.xlsx"],
|
||||
vec!["--connect", "7979", "--headless"],
|
||||
vec!["--connect", "7979", "--when-closed", "error"],
|
||||
vec!["--headless=yes"],
|
||||
] {
|
||||
let args: Vec<String> = flags.iter().map(|s| s.to_string()).collect();
|
||||
assert!(mcp_args(&args).is_err(), "{flags:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_texts() {
|
||||
assert_eq!(value_text(&json!(6.0)), "6");
|
||||
|
||||
@@ -129,7 +129,19 @@ fn commands_and_functions() {
|
||||
|
||||
#[test]
|
||||
fn mcp_over_stdio() {
|
||||
let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
// The suite's AI-MCP flag off (an empty flags file): plain `mcp` lets no agent into a window
|
||||
// and serves a session without one, whatever this machine's launcher allows.
|
||||
let flags = tmpdir("mcp-flags").join("flags.toml");
|
||||
std::fs::write(&flags, "").unwrap();
|
||||
let mut child = bin()
|
||||
.arg("mcp")
|
||||
.env("CRAFT_FLAGS_FILE", &flags)
|
||||
.env_remove("CRAFT_FLAGS")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
{
|
||||
let stdin = child.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Real CLI startup checks; all synthetic fixtures are retained.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn base(label: &str) -> PathBuf {
|
||||
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let p = std::env::temp_dir().join(format!("gridcraft-cli-confinement-{label}-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir_all(p.join("allowed")).unwrap();
|
||||
std::fs::create_dir_all(p.join("outside")).unwrap();
|
||||
std::fs::write(p.join("allowed/in.csv"), "inside,7\n").unwrap();
|
||||
std::fs::write(p.join("outside/in.csv"), "outside,91\n").unwrap();
|
||||
p
|
||||
}
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).stdin(Stdio::null()).output().unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn folder_confinement_cli_checks_initial_in_before_reading() {
|
||||
let p = base("startup");
|
||||
let root = p.join("allowed");
|
||||
let outside = p.join("outside/in.csv");
|
||||
let inside = root.join("in.csv");
|
||||
let denied = run(&["mcp", "--automation-read-root", root.to_str().unwrap(), "--in", outside.to_str().unwrap()]);
|
||||
assert!(!denied.status.success());
|
||||
assert!(String::from_utf8_lossy(&denied.stderr).contains("outside the read root"));
|
||||
let allowed = run(&["mcp", "--automation-read-root", root.to_str().unwrap(), "--in", inside.to_str().unwrap()]);
|
||||
assert!(allowed.status.success(), "{}", String::from_utf8_lossy(&allowed.stderr));
|
||||
let inline = format!("--automation-read-root={}", root.display());
|
||||
assert!(run(&["mcp", &inline, "--in", inside.to_str().unwrap()]).status.success());
|
||||
}
|
||||
#[test]
|
||||
fn folder_confinement_cli_rejects_ambiguous_or_unenforceable_configuration() {
|
||||
let p = base("options");
|
||||
let root = p.join("allowed");
|
||||
let r = root.to_str().unwrap();
|
||||
for args in [
|
||||
vec!["mcp", "--automation-read-root", r, "--automation-read-root", r],
|
||||
vec!["mcp", "--automation-write-root", r, "--automation-write-root", r],
|
||||
vec!["mcp", "--connect", "7979", "--automation-read-root", r],
|
||||
vec!["mcp", "--automation-read-root", ""],
|
||||
vec!["mcp", "--automation-read-root"],
|
||||
vec!["mcp", "--automation-read-root", "--sample", "sales"],
|
||||
] {
|
||||
let o = run(&args);
|
||||
assert!(!o.status.success(), "{args:?}");
|
||||
}
|
||||
assert!(!run(&["mcp", "--automation-read-root", p.join("missing").to_str().unwrap()]).status.success());
|
||||
assert!(!run(&["mcp", "--automation-read-root", root.join("in.csv").to_str().unwrap()]).status.success());
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! The crate's integration tests, one module per file, built as one test binary.
|
||||
mod cli;
|
||||
mod folder_confinement;
|
||||
mod sandbox;
|
||||
mod text_to_columns_quotes;
|
||||
|
||||
@@ -25,10 +25,9 @@ log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
@@ -228,7 +228,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = craft_print::browser::print_pdf(bytes) {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
@@ -280,6 +280,75 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
if let Err(e) = body.append_child(&iframe) {
|
||||
cleanup_print(&iframe, &url);
|
||||
return Err(js(e));
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
iframe_for_load.set_onload(None);
|
||||
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
|
||||
cleanup_print(&iframe_for_load, &url_for_cleanup);
|
||||
log::error!("print failed: {e:?}");
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
|
||||
// Both operations are idempotent: print can fail after dispatching `afterprint`.
|
||||
web_sys::Url::revoke_object_url(url).ok();
|
||||
iframe.remove();
|
||||
}
|
||||
|
||||
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
|
||||
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
|
||||
let iframe_for_cleanup = iframe.clone();
|
||||
let url_for_cleanup = url.to_owned();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
|
||||
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
|
||||
});
|
||||
// Listen before `print()`, which can dispatch `afterprint` before it returns.
|
||||
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
|
||||
let options = web_sys::AddEventListenerOptions::new();
|
||||
options.set_once(true);
|
||||
let callback = on_after_print.as_ref().unchecked_ref();
|
||||
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
|
||||
if let Err(e) = content_window.print() {
|
||||
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = on_after_print.into_js_value();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
|
||||
@@ -39,8 +39,11 @@ craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
gridcraft-mcp = { workspace = true }
|
||||
# The control channel's token (OS random numbers); already in the tree.
|
||||
getrandom = "0.4"
|
||||
# Agents in the open window: the ArtCraft Launcher's switch and the stale connection file.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
# `--control`: the framework's control server and its token, the ones the agents link runs.
|
||||
craft-automation = { workspace = true, features = ["agents", "ui"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
|
||||
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
|
||||
|
||||
@@ -11,15 +11,8 @@ use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
match platform {
|
||||
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
|
||||
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
|
||||
_ => env("XDG_CONFIG_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("gridcraft")),
|
||||
}
|
||||
// Shared with `gridcraft-cli mcp`, which finds the open window's agent connection there.
|
||||
gridcraft_mcp::agents::settings_dir_for(platform, env)
|
||||
}
|
||||
|
||||
/// The folder the settings and the log files live in.
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
//! Localhost JSON-lines control server. Each connection may send many requests; each line
|
||||
//! `{"id":…, "method":…, "params":…}` gets one reply line `{"id":…, "ok":…, …}`.
|
||||
//!
|
||||
//! The first line of a connection must authenticate with the app's token (#777; see
|
||||
//! `gridcraft_mcp::control_auth`). A connection that doesn't, or later sends a line that isn't
|
||||
//! JSON, is answered once and closed.
|
||||
//!
|
||||
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gridcraft_mcp::control_auth;
|
||||
use gridcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
const MAX_LINE: usize = 64 * 1024 * 1024;
|
||||
/// How long a new connection may take to send its token, in total.
|
||||
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// How many connections may be waiting to authenticate at once. Anyone on the machine can
|
||||
/// connect without the token, so past this a new connection is closed before anything is read:
|
||||
/// each waiting one holds a thread and a socket.
|
||||
const MAX_PENDING_AUTH: usize = 16;
|
||||
|
||||
/// How the server treats connections that haven't authenticated yet.
|
||||
#[derive(Clone, Copy)]
|
||||
struct AuthLimits {
|
||||
timeout: Duration,
|
||||
max_pending: usize,
|
||||
}
|
||||
|
||||
const AUTH_LIMITS: AuthLimits = AuthLimits { timeout: AUTH_TIMEOUT, max_pending: MAX_PENDING_AUTH };
|
||||
|
||||
/// A connection that is still waiting to authenticate; dropping it frees its place.
|
||||
struct Pending(Arc<AtomicUsize>);
|
||||
|
||||
impl Pending {
|
||||
/// A place among the `max` waiting connections, or `None` when they are all taken.
|
||||
fn claim(waiting: &Arc<AtomicUsize>, max: usize) -> Option<Pending> {
|
||||
waiting.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok()?;
|
||||
Some(Pending(Arc::clone(waiting)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pending {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// The secret of this run: the one the user chose (`--control-token`, `GRIDCRAFT_CONTROL_TOKEN`),
|
||||
/// else 256 random bits from the operating system, written to a file only the user can read.
|
||||
fn make_token(port: u16, chosen: Option<String>) -> std::io::Result<String> {
|
||||
if let Some(t) = chosen.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) {
|
||||
if t.len() < control_auth::MIN_TOKEN_LEN {
|
||||
return Err(std::io::Error::other(format!("the control token must have at least {} characters", control_auth::MIN_TOKEN_LEN)));
|
||||
}
|
||||
eprintln!("gridcraft: control channel on 127.0.0.1:{port} requires the token you set (clients: GRIDCRAFT_CONTROL_TOKEN)");
|
||||
return Ok(t);
|
||||
}
|
||||
let mut bytes = [0u8; 32];
|
||||
getrandom::fill(&mut bytes).map_err(|e| std::io::Error::other(format!("no random numbers for the control token: {e}")))?;
|
||||
let token = control_auth::hex(&bytes);
|
||||
let path = control_auth::write_token_file(port, &token)?;
|
||||
eprintln!("gridcraft: control channel on 127.0.0.1:{port}; its token is in {} (gridcraft-cli reads it)", path.display());
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub fn start(port: u16, chosen_token: Option<String>, ctx: egui::Context) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
let listener = TcpListener::bind(("127.0.0.1", port))?;
|
||||
let token: Arc<str> = make_token(port, chosen_token)?.into();
|
||||
let rx = serve_listener(listener, token, ctx)?;
|
||||
log::info!("control channel listening on 127.0.0.1:{port}");
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// Accept connections on `listener`; requests arrive on the returned receiver.
|
||||
fn serve_listener(listener: TcpListener, token: Arc<str>, ctx: egui::Context) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
serve_listener_with(listener, token, ctx, AUTH_LIMITS)
|
||||
}
|
||||
|
||||
fn serve_listener_with(listener: TcpListener, token: Arc<str>, ctx: egui::Context, limits: AuthLimits) -> std::io::Result<Receiver<ControlRequest>> {
|
||||
let (tx, rx) = channel();
|
||||
let waiting = Arc::new(AtomicUsize::new(0));
|
||||
std::thread::Builder::new().name("control".into()).spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else {
|
||||
// Out of sockets or handles: wait for some to free instead of spinning on the error.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
};
|
||||
// Dropping the stream closes it before anything is read.
|
||||
let Some(place) = Pending::claim(&waiting, limits.max_pending) else { continue };
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let _ =
|
||||
std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx, limits.timeout, Some(place)));
|
||||
}
|
||||
})?;
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// Read the connection's first line (at most [`control_auth::MAX_AUTH_LINE`] bytes, within
|
||||
/// `timeout` in total) and check the token. `true` when the peer may go on.
|
||||
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
|
||||
fn authenticate(reader: &mut BufReader<TcpStream>, out: &mut TcpStream, token: &str, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now().checked_add(timeout).unwrap_or_else(Instant::now);
|
||||
let mut first = Vec::new();
|
||||
let read = read_auth_line(reader, &mut first, deadline);
|
||||
let verdict = match (read, std::str::from_utf8(&first)) {
|
||||
(Ok(()), Ok(line)) if line.ends_with('\n') => control_auth::check_first_line(line, token),
|
||||
_ => Err(json!({"ok": false, "error": "authentication required"})),
|
||||
};
|
||||
let allowed = verdict.is_ok();
|
||||
let reply = verdict.unwrap_or_else(|e| e);
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = reader.get_ref().set_read_timeout(None);
|
||||
allowed
|
||||
}
|
||||
|
||||
/// Read the first line, at most [`control_auth::MAX_AUTH_LINE`] bytes, by `deadline`.
|
||||
///
|
||||
/// The timeout goes on the handle the reader reads: on Windows a `try_clone` of the stream keeps
|
||||
/// its own, so one set on the writing half never fired (a silent peer held its thread forever).
|
||||
/// It is shortened before every read, so a peer sending one byte at a time can't stretch it.
|
||||
#[allow(clippy::disallowed_methods)] // the desktop app (native only): wasm never runs it
|
||||
fn read_auth_line(reader: &mut BufReader<TcpStream>, line: &mut Vec<u8>, deadline: Instant) -> std::io::Result<()> {
|
||||
let max = control_auth::MAX_AUTH_LINE;
|
||||
while line.len() < max && line.last() != Some(&b'\n') {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
reader.get_ref().set_read_timeout(Some(left))?;
|
||||
let buf = reader.fill_buf()?;
|
||||
if buf.is_empty() {
|
||||
break;
|
||||
}
|
||||
let room = max.saturating_sub(line.len());
|
||||
let take = buf.iter().take(room).position(|b| *b == b'\n').map_or(buf.len().min(room), |i| i + 1);
|
||||
line.extend(buf.iter().take(take));
|
||||
reader.consume(take);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
|
||||
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
|
||||
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
|
||||
buf.clear();
|
||||
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
|
||||
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
|
||||
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
return Ok(true);
|
||||
}
|
||||
if buf.len() > max {
|
||||
return Err(format!("request too large (over {max} bytes); closing the connection"));
|
||||
}
|
||||
// Last line without a newline, then end of stream.
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// One request line, parsed.
|
||||
enum Line {
|
||||
Request {
|
||||
id: Json,
|
||||
method: String,
|
||||
params: Json,
|
||||
},
|
||||
Blank,
|
||||
/// Not a request: reply with this error and close the connection.
|
||||
Reject(String),
|
||||
}
|
||||
|
||||
fn parse_line(bytes: &[u8]) -> Line {
|
||||
let Ok(text) = std::str::from_utf8(bytes) else {
|
||||
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
|
||||
};
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Line::Blank;
|
||||
}
|
||||
if is_http_request_line(text) {
|
||||
return Line::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
|
||||
}
|
||||
let msg = match serde_json::from_str::<Json>(text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Line::Reject(format!("invalid JSON ({e}); expected one JSON request object per line; closing the connection")),
|
||||
};
|
||||
let Some(obj) = msg.as_object() else {
|
||||
return Line::Reject("not a control request (expected a JSON object); closing the connection".into());
|
||||
};
|
||||
let Some(method) = obj.get("method").and_then(Json::as_str) else {
|
||||
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
|
||||
};
|
||||
Line::Request {
|
||||
id: obj.get("id").cloned().unwrap_or(Json::Null),
|
||||
method: method.to_string(),
|
||||
params: obj.get("params").cloned().unwrap_or(json!({})),
|
||||
}
|
||||
}
|
||||
|
||||
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
|
||||
fn is_http_request_line(text: &str) -> bool {
|
||||
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
|
||||
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|
||||
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context, auth_timeout: Duration, place: Option<Pending>) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(read);
|
||||
let allowed = authenticate(&mut reader, &mut out, token, auth_timeout);
|
||||
// Authenticated or refused, the connection no longer counts as waiting.
|
||||
drop(place);
|
||||
if !allowed {
|
||||
return;
|
||||
}
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
|
||||
Ok(false) => break,
|
||||
// The peer is gone before sending a line: nobody to tell.
|
||||
Err(_) if buf.is_empty() => break,
|
||||
Err(e) => e,
|
||||
Ok(true) => match parse_line(&buf) {
|
||||
Line::Blank => continue,
|
||||
Line::Reject(e) => e,
|
||||
Line::Request { id, method, params } => {
|
||||
let (req, rx) = ControlRequest::new(method, params);
|
||||
let state = std::sync::Arc::clone(&req.state);
|
||||
if tx.send(req).is_err() {
|
||||
break;
|
||||
}
|
||||
// Wake the UI thread: egui only runs frames when something happens.
|
||||
ctx.request_repaint();
|
||||
let mut reply = rx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| {
|
||||
// Give up on the request as well as on its reply. While it is still
|
||||
// queued this keeps it from running late -- the client was told it had
|
||||
// failed, and an agent that retried after the error ran it twice (#1914);
|
||||
// if the app had already started it, its outcome is unknown instead.
|
||||
if ControlRequest::abandon(&state) {
|
||||
json!({"ok": false, "error": "timed out waiting for the UI (is the window minimised?)"})
|
||||
} else {
|
||||
json!({"ok": false, "error": "timed out waiting for the UI, which had already started the request, so it may still finish; its outcome is unknown"})
|
||||
}
|
||||
});
|
||||
if let Some(o) = reply.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
if writeln!(out, "{reply}").is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
// The connection closes either way; a peer that can't read the reason loses nothing.
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject}));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// Authenticate a new connection, send `input`, and read reply lines (after the
|
||||
/// authentication reply) until the server closes it.
|
||||
fn exchange(addr: std::net::SocketAddr, input: &[u8]) -> Vec<Json> {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
|
||||
c.write_all(input).unwrap();
|
||||
// A read timeout ends the list too: the server kept the connection open.
|
||||
let mut replies: Vec<Json> = BufReader::new(c).lines().map_while(Result::ok).map(|l| serde_json::from_str(&l).unwrap()).collect();
|
||||
assert_eq!(replies.first().map(|r| r["ok"].clone()), Some(json!(true)), "{replies:?}");
|
||||
replies.remove(0);
|
||||
replies
|
||||
}
|
||||
|
||||
fn serve_on_loopback() -> (std::net::SocketAddr, Receiver<ControlRequest>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
(addr, serve_listener(listener, TOKEN.into(), egui::Context::default()).unwrap())
|
||||
}
|
||||
|
||||
/// A browser can POST to the port: its request line closes the connection before the JSON
|
||||
/// line in its body is read, so nothing is dispatched.
|
||||
#[test]
|
||||
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
|
||||
let (addr, rx) = serve_on_loopback();
|
||||
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nContent-Type: text/plain\r\n\r\n\
|
||||
{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"cell.set\",\"params\":{\"cell\":\"A1\",\"input\":\"x\"}}}\n";
|
||||
let replies = exchange(addr, http);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
|
||||
assert!(rx.try_recv().is_err(), "the body was dispatched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_a_request_closes_the_connection() {
|
||||
let (addr, rx) = serve_on_loopback();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true}));
|
||||
}
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
|
||||
c.write_all(b"{\"id\":1,\"method\":\"a\"}\r\n\n{\"id\":2,\"method\":\"b\"}\n").unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
let mut auth_reply = String::new();
|
||||
r.read_line(&mut auth_reply).unwrap();
|
||||
for id in [1, 2] {
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Json>(&line).unwrap()["id"], id, "{line}");
|
||||
}
|
||||
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
|
||||
let mut input = junk.to_vec();
|
||||
input.extend_from_slice(b"{\"id\":2,\"method\":\"b\"}\n");
|
||||
let replies = exchange(addr, &input);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
}
|
||||
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
|
||||
assert!(is_http_request_line("PRI * HTTP/2.0"));
|
||||
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overlong_line_is_refused_without_reading_the_rest() {
|
||||
let mut buf = Vec::new();
|
||||
let long = [b'x'; 100];
|
||||
let mut input: &[u8] = &long;
|
||||
assert!(read_bounded_line(&mut input, &mut buf, 10).is_err());
|
||||
assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread");
|
||||
}
|
||||
|
||||
/// A server on a loopback port with a stand-in UI that echoes each method.
|
||||
fn spawn() -> std::net::SocketAddr {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default(), AUTH_TIMEOUT, None));
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
fn lines(addr: std::net::SocketAddr, send: &str) -> Vec<Json> {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(send.as_bytes()).unwrap();
|
||||
// Replies up to the server closing the connection.
|
||||
BufReader::new(c).lines().map_while(Result::ok).map(|l| serde_json::from_str(&l).unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_opens_the_connection() {
|
||||
let addr = spawn();
|
||||
let auth = control_auth::auth_line(1, TOKEN);
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(format!("{auth}\n{{\"id\":2,\"method\":\"ping\"}}\n").as_bytes()).unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Json>(&line).unwrap()["ok"], json!(true));
|
||||
line.clear();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Json = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].clone(), v["result"].clone()), (json!(2), json!("ping")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_but_the_token_first_closes_the_connection() {
|
||||
let addr = spawn();
|
||||
let wrong = control_auth::auth_line(1, "ffffffffffffffffffffffffffffffff");
|
||||
for first in [wrong.as_str(), "{\"id\":1,\"method\":\"app.save\",\"params\":{\"path\":\"/tmp/x\"}}", "POST / HTTP/1.1", ""] {
|
||||
// The second request is never served: one refusal, then end of stream.
|
||||
let got = lines(addr, &format!("{first}\n{{\"id\":2,\"method\":\"ping\"}}\n"));
|
||||
assert_eq!(got.len(), 1, "{first}: {got:?}");
|
||||
assert_eq!(got[0]["ok"], json!(false), "{first}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_line_after_auth_closes_the_connection() {
|
||||
let addr = spawn();
|
||||
let auth = control_auth::auth_line(1, TOKEN);
|
||||
let got = lines(addr, &format!("{auth}\nnot json\n{{\"id\":3,\"method\":\"ping\"}}\n"));
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
assert_eq!(got[1]["ok"], json!(false));
|
||||
}
|
||||
|
||||
/// Whether the server closed `c` (end of stream, or a refusal and then end of stream) within
|
||||
/// `within`, and how long it took.
|
||||
#[allow(clippy::disallowed_methods)] // a native-only test of the desktop app
|
||||
fn closed_within(c: TcpStream, within: Duration) -> (bool, Duration) {
|
||||
let start = Instant::now();
|
||||
c.set_read_timeout(Some(within)).unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
match r.read_line(&mut line) {
|
||||
Ok(0) => return (true, start.elapsed()),
|
||||
Ok(_) => continue,
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => return (false, start.elapsed()),
|
||||
Err(_) => return (true, start.elapsed()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The token deadline is for the whole first line: neither a silent peer nor one sending a
|
||||
/// byte at a time keeps the connection (and its thread) past it.
|
||||
#[test]
|
||||
fn a_silent_or_slow_peer_is_closed_at_the_auth_deadline() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let limits = AuthLimits { timeout: Duration::from_millis(300), max_pending: MAX_PENDING_AUTH };
|
||||
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
|
||||
|
||||
let silent = TcpStream::connect(addr).unwrap();
|
||||
let mut slow = TcpStream::connect(addr).unwrap();
|
||||
let mut drip = slow.try_clone().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
for b in control_auth::auth_line(1, TOKEN).bytes() {
|
||||
if drip.write_all(&[b]).is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
});
|
||||
let (closed, took) = closed_within(silent, Duration::from_secs(5));
|
||||
assert!(closed && took < Duration::from_secs(3), "silent peer kept for {took:?}");
|
||||
let (closed, took) = closed_within(slow.try_clone().unwrap(), Duration::from_secs(5));
|
||||
assert!(closed && took < Duration::from_secs(3), "byte-at-a-time peer kept for {took:?}");
|
||||
let _ = slow.flush();
|
||||
}
|
||||
|
||||
/// Peers without the token can't pile up threads: past the cap a new connection is closed at
|
||||
/// once, and a waiting one that authenticates frees its place.
|
||||
#[test]
|
||||
fn connections_waiting_to_authenticate_are_capped() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let limits = AuthLimits { timeout: Duration::from_secs(20), max_pending: 2 };
|
||||
let _rx = serve_listener_with(listener, TOKEN.into(), egui::Context::default(), limits).unwrap();
|
||||
|
||||
let mut first = TcpStream::connect(addr).unwrap();
|
||||
let _second = TcpStream::connect(addr).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let (closed, took) = closed_within(TcpStream::connect(addr).unwrap(), Duration::from_secs(5));
|
||||
assert!(closed && took < Duration::from_secs(3), "a third waiting connection was kept");
|
||||
|
||||
first.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
first.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(first.try_clone().unwrap()).read_line(&mut reply).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "{reply}");
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let mut next = TcpStream::connect(addr).unwrap();
|
||||
next.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
next.write_all(format!("{}\n", control_auth::auth_line(1, TOKEN)).as_bytes()).unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(next).read_line(&mut reply).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Json>(&reply).unwrap()["ok"], json!(true), "a freed place was not reused: {reply}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_token_must_be_long_enough() {
|
||||
assert!(make_token(1, Some("short".into())).is_err());
|
||||
assert_eq!(make_token(1, Some(format!(" {TOKEN} "))).unwrap(), TOKEN);
|
||||
}
|
||||
}
|
||||
+131
-19
@@ -1,11 +1,15 @@
|
||||
//! GridCraft desktop app.
|
||||
//!
|
||||
//! Usage: `gridcraft [--control <port> [--control-token <token>]] [--sample <name>] [files…]`
|
||||
//! Usage: `gridcraft [--control <port> [--control-token <token>] [--automation-read-root <dir>]
|
||||
//! [--automation-write-root <dir>]] [--sample <name>] [files…]`
|
||||
//!
|
||||
//! `--control <port>` (or `GRIDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control
|
||||
//! server: `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`.
|
||||
//! The first line of each connection must carry the token (`docs/control-protocol.md`).
|
||||
//! See `gridcraft_ui_egui::control` and `docs/control-protocol.md` for the methods.
|
||||
//! `--control <port>` (or `GRIDCRAFT_CONTROL_PORT`) serves the framework's loopback control server
|
||||
//! for the whole run (`craft_automation::server`, the one agents reach through the ArtCraft
|
||||
//! Launcher's switch): `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`,
|
||||
//! after the challenge handshake with the token in `agent-control.token` in the settings folder
|
||||
//! (or `--control-token` / `GRIDCRAFT_CONTROL_TOKEN`, 64 hex characters). Its file commands are
|
||||
//! confined to the agent folders, or to the automation roots given. See `gridcraft_ui_egui::control`
|
||||
//! and `docs/control-protocol.md` for the methods.
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -16,7 +20,6 @@ mod apple_events;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
#[cfg(any(target_os = "windows", target_os = "macos", test))]
|
||||
mod graphics;
|
||||
mod launch_profile;
|
||||
@@ -64,9 +67,13 @@ impl eframe::App for App {
|
||||
}
|
||||
apple_events::poll(&self.apple_events, &mut self.app, ctx);
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.windows.logic(&mut self.app, ctx);
|
||||
self.app.close_path(ctx);
|
||||
// While input an agent sent is being applied, the passes run with the agent folders.
|
||||
let windows = &mut self.windows;
|
||||
self.app.with_agent_input(|app| {
|
||||
app.logic(ctx);
|
||||
windows.logic(app, ctx);
|
||||
app.close_path(ctx);
|
||||
});
|
||||
}
|
||||
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
@@ -81,7 +88,8 @@ impl eframe::App for App {
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.windows.show(&mut self.app, ui);
|
||||
let windows = &mut self.windows;
|
||||
self.app.with_agent_input(|app| windows.show(app, ui));
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
print::finish_pending_jobs();
|
||||
@@ -114,6 +122,60 @@ fn config_dir() -> Option<std::path::PathBuf> {
|
||||
app_dirs::config_dir()
|
||||
}
|
||||
|
||||
/// Agents in the open window (`gridcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
|
||||
/// names GridCraft, the window serves agents on loopback and publishes the connection in its
|
||||
/// settings folder, where `gridcraft-cli mcp` finds it. A connection file a crashed run left is
|
||||
/// removed first. `settings` false (`GRIDCRAFT_NO_PREFS`) reads and saves no agent settings.
|
||||
fn agents_for(ctx: &egui::Context, settings: bool) -> gridcraft_ui_egui::agents::Agents {
|
||||
use gridcraft_mcp::agents::{LAUNCHER_APP_ID, read_settings, write_settings};
|
||||
let dir = config_dir().filter(|_| settings);
|
||||
if let Some(dir) = &dir {
|
||||
craft_control::agents::remove_stale_connection(dir);
|
||||
}
|
||||
let switch = craft_control::agents::AgentSwitch::watch(LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
let save_dir = dir.clone();
|
||||
let save: gridcraft_ui_egui::agents::SaveFn = Box::new(move |s| match &save_dir {
|
||||
Some(d) => write_settings(d, s).map_err(|e| format!("couldn't save the agent settings in {}: {e}", d.display())),
|
||||
None => Err("this run keeps no settings (GRIDCRAFT_NO_PREFS)".into()),
|
||||
});
|
||||
let saved = dir.as_deref().map(read_settings).unwrap_or_default();
|
||||
let version = format!("GridCraft {}", env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
gridcraft_ui_egui::agents::Agents::new(dir, version, switch, saved, save)
|
||||
}
|
||||
|
||||
/// The `--control` server bound before the window opens.
|
||||
struct LaunchControl {
|
||||
listener: std::net::TcpListener,
|
||||
token: String,
|
||||
/// The roots the launch named, if any (otherwise the agent folders apply).
|
||||
folders: Option<craft_control::agents::AgentFolders>,
|
||||
}
|
||||
|
||||
/// Binds `127.0.0.1:port` for `--control` with its token: the one given (64 hex characters),
|
||||
/// otherwise the one in `agent-control.token` in the settings folder (created when missing), which
|
||||
/// `gridcraft-cli send` reads.
|
||||
fn bind_control(port: u16, token: Option<&str>, args: &DesktopArgs) -> Result<LaunchControl, String> {
|
||||
use craft_automation::security::server_token;
|
||||
let token = match token.map(str::trim).filter(|t| !t.is_empty()) {
|
||||
Some(t) => server_token(Some(t), None).map_err(|e| format!("the control token: {e}"))?,
|
||||
None => {
|
||||
let dir = config_dir().ok_or("no settings folder for the control token; set GRIDCRAFT_CONTROL_TOKEN (64 hex characters)")?;
|
||||
server_token(None, Some(&dir.join(craft_control::agents::TOKEN_FILE))).map_err(|e| format!("the control token: {e}"))?
|
||||
}
|
||||
};
|
||||
let folders = (args.read_root.is_some() || args.write_root.is_some()).then(|| {
|
||||
let mut f = craft_control::agents::AgentFolders::default();
|
||||
f.read = args.read_root.as_deref().map(std::path::PathBuf::from);
|
||||
f.write = args.write_root.as_deref().map(std::path::PathBuf::from);
|
||||
f
|
||||
});
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("couldn't listen on 127.0.0.1:{port}: {e}"))?;
|
||||
Ok(LaunchControl { listener, token, folders })
|
||||
}
|
||||
|
||||
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
|
||||
/// them, and keep no log file.
|
||||
fn prefs_enabled() -> bool {
|
||||
@@ -354,6 +416,13 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
control_token: Option<String>,
|
||||
/// `--automation-read-root` / `--automation-write-root`: the folders `--control` requests may
|
||||
/// use instead of the agent folders.
|
||||
read_root: Option<String>,
|
||||
write_root: Option<String>,
|
||||
/// An option given without its value (`--automation-write-root` last, or followed by another
|
||||
/// option): the launch is refused rather than run with other folders.
|
||||
invalid: Option<String>,
|
||||
sample: Option<String>,
|
||||
files: Vec<String>,
|
||||
}
|
||||
@@ -375,6 +444,18 @@ fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Optio
|
||||
i += 1;
|
||||
parsed.control_token = args.get(i).cloned();
|
||||
}
|
||||
flag @ ("--automation-read-root" | "--automation-write-root") => {
|
||||
i += 1;
|
||||
match args.get(i).filter(|v| !v.is_empty() && !v.starts_with("--")) {
|
||||
Some(dir) if flag == "--automation-read-root" => parsed.read_root = Some(dir.clone()),
|
||||
Some(dir) => parsed.write_root = Some(dir.clone()),
|
||||
None => {
|
||||
parsed.invalid.get_or_insert_with(|| format!("{flag} needs a folder"));
|
||||
// The option in the value position is read as an option again.
|
||||
i -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
@@ -391,7 +472,10 @@ fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Optio
|
||||
/// document named `--control` is opened rather than read as a flag.
|
||||
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
|
||||
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
|
||||
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
|
||||
nightly
|
||||
&& args[..options_end]
|
||||
.iter()
|
||||
.any(|a| matches!(a.as_str(), "--control" | "--control-token" | "--automation-read-root" | "--automation-write-root"))
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
@@ -408,8 +492,10 @@ fn main() -> eframe::Result<()> {
|
||||
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
|
||||
// for a control server can never write the stable app's token file.
|
||||
if let Some(root) = launch_profile::current().root() {
|
||||
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
|
||||
Ok(()) => {}
|
||||
// The nightly channel has no control server; its profile's control folder must still be
|
||||
// its own, as the profile's other folders are.
|
||||
match profile_root::control_directory(root) {
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
@@ -463,7 +549,20 @@ fn main() -> eframe::Result<()> {
|
||||
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let parsed = desktop_args(&args, control_port, control_token);
|
||||
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
|
||||
let (control_port, control_token, sample, files) =
|
||||
(parsed.control_port, parsed.control_token.clone(), parsed.sample.clone(), parsed.files.clone());
|
||||
if let Some(problem) = &parsed.invalid {
|
||||
eprintln!("gridcraft: {problem}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
// `--control`: bound now, so a taken port or a bad token fails before a window opens.
|
||||
let control = match control_port.map(|port| bind_control(port, control_token.as_deref(), &parsed)).transpose() {
|
||||
Ok(control) => std::cell::Cell::new(control),
|
||||
Err(e) => {
|
||||
eprintln!("gridcraft: --control: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// The log file lives in the settings folder, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -588,11 +687,13 @@ fn main() -> eframe::Result<()> {
|
||||
};
|
||||
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
|
||||
if let Some(port) = control_port {
|
||||
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
|
||||
Ok(rx) => app.control_rx = Some(rx),
|
||||
Err(e) => log::error!("control channel on port {port}: {e}"),
|
||||
}
|
||||
if let Some(control) = control.take() {
|
||||
let host = craft_ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
|
||||
let (requests, server) = craft_automation::server::serve(control.listener, control.token, host)?;
|
||||
eprintln!("gridcraft: control server listening on {}", server.addr);
|
||||
app.agents = Some(agents_for(&cc.egui_ctx, prefs_enabled()).launched_with_control(server, requests, control.folders));
|
||||
} else if !nightly && prefs_enabled() && config_dir().is_some() {
|
||||
app.agents = Some(agents_for(&cc.egui_ctx, true));
|
||||
}
|
||||
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
|
||||
Ok(Box::new(App {
|
||||
@@ -720,6 +821,17 @@ mod launch_separator_tests {
|
||||
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_automation_root_without_its_folder_is_refused() {
|
||||
let args = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert!(desktop_args(&args(&["--control", "7979", "--automation-write-root"]), None, None).invalid.is_some());
|
||||
let next_is_an_option = desktop_args(&args(&["--automation-read-root", "--control", "7979"]), None, None);
|
||||
assert!(next_is_an_option.invalid.is_some());
|
||||
assert_eq!(next_is_an_option.control_port, Some(7979), "the option in the value position still counts");
|
||||
let read_only = desktop_args(&args(&["--control", "7979", "--automation-read-root", "in"]), None, None);
|
||||
assert_eq!((read_only.read_root.as_deref(), read_only.write_root.as_deref(), read_only.invalid), (Some("in"), None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_before_the_separator_still_names_the_port() {
|
||||
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
|
||||
|
||||
@@ -119,6 +119,11 @@ sync_github_name = true
|
||||
[people.RockerHX]
|
||||
sync_github_name = true
|
||||
|
||||
[people.switch87]
|
||||
real_name = "Gert Pellin"
|
||||
display_name = "Gert Pellin"
|
||||
sync_github_name = false
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
|
||||
@@ -141,6 +141,11 @@ pub trait Host {
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
range.iter().map(|c| self.cell_value(sheet, c)).collect()
|
||||
}
|
||||
/// Finds the smallest rectangle covering the non-empty cells of a block without reading its
|
||||
/// full grid. The outer `None` leaves the read to `range_values`. `Some(None)` means all blank.
|
||||
fn range_nonempty_bounds(&mut self, _sheet: usize, _range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
None
|
||||
}
|
||||
/// The sheet's used range (`Sheet::used_range`, which walks every stored row). Hosts that
|
||||
/// keep the workbook unchanged while evaluating can remember it.
|
||||
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
|
||||
|
||||
@@ -915,6 +915,70 @@ pub(crate) mod tests {
|
||||
assert!(!index_spills(5_000, 5_000, [].iter()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_references_skip_the_dense_grid_for_sparse_stored_values() {
|
||||
use crate::eval::{Area, Ev, Evaluator};
|
||||
use gridcraft_core::CellError;
|
||||
use gridcraft_model::StyleId;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
sh.set_cell(at("C3"), Cell::value(Value::Number(0.0)));
|
||||
let mut cached = Cell::formula(Formula::new("\"\""));
|
||||
cached.value = Value::text("");
|
||||
sh.set_cell(at("N39999"), cached);
|
||||
sh.set_cell(at("Q40001"), Cell::styled(Value::Empty, StyleId(1)));
|
||||
// These cells keep the sheet's used extent wide and tall without being in the trim range.
|
||||
sh.set_cell(at("Q1"), Cell::value(Value::Number(1.0)));
|
||||
sh.set_cell(at("A40001"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let mut ev = Evaluator::new(&mut host, 0, at("S1"));
|
||||
for (src, expected) in [("B2.:.Q40001", "C3:N39999"), ("TRIMRANGE(B2:Q40001,1,2)", "B3:N40001")] {
|
||||
let expr = gridcraft_formula::parse(src).unwrap();
|
||||
let result = ev.eval(&expr);
|
||||
let area = Area { sheet: 0, range: RangeRef::parse(expected).unwrap() };
|
||||
assert!(matches!(&result, Ev::R(areas) if areas.as_slice() == [area]), "{src}: {result:?}");
|
||||
}
|
||||
let blank = gridcraft_formula::parse("TRIMRANGE(O2:Q40001)").unwrap();
|
||||
assert!(matches!(ev.eval(&blank), Ev::V(Value::Error(CellError::Calc))));
|
||||
assert_eq!(host.materialized_range_cells, 0, "bounds reads must not allocate a dense grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_range_includes_a_spill_from_outside_the_block() {
|
||||
use crate::eval::Evaluator;
|
||||
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let at = |s: &str| CellRef::parse(s).unwrap();
|
||||
let anchor = (0, at("C1"));
|
||||
let target = at("I1");
|
||||
let source = Formula::new("SEQUENCE(2,5)");
|
||||
let consumer = Formula::new("COLUMNS(TRIMRANGE(C2:G4))");
|
||||
let exprs = [(anchor, source.expr_arc().unwrap()), ((0, target), consumer.expr_arc().unwrap())].into_iter().collect();
|
||||
sh.set_cell(anchor.1, Cell::formula(source));
|
||||
sh.set_cell(target, Cell::formula(consumer));
|
||||
// Extend the read area before the new spill has been committed to the sheet.
|
||||
sh.set_cell(at("H5"), Cell::value(Value::Number(1.0)));
|
||||
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
host.calculate(anchor);
|
||||
host.calculate((0, target));
|
||||
assert_eq!(host.results.get(&(0, target)), Some(&Value::Number(5.0)), "new spill in the current pass");
|
||||
|
||||
Calc::new().recalc_all(&mut wb);
|
||||
let exprs = HashMap::default();
|
||||
let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0);
|
||||
let consumer = gridcraft_formula::parse("COLUMNS(TRIMRANGE(C2:G4))").unwrap();
|
||||
let result = Evaluator::new(&mut host, 0, target).value(&consumer);
|
||||
assert_eq!(result, Value::Number(5.0), "stored spill from a completed recalculation");
|
||||
}
|
||||
|
||||
/// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already
|
||||
/// spilled on the sheet from the last calculation, as a full recalculation finds them.
|
||||
fn big_python_spill() -> (Workbook, HashMap<Key, Value>) {
|
||||
|
||||
@@ -57,6 +57,9 @@ pub(super) struct PassHost<'a> {
|
||||
/// looks at none of it).
|
||||
#[cfg(test)]
|
||||
pub(super) spill_visits: usize,
|
||||
/// Number of value slots allocated by dense range reads.
|
||||
#[cfg(test)]
|
||||
pub(super) materialized_range_cells: usize,
|
||||
/// The formulas in `cycles`.
|
||||
cycle_seen: HashSet<Key>,
|
||||
/// Iterative calculation: a circular reference reads the cell's previous value instead of
|
||||
@@ -114,6 +117,8 @@ impl<'a> PassHost<'a> {
|
||||
suspensions: 0,
|
||||
#[cfg(test)]
|
||||
spill_visits: 0,
|
||||
#[cfg(test)]
|
||||
materialized_range_cells: 0,
|
||||
cycle_seen: HashSet::default(),
|
||||
iterate: false,
|
||||
prev: HashMap::default(),
|
||||
@@ -238,6 +243,25 @@ fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &m
|
||||
}
|
||||
|
||||
impl PassHost<'_> {
|
||||
fn range_has_spill(&mut self, sheet: usize, range: RangeRef) -> bool {
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
if !arrays.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return false };
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would
|
||||
/// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is
|
||||
/// calculated from here, then the suspended ones again (reading the results kept so far).
|
||||
@@ -609,6 +633,10 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
fn range_values(&mut self, sheet: usize, range: RangeRef) -> Vec<Value> {
|
||||
let (h, w) = (range.height() as usize, range.width() as usize);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.materialized_range_cells += h * w;
|
||||
}
|
||||
let mut out = vec![Value::Empty; h * w];
|
||||
let Some(sh) = self.wb.sheet(sheet) else { return out };
|
||||
// Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go
|
||||
@@ -698,18 +726,7 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
// Spilled values sit between the stored cells (and the formulas just calculated may have
|
||||
// produced some): leave such blocks to `range_values`.
|
||||
let mut arrays = Vec::new();
|
||||
self.spill_index.meeting(sheet, range, &mut arrays);
|
||||
let mut stored = false;
|
||||
let _seen = stored_spill_in(sh, range, &mut |_, _| {
|
||||
stored = true;
|
||||
false
|
||||
});
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.spill_visits += _seen;
|
||||
}
|
||||
if !arrays.is_empty() || stored {
|
||||
if self.range_has_spill(sheet, range) {
|
||||
return false;
|
||||
}
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
@@ -720,6 +737,32 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
fn range_nonempty_bounds(&mut self, sheet: usize, range: RangeRef) -> Option<Option<RangeRef>> {
|
||||
if self.iterate || self.range_has_spill(sheet, range) {
|
||||
return None;
|
||||
}
|
||||
let sh = self.wb.sheet(sheet)?;
|
||||
// When fewer calculations are in play than cells to inspect, check their coordinates
|
||||
// first. A formula near the bottom of a dense range would otherwise cost two walks.
|
||||
let pass_cells = self.pending.len() + self.results.len();
|
||||
let checked_pass = (pass_cells as u64) < range.count() && pass_cells < sh.cells.len();
|
||||
if checked_pass && self.pending.iter().chain(self.results.keys()).any(|&(s, c)| s == sheet && range.contains(c)) {
|
||||
return None;
|
||||
}
|
||||
let mut bounds: Option<RangeRef> = None;
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
// With no pending or computed results in the block, formula and Python readers
|
||||
// see the stored values as well. Otherwise leave their evaluation to range_values.
|
||||
if !checked_pass && (cell.formula.is_some() || cell.py.is_some()) {
|
||||
return None;
|
||||
}
|
||||
if !cell.value.is_empty() {
|
||||
let cell_range = RangeRef::cell(c);
|
||||
bounds = Some(bounds.map_or(cell_range, |b| b.union(&cell_range)));
|
||||
}
|
||||
}
|
||||
Some(bounds)
|
||||
}
|
||||
fn range_sum(&mut self, sheet: usize, range: RangeRef) -> Option<(f64, u64)> {
|
||||
// Constants can't change during a pass, so a block's result stays valid for it. Spills
|
||||
// found in this pass (and iteration, which tracks what a read depends on) go the long way.
|
||||
|
||||
@@ -810,6 +810,7 @@ fn arrays_do_not_spill_in_tables() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
t.set("C4", "=SEQUENCE(2)");
|
||||
t.set("E1", "=SEQUENCE(4)");
|
||||
@@ -839,6 +840,7 @@ fn one_value_array_in_a_table_is_not_a_spill() {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
};
|
||||
let mut t = T::new();
|
||||
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
|
||||
@@ -1569,6 +1571,7 @@ fn subtotal_skips_filtered_rows() {
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
}],
|
||||
style: String::new(),
|
||||
@@ -1580,6 +1583,7 @@ fn subtotal_skips_filtered_rows() {
|
||||
filter: crit(),
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
|
||||
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
|
||||
@@ -2497,6 +2501,21 @@ fn blank_lookup_values_match_excel_windows_observation() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_blank_lookup_argument_is_numeric_zero() {
|
||||
// #4044: `XMATCH(, array)` writes a blank argument, which Excel reads as numeric zero. Only a
|
||||
// reference to a blank cell (B1 here) is a blank lookup value.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=XMATCH(,{0,1,3})");
|
||||
t.set("A2", "=XMATCH(B1,{0,1,3})");
|
||||
t.set("A3", "=XLOOKUP(,{0,1,3},{10,20,30})");
|
||||
t.set("A4", "=XLOOKUP(B1,{0,1,3},{10,20,30},\"none\")");
|
||||
assert_eq!(t.get("A1"), Value::Number(1.0));
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::NA));
|
||||
assert_eq!(t.get("A3"), Value::Number(10.0));
|
||||
assert_eq!(t.get("A4"), Value::from("none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_width_is_the_column_width_dialog_value_rounded() {
|
||||
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
|
||||
|
||||
@@ -95,8 +95,15 @@ impl Evaluator<'_> {
|
||||
if (h as u64) * (w as u64) > MAX_CELLS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
|
||||
let ((r0, r1), (c0, c1)) = if let Some(nonempty) = self.host.range_nonempty_bounds(a.sheet, part) {
|
||||
let nonempty = nonempty.ok_or(CellError::Calc)?;
|
||||
let row = |c: CellRef| (c.row - part.start.row) as usize;
|
||||
let col = |c: CellRef| (c.col - part.start.col) as usize;
|
||||
((row(nonempty.start), row(nonempty.end)), (col(nonempty.start), col(nonempty.end)))
|
||||
} else {
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
bounds(&values, w).ok_or(CellError::Calc)?
|
||||
};
|
||||
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
|
||||
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
|
||||
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
|
||||
|
||||
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use axis::{Scale, format_number, nice_scale};
|
||||
pub use raster::rasterize;
|
||||
pub use render::{Swatch, legend_entries, render, supports_trendline};
|
||||
pub use render::{ChartLabels, Swatch, legend_entries, legend_entries_with, render, render_with_labels, supports_trendline};
|
||||
pub use resolve::{default_palette, has_volatile_series, resolve, series_color};
|
||||
pub use sparkline::render_sparkline;
|
||||
|
||||
|
||||
@@ -20,9 +20,9 @@ mod trend;
|
||||
|
||||
use cartesian::{cartesian, scatter};
|
||||
use frame::{Bx, axis_titles, chart_title};
|
||||
use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall};
|
||||
use kinds::{box_whisker, doughnut, funnel, histogram, pareto, pie, radar, stock, treemap, waterfall};
|
||||
use legend::draw_legend;
|
||||
pub use legend::{Swatch, legend_entries};
|
||||
pub use legend::{ChartLabels, Swatch, legend_entries, legend_entries_with};
|
||||
pub use trend::supports_trendline;
|
||||
|
||||
pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF];
|
||||
@@ -40,9 +40,9 @@ const AXIS_TITLE_SIZE: f32 = 10.0;
|
||||
/// Most categories drawn by category-axis charts.
|
||||
const MAX_CATS: usize = 20_000;
|
||||
/// Lines with more points than this are decimated (min/max per pixel column).
|
||||
const MAX_LINE_PTS: usize = 2000;
|
||||
pub(crate) const MAX_LINE_PTS: usize = 2000;
|
||||
/// Most markers per series (after de-duplicating by pixel).
|
||||
const MAX_MARKERS: usize = 5000;
|
||||
pub(crate) const MAX_MARKERS: usize = 5000;
|
||||
/// Data labels are skipped when a series has more points than this.
|
||||
const MAX_LABELS: usize = 200;
|
||||
/// Columns and bars narrower than this (in pixels) are merged per pixel column into one rectangle.
|
||||
@@ -217,6 +217,11 @@ pub(crate) fn sanitized(d: &ChartData) -> Cow<'_, ChartData> {
|
||||
|
||||
/// Lays out and draws a chart into a `w`×`h` box at the origin. Empty for a degenerate box.
|
||||
pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure) -> Vec<Prim> {
|
||||
render_with_labels(chart, data, w, h, m, &ChartLabels::default())
|
||||
}
|
||||
|
||||
/// [`render`] with interface strings supplied by the UI.
|
||||
pub fn render_with_labels(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure, labels: &ChartLabels<'_>) -> Vec<Prim> {
|
||||
if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e7 || h > 1e7 {
|
||||
return vec![];
|
||||
}
|
||||
@@ -233,7 +238,7 @@ pub fn render(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &dyn Measure)
|
||||
area.y += used;
|
||||
area.h -= used;
|
||||
}
|
||||
let entries = legend_entries(chart, &data);
|
||||
let entries = legend_entries_with(chart, &data, labels);
|
||||
if !entries.is_empty() && area.ok() {
|
||||
area = draw_legend(&mut ctx, &entries, chart.legend, area);
|
||||
}
|
||||
@@ -261,6 +266,7 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
BarClustered | BarStacked | BarStacked100 => cartesian(ctx, chart, data, area, true),
|
||||
Scatter | ScatterLines | Bubble => scatter(ctx, chart, data, area),
|
||||
Histogram => histogram(ctx, chart, data, area),
|
||||
Pareto => pareto(ctx, chart, data, area),
|
||||
Waterfall => waterfall(ctx, chart, data, area),
|
||||
BoxWhisker => box_whisker(ctx, chart, data, area),
|
||||
Stock => stock(ctx, chart, data, area),
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range};
|
||||
use super::legend::{cat_label, point_color};
|
||||
use super::legend::{cat_label, pareto_line_color, point_color};
|
||||
use super::lines::decimate;
|
||||
use super::{
|
||||
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
|
||||
QuartileMethod, Rgba, STOCK, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
|
||||
AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_LINE_PTS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim,
|
||||
QuartileMethod, Rgba, STOCK, Scale, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- histogram
|
||||
|
||||
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let Some((lo, hi)) = value_range(vals.iter().copied()) else { return };
|
||||
/// Histogram bins for `vals`: right-inclusive labels and counts, as Excel's histogram and the
|
||||
/// numeric-only form of a Pareto chart use.
|
||||
fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
|
||||
let (lo, hi) = value_range(vals.iter().copied())?;
|
||||
let n = vals.len();
|
||||
let span = hi - lo;
|
||||
let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100);
|
||||
@@ -22,13 +25,12 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
// equal to an edge belongs to the bin that ends there.
|
||||
let edges: Vec<f64> = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect();
|
||||
let mut counts = vec![0usize; bins];
|
||||
for v in &vals {
|
||||
for v in vals {
|
||||
let b = edges.partition_point(|e| e < v).min(bins - 1);
|
||||
if let Some(c) = counts.get_mut(b) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let f = Fmt::new(&s.number_format);
|
||||
let labels: Vec<String> = (0..bins)
|
||||
.map(|b| {
|
||||
let a = lo + b as f64 * width;
|
||||
@@ -37,6 +39,15 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0)))
|
||||
})
|
||||
.collect();
|
||||
Some((labels, counts))
|
||||
}
|
||||
|
||||
pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let vals: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let f = Fmt::new(&s.number_format);
|
||||
let Some((labels, counts)) = histogram_bins(&vals, &f) else { return };
|
||||
let bins = counts.len();
|
||||
let maxc = counts.iter().copied().max().unwrap_or(0) as f64;
|
||||
let ys = nice_scale(0.0, maxc, true);
|
||||
let fc = Fmt::new("General");
|
||||
@@ -55,6 +66,111 @@ pub(super) fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pareto
|
||||
|
||||
/// Sorted columns and a cumulative-percentage line on a secondary 0–100% axis.
|
||||
pub(super) fn pareto(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let f = Fmt::new(&s.number_format);
|
||||
// With no category range Excel charts a Pareto's numbers in histogram bins (the Pareto page:
|
||||
// "If you select two columns of numbers ... Excel charts your data in bins").
|
||||
let binned = chart.series.first().is_some_and(|x| x.categories.is_none());
|
||||
let (labels, vals): (Vec<String>, Vec<f64>) = if binned {
|
||||
let raw: Vec<f64> = s.values.iter().flatten().copied().collect();
|
||||
let Some((labels, counts)) = histogram_bins(&raw, &f) else { return };
|
||||
let mut items: Vec<(String, f64)> = labels.into_iter().zip(counts.into_iter().map(|c| c as f64)).collect();
|
||||
items.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
items.into_iter().unzip()
|
||||
} else {
|
||||
let n = data.categories.len().max(s.values.len()).min(MAX_CATS);
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
// Excel groups equal categories and sums their values before sorting (the Pareto doc's
|
||||
// "groups the same categories and sums the corresponding numbers").
|
||||
let mut groups: Vec<(String, f64)> = Vec::new();
|
||||
let mut index: HashMap<String, usize> = HashMap::new();
|
||||
for j in 0..n {
|
||||
let label = cat_label(data, j);
|
||||
let v = s.values.get(j).copied().flatten().unwrap_or(0.0);
|
||||
match index.get(&label) {
|
||||
Some(&i) => {
|
||||
if let Some(g) = groups.get_mut(i) {
|
||||
g.1 += v;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
index.insert(label.clone(), groups.len());
|
||||
groups.push((label, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Largest first; a stable sort keeps first-appearance order for equal sums.
|
||||
groups.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
(groups.iter().map(|(l, _)| l.clone()).collect(), groups.iter().map(|(_, v)| *v).collect())
|
||||
};
|
||||
let n = labels.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let hi = vals.iter().copied().fold(0.0f64, f64::max);
|
||||
let lo = vals.iter().copied().fold(0.0f64, f64::min);
|
||||
let ys = nice_scale(lo, hi, true);
|
||||
let pct = Fmt::new("0%");
|
||||
let value_fmt = if binned { Fmt::new("General") } else { Fmt::new(&s.number_format) };
|
||||
// A cumulative percentage axis is fixed at 0–100%: Excel shows it that way, and the line
|
||||
// below maps each cumulative share straight onto the plot height.
|
||||
let ys2 = Scale { min: 0.0, max: 1.0, step: 0.2 };
|
||||
let plot = frame(
|
||||
ctx,
|
||||
area,
|
||||
CatAxis::Labels(&labels, &[]),
|
||||
&ValAxis { scale: ys, fmt: &value_fmt },
|
||||
Some(&ValAxis { scale: ys2, fmt: &pct }),
|
||||
false,
|
||||
chart.gridlines,
|
||||
);
|
||||
if !plot.ok() {
|
||||
return;
|
||||
}
|
||||
let total: f64 = vals.iter().copied().sum();
|
||||
// A cumulative percentage is only meaningful when every category is nonnegative. The binned
|
||||
// path counts values, so its counts always are.
|
||||
let cumulative = total.is_finite() && total != 0.0 && (binned || vals.iter().all(|v| *v >= 0.0));
|
||||
let cw = plot.w / n as f32;
|
||||
let bw = (cw * 0.72).clamp(1.0, 120.0);
|
||||
let y0 = plot.bottom() - ys.frac(0.0) * plot.h;
|
||||
let mut pts = Vec::with_capacity(n);
|
||||
let mut cum = 0.0;
|
||||
for (j, v) in vals.iter().enumerate() {
|
||||
let x = plot.x + (j as f32 + 0.5) * cw;
|
||||
let yv = plot.bottom() - ys.frac(*v) * plot.h;
|
||||
ctx.rect(x - bw / 2.0, yv.min(y0), bw, (y0 - yv).abs().max(0.5), s.color, None);
|
||||
if chart.data_labels && n <= MAX_LABELS {
|
||||
let t = value_fmt.format(*v, None);
|
||||
if *v >= 0.0 {
|
||||
ctx.text(x, yv.min(y0) - 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom));
|
||||
} else {
|
||||
ctx.text(x, yv.max(y0) + 2.0, &t, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Top));
|
||||
}
|
||||
}
|
||||
if cumulative {
|
||||
cum += *v;
|
||||
let frac = (cum / total).clamp(0.0, 1.0) as f32;
|
||||
pts.push([x, plot.bottom() - frac * plot.h]);
|
||||
}
|
||||
}
|
||||
if pts.len() >= 2 {
|
||||
let color = pareto_line_color(data);
|
||||
// Keep the line and markers bounded on category-heavy charts, as the other renderers do.
|
||||
let markers: Vec<[f32; 2]> = if cw >= 3.0 { pts.iter().take(MAX_MARKERS).copied().collect() } else { Vec::new() };
|
||||
ctx.line(decimate(pts, MAX_LINE_PTS), color, 1.5);
|
||||
for p in markers {
|
||||
ctx.out.push(Prim::Circle { cx: p[0], cy: p[1], r: 2.0, fill: Some(color), stroke: Some((WHITE, 0.75)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- waterfall
|
||||
|
||||
pub(super) fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
|
||||
@@ -31,8 +31,32 @@ pub(super) fn cat_label(data: &ChartData, j: usize) -> String {
|
||||
data.categories.get(j).cloned().unwrap_or_else(|| (j + 1).to_string())
|
||||
}
|
||||
|
||||
/// The cumulative line's colour: the second palette colour, so it stands apart from the bars.
|
||||
pub(super) fn pareto_line_color(data: &ChartData) -> Rgba {
|
||||
data.palette.get(1).copied().or_else(|| data.series.first().map(|_| series_color(&Theme::default(), 1))).unwrap_or(TEXT)
|
||||
}
|
||||
|
||||
/// Interface strings a chart legend can need. The UI passes translated text; the default is
|
||||
/// English for callers without an interface language (PDF export, tests).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ChartLabels<'a> {
|
||||
/// Legend name of a Pareto chart's cumulative line.
|
||||
pub cumulative: &'a str,
|
||||
}
|
||||
|
||||
impl Default for ChartLabels<'_> {
|
||||
fn default() -> Self {
|
||||
Self { cumulative: "Cumulative %" }
|
||||
}
|
||||
}
|
||||
|
||||
/// Legend entries (text, colour, swatch) `render` draws for this chart; empty when hidden.
|
||||
pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swatch)> {
|
||||
legend_entries_with(chart, data, &ChartLabels::default())
|
||||
}
|
||||
|
||||
/// [`legend_entries`] with interface strings supplied by the UI.
|
||||
pub fn legend_entries_with(chart: &Chart, data: &ChartData, labels: &ChartLabels<'_>) -> Vec<(String, Rgba, Swatch)> {
|
||||
if chart.legend == LegendPos::None {
|
||||
return vec![];
|
||||
}
|
||||
@@ -44,6 +68,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
|
||||
(0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect()
|
||||
}
|
||||
ChartKind::Histogram | ChartKind::Funnel | ChartKind::Stock => vec![],
|
||||
ChartKind::Pareto => match data.series.first() {
|
||||
Some(s) => vec![(s.name.clone(), s.color, Swatch::Box), (labels.cumulative.to_string(), pareto_line_color(data), Swatch::Line)],
|
||||
None => vec![],
|
||||
},
|
||||
ChartKind::Waterfall => {
|
||||
if data.series.is_empty() {
|
||||
return vec![];
|
||||
|
||||
+196
-1
@@ -3,12 +3,13 @@ use std::sync::Arc;
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, SparklineKind, Style, Workbook};
|
||||
|
||||
use crate::render::MAX_MARKERS;
|
||||
use crate::*;
|
||||
|
||||
mod budget;
|
||||
mod data_table;
|
||||
|
||||
const ALL_KINDS: [ChartKind; 28] = [
|
||||
const ALL_KINDS: [ChartKind; 29] = [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
@@ -30,6 +31,7 @@ const ALL_KINDS: [ChartKind; 28] = [
|
||||
ChartKind::Bubble,
|
||||
ChartKind::Radar,
|
||||
ChartKind::Histogram,
|
||||
ChartKind::Pareto,
|
||||
ChartKind::Waterfall,
|
||||
ChartKind::Funnel,
|
||||
ChartKind::Treemap,
|
||||
@@ -154,6 +156,198 @@ fn every_kind_renders_sanely() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_sorts_categories_and_draws_the_cumulative_line() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
// A appears twice: Excel groups equal categories and sums them (A = 15).
|
||||
let cats = ["A", "B", "A", "C"];
|
||||
let vals = [10.0, 40.0, 5.0, 20.0];
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats.iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
let x_of = |label: &str| {
|
||||
prims.iter().find_map(|p| match p {
|
||||
Prim::Text { x, text, .. } if text == label => Some(*x),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let (a, b, cc) = (x_of("A").unwrap(), x_of("B").unwrap(), x_of("C").unwrap());
|
||||
assert!(b < cc && cc < a, "grouped and sorted largest first: B C A");
|
||||
// Three cumulative markers and the line itself.
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3);
|
||||
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
|
||||
let t = texts(&prims);
|
||||
assert!(t.contains(&"100%"), "right percentage axis labels: {t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_secondary_axis_is_fixed_at_100_percent() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let cats = ["A", "B", "C", "D", "E"];
|
||||
let vals = [50.0, 20.0, 10.0, 5.0, 15.0];
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats.iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
// The secondary axis runs 0–100%, so the cumulative line can use the plot's full height.
|
||||
let mut ticks: Vec<(f32, &str)> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Text { y, text, .. } if text.ends_with('%') => Some((*y, text.as_str())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
ticks.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let labels: Vec<&str> = ticks.iter().map(|(_, t)| *t).collect();
|
||||
// Top of the plot first: 100% down to 0%, with no 120% headroom.
|
||||
assert_eq!(labels, ["100%", "80%", "60%", "40%", "20%", "0%"], "fixed 0–100% axis with a 20% step");
|
||||
// Evenly spaced: 0.2 of the scale per step.
|
||||
let first = ticks.first().map(|(y, _)| *y).unwrap_or_default();
|
||||
let last = ticks.last().map(|(y, _)| *y).unwrap_or_default();
|
||||
let step = (last - first) / 5.0;
|
||||
for (i, (y, label)) in ticks.iter().enumerate() {
|
||||
assert!((first + step * i as f32 - y).abs() < 0.5, "{label} sits on its 0.2 step: {ticks:?}");
|
||||
}
|
||||
// The cumulative line's last point (100%) lands on the 100% tick, and A's 50% midway.
|
||||
let line = prims
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Line { pts, .. } if pts.len() == 5 => Some(pts.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("cumulative line");
|
||||
let top = first;
|
||||
let mid = (first + last) / 2.0;
|
||||
assert!((line[4][1] - top).abs() < 0.01, "line top {} on the 100% tick {top}", line[4][1]);
|
||||
assert!((line[0][1] - mid).abs() < 0.01, "A's 50% {} halfway up the axis ({mid})", line[0][1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_bins_numbers_when_there_is_no_category_range() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
c.series.push(Series { name: Some("Values".into()), values: "Data!$A$1:$A$6".into(), ..Default::default() });
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: vec![],
|
||||
series: vec![series("Values", &[1.0, 1.0, 1.0, 2.0, 2.0, 3.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 3, "three bins");
|
||||
assert!(prims.iter().any(|p| matches!(p, Prim::Line { pts, .. } if pts.len() == 3)), "cumulative line");
|
||||
let t = texts(&prims);
|
||||
assert!(t.iter().any(|s| s.starts_with('[') && s.contains(", ")), "bin labels: {t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_skips_cumulative_line_for_signed_categories() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: vec!["A".into(), "B".into()],
|
||||
series: vec![series("Count", &[10.0, -5.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
// A negative category makes the cumulative percentage meaningless, so no line or markers.
|
||||
// The cumulative line is the only 1.5 px polyline a Pareto draws (bars are rects, axes 0.75).
|
||||
let line = |prims: &[Prim]| prims.iter().any(|p| matches!(p, Prim::Line { pts, width, .. } if *width == 1.5 && pts.len() >= 2));
|
||||
assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
|
||||
assert!(!line(&prims), "signed categories draw no cumulative line");
|
||||
// The same chart with nonnegative values does draw it, so the check above can fail.
|
||||
let d = ChartData { series: vec![series("Count", &[10.0, 5.0], [20, 96, 130, 255], ChartKind::Pareto)], ..d };
|
||||
assert!(line(&render(&c, &d, 640.0, 400.0, &ApproxMeasure)), "nonnegative categories draw the cumulative line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_caps_cumulative_line_and_markers() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.title = None;
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.gridlines = false;
|
||||
let n = MAX_MARKERS + 1000;
|
||||
let cats: Vec<String> = (0..n).map(|i| format!("C{i}")).collect();
|
||||
let vals: Vec<f64> = (0..n).map(|i| (i % 7 + 1) as f64).collect();
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: cats,
|
||||
series: vec![series("Count", &vals, [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
// Wide enough for markers: they stop at MAX_MARKERS.
|
||||
let wide = render(&c, &d, 30_000.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(wide.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), MAX_MARKERS);
|
||||
// Narrow columns carry no marker information; the line is decimated instead.
|
||||
let narrow = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
assert_eq!(narrow.iter().filter(|p| matches!(p, Prim::Circle { r, .. } if *r == 2.0)).count(), 0);
|
||||
let longest = narrow.iter().filter_map(|p| match p {
|
||||
Prim::Line { pts, .. } if pts.len() > 2 => Some(pts.len()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(longest.max().unwrap_or(0) < n, "the cumulative line is decimated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_legend_uses_the_supplied_label() {
|
||||
let mut c = chart(ChartKind::Pareto);
|
||||
c.legend = LegendPos::Bottom;
|
||||
let d = sample(ChartKind::Pareto);
|
||||
let entries = legend_entries_with(&c, &d, &ChartLabels { cumulative: "Kumuliert %" });
|
||||
assert!(entries.iter().any(|(name, _, sw)| name == "Kumuliert %" && *sw == Swatch::Line), "{entries:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_line_falls_back_to_the_second_theme_accent() {
|
||||
let c = chart(ChartKind::Pareto);
|
||||
// A resolved short palette (one series) has no second colour: the line must still stand
|
||||
// apart from the bars instead of reusing the first series colour.
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("Count", &[4.0, 3.0, 2.0, 1.0], [20, 96, 130, 255], ChartKind::Pareto)],
|
||||
};
|
||||
let accent = series_color(&gridcraft_model::Theme::default(), 1);
|
||||
assert_ne!(accent, d.series[0].color);
|
||||
let entries = legend_entries(&c, &d);
|
||||
assert_eq!(entries.get(1).map(|e| e.1), Some(accent), "the legend swatch matches the line");
|
||||
let lines: Vec<Rgba> = render(&c, &d, 640.0, 400.0, &ApproxMeasure)
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Line { color, width, .. } if *width == 1.5 => Some(*color),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(lines.contains(&accent), "{lines:?}");
|
||||
// A second palette colour still takes precedence.
|
||||
let d = ChartData { palette: vec![[1, 2, 3, 255], [9, 8, 7, 255]], ..d };
|
||||
assert_eq!(legend_entries(&c, &d).get(1).map(|e| e.1), Some([9, 8, 7, 255]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doughnut_draws_each_series_as_a_ring() {
|
||||
let mut c = chart(ChartKind::Doughnut);
|
||||
@@ -472,6 +666,7 @@ fn legend_counts() {
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Pie), &d).len(), 6);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Waterfall), &d).len(), 3);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Histogram), &d).len(), 0);
|
||||
assert_eq!(legend_entries(&chart(ChartKind::Pareto), &d).len(), 2);
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.legend = LegendPos::None;
|
||||
assert!(legend_entries(&c, &d).is_empty());
|
||||
|
||||
@@ -2,13 +2,32 @@
|
||||
//!
|
||||
//! Internally rows and columns are 0-based (`A1` = row 0, col 0). The sheet is 1,048,576 rows by
|
||||
//! 16,384 columns (`XFD1048576`), like Excel.
|
||||
//!
|
||||
//! # Excel's limits
|
||||
//!
|
||||
//! The constants below are Excel's documented limits (Microsoft's "Excel specifications and
|
||||
//! limits" page, the "Worksheet and workbook specifications" table). They are the size of the grid
|
||||
//! and the readers' bound of legitimate input: a file Excel wrote never exceeds them, so a part
|
||||
//! that does is malformed or crafted. The XLSX reader drops what the grid can't hold with a
|
||||
//! warning, and keeps text longer than a cell allows whole with one, since cutting it would lose
|
||||
//! data (the XLSB reader still refuses such text). Excel has raised
|
||||
//! these over the years (65,536 × 256 before Excel 2007) and may again; a new value goes here, and
|
||||
//! the places that still spell a number out (warning texts, a few function bounds) are pointed at
|
||||
//! these constants as they are touched. The old limits need no entry: a file written under them
|
||||
//! fits the current ones.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Rows in a sheet (`1048576` is the last row number).
|
||||
pub const MAX_ROWS: u32 = 1_048_576;
|
||||
/// Columns in a sheet (`XFD` is the last column).
|
||||
pub const MAX_COLS: u32 = 16_384;
|
||||
/// Characters in one cell's text, counted in UTF-16 units (a character outside the Basic
|
||||
/// Multilingual Plane counts as two). [`MAX_TEXT_CHARS`](crate::value::MAX_TEXT_CHARS), which
|
||||
/// `cap_text` and the functions use, is this value as a `usize`.
|
||||
pub const MAX_CELL_CHARS: u32 = 32_767;
|
||||
|
||||
/// A cell position (0-based).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
|
||||
|
||||
@@ -12,8 +12,8 @@ pub mod region;
|
||||
pub mod value;
|
||||
|
||||
pub use addr::{
|
||||
CategoryLevels, CellRef, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet, sheet_needs_quotes,
|
||||
split_areas, split_sheet, unquote_sheet,
|
||||
CategoryLevels, CellRef, MAX_CELL_CHARS, MAX_COLS, MAX_ROWS, RangeRef, category_levels, col_to_letters, letters_to_col, quote_sheet,
|
||||
sheet_needs_quotes, split_areas, split_sheet, unquote_sheet,
|
||||
};
|
||||
pub use date::DateSystem;
|
||||
pub use region::Region;
|
||||
|
||||
@@ -522,8 +522,9 @@ pub fn sci_text(n: f64, sig: usize) -> String {
|
||||
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
|
||||
}
|
||||
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub const MAX_TEXT_CHARS: usize = 32_767;
|
||||
/// Longest text a cell can hold, in UTF-16 code units: Excel's limit,
|
||||
/// [`MAX_CELL_CHARS`](crate::addr::MAX_CELL_CHARS), as a `usize`.
|
||||
pub const MAX_TEXT_CHARS: usize = crate::addr::MAX_CELL_CHARS as usize;
|
||||
|
||||
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
|
||||
pub fn cap_text(mut s: String) -> String {
|
||||
|
||||
@@ -326,6 +326,20 @@ impl<'a> Binder<'a> {
|
||||
return true;
|
||||
}
|
||||
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
|
||||
// `DATEADD`'s, `DATESINPERIOD`'s and `PARALLELPERIOD`'s interval is catalogued as
|
||||
// `Text` but is a documented enumeration, so neither a variable nor a model table
|
||||
// or measure named `MONTH` may replace the written keyword: `DATEADD(d, 1, MONTH)`,
|
||||
// `DATESINPERIOD(d, s, -1, MONTH)` and `PARALLELPERIOD(d, -1, MONTH)` shift by the
|
||||
// written interval. `WEEK` and `DAY` are not every function's interval vocabulary.
|
||||
let interval_keyword = match (spec.name, index) {
|
||||
("DATEADD", 2) => ["DAY", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
("DATESINPERIOD", 3) => ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
("PARALLELPERIOD", 2) => ["MONTH", "QUARTER", "YEAR"].iter().any(|interval| keyword.eq_ignore_ascii_case(interval)),
|
||||
_ => false,
|
||||
};
|
||||
if interval_keyword {
|
||||
return true;
|
||||
}
|
||||
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
|
||||
!named && !variable
|
||||
});
|
||||
|
||||
@@ -39,19 +39,19 @@ mod support;
|
||||
// marker line in both lists, in `ALL_FAMILIES` order, so a family branch replaces exactly its own
|
||||
// line instead of inserting at a shared anchor and conflicting with its siblings.
|
||||
mod aggregation;
|
||||
// date_time
|
||||
mod date_time;
|
||||
// filter
|
||||
// financial
|
||||
mod information;
|
||||
mod logical;
|
||||
// math_trig
|
||||
mod math_trig;
|
||||
mod model_info;
|
||||
// other
|
||||
// parent_child
|
||||
// statistical
|
||||
// table_manipulation
|
||||
// text
|
||||
// time_intelligence
|
||||
mod time_intelligence;
|
||||
// visual
|
||||
|
||||
use std::cmp::Ordering;
|
||||
@@ -108,19 +108,19 @@ pub const ALL_FAMILIES: &[&str] = &[
|
||||
/// own marker line below with its `Family` entry.
|
||||
const FAMILIES: &[Family] = &[
|
||||
Family { name: "aggregation", scalar: aggregation::call, table: aggregation::call_table },
|
||||
// date_time
|
||||
Family { name: "date_time", scalar: date_time::call, table: date_time::call_table },
|
||||
// filter
|
||||
// financial
|
||||
Family { name: "information", scalar: information::call, table: information::call_table },
|
||||
Family { name: "logical", scalar: logical::call, table: logical::call_table },
|
||||
// math_trig
|
||||
Family { name: "math_trig", scalar: math_trig::call, table: math_trig::call_table },
|
||||
Family { name: "model_info", scalar: model_info::call, table: model_info::call_table },
|
||||
// other
|
||||
// parent_child
|
||||
// statistical
|
||||
// table_manipulation
|
||||
// text
|
||||
// time_intelligence
|
||||
Family { name: "time_intelligence", scalar: time_intelligence::call, table: time_intelligence::call_table },
|
||||
// visual
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
//! Date and time functions.
|
||||
//!
|
||||
//! Dates are OLE/Excel serials (`Scalar::DateTime`), the same values Excel stores: whole days
|
||||
//! since 1899-12-30 plus a fraction for the time of day. The scalar functions follow Excel's
|
||||
//! documented results (`WEEKNUM` return types, `YEARFRAC` day-count bases, `NETWORKDAYS` weekend
|
||||
//! codes), and the table functions build date tables from literal bounds or from the model's
|
||||
//! DateTime columns.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::time_intelligence::is_date_type;
|
||||
use super::*;
|
||||
|
||||
/// Last serial Excel/DAX accepts as a date: 9999-12-31.
|
||||
const MAX_DATE_SERIAL: f64 = 2_958_465.0;
|
||||
|
||||
/// Hard ceiling for date tables built row-by-row by `CALENDAR`/`CALENDARAUTO`. It mirrors the
|
||||
/// `MAX_GENERATED_ROWS` limit in `eval::table_manipulation` (which is private to that module),
|
||||
/// so a pathological date span fails like every other oversized generated table instead of
|
||||
/// exhausting memory.
|
||||
const MAX_GENERATED_ROWS: i64 = 1_000_000;
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let upper = name.to_ascii_uppercase();
|
||||
let result = match upper.as_str() {
|
||||
"DATEDIFF" => datediff(ev, args, ctx),
|
||||
"DATEVALUE" => datevalue(ev, args, ctx),
|
||||
"TIME" => time(ev, args, ctx),
|
||||
"WEEKDAY" => weekday(ev, args, ctx),
|
||||
"NETWORKDAYS" => networkdays(ev, args, ctx),
|
||||
"NOW" => now(),
|
||||
"QUARTER" => quarter(ev, args, ctx),
|
||||
"TIMEVALUE" => timevalue(ev, args, ctx),
|
||||
"TODAY" => today(),
|
||||
"UTCNOW" => utc_now(),
|
||||
"UTCTODAY" => utc_today(),
|
||||
"WEEKNUM" => weeknum(ev, args, ctx),
|
||||
"YEARFRAC" => yearfrac(ev, args, ctx),
|
||||
// Table functions only make sense where a table is expected. Returning an explanatory
|
||||
// error beats reporting them as unimplemented when they appear in a scalar context.
|
||||
"CALENDAR" | "CALENDARAUTO" => Err(EvalError::new(format!("{upper} returns a table, not a scalar value"))),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
let upper = name.to_ascii_uppercase();
|
||||
let result = match upper.as_str() {
|
||||
"CALENDAR" => calendar(ev, args, ctx),
|
||||
"CALENDARAUTO" => calendar_auto(ev, args, ctx),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Argument coercion
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Coerces a scalar to a date serial. BLANK is 0 like every other DAX numeric coercion, text is
|
||||
/// read with the shared date/time parser first (so `DATEDIFF` keeps the time of day a text
|
||||
/// argument carries) and with `DATEVALUE`'s whole-day forms only for the shapes that parser
|
||||
/// rejects, and numbers are already serials.
|
||||
fn coerce_date(value: &Scalar) -> Option<f64> {
|
||||
match value {
|
||||
Scalar::Blank => Some(0.0),
|
||||
Scalar::String(text) => support::parse_date_text(text)
|
||||
.or_else(|| parse_date_serial(text))
|
||||
.or_else(|| text.trim().parse::<f64>().ok().filter(|serial| serial.is_finite())),
|
||||
other => other.to_number().filter(|serial| serial.is_finite()),
|
||||
}
|
||||
}
|
||||
|
||||
fn date_arg(name: &str, values: &[Scalar], index: usize) -> Result<f64, EvalError> {
|
||||
let value = values.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let serial = coerce_date(value).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))?;
|
||||
// Validating the range bounds every date loop (NETWORKDAYS, YEARFRAC) by the calendar.
|
||||
if !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
|
||||
return Err(EvalError::new(format!("{name} argument {} is outside the supported date range", index + 1)));
|
||||
}
|
||||
Ok(serial)
|
||||
}
|
||||
|
||||
fn optional_int(name: &str, values: &[Scalar], index: usize, default: i64) -> Result<i64, EvalError> {
|
||||
match values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
|
||||
Ok(number as i64)
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text parsing
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Splits `DATE[ T]TIME` text at the first `T` or space. A string without a separator is all
|
||||
/// date (or all time); the caller decides which.
|
||||
fn split_date_time(text: &str) -> (&str, Option<&str>) {
|
||||
match text.split_once(['T', ' ']) {
|
||||
Some((date, time)) => (date.trim(), Some(time.trim())),
|
||||
None => (text.trim(), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the date forms `DATEVALUE` accepts on a US-locale client: `YYYY-MM-DD`, `YYYY/MM/DD`,
|
||||
/// `MM/DD/YYYY` (two-digit years add 2000 below 30 and 1900 otherwise) and the same dates with a
|
||||
/// trailing time. Returns whole-day serials; the time of day is ignored.
|
||||
fn parse_date_serial(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date_part, _) = split_date_time(text);
|
||||
let parts: Vec<&str> = date_part.split(['-', '/']).filter(|part| !part.is_empty()).collect();
|
||||
if parts.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
let numbers: Option<Vec<i64>> = parts.iter().map(|part| part.parse::<i64>().ok()).collect();
|
||||
let numbers = numbers?;
|
||||
let leading_year = parts[0].len() >= 4 && parts[0].chars().all(|c| c.is_ascii_digit());
|
||||
if leading_year {
|
||||
// ISO order. The shared parser already knows this shape; re-reading the parts rejects
|
||||
// impossible dates (2024-02-30) that its serial rollover would silently accept.
|
||||
let serial = support::parse_date_text(date_part)?;
|
||||
if support::date_parts(serial) != (numbers[0], numbers[1], numbers[2]) || !(0.0..=MAX_DATE_SERIAL).contains(&serial) {
|
||||
return None;
|
||||
}
|
||||
return Some(serial.floor());
|
||||
}
|
||||
// Month-first order, the default of the documented en-US client.
|
||||
let (mut year, month, day) = (numbers[2], numbers[0], numbers[1]);
|
||||
if year < 100 {
|
||||
year += if year < 30 { 2000 } else { 1900 };
|
||||
}
|
||||
if !(1..=12).contains(&month) || day < 1 || day > support::days_in_month(year, month) {
|
||||
return None;
|
||||
}
|
||||
let serial = support::date_serial(year, month, day, 0, 0, 0);
|
||||
(0.0..=MAX_DATE_SERIAL).contains(&serial).then_some(serial)
|
||||
}
|
||||
|
||||
/// Parses a clock time into a day fraction: `HH:MM`, `HH:MM:SS`, fractional seconds optional, and
|
||||
/// an `AM`/`PM` suffix on a 12-hour clock.
|
||||
fn parse_clock(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let upper = text.to_ascii_uppercase();
|
||||
let (clock, meridiem) = if let Some(rest) = upper.strip_suffix("PM") {
|
||||
(rest.trim(), Some(true))
|
||||
} else if let Some(rest) = upper.strip_suffix("AM") {
|
||||
(rest.trim(), Some(false))
|
||||
} else {
|
||||
(text, None)
|
||||
};
|
||||
let parts: Vec<&str> = clock.split(':').collect();
|
||||
if parts.len() < 2 || parts.len() > 3 {
|
||||
return None;
|
||||
}
|
||||
let hour: i64 = parts[0].trim().parse().ok()?;
|
||||
let minute: i64 = parts[1].trim().parse().ok()?;
|
||||
let second: f64 = match parts.get(2) {
|
||||
Some(part) => part.trim().parse().ok()?,
|
||||
None => 0.0,
|
||||
};
|
||||
if !(0..=59).contains(&minute) || !(0.0..60.0).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
let hour = match meridiem {
|
||||
Some(pm) => {
|
||||
if !(1..=12).contains(&hour) {
|
||||
return None;
|
||||
}
|
||||
match (hour, pm) {
|
||||
(12, true) => 12,
|
||||
(12, false) => 0,
|
||||
(hour, true) => hour + 12,
|
||||
(hour, false) => hour,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !(0..=23).contains(&hour) {
|
||||
return None;
|
||||
}
|
||||
hour
|
||||
}
|
||||
};
|
||||
Some((hour as f64 * 3600.0 + minute as f64 * 60.0 + second) / 86_400.0)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Scalars
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `DATEVALUE ( <DateText> )` — the date part of a text date as a whole-day serial.
|
||||
fn datevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let value = values.first().ok_or_else(|| EvalError::new("DATEVALUE is missing argument 1"))?;
|
||||
if let Scalar::DateTime(serial) = value {
|
||||
return Ok(Scalar::DateTime(serial.floor()));
|
||||
}
|
||||
let text = value.to_text();
|
||||
let serial = parse_date_serial(&text).ok_or_else(|| EvalError::new(format!("DATEVALUE cannot convert `{text}` to a date")))?;
|
||||
Ok(Scalar::DateTime(serial))
|
||||
}
|
||||
|
||||
/// `DATEDIFF ( <Date1>, <Date2>, <Interval> )`: the number of interval boundaries crossed between
|
||||
/// the two dates, positively when Date2 is later. `Interval` is a keyword (the binder keeps it as
|
||||
/// a keyword expression, which evaluates to its text).
|
||||
fn datediff(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("DATEDIFF", &values, 0)?;
|
||||
let end = date_arg("DATEDIFF", &values, 1)?;
|
||||
let interval = values.get(2).ok_or_else(|| EvalError::new("DATEDIFF is missing argument 3"))?.to_text();
|
||||
let (start_year, start_month, _) = support::date_parts(start);
|
||||
let (end_year, end_month, _) = support::date_parts(end);
|
||||
// Sub-day intervals count boundaries, not elapsed time: floor each serial to the unit and
|
||||
// subtract, so `10:59:59` to `11:00:01` is one HOUR even though only two seconds passed.
|
||||
// Snap to whole seconds first: serial construction can land a hair below an exact second,
|
||||
// and flooring that would count one boundary too few.
|
||||
let boundaries = |serial: f64, per_day: f64| {
|
||||
let seconds = (serial * 86_400.0).round();
|
||||
(seconds / (86_400.0 / per_day)).floor()
|
||||
};
|
||||
// A week starts on Sunday; serial 1 (1900-01-01) is Excel's first Sunday, so week 0 starts
|
||||
// there and every seven days is another boundary.
|
||||
let week = |serial: f64| (serial.floor() - 1.0).div_euclid(7.0);
|
||||
let count = match interval.trim().to_ascii_uppercase().as_str() {
|
||||
"SECOND" => boundaries(end, 86_400.0) - boundaries(start, 86_400.0),
|
||||
"MINUTE" => boundaries(end, 1_440.0) - boundaries(start, 1_440.0),
|
||||
"HOUR" => boundaries(end, 24.0) - boundaries(start, 24.0),
|
||||
"DAY" => end.floor() - start.floor(),
|
||||
"WEEK" => week(end) - week(start),
|
||||
"MONTH" => ((end_year - start_year) * 12 + (end_month - start_month)) as f64,
|
||||
"QUARTER" => ((end_year - start_year) * 4 + (end_month - 1) / 3 - (start_month - 1) / 3) as f64,
|
||||
"YEAR" => (end_year - start_year) as f64,
|
||||
other => {
|
||||
return Err(EvalError::new(format!("DATEDIFF interval `{other}` must be SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR")));
|
||||
}
|
||||
};
|
||||
if !count.is_finite() || count.abs() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("DATEDIFF result is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(Scalar::Integer(count as i64))
|
||||
}
|
||||
|
||||
/// `TIME ( <Hour>, <Minute>, <Second> )`: a time on the 1899-12-30 epoch. Each argument is capped
|
||||
/// at 32,767 and the total wraps inside one day, as the catalog documents (`TIME ( 50, 0, 0 )` is
|
||||
/// 02:00, not 02:00 the next day).
|
||||
fn time(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
const MAX_TIME_PART: f64 = 32_767.0;
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let mut parts = [0.0f64; 3];
|
||||
for (index, part) in parts.iter_mut().enumerate() {
|
||||
let value = values.get(index).ok_or_else(|| EvalError::new(format!("TIME is missing argument {}", index + 1)))?.to_number();
|
||||
let value = value.filter(|value| value.is_finite()).ok_or_else(|| EvalError::new(format!("TIME argument {} must be numeric", index + 1)))?;
|
||||
if !(0.0..=MAX_TIME_PART).contains(&value) {
|
||||
return Err(EvalError::new(format!("TIME argument {} must be between 0 and 32767", index + 1)));
|
||||
}
|
||||
*part = value;
|
||||
}
|
||||
let seconds = parts[0] * 3_600.0 + parts[1] * 60.0 + parts[2];
|
||||
Ok(Scalar::DateTime(seconds.rem_euclid(86_400.0) / 86_400.0))
|
||||
}
|
||||
|
||||
/// `WEEKDAY ( <Date> [, <ReturnType>] )`: return type 1 numbers Sunday 1 through Saturday 7,
|
||||
/// 2 numbers Monday 1 through Sunday 7, 3 numbers Monday 0 through Sunday 6, and 11-17 start the
|
||||
/// week on Monday through Sunday with the first day numbered 1.
|
||||
fn weekday(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("WEEKDAY", &values, 0)?;
|
||||
let return_type = optional_int("WEEKDAY", &values, 1, 1)?;
|
||||
// Days since the epoch, 1899-12-30 was a Saturday, so serial 0 is Saturday and the
|
||||
// zero-based day of week with Sunday first is (days + 6) mod 7.
|
||||
let days = serial.floor() as i64;
|
||||
let sunday_first = (days + 6).rem_euclid(7);
|
||||
let index = match return_type {
|
||||
1 => sunday_first + 1,
|
||||
2 => (sunday_first + 6).rem_euclid(7) + 1,
|
||||
3 => (sunday_first + 6).rem_euclid(7),
|
||||
11..=17 => {
|
||||
// The first day of the week is Monday for 11 through Sunday for 17.
|
||||
let first = (return_type - 10).rem_euclid(7);
|
||||
(sunday_first - first).rem_euclid(7) + 1
|
||||
}
|
||||
other => {
|
||||
return Err(EvalError::new(format!("WEEKDAY return type `{other}` must be 1, 2, 3 or 11 to 17")));
|
||||
}
|
||||
};
|
||||
Ok(Scalar::Integer(index))
|
||||
}
|
||||
|
||||
/// `TIMEVALUE ( <TimeText> )` — the time of day as a fraction, ignoring any date portion.
|
||||
fn timevalue(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let value = values.first().ok_or_else(|| EvalError::new("TIMEVALUE is missing argument 1"))?;
|
||||
if let Scalar::DateTime(serial) = value {
|
||||
return Ok(Scalar::DateTime(serial.rem_euclid(1.0)));
|
||||
}
|
||||
let text = value.to_text();
|
||||
let fraction = parse_time_text(&text).ok_or_else(|| EvalError::new(format!("TIMEVALUE cannot convert `{text}` to a time")))?;
|
||||
Ok(Scalar::DateTime(fraction))
|
||||
}
|
||||
|
||||
fn parse_time_text(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date_part, time_part) = split_date_time(text);
|
||||
if parse_date_serial(date_part).is_some() {
|
||||
// A full date-time string keeps only its time; a date alone is midnight.
|
||||
return match time_part {
|
||||
Some(time) => parse_clock(time),
|
||||
None => Some(0.0),
|
||||
};
|
||||
}
|
||||
parse_clock(text)
|
||||
}
|
||||
|
||||
/// `QUARTER ( <Date> )` — 1 (January-March) through 4 (October-December).
|
||||
fn quarter(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("QUARTER", &values, 0)?;
|
||||
let (_, month, _) = support::date_parts(serial);
|
||||
Ok(Scalar::Integer((month - 1).div_euclid(3) + 1))
|
||||
}
|
||||
|
||||
/// `WEEKNUM ( <Date> [, <ReturnType>] )`.
|
||||
///
|
||||
/// Return types 1 and 2-17 use week system 1 (the week containing January 1 is week 1) with the
|
||||
/// week starting on Sunday (1), Monday (2, 11), Tuesday (12), Wednesday (13), Thursday (14),
|
||||
/// Friday (15), Saturday (16) or Sunday (17). Return type 21 is ISO 8601, where the week with the
|
||||
/// first Thursday is week 1 and the result follows the ISO week even across a year boundary.
|
||||
fn weeknum(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let serial = date_arg("WEEKNUM", &values, 0)?.floor();
|
||||
let return_type = optional_int("WEEKNUM", &values, 1, 1)?;
|
||||
let week = match return_type {
|
||||
21 => iso_week(serial),
|
||||
1 => week_system1(serial, 7),
|
||||
2 | 11 => week_system1(serial, 1),
|
||||
12 => week_system1(serial, 2),
|
||||
13 => week_system1(serial, 3),
|
||||
14 => week_system1(serial, 4),
|
||||
15 => week_system1(serial, 5),
|
||||
16 => week_system1(serial, 6),
|
||||
17 => week_system1(serial, 7),
|
||||
other => return Err(EvalError::new(format!("WEEKNUM return type {other} is not supported"))),
|
||||
};
|
||||
Ok(Scalar::Integer(week))
|
||||
}
|
||||
|
||||
/// Week number in week system 1 for a week starting on `week_start` (Monday 1 .. Sunday 7).
|
||||
fn week_system1(serial: f64, week_start: i64) -> i64 {
|
||||
let (year, _, _) = support::date_parts(serial);
|
||||
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0);
|
||||
let day_of_year = (serial - jan1) as i64 + 1;
|
||||
let lead = (iso_weekday(jan1) - week_start).rem_euclid(7);
|
||||
(day_of_year + lead - 1).div_euclid(7) + 1
|
||||
}
|
||||
|
||||
/// ISO 8601 week number. Dates that belong to the neighbouring ISO year report that year's week
|
||||
/// number (2021-01-01 is week 53, 2018-12-31 is week 1), matching Excel's return type 21.
|
||||
fn iso_week(serial: f64) -> i64 {
|
||||
// The Thursday of the week decides the ISO year: week 1 is the week that contains it.
|
||||
let thursday = serial as i64 - iso_weekday(serial) + 4;
|
||||
let year = if thursday < 1 { 1900 } else { support::date_parts(thursday as f64).0 };
|
||||
let jan1 = support::date_serial(year, 1, 1, 0, 0, 0) as i64;
|
||||
(thursday - jan1).div_euclid(7) + 1
|
||||
}
|
||||
|
||||
/// Weekday with Monday 1 .. Sunday 7. The shared helper returns Excel's default Sunday-first
|
||||
/// numbering (`date_weekday`), which week-number arithmetic and NETWORKDAYS do not use.
|
||||
fn iso_weekday(serial: f64) -> i64 {
|
||||
((support::date_weekday(serial) + 5) % 7) + 1
|
||||
}
|
||||
|
||||
/// `YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] )`.
|
||||
///
|
||||
/// Basis 0 is US (NASD) 30/360, 1 actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360,
|
||||
/// matching Excel's `YEARFRAC` (the same rules the worksheet engine in `crates/functions` uses).
|
||||
/// Excel ignores the argument order and returns the positive fraction for a reversed pair.
|
||||
fn yearfrac(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("YEARFRAC", &values, 0)?.floor();
|
||||
let end = date_arg("YEARFRAC", &values, 1)?.floor();
|
||||
let basis = optional_int("YEARFRAC", &values, 2, 0)?;
|
||||
if !(0..=4).contains(&basis) {
|
||||
return Err(EvalError::new(format!("YEARFRAC basis {basis} is not supported")));
|
||||
}
|
||||
let (start, end) = if start <= end { (start, end) } else { (end, start) };
|
||||
let (year1, month1, day1) = support::date_parts(start);
|
||||
let (year2, month2, day2) = support::date_parts(end);
|
||||
let days = end - start;
|
||||
let fraction = match basis {
|
||||
0 => {
|
||||
let mut day1 = day1;
|
||||
let mut day2 = day2;
|
||||
let start_feb_end = month1 == 2 && day1 == support::days_in_month(year1, 2);
|
||||
let end_feb_end = month2 == 2 && day2 == support::days_in_month(year2, 2);
|
||||
if day1 == 31 && day2 == 31 {
|
||||
day1 = 30;
|
||||
day2 = 30;
|
||||
} else if day1 == 31 {
|
||||
day1 = 30;
|
||||
} else if day1 == 30 && day2 == 31 {
|
||||
day2 = 30;
|
||||
} else if start_feb_end && end_feb_end {
|
||||
day1 = 30;
|
||||
day2 = 30;
|
||||
} else if start_feb_end {
|
||||
day1 = 30;
|
||||
}
|
||||
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
|
||||
}
|
||||
1 => {
|
||||
let within_year = year1 == year2 || (year2 == year1 + 1 && (month1 > month2 || (month1 == month2 && day1 >= day2)));
|
||||
let year_length = if within_year {
|
||||
let leap_day_between =
|
||||
(year1..=year2).any(|year| support::is_leap_year(year) && (start..=end).contains(&support::date_serial(year, 2, 29, 0, 0, 0)));
|
||||
if (year1 == year2 && support::is_leap_year(year1)) || leap_day_between || (month2 == 2 && day2 == 29) { 366.0 } else { 365.0 }
|
||||
} else {
|
||||
let years = (year2 - year1 + 1) as f64;
|
||||
let span = support::date_serial(year2 + 1, 1, 1, 0, 0, 0) - support::date_serial(year1, 1, 1, 0, 0, 0);
|
||||
span / years
|
||||
};
|
||||
days / year_length
|
||||
}
|
||||
2 => days / 360.0,
|
||||
3 => days / 365.0,
|
||||
_ => {
|
||||
let day1 = day1.min(30);
|
||||
let day2 = day2.min(30);
|
||||
((year2 - year1) * 360 + (month2 - month1) * 30 + (day2 - day1)) as f64 / 360.0
|
||||
}
|
||||
};
|
||||
Ok(Scalar::Decimal(fraction))
|
||||
}
|
||||
|
||||
/// `NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] )` — whole working days,
|
||||
/// both ends included. Weekend codes are 1 (Saturday/Sunday, the default), 2-7 for the pairs
|
||||
/// starting on Sunday through Friday, and 11-17 for a single day starting on Sunday. A reversed
|
||||
/// range returns the negative count, as Excel does.
|
||||
fn networkdays(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
// The optional holidays argument is a table, so it cannot go through eager scalar evaluation.
|
||||
let scalars = args.iter().take(3).map(|arg| ev.eval(arg, ctx)).collect::<Result<Vec<_>, EvalError>>()?;
|
||||
let start = date_arg("NETWORKDAYS", &scalars, 0)?.floor();
|
||||
let end = date_arg("NETWORKDAYS", &scalars, 1)?.floor();
|
||||
let code = optional_int("NETWORKDAYS", &scalars, 2, 1)?;
|
||||
let weekends = weekend_days(code)?;
|
||||
let holidays = match args.get(3) {
|
||||
Some(expr) => {
|
||||
let table = support::eval_table(ev, expr, ctx)?;
|
||||
holiday_days(&table)?
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
};
|
||||
let (start, end, sign) = if start <= end { (start, end, 1) } else { (end, start, -1) };
|
||||
let mut count = 0i64;
|
||||
let mut day = start as i64;
|
||||
let last = end as i64;
|
||||
while day <= last {
|
||||
let weekday = iso_weekday(day as f64) as usize;
|
||||
if !weekends[weekday] && !holidays.contains(&day) {
|
||||
count += 1;
|
||||
}
|
||||
day += 1;
|
||||
}
|
||||
Ok(Scalar::Integer(sign * count))
|
||||
}
|
||||
|
||||
/// Weekend lookup indexed by weekday (Monday 1 .. Sunday 7).
|
||||
fn weekend_days(code: i64) -> Result<[bool; 8], EvalError> {
|
||||
let mut days = [false; 8];
|
||||
match code {
|
||||
1..=7 => {
|
||||
let first = ((code + 4) % 7) + 1;
|
||||
days[first as usize] = true;
|
||||
days[(first % 7 + 1) as usize] = true;
|
||||
}
|
||||
11..=17 => {
|
||||
days[(((code - 11 + 6) % 7) + 1) as usize] = true;
|
||||
}
|
||||
other => return Err(EvalError::new(format!("NETWORKDAYS weekend code {other} is not supported"))),
|
||||
}
|
||||
Ok(days)
|
||||
}
|
||||
|
||||
fn holiday_days(table: &TableValue) -> Result<BTreeSet<i64>, EvalError> {
|
||||
let mut days = BTreeSet::new();
|
||||
if table.columns.is_empty() {
|
||||
return Ok(days);
|
||||
}
|
||||
for row in &table.rows {
|
||||
let Some(value) = row.first() else { continue };
|
||||
if value.is_blank() {
|
||||
continue;
|
||||
}
|
||||
let serial = coerce_date(value).ok_or_else(|| EvalError::new("NETWORKDAYS holidays must be dates"))?;
|
||||
days.insert(serial.floor() as i64);
|
||||
}
|
||||
Ok(days)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Clock
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `NOW ()` — the current date and time. The clock is read once per evaluation and uses the
|
||||
/// host's local timezone, as Excel does.
|
||||
fn now() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::now_serial()))
|
||||
}
|
||||
|
||||
/// `TODAY ()` — the current local date at midnight.
|
||||
fn today() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::today_serial()))
|
||||
}
|
||||
|
||||
/// `UTCNOW ()` — the current Coordinated Universal Time date and time.
|
||||
fn utc_now() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::utc_now_serial()))
|
||||
}
|
||||
|
||||
/// `UTCTODAY ()` — the current UTC date at midnight.
|
||||
fn utc_today() -> Result<Scalar, EvalError> {
|
||||
Ok(Scalar::DateTime(support::utc_today_serial()))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Tables
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// `CALENDAR ( <StartDate>, <EndDate> )` — one `Date` column with every day in the closed range.
|
||||
fn calendar(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let start = date_arg("CALENDAR", &values, 0)?.floor();
|
||||
let end = date_arg("CALENDAR", &values, 1)?.floor();
|
||||
date_table(start, end, "CALENDAR")
|
||||
}
|
||||
|
||||
/// `CALENDARAUTO ( [<FiscalYearEndMonth>] )` — a contiguous date table covering the whole fiscal
|
||||
/// years spanned by the model's DateTime columns.
|
||||
fn calendar_auto(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let values = support::eval_all(ev, args, ctx)?;
|
||||
let fiscal_end = optional_int("CALENDARAUTO", &values, 0, 12)?;
|
||||
if !(1..=12).contains(&fiscal_end) {
|
||||
return Err(EvalError::new("CALENDARAUTO FiscalYearEndMonth must be between 1 and 12"));
|
||||
}
|
||||
let mut bounds: Option<(f64, f64)> = None;
|
||||
for table in &ev.model().tables {
|
||||
for (index, column) in table.columns.iter().enumerate() {
|
||||
let is_datetime = column.data_type.as_deref().is_some_and(is_date_type);
|
||||
if !is_datetime {
|
||||
continue;
|
||||
}
|
||||
for row in &table.rows {
|
||||
let Some(value) = row.get(index) else { continue };
|
||||
if value.is_blank() {
|
||||
continue;
|
||||
}
|
||||
let Some(serial) = coerce_date(value) else { continue };
|
||||
let serial = serial.floor();
|
||||
bounds = Some(match bounds {
|
||||
Some((min, max)) => (min.min(serial), max.max(serial)),
|
||||
None => (serial, serial),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((min, max)) = bounds else {
|
||||
return Err(EvalError::new("CALENDARAUTO requires a model with at least one DateTime column"));
|
||||
};
|
||||
let start = fiscal_year_start(min, fiscal_end);
|
||||
let end = fiscal_year_end(max, fiscal_end);
|
||||
date_table(start, end, "CALENDARAUTO")
|
||||
}
|
||||
|
||||
/// First day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
|
||||
fn fiscal_year_start(serial: f64, end_month: i64) -> f64 {
|
||||
let (year, month, _) = support::date_parts(serial);
|
||||
let fiscal_year = if month <= end_month { year } else { year + 1 };
|
||||
support::date_serial(fiscal_year - 1, end_month + 1, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Last day of the fiscal year containing `serial` when the fiscal year ends in `end_month`.
|
||||
fn fiscal_year_end(serial: f64, end_month: i64) -> f64 {
|
||||
let (year, month, _) = support::date_parts(serial);
|
||||
let fiscal_year = if month <= end_month { year } else { year + 1 };
|
||||
support::date_serial(fiscal_year, end_month, support::days_in_month(fiscal_year, end_month), 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Builds the one-column `Date` table shared by CALENDAR and CALENDARAUTO.
|
||||
fn date_table(start: f64, end: f64, name: &str) -> Result<TableValue, EvalError> {
|
||||
if end < start {
|
||||
return Err(EvalError::new(format!("{name} requires the start date to be on or before the end date")));
|
||||
}
|
||||
if start < 0.0 || end > MAX_DATE_SERIAL {
|
||||
return Err(EvalError::new(format!("{name} dates must be between 1899-12-30 and 9999-12-31")));
|
||||
}
|
||||
let count = (end - start) as i64 + 1;
|
||||
if count > MAX_GENERATED_ROWS {
|
||||
return Err(EvalError::new(format!("{name} result is too large")));
|
||||
}
|
||||
let rows = (0..count).map(|offset| vec![Scalar::DateTime(start + offset as f64)]).collect();
|
||||
Ok(TableValue::new(vec![TableColumn { name: "Date".into() }], rows))
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! Math and trigonometry functions.
|
||||
//!
|
||||
//! The inverse trigonometric and hyperbolic families follow Excel's domains: a value outside the
|
||||
//! documented range raises an error instead of returning NaN. `CONVERT` follows the catalog and
|
||||
//! dax.guide, i.e. `CONVERT ( <Expression>, <DataType> )` with a bare type keyword.
|
||||
//!
|
||||
//! `RAND`/`RANDBETWEEN` use a local xorshift64* generator seeded from the clock (`js_sys::Date` on
|
||||
//! wasm, where `SystemTime::now` traps) and a per-call salt; the catalog already flags both
|
||||
//! functions as volatile.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::support::{args as arg_values, eval_all, parse_date_text, round_direction};
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
match name.as_str() {
|
||||
"ACOS" | "ACOSH" | "ACOT" | "ACOTH" | "ASIN" | "ASINH" | "ATAN" | "ATANH" | "CONVERT" | "COSH" | "COT" | "COTH" | "CURRENCY" | "EVEN"
|
||||
| "MOD" | "MROUND" | "ODD" | "QUOTIENT" | "RAND" | "RANDBETWEEN" | "ROUNDDOWN" | "SINH" | "SQRTPI" | "TANH" => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(evaluate(&name, ev, args, ctx))
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn evaluate(name: &str, ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values(name, &values);
|
||||
match name {
|
||||
"ACOS" => {
|
||||
let x = domain_number(&a, -1.0, 1.0)?;
|
||||
Ok(Scalar::Decimal(x.acos()))
|
||||
}
|
||||
"ACOSH" => {
|
||||
let x = domain_number(&a, 1.0, f64::INFINITY)?;
|
||||
Ok(Scalar::Decimal(x.acosh()))
|
||||
}
|
||||
"ACOT" => {
|
||||
// Principal value in (0, pi), unlike ATAN's (-pi/2, pi/2).
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(std::f64::consts::FRAC_PI_2 - x.atan()))
|
||||
}
|
||||
"ACOTH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x.abs() <= 1.0 {
|
||||
return Err(EvalError::new("ACOTH argument must have an absolute value greater than 1"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(0.5 * ((x + 1.0) / (x - 1.0)).ln(), name)?))
|
||||
}
|
||||
"ASIN" => {
|
||||
let x = domain_number(&a, -1.0, 1.0)?;
|
||||
Ok(Scalar::Decimal(x.asin()))
|
||||
}
|
||||
"ASINH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.asinh()))
|
||||
}
|
||||
"ATAN" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.atan()))
|
||||
}
|
||||
"ATANH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x <= -1.0 || x >= 1.0 {
|
||||
return Err(EvalError::new("ATANH argument must be greater than -1 and less than 1"));
|
||||
}
|
||||
Ok(Scalar::Decimal(x.atanh()))
|
||||
}
|
||||
"CONVERT" => convert(&values),
|
||||
"COSH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(finite(x.cosh(), name)?))
|
||||
}
|
||||
"COT" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
let tangent = x.tan();
|
||||
if tangent == 0.0 {
|
||||
return Err(EvalError::new("COT is undefined at multiples of pi"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
|
||||
}
|
||||
"COTH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
let tangent = x.tanh();
|
||||
if tangent == 0.0 {
|
||||
return Err(EvalError::new("COTH is undefined at zero"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite(1.0 / tangent, name)?))
|
||||
}
|
||||
"CURRENCY" => currency(a.arg(0)?),
|
||||
"EVEN" => Ok(Scalar::Integer(round_away_to_even(finite(a.number(0)?, name)?)?)),
|
||||
"MROUND" => {
|
||||
let number = finite(a.number(0)?, name)?;
|
||||
let multiple = finite(a.number(1)?, name)?;
|
||||
Ok(Scalar::Decimal(mround(number, multiple)?))
|
||||
}
|
||||
"MOD" => modulo(a.arg(0)?, a.arg(1)?),
|
||||
// ROUNDDOWN rounds toward zero (support::round_direction), so negatives go up.
|
||||
"ROUNDDOWN" => Ok(Scalar::Decimal(round_direction(finite(a.number(0)?, name)?, a.number(1)? as i32, false))),
|
||||
"ODD" => Ok(Scalar::Integer(round_away_to_odd(finite(a.number(0)?, name)?)?)),
|
||||
"QUOTIENT" => {
|
||||
let numerator = finite(a.number(0)?, name)?;
|
||||
let denominator = finite(a.number(1)?, name)?;
|
||||
if denominator == 0.0 {
|
||||
return Err(EvalError::new("QUOTIENT denominator must not be zero"));
|
||||
}
|
||||
Ok(Scalar::Integer(truncate_i64(finite(numerator / denominator, name)?)?))
|
||||
}
|
||||
"RAND" => Ok(Scalar::Decimal(next_random_fraction())),
|
||||
"RANDBETWEEN" => {
|
||||
let bottom = truncate_i64(finite(a.number(0)?, name)?)?;
|
||||
let top = truncate_i64(finite(a.number(1)?, name)?)?;
|
||||
if bottom > top {
|
||||
return Err(EvalError::new("RANDBETWEEN bottom must not be greater than top"));
|
||||
}
|
||||
let span = (top as i128) - (bottom as i128) + 1;
|
||||
let offset = (next_random_u64() as u128 % span as u128) as i128;
|
||||
Ok(Scalar::Integer((bottom as i128 + offset) as i64))
|
||||
}
|
||||
"SINH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(finite(x.sinh(), name)?))
|
||||
}
|
||||
"SQRTPI" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
if x < 0.0 {
|
||||
return Err(EvalError::new("SQRTPI argument must not be negative"));
|
||||
}
|
||||
Ok(Scalar::Decimal(finite((x * std::f64::consts::PI).sqrt(), name)?))
|
||||
}
|
||||
"TANH" => {
|
||||
let x = finite(a.number(0)?, name)?;
|
||||
Ok(Scalar::Decimal(x.tanh()))
|
||||
}
|
||||
_ => Err(EvalError::new(format!("{name} is not a math function"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn finite(value: f64, function: &str) -> Result<f64, EvalError> {
|
||||
if value.is_finite() { Ok(value) } else { Err(EvalError::new(format!("{function} result is not a finite number"))) }
|
||||
}
|
||||
|
||||
/// Reads the first argument as a finite number inside `[low, high]`.
|
||||
fn domain_number(a: &super::support::Args<'_>, low: f64, high: f64) -> Result<f64, EvalError> {
|
||||
let x = finite(a.number(0)?, a.name)?;
|
||||
if x < low || x > high {
|
||||
return Err(EvalError::new(format!("{} argument is outside the valid domain", a.name)));
|
||||
}
|
||||
Ok(x)
|
||||
}
|
||||
|
||||
fn truncate_i64(value: f64) -> Result<i64, EvalError> {
|
||||
if !value.is_finite() || value.trunc() < -9_223_372_036_854_775_808.0 || value.trunc() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("value is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(value.trunc() as i64)
|
||||
}
|
||||
|
||||
/// CURRENCY rounds half away from zero to four decimals and stores the fixed-point integer.
|
||||
fn currency(value: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CURRENCY argument must be convertible to a number"))?;
|
||||
let scaled = (number * 10_000.0).round();
|
||||
if !scaled.is_finite() || scaled.abs() > i64::MAX as f64 {
|
||||
return Err(EvalError::new("CURRENCY value is outside the representable range"));
|
||||
}
|
||||
Ok(Scalar::Currency(scaled as i64))
|
||||
}
|
||||
|
||||
fn round_away_to_even(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = magnitude_i64(number)?;
|
||||
let rounded = if magnitude % 2 == 0 {
|
||||
magnitude
|
||||
} else {
|
||||
magnitude.checked_add(1).ok_or_else(|| EvalError::new("EVEN result is outside the 64-bit integer range"))?
|
||||
};
|
||||
Ok(with_sign(rounded, number))
|
||||
}
|
||||
|
||||
fn round_away_to_odd(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = magnitude_i64(number)?;
|
||||
let rounded = if magnitude % 2 == 1 {
|
||||
magnitude
|
||||
} else {
|
||||
magnitude.checked_add(1).ok_or_else(|| EvalError::new("ODD result is outside the 64-bit integer range"))?
|
||||
};
|
||||
Ok(with_sign(rounded, number))
|
||||
}
|
||||
|
||||
/// Absolute value rounded away from zero to an integer that still fits in an `i64`.
|
||||
fn magnitude_i64(number: f64) -> Result<i64, EvalError> {
|
||||
let magnitude = number.abs().ceil();
|
||||
if !magnitude.is_finite() || magnitude >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new("number is outside the 64-bit integer range"));
|
||||
}
|
||||
Ok(magnitude as i64)
|
||||
}
|
||||
|
||||
fn with_sign(magnitude: i64, number: f64) -> i64 {
|
||||
if number < 0.0 { -magnitude } else { magnitude }
|
||||
}
|
||||
|
||||
fn mround(number: f64, multiple: f64) -> Result<f64, EvalError> {
|
||||
if multiple == 0.0 {
|
||||
return Ok(0.0);
|
||||
}
|
||||
if (number > 0.0 && multiple < 0.0) || (number < 0.0 && multiple > 0.0) {
|
||||
return Err(EvalError::new("MROUND number and multiple must have the same sign"));
|
||||
}
|
||||
finite((number / multiple).round() * multiple, "MROUND")
|
||||
}
|
||||
|
||||
/// `MOD ( <Number>, <Divisor> )`: the remainder whose sign follows the *divisor*
|
||||
/// (`number - divisor * FLOOR ( number / divisor )`), unlike Rust's `%`, which follows the
|
||||
/// dividend. A zero divisor is a division-by-zero error in DAX, not BLANK. Two integer operands
|
||||
/// keep the Integer type the catalog documents; anything else returns a Decimal.
|
||||
fn modulo(number: &Scalar, divisor: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let divisor_number = finite(divisor.to_number().ok_or_else(|| EvalError::new("MOD argument 2 must be numeric"))?, "MOD")?;
|
||||
if divisor_number == 0.0 {
|
||||
return Err(EvalError::new("MOD divisor must not be zero"));
|
||||
}
|
||||
if let (Scalar::Integer(number), Scalar::Integer(divisor)) = (number, divisor) {
|
||||
let divisor = *divisor;
|
||||
let remainder = number.checked_rem(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?;
|
||||
if remainder != 0 && (remainder < 0) != (divisor < 0) {
|
||||
return Ok(Scalar::Integer(
|
||||
remainder.checked_add(divisor).ok_or_else(|| EvalError::new("MOD result is outside the 64-bit integer range"))?,
|
||||
));
|
||||
}
|
||||
return Ok(Scalar::Integer(remainder));
|
||||
}
|
||||
let number = finite(number.to_number().ok_or_else(|| EvalError::new("MOD argument 1 must be numeric"))?, "MOD")?;
|
||||
Ok(Scalar::Decimal(finite(number - divisor_number * (number / divisor_number).floor(), "MOD")?))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Random numbers
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Clock entropy for the PRNG seed. `SystemTime::now` traps on wasm, so it is only compiled for
|
||||
/// native targets; wasm falls back to the counter that the caller mixes in.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn clock_nanos() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|duration| duration.as_nanos() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The browser's wall clock in nanoseconds. `SystemTime::now` traps on wasm, and a fixed seed
|
||||
/// would make every page load produce the same `RAND()` sequence, so the shared `js_sys::Date`
|
||||
/// clock that `support.rs` already uses seeds the generator instead.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn clock_nanos() -> u64 {
|
||||
(js_sys::Date::now() * 1_000_000.0) as u64
|
||||
}
|
||||
|
||||
fn next_random_u64() -> u64 {
|
||||
static STATE: AtomicU64 = AtomicU64::new(0);
|
||||
static SALT: AtomicU64 = AtomicU64::new(0);
|
||||
let mut state = STATE.load(Ordering::Relaxed);
|
||||
if state == 0 {
|
||||
let salt = SALT.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed);
|
||||
state = clock_nanos() ^ salt;
|
||||
if state == 0 {
|
||||
state = 0x9E37_79B9_7F4A_7C15;
|
||||
}
|
||||
}
|
||||
// xorshift64*: full-period, small and dependency-free.
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
STATE.store(state, Ordering::Relaxed);
|
||||
state.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
fn next_random_fraction() -> f64 {
|
||||
// 53 random mantissa bits give a uniform value in [0, 1).
|
||||
(next_random_u64() >> 11) as f64 / 9_007_199_254_740_992.0
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// CONVERT
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
fn convert(values: &[Scalar]) -> Result<Scalar, EvalError> {
|
||||
match values {
|
||||
[value, target] => convert_type(value, target),
|
||||
_ => Err(EvalError::new("CONVERT expects an expression and a data type")),
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_type(value: &Scalar, target: &Scalar) -> Result<Scalar, EvalError> {
|
||||
let target = target.to_text().trim().to_ascii_uppercase();
|
||||
match target.as_str() {
|
||||
"BOOLEAN" | "LOGICAL" => {
|
||||
let boolean = value.to_bool().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to BOOLEAN"))?;
|
||||
Ok(Scalar::Boolean(boolean))
|
||||
}
|
||||
// "DECIMAL" is the DAX synonym for the fixed-decimal Currency type, not a double.
|
||||
"CURRENCY" | "DECIMAL" | "FIXEDDECIMAL" => currency(value),
|
||||
"DATETIME" => convert_datetime(value),
|
||||
"DOUBLE" => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DOUBLE"))?;
|
||||
Ok(Scalar::Decimal(finite(number, "CONVERT")?))
|
||||
}
|
||||
"INTEGER" | "INT64" => {
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to INTEGER"))?;
|
||||
Ok(Scalar::Integer(truncate_i64(number)?))
|
||||
}
|
||||
"STRING" | "TEXT" => Ok(Scalar::String(value.to_dax_text())),
|
||||
other => Err(EvalError::new(format!("CONVERT does not recognize the data type `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_datetime(value: &Scalar) -> Result<Scalar, EvalError> {
|
||||
match value {
|
||||
Scalar::DateTime(_) => Ok(value.clone()),
|
||||
Scalar::String(text) => {
|
||||
let serial = parse_date_text(text).ok_or_else(|| EvalError::new("CONVERT cannot parse the text as DATETIME"))?;
|
||||
Ok(Scalar::DateTime(serial))
|
||||
}
|
||||
other => {
|
||||
let number = other.to_number().ok_or_else(|| EvalError::new("CONVERT cannot convert the value to DATETIME"))?;
|
||||
Ok(Scalar::DateTime(finite(number, "CONVERT")?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Time-intelligence functions.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
mod ranges;
|
||||
mod totals;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Whether `data_type` names one of the two date types. `CALENDARAUTO`, the range functions and
|
||||
/// the total functions share this test, so a column the model declares as `Date` counts as a date
|
||||
/// everywhere instead of only in some of them.
|
||||
pub(super) fn is_date_type(data_type: &str) -> bool {
|
||||
data_type.eq_ignore_ascii_case("DateTime") || data_type.eq_ignore_ascii_case("Date")
|
||||
}
|
||||
|
||||
/// [`is_date_type`] for a column's optional declared type: an undeclared type is not judged.
|
||||
pub(super) fn is_date_column(data_type: Option<&str>) -> bool {
|
||||
data_type.is_none_or(is_date_type)
|
||||
}
|
||||
|
||||
/// The month and day a `YearEndDate` argument names. The range functions (`DATESYTD`, ...) and the
|
||||
/// total functions (`TOTALYTD`, ...) both parse that argument here, so the documented `"6/30/2008"`
|
||||
/// and `"6/30"` forms behave the same in both families and an impossible day (`"2/30"`) is rejected
|
||||
/// by both instead of being clamped in one and rejected in the other. A month/day-only form is
|
||||
/// checked against a leap year, so `"2/29"` stays valid.
|
||||
pub(super) fn year_end_parts(value: &Scalar) -> Option<(i64, i64)> {
|
||||
let (year, month, day) = match value {
|
||||
Scalar::String(text) => {
|
||||
let parts: Vec<&str> = text.trim().split(['/', '-']).map(str::trim).collect();
|
||||
// An empty component (`"6/-30"`, `"6/"`) is not a date: reject it instead of letting
|
||||
// the remaining parts parse as a valid month and day.
|
||||
if parts.iter().any(|part| part.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let numbers: Vec<i64> = parts.iter().map(|part| part.parse::<i64>().ok()).collect::<Option<Vec<i64>>>()?;
|
||||
match numbers.as_slice() {
|
||||
// `M/D`: only the month and day matter, and the year is never read back.
|
||||
[month, day] => (2000, *month, *day),
|
||||
// `Y/M/D` and `M/D/Y` are both documented shapes; a two-digit year is ignored.
|
||||
[first, second, third] if *first > 31 => (*first, *second, *third),
|
||||
[month, day, year] => (if *year > 99 { *year } else { 2000 }, *month, *day),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let (year, month, day) = super::support::date_parts(super::support::date_value(other)?);
|
||||
(year, month, day)
|
||||
}
|
||||
};
|
||||
((1..=12).contains(&month) && day >= 1 && day <= super::support::days_in_month(year, month)).then_some((month, day))
|
||||
}
|
||||
|
||||
/// The column a table argument contributes to the range and total functions, chosen by one rule so
|
||||
/// `DATESWTD(Calendar)` and `TOTALWTD(…, Calendar)` never disagree: a column whose declared type is
|
||||
/// a date type, then a column named `Date` that is not declared as another type, then — only when it
|
||||
/// cannot be ambiguous — the table's single untyped column.
|
||||
pub(super) fn table_date_column(table: &crate::model::ModelTable) -> Option<usize> {
|
||||
if let Some(index) = table.columns.iter().position(|column| column.data_type.as_deref().is_some_and(is_date_type)) {
|
||||
return Some(index);
|
||||
}
|
||||
if let Some(index) =
|
||||
table.columns.iter().position(|column| column.name.eq_ignore_ascii_case("Date") && is_date_column(column.data_type.as_deref()))
|
||||
{
|
||||
return Some(index);
|
||||
}
|
||||
let untyped: Vec<usize> = table.columns.iter().enumerate().filter(|(_, column)| column.data_type.is_none()).map(|(index, _)| index).collect();
|
||||
match untyped.as_slice() {
|
||||
[index] => Some(*index),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
totals::call(ev, name, args, ctx).or_else(|| ranges::call(ev, name, args, ctx))
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
totals::call_table(ev, name, args, ctx).or_else(|| ranges::call_table(ev, name, args, ctx))
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
//! Time-intelligence range functions (period tables).
|
||||
//!
|
||||
//! Every function here works the same way: it reads the dates visible in the current filter
|
||||
//! context for a DateTime column, derives a calendar window from them, and materializes the
|
||||
//! window as a one-column table whose rows are the *model's own* date values (so the result keeps
|
||||
//! the date table's lineage and `CALCULATE` can use it as a filter).
|
||||
//!
|
||||
//! * The visible range comes from the filter context when the date column (or the date table) is
|
||||
//! filtered, otherwise from the whole table. The window is anchored on the first visible date
|
||||
//! (`PREVIOUS*`), the last visible date (`NEXT*`, `START*`, `END*`, `DATES*TD`), or both
|
||||
//! (`DATEADD`, `DATESBETWEEN`, ...).
|
||||
//! * The window is intersected with the dates that exist in the column, so a non-contiguous date
|
||||
//! table only loses the missing days.
|
||||
//! * The table forms replace any filter on the date column, per the documented time-intelligence
|
||||
//! contract; the scalar conveniences (`FIRSTDATE` used as a value, ...) only accept a
|
||||
//! single-row result.
|
||||
//!
|
||||
//! Week-based functions (`DATESWTD`, `STARTOFWEEK`, `ENDOFWEEK`, `NEXTWEEK`, `PREVIOUSWEEK`) take
|
||||
//! a calendar reference in the catalog. GridCraft has no calendar objects, so the reference is
|
||||
//! resolved to the calendar table's date column and weeks are Sunday-based, which is the Excel /
|
||||
//! `WEEKDAY` default.
|
||||
//!
|
||||
//! https://dax.guide/datesinperiod/ (boundary date excluded), https://dax.guide/dateadd/
|
||||
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, derived_row_frame, edate};
|
||||
use super::*;
|
||||
|
||||
/// Every function that this module answers for.
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"DATEADD",
|
||||
"DATESBETWEEN",
|
||||
"DATESINPERIOD",
|
||||
"DATESMTD",
|
||||
"DATESQTD",
|
||||
"DATESWTD",
|
||||
"DATESYTD",
|
||||
"ENDOFMONTH",
|
||||
"ENDOFQUARTER",
|
||||
"ENDOFWEEK",
|
||||
"ENDOFYEAR",
|
||||
"FIRSTDATE",
|
||||
"FIRSTNONBLANK",
|
||||
"LASTDATE",
|
||||
"LASTNONBLANK",
|
||||
"NEXTDAY",
|
||||
"NEXTMONTH",
|
||||
"NEXTQUARTER",
|
||||
"NEXTWEEK",
|
||||
"NEXTYEAR",
|
||||
"PARALLELPERIOD",
|
||||
"PREVIOUSDAY",
|
||||
"PREVIOUSMONTH",
|
||||
"PREVIOUSQUARTER",
|
||||
"PREVIOUSWEEK",
|
||||
"PREVIOUSYEAR",
|
||||
"SAMEPERIODLASTYEAR",
|
||||
"STARTOFMONTH",
|
||||
"STARTOFQUARTER",
|
||||
"STARTOFWEEK",
|
||||
"STARTOFYEAR",
|
||||
];
|
||||
|
||||
/// Sanity bound for interval counts: the arithmetic stays exact and the loops over the date
|
||||
/// table stay bounded by the model, so only absurd inputs need rejecting.
|
||||
const MAX_INTERVALS: f64 = 1_000_000.0;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Interval {
|
||||
Day,
|
||||
Week,
|
||||
Month,
|
||||
Quarter,
|
||||
Year,
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
if !FUNCTIONS.contains(&name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let result = match name.as_str() {
|
||||
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true).and_then(|table| scalar_result(&name, table)),
|
||||
"LASTNONBLANK" => nonblank(ev, args, ctx, false).and_then(|table| scalar_result(&name, table)),
|
||||
_ => compute_table(ev, &name, args, ctx).and_then(|table| scalar_result(&name, table)),
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
if !FUNCTIONS.contains(&name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some(match name.as_str() {
|
||||
"FIRSTNONBLANK" => nonblank(ev, args, ctx, true),
|
||||
"LASTNONBLANK" => nonblank(ev, args, ctx, false),
|
||||
_ => compute_table(ev, &name, args, ctx),
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts a one-row, one-column result to its value; anything else cannot be used as a scalar.
|
||||
fn scalar_result(name: &str, table: TableValue) -> Result<Scalar, EvalError> {
|
||||
match table.rows.as_slice() {
|
||||
[] => Ok(Scalar::Blank),
|
||||
[row] => Ok(row.first().cloned().unwrap_or(Scalar::Blank)),
|
||||
rows => Err(EvalError::new(format!("{name} returns a table with {} rows; use it as a CALCULATE filter instead of a scalar", rows.len()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The date column a time-intelligence call is anchored on.
|
||||
struct DateAxis {
|
||||
table: usize,
|
||||
name: String,
|
||||
/// Every date that exists in the column, ascending, as (day serial, original value).
|
||||
dates: Vec<(f64, Scalar)>,
|
||||
/// First and last visible date, absent when the filter context selects no date.
|
||||
min: Option<f64>,
|
||||
max: Option<f64>,
|
||||
/// The distinct visible dates, ascending. Used to tell a selection that actually contains the
|
||||
/// month's last two days from one that merely ends near its boundary.
|
||||
visible_dates: Vec<f64>,
|
||||
/// The visible cells themselves, as (day serial, original value): `FIRSTDATE`/`LASTDATE` pick
|
||||
/// an exact cell, so they must choose among the values the filter context selects, not among
|
||||
/// every timestamp the day happens to hold.
|
||||
visible_values: Vec<(f64, Scalar)>,
|
||||
}
|
||||
|
||||
impl DateAxis {
|
||||
fn empty(&self) -> TableValue {
|
||||
TableValue::new(vec![TableColumn { name: self.name.clone() }], Vec::new()).with_lineage(self.table)
|
||||
}
|
||||
|
||||
/// The dates of the column between two inclusive boundaries.
|
||||
fn table(&self, start: f64, end: f64) -> TableValue {
|
||||
let start = start.floor();
|
||||
let end = end.floor();
|
||||
let rows = if start > end {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.dates.iter().filter(|(serial, _)| (start..=end).contains(serial)).map(|(_, value)| vec![value.clone()]).collect()
|
||||
};
|
||||
TableValue::new(vec![TableColumn { name: self.name.clone() }], rows).with_lineage(self.table)
|
||||
}
|
||||
|
||||
/// `DATEADD` documents a contiguous dates argument: shifting a selection with a missing day
|
||||
/// would sweep in the blocked date, so it is an error rather than a silently wider result.
|
||||
fn require_contiguous(&self, name: &str) -> Result<(), EvalError> {
|
||||
let Some(pair) = self.visible_dates.windows(2).find(|pair| pair[1] != pair[0] + 1.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
// Report the gap by calendar day: a serial alone does not tell the reader which day the
|
||||
// selection skipped.
|
||||
let day = |serial: f64| Scalar::DateTime(serial).to_dax_text().split(' ').next().unwrap_or_default().to_owned();
|
||||
Err(EvalError::new(format!(
|
||||
"{name} needs a contiguous range of visible dates; the selection skips from {} to {}",
|
||||
day(pair[0]),
|
||||
day(pair[1])
|
||||
)))
|
||||
}
|
||||
|
||||
/// One cell of `date` as a one-row table: the earliest cell of the day, or the latest when
|
||||
/// `last` is set. Single-date operations (`FIRSTDATE`, `LASTDATE`, `PREVIOUSDAY`, ...) must stay
|
||||
/// scalar, so they pick one exact cell value even when the day holds several timestamps; the
|
||||
/// range tables keep every cell.
|
||||
fn single(&self, date: f64, last: bool) -> TableValue {
|
||||
let day = date.floor();
|
||||
let visible: Vec<&Scalar> = self.visible_values.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect();
|
||||
// A day the filter context selects contributes its visible cells; a day outside the
|
||||
// selection (a `NEXTDAY` probe, say) falls back to every cell the column holds.
|
||||
let cells =
|
||||
if visible.is_empty() { self.dates.iter().filter(|(serial, _)| *serial == day).map(|(_, value)| value).collect() } else { visible };
|
||||
let ordering = |value: &&Scalar| date_value(value).unwrap_or(f64::NEG_INFINITY);
|
||||
let picked = if last {
|
||||
cells.into_iter().max_by(|a, b| ordering(a).total_cmp(&ordering(b)))
|
||||
} else {
|
||||
cells.into_iter().min_by(|a, b| ordering(a).total_cmp(&ordering(b)))
|
||||
};
|
||||
match picked {
|
||||
Some(value) => TableValue::new(vec![TableColumn { name: self.name.clone() }], vec![vec![value.clone()]]).with_lineage(self.table),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first date that exists in `[start, end]`, as a one-row table.
|
||||
fn first_in(&self, start: f64, end: f64) -> TableValue {
|
||||
let mut table = self.table(start, end);
|
||||
table.rows.truncate(1);
|
||||
table
|
||||
}
|
||||
|
||||
/// The last date that exists in `[start, end]`, as a one-row table.
|
||||
fn last_in(&self, start: f64, end: f64) -> TableValue {
|
||||
let mut table = self.table(start, end);
|
||||
let last = table.rows.pop();
|
||||
table.rows = last.into_iter().collect();
|
||||
table
|
||||
}
|
||||
|
||||
fn first(&self) -> TableValue {
|
||||
match self.min {
|
||||
Some(min) => self.single(min, false),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn last(&self) -> TableValue {
|
||||
match self.max {
|
||||
Some(max) => self.single(max, true),
|
||||
None => self.empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn visible(&self) -> Option<(f64, f64)> {
|
||||
Some((self.min?, self.max?))
|
||||
}
|
||||
|
||||
/// Whether the selection contains both of the last two days of `max`'s month. `max` is the
|
||||
/// selection's last visible date; the two days have to be on the axis itself, so a selection
|
||||
/// that stops on the month-end date alone (or on its penultimate day) does not qualify.
|
||||
fn includes_last_two_days(&self, max: f64) -> bool {
|
||||
let last = month_end(max);
|
||||
let penultimate = last - 1.0;
|
||||
let contains = |date: f64| self.visible_dates.binary_search_by(|visible| visible.total_cmp(&date)).is_ok();
|
||||
contains(penultimate) && contains(last)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the `Dates` argument (a DateTime column, or a calendar table for the week-based
|
||||
/// functions) and reads the dates visible in the current filter context.
|
||||
fn date_axis(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &Context, name: &str) -> Result<DateAxis, EvalError> {
|
||||
let model = ev.model();
|
||||
let (table, column) = match expr {
|
||||
BoundExpr::Column { table, column } => (*table, *column),
|
||||
BoundExpr::UnqualifiedColumn { name: column } => {
|
||||
let tables = model.tables_with_column(column);
|
||||
let table = match tables.as_slice() {
|
||||
[table] => *table,
|
||||
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column}]`"))),
|
||||
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column}]` is ambiguous"))),
|
||||
};
|
||||
let index = model.column_index(table, column).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column}]`")))?;
|
||||
(table, index)
|
||||
}
|
||||
BoundExpr::Table(table) => {
|
||||
let model_table = model.tables.get(*table).ok_or_else(|| EvalError::new(format!("{name} needs a date table")))?;
|
||||
let index = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("{name} needs a calendar with a date column")))?;
|
||||
(*table, index)
|
||||
}
|
||||
_ => return Err(EvalError::new(format!("{name} needs a date column reference"))),
|
||||
};
|
||||
|
||||
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid date table")))?;
|
||||
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid date column")))?;
|
||||
if let Some(data_type) = &model_column.data_type
|
||||
&& !is_date_type(data_type)
|
||||
{
|
||||
return Err(EvalError::new(format!("{name} needs a DateTime column; `{}[{}]` is {data_type}", model_table.name, model_column.name)));
|
||||
}
|
||||
|
||||
// `date_value` rather than `to_number`: BLANK is not the serial 0 (1899-12-30), and a
|
||||
// non-finite number is not a date, so neither may enter the axis.
|
||||
let mut dates: Vec<(f64, Scalar)> = model_table
|
||||
.rows
|
||||
.iter()
|
||||
.filter_map(|row| row.get(column))
|
||||
.filter_map(|value| date_value(value).filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
|
||||
.collect();
|
||||
dates.sort_by(|left, right| {
|
||||
left.0
|
||||
.total_cmp(&right.0)
|
||||
.then_with(|| date_value(&left.1).unwrap_or(f64::NEG_INFINITY).total_cmp(&date_value(&right.1).unwrap_or(f64::NEG_INFINITY)))
|
||||
});
|
||||
// Deduplicate exact cell values, never whole days: a column can hold several timestamps that
|
||||
// share a day, and the window's filter keys are those exact values, so dropping one would
|
||||
// silently exclude its row from every range table.
|
||||
let mut seen = BTreeSet::new();
|
||||
dates.retain(|(_, value)| seen.insert(ScalarKey::from(value)));
|
||||
|
||||
// The visible dates honour the filter context. Only filters on the date table itself count:
|
||||
// a filter on a fact table does not restrict the dimension it points at.
|
||||
let mut min: Option<f64> = None;
|
||||
let mut max: Option<f64> = None;
|
||||
let mut visible_dates: Vec<f64> = Vec::new();
|
||||
let mut visible_values: Vec<(f64, Scalar)> = Vec::new();
|
||||
for row in visible_rows(ev, table, ctx) {
|
||||
if let Some(value) = row.get(column)
|
||||
&& let Some(serial) = date_value(value).filter(|serial| serial.is_finite())
|
||||
{
|
||||
let serial = serial.floor();
|
||||
min = Some(min.map_or(serial, |value| value.min(serial)));
|
||||
max = Some(max.map_or(serial, |value| value.max(serial)));
|
||||
visible_dates.push(serial);
|
||||
visible_values.push((serial, value.clone()));
|
||||
}
|
||||
}
|
||||
visible_dates.sort_by(|left, right| left.total_cmp(right));
|
||||
visible_dates.dedup_by(|left, right| left.total_cmp(right).is_eq());
|
||||
|
||||
Ok(DateAxis { table, name: model_column.name.clone(), dates, min, max, visible_dates, visible_values })
|
||||
}
|
||||
|
||||
/// The model rows of a table that survive the filters currently in effect, in model column order.
|
||||
///
|
||||
/// Filtering goes through [`Evaluator::table`] so filters that reach the table through an active
|
||||
/// relationship (a snowflaked dimension on the one side, or a bidirectional relationship) apply
|
||||
/// too, not just filters set on the table's own columns.
|
||||
fn visible_rows(ev: &Evaluator<'_>, table: usize, ctx: &Context) -> Vec<Vec<Scalar>> {
|
||||
// A range function's column argument takes the current row: the row context transitions to
|
||||
// filters, exactly as `CALCULATE` does, instead of the whole date column being visible.
|
||||
ev.table(table, &ev.transitioned_filters(ctx)).rows
|
||||
}
|
||||
|
||||
/// Resolves a `ColumnName` argument to (table, column, column name).
|
||||
fn column_target(ev: &Evaluator<'_>, expr: &BoundExpr, name: &str) -> Result<(usize, usize, String), EvalError> {
|
||||
let model = ev.model();
|
||||
let (table, column) = match expr {
|
||||
BoundExpr::Column { table, column } => (*table, *column),
|
||||
BoundExpr::UnqualifiedColumn { name: column_name } => {
|
||||
let tables = model.tables_with_column(column_name);
|
||||
let table = match tables.as_slice() {
|
||||
[table] => *table,
|
||||
[] => return Err(EvalError::new(format!("{name} names the unknown column `[{column_name}]`"))),
|
||||
_ => return Err(EvalError::new(format!("{name} needs a qualified column; `[{column_name}]` is ambiguous"))),
|
||||
};
|
||||
let index =
|
||||
model.column_index(table, column_name).ok_or_else(|| EvalError::new(format!("{name} names the unknown column `[{column_name}]`")))?;
|
||||
(table, index)
|
||||
}
|
||||
_ => return Err(EvalError::new(format!("{name} needs a column reference"))),
|
||||
};
|
||||
let model_table = model.tables.get(table).ok_or_else(|| EvalError::new(format!("{name} needs a valid table")))?;
|
||||
let model_column = model_table.columns.get(column).ok_or_else(|| EvalError::new(format!("{name} needs a valid column")))?;
|
||||
Ok((table, column, model_column.name.clone()))
|
||||
}
|
||||
|
||||
fn number_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<f64, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))
|
||||
}
|
||||
|
||||
fn interval_count(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<i64, EvalError> {
|
||||
let value = number_arg(ev, args, index, ctx, name)?;
|
||||
if !value.is_finite() || value.abs() > MAX_INTERVALS {
|
||||
return Err(EvalError::new(format!("{name} interval count is out of range")));
|
||||
}
|
||||
Ok(value.trunc() as i64)
|
||||
}
|
||||
|
||||
fn interval_arg(
|
||||
ev: &Evaluator<'_>,
|
||||
args: &[BoundExpr],
|
||||
index: usize,
|
||||
ctx: &mut Context,
|
||||
name: &str,
|
||||
allow_day: bool,
|
||||
allow_week: bool,
|
||||
) -> Result<Interval, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
let text = value.to_text();
|
||||
match text.trim().to_ascii_uppercase().as_str() {
|
||||
"DAY" if allow_day => Ok(Interval::Day),
|
||||
"WEEK" if allow_week => Ok(Interval::Week),
|
||||
"MONTH" => Ok(Interval::Month),
|
||||
"QUARTER" => Ok(Interval::Quarter),
|
||||
"YEAR" => Ok(Interval::Year),
|
||||
other => Err(EvalError::new(format!("{name} does not support the interval `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A date argument that accepts BLANK (meaning "use the visible boundary").
|
||||
fn optional_date(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<f64>, EvalError> {
|
||||
let expr = args.get(index).ok_or_else(|| EvalError::new(format!("{name} is missing argument {}", index + 1)))?;
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
if value.is_blank() {
|
||||
return Ok(None);
|
||||
}
|
||||
date_value(&value).map(|serial| Some(serial.floor())).ok_or_else(|| EvalError::new(format!("{name} argument {} must be a date", index + 1)))
|
||||
}
|
||||
|
||||
fn year_end_arg(ev: &Evaluator<'_>, args: &[BoundExpr], index: usize, ctx: &mut Context, name: &str) -> Result<Option<(i64, i64)>, EvalError> {
|
||||
let Some(expr) = args.get(index) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
if value.is_blank() {
|
||||
return Ok(None);
|
||||
}
|
||||
year_end_parts(&value).map(Some).ok_or_else(|| EvalError::new(format!("{name} YearEndDate must be a date such as \"6/30/2024\"")))
|
||||
}
|
||||
|
||||
fn month_start(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
date_serial(year, month, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn month_end(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
date_serial(year, month, days_in_month(year, month), 0, 0, 0)
|
||||
}
|
||||
|
||||
fn quarter_start(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let first = (month - 1).div_euclid(3) * 3 + 1;
|
||||
date_serial(year, first, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn quarter_end(serial: f64) -> f64 {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let last = (month - 1).div_euclid(3) * 3 + 3;
|
||||
date_serial(year, last, days_in_month(year, last), 0, 0, 0)
|
||||
}
|
||||
|
||||
fn year_start(serial: f64) -> f64 {
|
||||
date_serial(date_parts(serial).0, 1, 1, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn week_start(serial: f64) -> f64 {
|
||||
// `date_weekday` uses the Excel WEEKDAY convention: Sunday = 1 ... Saturday = 7.
|
||||
serial.floor() - (date_weekday(serial) - 1) as f64
|
||||
}
|
||||
|
||||
fn week_end(serial: f64) -> f64 {
|
||||
week_start(serial) + 6.0
|
||||
}
|
||||
|
||||
/// End of the period (month/quarter/year) containing a date; day and week intervals are whole
|
||||
/// numbers of days, so their aligned end is the date itself.
|
||||
fn align_end(serial: f64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day | Interval::Week => serial.floor(),
|
||||
Interval::Month => month_end(serial),
|
||||
Interval::Quarter => quarter_end(serial),
|
||||
Interval::Year => year_end_default(serial),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start of the period (month/quarter/year) containing a date.
|
||||
fn align_start(serial: f64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day | Interval::Week => serial.floor(),
|
||||
Interval::Month => month_start(serial),
|
||||
Interval::Quarter => quarter_start(serial),
|
||||
Interval::Year => year_start(serial),
|
||||
}
|
||||
}
|
||||
|
||||
fn year_end_default(serial: f64) -> f64 {
|
||||
date_serial(date_parts(serial).0, 12, 31, 0, 0, 0)
|
||||
}
|
||||
|
||||
fn shift(serial: f64, count: i64, interval: Interval) -> f64 {
|
||||
match interval {
|
||||
Interval::Day => serial + count as f64,
|
||||
Interval::Week => serial + 7.0 * count as f64,
|
||||
Interval::Month => edate(serial, count),
|
||||
Interval::Quarter => edate(serial, count.saturating_mul(3)),
|
||||
Interval::Year => edate(serial, count.saturating_mul(12)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last day of a fiscal year that starts the day after the previous year's end date.
|
||||
fn fiscal_end(year: i64, month: i64, day: i64) -> f64 {
|
||||
date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0)
|
||||
}
|
||||
|
||||
/// The (start, end) of the fiscal year containing `serial`; the default year ends December 31.
|
||||
fn fiscal_bounds(serial: f64, year_end: Option<(i64, i64)>) -> (f64, f64) {
|
||||
let (month, day) = year_end.unwrap_or((12, 31));
|
||||
let (year, _, _) = date_parts(serial);
|
||||
let end_this_year = fiscal_end(year, month, day);
|
||||
let end_year = if serial.floor() <= end_this_year { year } else { year + 1 };
|
||||
let end = fiscal_end(end_year, month, day);
|
||||
let start = fiscal_end(end_year - 1, month, day) + 1.0;
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// The previous calendar month's window.
|
||||
fn previous_month(serial: f64) -> (f64, f64) {
|
||||
let last = month_start(serial) - 1.0;
|
||||
(month_start(last), last)
|
||||
}
|
||||
|
||||
fn next_month(serial: f64) -> (f64, f64) {
|
||||
let first = month_end(serial) + 1.0;
|
||||
(first, month_end(first))
|
||||
}
|
||||
|
||||
fn previous_quarter(serial: f64) -> (f64, f64) {
|
||||
let last = quarter_start(serial) - 1.0;
|
||||
(quarter_start(last), last)
|
||||
}
|
||||
|
||||
fn next_quarter(serial: f64) -> (f64, f64) {
|
||||
let first = quarter_end(serial) + 1.0;
|
||||
(first, quarter_end(first))
|
||||
}
|
||||
|
||||
fn previous_week(serial: f64) -> (f64, f64) {
|
||||
let last = week_start(serial) - 1.0;
|
||||
(week_start(last), last)
|
||||
}
|
||||
|
||||
fn next_week(serial: f64) -> (f64, f64) {
|
||||
let first = week_end(serial) + 1.0;
|
||||
(first, week_end(first))
|
||||
}
|
||||
|
||||
fn compute_table(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
let dates_expr = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a date column")))?;
|
||||
let axis = date_axis(ev, dates_expr, ctx, name)?;
|
||||
|
||||
match name {
|
||||
"FIRSTDATE" => Ok(axis.first()),
|
||||
"LASTDATE" => Ok(axis.last()),
|
||||
"DATEADD" => {
|
||||
// Arguments 4/5 (Extension/Truncation) exist only for model calendars. GridCraft has
|
||||
// no calendar objects, so the date-column rules always apply: a selection that ends on
|
||||
// the last day of a period extends to the end of the shifted period, and day positions
|
||||
// that do not exist in the target month move to its last day (dax.guide/DATEADD).
|
||||
let count = interval_count(ev, args, 1, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 2, ctx, name, true, false)?;
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
axis.require_contiguous(name)?;
|
||||
let start = shift(min, count, interval);
|
||||
let mut end = shift(max, count, interval);
|
||||
// A selection that covers a whole period selects the whole target period. A selection
|
||||
// that contains both of the last two days of its month (but not the whole period)
|
||||
// still reaches the end of the shifted month, so a full February shifted by a year
|
||||
// keeps February 29: "if the Dates argument includes all the days in April (30 rows),
|
||||
// the result for the previous month includes all the days in March (31 days)"
|
||||
// (dax.guide/DATEADD).
|
||||
let month_edge = axis.includes_last_two_days(max);
|
||||
if align_start(min, interval) == min && align_end(max, interval).floor() == max {
|
||||
// The selection covers a whole period: the shift covers the whole target period.
|
||||
end = align_end(end, interval);
|
||||
} else if month_edge && matches!(interval, Interval::Month | Interval::Quarter | Interval::Year) {
|
||||
// It runs to the end of its month instead: the shift reaches the end of the
|
||||
// target month (a full February shifted by a year keeps February 29).
|
||||
end = month_end(end);
|
||||
}
|
||||
Ok(axis.table(start.min(end), start.max(end)))
|
||||
}
|
||||
"DATESBETWEEN" => {
|
||||
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
|
||||
let end = optional_date(ev, args, 2, ctx, name)?.or(axis.max);
|
||||
match (start, end) {
|
||||
(Some(start), Some(end)) => Ok(axis.table(start, end)),
|
||||
_ => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"DATESINPERIOD" => {
|
||||
let start = optional_date(ev, args, 1, ctx, name)?.or(axis.min);
|
||||
let count = interval_count(ev, args, 2, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 3, ctx, name, true, true)?;
|
||||
let aligned = match args.get(4) {
|
||||
Some(expr) => {
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
match value.to_text().trim().to_ascii_uppercase().as_str() {
|
||||
"ENDALIGNED" => true,
|
||||
"" | "PRECISE" => false,
|
||||
other => return Err(EvalError::new(format!("{name} does not support the EndBehavior `{other}`"))),
|
||||
}
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
let Some(start) = start else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
if count == 0 {
|
||||
return Ok(axis.empty());
|
||||
}
|
||||
let mut boundary = shift(start, count, interval);
|
||||
if aligned && align_end(start, interval).floor() == start.floor() {
|
||||
boundary = align_end(boundary, interval);
|
||||
}
|
||||
let (low, high) = if count > 0 { (start, boundary - 1.0) } else { (boundary + 1.0, start) };
|
||||
Ok(axis.table(low, high))
|
||||
}
|
||||
"DATESMTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(month_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESQTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(quarter_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESWTD" => match axis.max {
|
||||
Some(max) => Ok(axis.table(week_start(max), max)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"DATESYTD" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, _) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.table(start, max))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"ENDOFMONTH" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(month_start(max), month_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFQUARTER" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(quarter_start(max), quarter_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFWEEK" => match axis.max {
|
||||
Some(max) => Ok(axis.last_in(week_start(max), week_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"ENDOFYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.last_in(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"NEXTDAY" => match axis.max {
|
||||
Some(max) => Ok(axis.single(max + 1.0, true)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSDAY" => match axis.min {
|
||||
Some(min) => Ok(axis.single(min - 1.0, true)),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTMONTH" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_month(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSMONTH" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_month(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTQUARTER" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_quarter(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSQUARTER" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_quarter(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTWEEK" => match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = next_week(max);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"PREVIOUSWEEK" => match axis.min {
|
||||
Some(min) => {
|
||||
let (start, end) = previous_week(min);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"NEXTYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (_, end) = fiscal_bounds(max, year_end);
|
||||
let (start, next_end) = fiscal_bounds(end + 1.0, year_end);
|
||||
Ok(axis.table(start, next_end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"PREVIOUSYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.min {
|
||||
Some(min) => {
|
||||
let (start, _) = fiscal_bounds(min, year_end);
|
||||
let (previous_start, previous_end) = fiscal_bounds(start - 1.0, year_end);
|
||||
Ok(axis.table(previous_start, previous_end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
"PARALLELPERIOD" => {
|
||||
let count = interval_count(ev, args, 1, ctx, name)?;
|
||||
let interval = interval_arg(ev, args, 2, ctx, name, false, false)?;
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
let start = align_start(shift(min, count, interval), interval);
|
||||
let end = align_end(shift(max, count, interval), interval);
|
||||
Ok(axis.table(start, end))
|
||||
}
|
||||
"SAMEPERIODLASTYEAR" => {
|
||||
let Some((min, max)) = axis.visible() else {
|
||||
return Ok(axis.empty());
|
||||
};
|
||||
let start = edate(min, -12);
|
||||
let mut end = edate(max, -12);
|
||||
// It is `DATEADD(Dates, -1, YEAR)`: a selection containing the last two days of its
|
||||
// month reaches the end of the shifted month, leap day included.
|
||||
if axis.includes_last_two_days(max) {
|
||||
end = month_end(end);
|
||||
}
|
||||
Ok(axis.table(start.min(end), start.max(end)))
|
||||
}
|
||||
"STARTOFMONTH" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(month_start(max), month_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFQUARTER" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(quarter_start(max), quarter_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFWEEK" => match axis.max {
|
||||
Some(max) => Ok(axis.first_in(week_start(max), week_end(max))),
|
||||
None => Ok(axis.empty()),
|
||||
},
|
||||
"STARTOFYEAR" => {
|
||||
let year_end = year_end_arg(ev, args, 1, ctx, name)?;
|
||||
match axis.max {
|
||||
Some(max) => {
|
||||
let (start, end) = fiscal_bounds(max, year_end);
|
||||
Ok(axis.first_in(start, end))
|
||||
}
|
||||
None => Ok(axis.empty()),
|
||||
}
|
||||
}
|
||||
_ => Err(EvalError::new(format!("DAX function `{name}` is not implemented by this evaluator"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_blank_scalar(value: &Scalar) -> bool {
|
||||
value.is_blank() || matches!(value, Scalar::String(text) if text.is_empty())
|
||||
}
|
||||
|
||||
/// `FIRSTNONBLANK`/`LASTNONBLANK`: walk the visible values of the column in sort order and return
|
||||
/// the value whose accompanying expression is not blank.
|
||||
fn nonblank(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<TableValue, EvalError> {
|
||||
let name = if first { "FIRSTNONBLANK" } else { "LASTNONBLANK" };
|
||||
let target = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
|
||||
let expression = args.get(1).ok_or_else(|| EvalError::new(format!("{name} needs a value expression")))?;
|
||||
let (table, column, column_name) = column_target(ev, target, name)?;
|
||||
|
||||
let visible = visible_rows(ev, table, ctx);
|
||||
let mut entries: Vec<(ScalarKey, Scalar)> = Vec::new();
|
||||
let mut seen: BTreeSet<ScalarKey> = BTreeSet::new();
|
||||
for row in &visible {
|
||||
if let Some(value) = row.get(column) {
|
||||
let key = ScalarKey::from(value);
|
||||
if seen.insert(key.clone()) {
|
||||
entries.push((key, value.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
entries.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
if !first {
|
||||
entries.reverse();
|
||||
}
|
||||
|
||||
for (key, value) in entries {
|
||||
let previous = ctx.filters.filters.get(&(table, column)).cloned();
|
||||
// `FilterContext::set` folds the key the same way the filter's `matches` does, so a
|
||||
// mixed-case text candidate still selects its rows.
|
||||
ctx.filters.set(table, column, [key]);
|
||||
// The row context is `VALUES(column)`, not one model row: a measure's context transition
|
||||
// must keep every row that shares the candidate value.
|
||||
ctx.rows.push(derived_row_frame(Some(table), vec![column_name.clone()], vec![value.clone()], vec![Some(column)]));
|
||||
let evaluated = ev.eval(expression, ctx);
|
||||
ctx.rows.pop();
|
||||
match previous {
|
||||
Some(values) => {
|
||||
ctx.filters.set(table, column, values);
|
||||
}
|
||||
None => {
|
||||
ctx.filters.filters.remove(&(table, column));
|
||||
}
|
||||
}
|
||||
if !is_blank_scalar(&evaluated?) {
|
||||
return Ok(TableValue::new(vec![TableColumn { name: column_name }], vec![vec![value]]).with_lineage(table));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(TableValue::new(vec![TableColumn { name: column_name }], Vec::new()).with_lineage(table))
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Time-intelligence scalar totals and balance functions.
|
||||
//!
|
||||
//! `TOTAL*` are CALCULATE sugar: the expression is evaluated over a period-to-date window
|
||||
//! derived from the last date visible on the date column. `OPENINGBALANCE*`/`CLOSINGBALANCE*`
|
||||
//! evaluate the expression on the period's boundary date (the last date, or the day before the
|
||||
//! first), matching Excel's `CALCULATE(<expr>, ENDOF.../PREVIOUSDAY(STARTOF...))` definitions.
|
||||
//!
|
||||
//! The window is applied as a filter on the date column. Like the table filter produced by
|
||||
//! `DATESMTD`/`ENDOFMONTH` inside CALCULATE, it replaces the existing filters on the date table
|
||||
//! (otherwise a matrix row filtered by month could never accumulate a quarter or a year) while
|
||||
//! filters on other tables keep applying. When the date column is a fact table's own date rather
|
||||
//! than a date dimension key, only that column's filter is replaced and the fact table's other
|
||||
//! filters keep applying — the same rows `CALCULATE (<expr>, DATESYTD (<date>))` would see.
|
||||
//!
|
||||
//! Week periods follow DAX's Sunday-first convention (`STARTOFWEEK`); the optional
|
||||
//! `YearEndDate` argument only contributes its month and day, as documented for `TOTALYTD`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::ast::BinaryOp;
|
||||
use crate::value::ScalarKey;
|
||||
|
||||
use super::super::support::{date_parts, date_serial, date_value, date_weekday, days_in_month, eomonth};
|
||||
use super::*;
|
||||
|
||||
/// The calendar period a total or a balance slice is anchored to.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Period {
|
||||
Month,
|
||||
Quarter,
|
||||
Week,
|
||||
Year,
|
||||
}
|
||||
|
||||
/// A resolved date column: the table it belongs to and its column index.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DateColumn {
|
||||
table: usize,
|
||||
column: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let result = match name.to_ascii_uppercase().as_str() {
|
||||
"TOTALMTD" => total(ev, name, args, ctx, Period::Month),
|
||||
"TOTALQTD" => total(ev, name, args, ctx, Period::Quarter),
|
||||
"TOTALWTD" => total(ev, name, args, ctx, Period::Week),
|
||||
"TOTALYTD" => total(ev, name, args, ctx, Period::Year),
|
||||
"OPENINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, true),
|
||||
"OPENINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, true),
|
||||
"OPENINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, true),
|
||||
"OPENINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, true),
|
||||
"CLOSINGBALANCEMONTH" => balance(ev, name, args, ctx, Period::Month, false),
|
||||
"CLOSINGBALANCEQUARTER" => balance(ev, name, args, ctx, Period::Quarter, false),
|
||||
"CLOSINGBALANCEWEEK" => balance(ev, name, args, ctx, Period::Week, false),
|
||||
"CLOSINGBALANCEYEAR" => balance(ev, name, args, ctx, Period::Year, false),
|
||||
"FIRSTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, true),
|
||||
"LASTNONBLANKVALUE" => non_blank_value(ev, name, args, ctx, false),
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// `TOTALMTD`/`TOTALQTD`/`TOTALWTD`/`TOTALYTD`.
|
||||
fn total(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period) -> Result<Scalar, EvalError> {
|
||||
let max = if period == Period::Year { 4 } else { 3 };
|
||||
if args.len() < 2 || args.len() > max {
|
||||
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
|
||||
}
|
||||
// These functions are CALCULATE sugar: the row context transitions to filters first, and the
|
||||
// expression then runs without row frames, so a measure argument cannot re-transition the
|
||||
// window away.
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let dates = date_column(ev, &args[1])?;
|
||||
let visible = visible_dates(ev, dates, &base);
|
||||
let Some(last) = visible.last().copied() else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
|
||||
let (start, _) = period_bounds(period, last, year_end);
|
||||
|
||||
let mut filters = date_table_filters(ev, &base, dates);
|
||||
if let Some(filter) = args.get(2) {
|
||||
apply_filter_arg(ev, filter, &mut filters, ctx)?;
|
||||
}
|
||||
// The window only keeps dates that exist in the date column, exactly like DATESMTD/YTD; the
|
||||
// keys use the column's own values so an untyped date column still matches its rows.
|
||||
let window = dates_between(ev, dates, start, last);
|
||||
// `TOTALYTD` is `CALCULATE(expr, DATESYTD(dates), filter)`: a filter argument on the date
|
||||
// column intersects the window instead of being replaced by it.
|
||||
let window: BTreeSet<ScalarKey> = window.iter().map(|(_, value)| ScalarKey::from(value)).collect();
|
||||
let keys = match filters.filters.get(&(dates.table, dates.column)) {
|
||||
Some(existing) => existing.intersection(&window).cloned().collect(),
|
||||
None => window,
|
||||
};
|
||||
filters.set(dates.table, dates.column, keys);
|
||||
let mut inner = nested_context(filters, ctx);
|
||||
ev.eval(&args[0], &mut inner)
|
||||
}
|
||||
|
||||
/// `OPENINGBALANCE*`/`CLOSINGBALANCE*`: `CALCULATE(<expression>, <boundary date>)`.
|
||||
///
|
||||
/// Excel defines the closing balance on the last date of the period and the opening balance on
|
||||
/// the day before the first date (`PREVIOUSDAY(STARTOF...)`). The expression is evaluated with a
|
||||
/// single-date filter, so a boundary date without data yields BLANK — including on sparse fact
|
||||
/// tables, where a "last date with a value" scan would invent a value Excel does not return.
|
||||
fn balance(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, period: Period, opening: bool) -> Result<Scalar, EvalError> {
|
||||
let max = if period == Period::Year { 4 } else { 3 };
|
||||
if args.len() < 2 || args.len() > max {
|
||||
return Err(EvalError::new(format!("{name} expects between 2 and {max} arguments")));
|
||||
}
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let dates = date_column(ev, &args[1])?;
|
||||
let visible = visible_dates(ev, dates, &base);
|
||||
let Some(last) = visible.last().copied() else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
let year_end = if period == Period::Year && args.len() >= 4 { Some(year_end_serial(ev, &args[3], ctx)?) } else { None };
|
||||
let (start, end) = period_bounds(period, last, year_end);
|
||||
// Every cell of the boundary day, not one per day: a fact date column can hold several
|
||||
// timestamps that share a day, and all of them belong to the period's boundary.
|
||||
let boundary = if opening {
|
||||
// PREVIOUSDAY(STARTOF...): the stored cells of the day before the period, when they exist.
|
||||
let day = start.floor() - 1.0;
|
||||
dates_between(ev, dates, day, day)
|
||||
} else {
|
||||
// `ENDOF*` is the last day that exists in the column, not the calendar end of the period.
|
||||
let window = dates_between(ev, dates, start, end);
|
||||
let Some(boundary_day) = window.last().map(|(date, _)| *date) else {
|
||||
return Ok(Scalar::Blank);
|
||||
};
|
||||
window.into_iter().filter(|(date, _)| *date == boundary_day).collect()
|
||||
};
|
||||
if boundary.is_empty() {
|
||||
return Ok(Scalar::Blank);
|
||||
}
|
||||
let boundary_keys: BTreeSet<ScalarKey> = boundary.iter().map(|(_, value)| ScalarKey::from(value)).collect();
|
||||
|
||||
let mut filters = date_table_filters(ev, &base, dates);
|
||||
if let Some(filter) = args.get(2) {
|
||||
apply_filter_arg(ev, filter, &mut filters, ctx)?;
|
||||
}
|
||||
let keys = match filters.filters.get(&(dates.table, dates.column)) {
|
||||
Some(existing) => existing.intersection(&boundary_keys).cloned().collect(),
|
||||
None => boundary_keys,
|
||||
};
|
||||
filters.set(dates.table, dates.column, keys);
|
||||
let mut inner = nested_context(filters, ctx);
|
||||
ev.eval(&args[0], &mut inner)
|
||||
}
|
||||
|
||||
/// `FIRSTNONBLANKVALUE`/`LASTNONBLANKVALUE`: the expression value at the first (last) visible
|
||||
/// value of the column whose expression result is not blank.
|
||||
fn non_blank_value(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context, first: bool) -> Result<Scalar, EvalError> {
|
||||
if args.len() != 2 {
|
||||
return Err(EvalError::new(format!("{name} expects 2 arguments")));
|
||||
}
|
||||
// CALCULATE sugar, like `TOTAL*`: the row context transitions to filters first, and the
|
||||
// expression runs with no row frames so a measure argument cannot re-transition the candidate
|
||||
// filter away.
|
||||
let base = ev.transitioned_filters(ctx);
|
||||
let (table, column) = column_reference(ev, &args[0])?;
|
||||
let source = ev.table(table, &base);
|
||||
let values = source.column(column);
|
||||
let keys: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(ScalarKey::from).collect();
|
||||
let ordered: Vec<ScalarKey> = if first { keys.into_iter().collect() } else { keys.into_iter().rev().collect() };
|
||||
let mut inner = nested_context(base, ctx);
|
||||
for key in ordered {
|
||||
inner.filters.set(table, column, [key]);
|
||||
let value = ev.eval(&args[1], &mut inner)?;
|
||||
if !value.is_blank() {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
Ok(Scalar::Blank)
|
||||
}
|
||||
|
||||
/// Resolves a date-column argument. The week functions in the catalog take a calendar/table
|
||||
/// reference, so a table argument is accepted too and its date column is chosen the same way
|
||||
/// `ranges::date_axis` chooses one: a column whose declared type is a date type first, a column
|
||||
/// named `Date` only as the fallback. An untyped column is never preferred over a typed one.
|
||||
fn date_column(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<DateColumn, EvalError> {
|
||||
if let BoundExpr::Table(table) = expr {
|
||||
let Some(model_table) = ev.model().tables.get(*table) else {
|
||||
return Err(EvalError::new("the date table is out of range"));
|
||||
};
|
||||
let column = table_date_column(model_table).ok_or_else(|| EvalError::new(format!("table `{}` has no date column", model_table.name)))?;
|
||||
return Ok(DateColumn { table: *table, column });
|
||||
}
|
||||
let (table, column) = column_reference(ev, expr)?;
|
||||
let Some(model_table) = ev.model().tables.get(table) else {
|
||||
return Err(EvalError::new("the date table is out of range"));
|
||||
};
|
||||
let Some(model_column) = model_table.columns.get(column) else {
|
||||
return Err(EvalError::new("the date column is out of range"));
|
||||
};
|
||||
if !is_date_column(model_column.data_type.as_deref()) {
|
||||
return Err(EvalError::new(format!("`{}`[{}] is not a date column", model_table.name, model_column.name)));
|
||||
}
|
||||
Ok(DateColumn { table, column })
|
||||
}
|
||||
|
||||
/// Resolves a plain column argument without a type restriction.
|
||||
fn column_reference(ev: &Evaluator<'_>, expr: &BoundExpr) -> Result<(usize, usize), EvalError> {
|
||||
match expr {
|
||||
BoundExpr::Column { table, column } => {
|
||||
let Some(model_table) = ev.model().tables.get(*table) else {
|
||||
return Err(EvalError::new("the column's table is out of range"));
|
||||
};
|
||||
if model_table.columns.get(*column).is_none() {
|
||||
return Err(EvalError::new("the column is out of range"));
|
||||
}
|
||||
Ok((*table, *column))
|
||||
}
|
||||
BoundExpr::UnqualifiedColumn { name } => {
|
||||
let tables = ev.model().tables_with_column(name);
|
||||
let [table] = tables.as_slice() else {
|
||||
return Err(EvalError::new(format!("column `[{name}]` is ambiguous or not in the model")));
|
||||
};
|
||||
let column = ev.model().column_index(*table, name).ok_or_else(|| EvalError::new(format!("column `[{name}]` is not in the model")))?;
|
||||
Ok((*table, column))
|
||||
}
|
||||
_ => Err(EvalError::new("this function needs a column reference")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The date values visible in the current filter context. Filters propagate to the date table
|
||||
/// only along bidirectional relationships, which `Evaluator::table` already models; filters on
|
||||
/// the fact table of a single-direction date relationship must not shrink the calendar.
|
||||
fn visible_dates(ev: &Evaluator<'_>, dates: DateColumn, filters: &FilterContext) -> Vec<f64> {
|
||||
let table = ev.table(dates.table, filters);
|
||||
let values: Vec<f64> = table.column(dates.column).iter().filter_map(date_value).collect();
|
||||
normalized(values)
|
||||
}
|
||||
|
||||
/// The dates of the column in `[start, end]`, each with the column's own value so a filter built
|
||||
/// from them matches the stored cells even when the column has no declared date type. Serials are
|
||||
/// rounded down to their day, so a DateTime cell that carries a time of day still matches the
|
||||
/// whole-day bounds; every cell of a day is kept, because the filter keys are the exact cell
|
||||
/// values and a day may hold more than one timestamp.
|
||||
fn dates_between(ev: &Evaluator<'_>, dates: DateColumn, start: f64, end: f64) -> Vec<(f64, Scalar)> {
|
||||
let Some(model_table) = ev.model().tables.get(dates.table) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut values: Vec<(f64, Scalar)> = model_table
|
||||
.rows
|
||||
.iter()
|
||||
.filter_map(|row| row.get(dates.column).map(|value| (value, date_value(value))))
|
||||
.filter_map(|(value, serial)| serial.filter(|serial| serial.is_finite()).map(|serial| (serial.floor(), value.clone())))
|
||||
.filter(|(date, _)| *date >= start - 1e-9 && *date <= end + 1e-9)
|
||||
.collect();
|
||||
values.sort_by(|left, right| left.0.total_cmp(&right.0));
|
||||
values
|
||||
}
|
||||
|
||||
/// Sorts ascending and drops duplicate days.
|
||||
fn normalized(mut dates: Vec<f64>) -> Vec<f64> {
|
||||
dates.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
dates.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
dates
|
||||
}
|
||||
|
||||
/// The context a `TOTAL*`/`BALANCE*`/`NONBLANKVALUE` expression runs in: the window's filters with
|
||||
/// no row frames, carrying the caller's variables and grouping scope. A measure evaluated inside a
|
||||
/// `SUMMARIZE`/`SUMMARIZECOLUMNS` group must still see the group's scope (`ISINSCOPE`), so the scope
|
||||
/// is propagated rather than reset.
|
||||
fn nested_context(filters: FilterContext, ctx: &Context) -> Context {
|
||||
Context { filters, rows: Vec::new(), vars: ctx.vars.clone(), grouping_scope: ctx.grouping_scope.clone() }
|
||||
}
|
||||
|
||||
/// Removes the filters the computed window replaces. A date dimension key replaces every filter on
|
||||
/// the whole date table; any other date column (a fact table's own date) replaces only that
|
||||
/// column's filter, so the fact table keeps its other slices.
|
||||
fn date_table_filters(ev: &Evaluator<'_>, filters: &FilterContext, dates: DateColumn) -> FilterContext {
|
||||
let model = ev.model();
|
||||
let is_dimension_key = model.relationships.iter().any(|relationship| {
|
||||
model.table_index(&relationship.to_table) == Some(dates.table)
|
||||
&& model.column_index(dates.table, &relationship.to_column) == Some(dates.column)
|
||||
});
|
||||
let mut filters = filters.clone();
|
||||
if is_dimension_key {
|
||||
filters.filters.retain(|(table, _), _| *table != dates.table);
|
||||
} else {
|
||||
filters.filters.remove(&(dates.table, dates.column));
|
||||
}
|
||||
filters
|
||||
}
|
||||
|
||||
/// The first and last day of the period containing `anchor`.
|
||||
fn period_bounds(period: Period, anchor: f64, year_end: Option<f64>) -> (f64, f64) {
|
||||
let anchor = anchor.floor();
|
||||
let (year, month, _) = date_parts(anchor);
|
||||
match period {
|
||||
Period::Month => (date_serial(year, month, 1, 0, 0, 0), eomonth(anchor, 0)),
|
||||
Period::Quarter => {
|
||||
let first_month = (month - 1) / 3 * 3 + 1;
|
||||
let start = date_serial(year, first_month, 1, 0, 0, 0);
|
||||
(start, eomonth(start, 2))
|
||||
}
|
||||
Period::Week => {
|
||||
// WEEKDAY numbers are Sunday = 1 ... Saturday = 7.
|
||||
let start = anchor - (date_weekday(anchor) - 1) as f64;
|
||||
(start, start + 6.0)
|
||||
}
|
||||
Period::Year => match year_end {
|
||||
Some(year_end) => fiscal_bounds(anchor, year_end),
|
||||
None => (date_serial(year, 1, 1, 0, 0, 0), date_serial(year, 12, 31, 0, 0, 0)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The fiscal year containing `anchor` for a year-end month/day. The year-end date itself
|
||||
/// belongs to the fiscal year that ends on it.
|
||||
fn fiscal_bounds(anchor: f64, year_end: f64) -> (f64, f64) {
|
||||
let (_, end_month, end_day) = date_parts(year_end);
|
||||
let (year, _, _) = date_parts(anchor);
|
||||
let year_end_in = |year: i64| date_serial(year, end_month, end_day.min(days_in_month(year, end_month)), 0, 0, 0);
|
||||
let end_this_year = year_end_in(year);
|
||||
if anchor <= end_this_year + 1e-9 { (year_end_in(year - 1) + 1.0, end_this_year) } else { (end_this_year + 1.0, year_end_in(year + 1)) }
|
||||
}
|
||||
|
||||
/// Evaluates the optional `YearEndDate` argument. Only its month and day matter.
|
||||
fn year_end_serial(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<f64, EvalError> {
|
||||
let value = ev.eval(expr, ctx)?;
|
||||
let serial = parse_year_end(&value).ok_or_else(|| EvalError::new("YearEndDate must be a date"))?;
|
||||
if !serial.is_finite() {
|
||||
return Err(EvalError::new("YearEndDate must be a date"));
|
||||
}
|
||||
Ok(serial.floor())
|
||||
}
|
||||
|
||||
/// Parses a year-end date. Unlike `parse_date_text`, this accepts the `M/D/YYYY` form used in
|
||||
/// Parses a year-end date through the shared parser, then pins it to a leap year: only the month
|
||||
/// and day are used, so `"6/30/2008"` and `"6/30"` name the same fiscal year end.
|
||||
fn parse_year_end(value: &Scalar) -> Option<f64> {
|
||||
let (month, day) = super::year_end_parts(value)?;
|
||||
Some(date_serial(2000, month, day, 0, 0, 0))
|
||||
}
|
||||
|
||||
/// Applies one CALCULATE-style filter argument to `filters`, the way the core CALCULATE does:
|
||||
/// column predicate, `ALL`/`REMOVEFILTERS` (no argument, column or table), or a table expression
|
||||
/// over a model table. Removal runs before the period window is applied, so the window still
|
||||
/// lands even when the modifier cleared the date table's own filters.
|
||||
fn apply_filter_arg(ev: &Evaluator<'_>, expr: &BoundExpr, filters: &mut FilterContext, ctx: &mut Context) -> Result<(), EvalError> {
|
||||
match expr {
|
||||
BoundExpr::Binary { op, left, right }
|
||||
if matches!(op, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge)
|
||||
&& matches!(**left, BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) =>
|
||||
{
|
||||
let (table, column) = column_reference(ev, left)?;
|
||||
let value = ev.eval(right, ctx)?;
|
||||
// `col <op> v` is FILTER(ALL(col), …): the candidates come from the whole column and
|
||||
// compare with DAX semantics (numeric across types, text ignoring case).
|
||||
use std::cmp::Ordering::{Equal, Greater, Less};
|
||||
let keep = |candidate: &Scalar| {
|
||||
let order = candidate.compare(&value);
|
||||
match op {
|
||||
BinaryOp::Eq => order == Some(Equal),
|
||||
BinaryOp::Ne => order != Some(Equal),
|
||||
BinaryOp::Lt => order == Some(Less),
|
||||
BinaryOp::Le => matches!(order, Some(Less | Equal)),
|
||||
BinaryOp::Gt => order == Some(Greater),
|
||||
_ => matches!(order, Some(Greater | Equal)),
|
||||
}
|
||||
};
|
||||
let keys = ev
|
||||
.table(table, &FilterContext::default())
|
||||
.column(column)
|
||||
.into_iter()
|
||||
.filter(|candidate| keep(candidate))
|
||||
.map(|candidate| ScalarKey::from(&candidate));
|
||||
filters.set(table, column, keys);
|
||||
Ok(())
|
||||
}
|
||||
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("ALL") || spec.name.eq_ignore_ascii_case("REMOVEFILTERS") => {
|
||||
match args.first() {
|
||||
// No argument removes every filter: `ALL ()` is `ALL(<every table>)`.
|
||||
None => filters.clear(),
|
||||
// A column argument clears only that column; a table argument clears the table.
|
||||
// Unqualified columns resolve to the single model column with that name.
|
||||
Some(BoundExpr::Column { .. } | BoundExpr::UnqualifiedColumn { .. }) => {
|
||||
for arg in args {
|
||||
let (table, column) = column_reference(ev, arg)?;
|
||||
filters.filters.remove(&(table, column));
|
||||
}
|
||||
}
|
||||
Some(BoundExpr::Table(table)) => filters.remove_table(*table),
|
||||
Some(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
BoundExpr::Call { spec, args } if spec.name.eq_ignore_ascii_case("KEEPFILTERS") => {
|
||||
// KEEPFILTERS applies its inner filter and intersects it with what is already there.
|
||||
let inner = args.first().ok_or_else(|| EvalError::new("KEEPFILTERS needs a filter"))?;
|
||||
let mut applied = filters.clone();
|
||||
apply_filter_arg(ev, inner, &mut applied, ctx)?;
|
||||
for (key, values) in applied.filters {
|
||||
let merged = match filters.filters.get(&key) {
|
||||
Some(existing) => existing.intersection(&values).cloned().collect(),
|
||||
None => values,
|
||||
};
|
||||
filters.filters.insert(key, merged);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
let table = ev.eval_table(expr, ctx)?;
|
||||
let Some(index) = table.lineage else {
|
||||
return Err(EvalError::new("a filter table needs a source table"));
|
||||
};
|
||||
for (position, column) in table.columns.iter().enumerate() {
|
||||
let Some(model_column) = ev.model().column_index(index, &column.name) else { continue };
|
||||
let keys: BTreeSet<ScalarKey> = table.rows.iter().filter_map(|row| row.get(position)).map(ScalarKey::from).collect();
|
||||
filters.set(index, model_column, keys);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nested_context_keeps_the_grouping_scope() {
|
||||
// A date total called from inside a `SUMMARIZE` group runs its expression in a nested
|
||||
// context; the group's scope has to survive so `ISINSCOPE` still sees the group.
|
||||
let ctx = Context {
|
||||
filters: FilterContext::default(),
|
||||
rows: Vec::new(),
|
||||
vars: vec![Scalar::Integer(7)],
|
||||
grouping_scope: Some(vec![(0, 1), (0, 2)]),
|
||||
};
|
||||
let inner = nested_context(FilterContext::default(), &ctx);
|
||||
assert_eq!(inner.grouping_scope, Some(vec![(0, 1), (0, 2)]));
|
||||
assert_eq!(inner.vars, vec![Scalar::Integer(7)]);
|
||||
assert!(inner.rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_context_starts_outside_any_group() {
|
||||
// The same call outside a grouping has no scope to carry.
|
||||
let ctx = Context { filters: FilterContext::default(), rows: Vec::new(), vars: Vec::new(), grouping_scope: None };
|
||||
assert_eq!(nested_context(FilterContext::default(), &ctx).grouping_scope, None);
|
||||
}
|
||||
}
|
||||
@@ -242,11 +242,55 @@ fn an_interval_keyword_is_not_shadowed_by_a_variable() {
|
||||
let bound = bind(&model, "VAR YEAR = 1 RETURN DATEDIFF ( Sales[Amount], Sales[Amount], YEAR )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
|
||||
// `DATEADD`'s interval is catalogued as text, but it is the same documented enumeration: a
|
||||
// variable holding another interval must not replace it.
|
||||
let bound = bind(&model, "VAR MONTH = \"DAY\" RETURN DATEADD ( Sales[Amount], 1, MONTH )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"MONTH\")"), "{debug}");
|
||||
// `DATESINPERIOD`'s fourth argument is the same documented enumeration, including `WEEK`,
|
||||
// which `DATEADD` does not accept.
|
||||
for interval in ["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"] {
|
||||
let formula = format!("VAR {interval} = \"DAY\" RETURN DATESINPERIOD ( Date[Date], Date[Date], -1, {interval} )");
|
||||
let bound = bind(&model, &formula);
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
|
||||
}
|
||||
// `PARALLELPERIOD`'s third argument is the month-boundary enumeration: a variable holding
|
||||
// `YEAR` must not turn `-1, MONTH` into a year shift.
|
||||
for interval in ["MONTH", "QUARTER", "YEAR"] {
|
||||
let formula = format!("VAR {interval} = \"YEAR\" RETURN PARALLELPERIOD ( Date[Date], -1, {interval} )");
|
||||
let bound = bind(&model, &formula);
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains(&format!("Keyword(\"{interval}\")")), "{formula}: {debug}");
|
||||
}
|
||||
// A variable still wins where the parameter is documented as text: RANKX's Ties argument.
|
||||
let bound = bind(&model, "VAR DENSE = 1 RETURN RANKX ( Sales, Sales[Amount], 42, DENSE )");
|
||||
assert!(format!("{bound:?}").contains("Variable"), "{bound:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interval_keyword_is_not_shadowed_by_a_model_name() {
|
||||
let mut model = sample_model();
|
||||
model.tables.push(ModelTable {
|
||||
name: "YEAR".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![],
|
||||
});
|
||||
// A model table called `YEAR` is not the interval: `DATEADD` must still bind the keyword.
|
||||
let bound = bind(&model, "DATEADD ( Sales[Amount], 1, YEAR )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
|
||||
// A position that does not take an interval keyword still resolves names: `YEAR` in RANKX's
|
||||
// Order slot is not an order word, so the model table wins and must bind as that table.
|
||||
let year_table = model.tables.len() - 1;
|
||||
match bind(&model, "RANKX ( Sales, Sales[Amount], 42, YEAR )") {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(args.get(3), Some(BoundExpr::Table(table)) if *table == year_table), "{args:?}");
|
||||
}
|
||||
other => panic!("expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_order_keywords_bind_at_their_argument_positions() {
|
||||
let model = sample_model();
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Evaluation tests for the date/time function family.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::value::{Scalar, TableColumn, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The OLE Automation serial of a date, built with `chrono` (a normal dependency of the crate,
|
||||
/// independent of the evaluator under test) from the 1899-12-30 epoch.
|
||||
fn serial(year: i32, month: u32, day: u32) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year, month, day).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn model() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Order Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 15)), Scalar::Decimal(20.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 3, 10)), Scalar::Decimal(30.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
// No rows: CALENDARAUTO must take its bounds from the Sales date column.
|
||||
rows: Vec::new(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A model whose only column is numeric: CALENDARAUTO has nothing to scan.
|
||||
fn model_without_dates() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Numbers".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(1)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Empty".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: Vec::new(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A model whose date column is declared `Date` rather than `DateTime`: DAX has both date types,
|
||||
/// so the fiscal calendar has to be built from either.
|
||||
fn model_with_date_typed_columns() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Order Date".into(), data_type: Some("Date".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2023, 6, 15)), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::DateTime(serial(2023, 3, 31)), Scalar::Decimal(20.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_in(model: &DataModel, src: &str) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval_table_in(model: &DataModel, src: &str) -> Result<TableValue, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval(src: &str) -> Result<Scalar, String> {
|
||||
eval_in(&model(), src)
|
||||
}
|
||||
|
||||
fn eval_table(src: &str) -> Result<TableValue, String> {
|
||||
eval_table_in(&model(), src)
|
||||
}
|
||||
|
||||
fn value(src: &str) -> Scalar {
|
||||
eval(src).unwrap_or_else(|error| panic!("{src}: {error}"))
|
||||
}
|
||||
|
||||
fn assert_close(actual: Scalar, expected: f64, label: &str) {
|
||||
match actual {
|
||||
Scalar::Decimal(value) if (value - expected).abs() <= 1e-12 => {}
|
||||
other => panic!("{label}: expected {expected}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Text conversion
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn datevalue_reads_the_common_text_dates() {
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15\")"), Scalar::DateTime(45_306.0));
|
||||
assert_eq!(value("DATEVALUE(\"2024/1/15\")"), Scalar::DateTime(45_306.0));
|
||||
// The documented en-US form, month first.
|
||||
assert_eq!(value("DATEVALUE(\"1/8/2009\")"), Scalar::DateTime(39_821.0));
|
||||
// A time portion is ignored: DATEVALUE returns the date.
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(45_306.0));
|
||||
// A 12-hour clock suffix is accepted in both date orders.
|
||||
let expected = Scalar::DateTime(serial(2024, 1, 15));
|
||||
assert_eq!(value("DATEVALUE(\"2024-01-15 4:48 PM\")"), expected);
|
||||
assert_eq!(value("DATEVALUE(\"1/15/2024 4:48 PM\")"), expected);
|
||||
assert_eq!(value("DATEVALUE(DATE(2024,1,15))"), Scalar::DateTime(45_306.0));
|
||||
assert_eq!(value("DATEVALUE(\"2024-02-29\")"), Scalar::DateTime(45_351.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datevalue_rejects_invalid_text() {
|
||||
assert!(eval("DATEVALUE(\"not a date\")").is_err());
|
||||
// Impossible days and month-first days above 12 are errors, not serial rollover.
|
||||
assert!(eval("DATEVALUE(\"2024-02-30\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"31/12/2024\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"2024-13-01\")").is_err());
|
||||
assert!(eval("DATEVALUE(\"\")").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timevalue_reads_the_common_text_times() {
|
||||
let clock = (16.0 * 3600.0 + 48.0 * 60.0 + 23.0) / 86_400.0;
|
||||
assert_eq!(value("TIMEVALUE(\"16:48:23\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"4:48:23 PM\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"2024-01-15 16:48:23\")"), Scalar::DateTime(clock));
|
||||
assert_eq!(value("TIMEVALUE(\"12:00 AM\")"), Scalar::DateTime(0.0));
|
||||
assert_eq!(value("TIMEVALUE(\"12:30 PM\")"), Scalar::DateTime((12.0 * 3600.0 + 30.0 * 60.0) / 86_400.0));
|
||||
assert_eq!(value("TIMEVALUE(\"6:00\")"), Scalar::DateTime(0.25));
|
||||
assert_eq!(value("TIMEVALUE(\"2024-01-15\")"), Scalar::DateTime(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timevalue_rejects_invalid_text() {
|
||||
assert!(eval("TIMEVALUE(\"25:00\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"12:61\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"lunch\")").is_err());
|
||||
assert!(eval("TIMEVALUE(\"13:00 PM\")").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Scalar date parts
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn quarter_maps_month_to_calendar_quarter() {
|
||||
assert_eq!(value("QUARTER(DATE(2024,1,15))"), Scalar::Integer(1));
|
||||
assert_eq!(value("QUARTER(DATE(2024,3,31))"), Scalar::Integer(1));
|
||||
assert_eq!(value("QUARTER(DATE(2024,4,1))"), Scalar::Integer(2));
|
||||
assert_eq!(value("QUARTER(DATE(2024,7,1))"), Scalar::Integer(3));
|
||||
assert_eq!(value("QUARTER(DATE(2024,10,5))"), Scalar::Integer(4));
|
||||
assert_eq!(value("QUARTER(DATE(2024,12,31))"), Scalar::Integer(4));
|
||||
assert_eq!(value("QUARTER(\"2024-05-15\")"), Scalar::Integer(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeknum_matches_excel_week_systems() {
|
||||
// System 1: the week containing January 1 is week 1, weeks start on Sunday by default.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,1))"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15))"), Scalar::Integer(3));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), Scalar::Integer(3));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 2)"), value("WEEKNUM(DATE(2024,1,15), 11)"));
|
||||
// Monday start: Sunday 2024-01-07 still belongs to week 1.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,7), 2)"), Scalar::Integer(1));
|
||||
// Sunday start: the same Sunday begins week 2.
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,7))"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,8), 2)"), Scalar::Integer(2));
|
||||
// A year can end in week 53 when January 1 falls late in the week.
|
||||
assert_eq!(value("WEEKNUM(DATE(2023,12,31))"), Scalar::Integer(53));
|
||||
assert_eq!(value("WEEKNUM(\"2024-01-15\")"), Scalar::Integer(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeknum_iso_weeks_cross_year_boundaries() {
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,1,15), 21)"), Scalar::Integer(3));
|
||||
// 2021-01-01 (Friday) belongs to ISO week 53 of 2020.
|
||||
assert_eq!(value("WEEKNUM(DATE(2021,1,1), 21)"), Scalar::Integer(53));
|
||||
// 2018-12-31 (Monday) and 2024-12-30 (Monday) are week 1 of the next year.
|
||||
assert_eq!(value("WEEKNUM(DATE(2018,12,31), 21)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,12,30), 21)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKNUM(DATE(2024,12,29), 21)"), Scalar::Integer(52));
|
||||
assert_eq!(value("WEEKNUM(DATE(2020,12,31), 21)"), Scalar::Integer(53));
|
||||
assert!(eval("WEEKNUM(DATE(2024,1,1), 3)").is_err());
|
||||
assert!(eval("WEEKNUM(DATE(2024,1,1), 10)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// YEARFRAC
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn yearfrac_supports_every_basis() {
|
||||
let start = "DATE(2024,1,1)";
|
||||
let end = "DATE(2024,7,1)";
|
||||
// Leap year 2024: Jan 1 to Jul 1 is 182 actual days.
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end})")), 0.5, "basis 0 default");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 0)")), 180.0 / 360.0, "basis 0");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 1)")), 182.0 / 366.0, "basis 1");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 2)")), 182.0 / 360.0, "basis 2");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 3)")), 182.0 / 365.0, "basis 3");
|
||||
assert_close(value(&format!("YEARFRAC({start}, {end}, 4)")), 180.0 / 360.0, "basis 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yearfrac_handles_calendar_boundaries_and_reversed_ranges() {
|
||||
// A whole leap year is 1 for the 30/360 convention and 365/366 for actual/actual.
|
||||
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 0)"), 1.0, "30/360 whole year");
|
||||
assert_close(value("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 1)"), 365.0 / 366.0, "actual/actual whole year");
|
||||
// Excel's US 30/360 February rule: the end of February counts as day 30 but March 31 keeps 31.
|
||||
assert_close(value("YEARFRAC(DATE(2019,2,28), DATE(2019,3,31), 0)"), 31.0 / 360.0, "February rule");
|
||||
// Two end-of-February dates collapse to 30/30, which is a full year.
|
||||
assert_close(value("YEARFRAC(DATE(2011,2,28), DATE(2012,2,29), 0)"), 1.0, "February to February");
|
||||
// actual/actual uses 366 when the period contains a February 29.
|
||||
assert_close(value("YEARFRAC(DATE(2011,3,1), DATE(2012,2,29), 1)"), 365.0 / 366.0, "leap day between");
|
||||
// Multi-year actual/actual divides by the average calendar year length.
|
||||
assert_close(value("YEARFRAC(DATE(2000,1,1), DATE(2003,1,1), 1)"), 1096.0 / (1461.0 / 4.0), "average year");
|
||||
// Excel ignores the argument order: the reversed pair returns the positive fraction.
|
||||
assert_close(value("YEARFRAC(DATE(2024,7,1), DATE(2024,1,1), 2)"), 182.0 / 360.0, "reversed");
|
||||
assert_close(value("YEARFRAC(\"2024-01-01\", \"2024-07-01\", 2)"), 182.0 / 360.0, "text dates");
|
||||
// dax.guide's documented example: 2011-01-01 .. 2011-12-15.
|
||||
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 0)"), 344.0 / 360.0, "dax.guide 30/360");
|
||||
assert_close(value("YEARFRAC(DATE(2011,1,1), DATE(2011,12,15), 1)"), 348.0 / 365.0, "dax.guide actual/actual");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yearfrac_rejects_unknown_bases() {
|
||||
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), 5)").is_err());
|
||||
assert!(eval("YEARFRAC(DATE(2024,1,1), DATE(2024,12,31), -1)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// NETWORKDAYS
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn networkdays_counts_working_days_with_weekends_and_holidays() {
|
||||
// January 2024 has 31 days, starting on a Monday, with 8 weekend days.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31))"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1)"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,15) })"), Scalar::Integer(22));
|
||||
// A holiday already on a weekend does not count twice.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,6) })"), Scalar::Integer(23));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 1, { DATE(2024,1,1), DATE(2024,1,15) })"), Scalar::Integer(21));
|
||||
// Weekend code 2 is Sunday/Monday, 11 is Sunday only.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 2)"), Scalar::Integer(22));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 11)"), Scalar::Integer(27));
|
||||
// A reversed range returns the negative count.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,31), DATE(2024,1,1))"), Scalar::Integer(-23));
|
||||
// A single working day and a single weekend day.
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,2), DATE(2024,1,2))"), Scalar::Integer(1));
|
||||
assert_eq!(value("NETWORKDAYS(DATE(2024,1,6), DATE(2024,1,6))"), Scalar::Integer(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn networkdays_rejects_bad_weekend_codes() {
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 0)").is_err());
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 8)").is_err());
|
||||
assert!(eval("NETWORKDAYS(DATE(2024,1,1), DATE(2024,1,31), 18)").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// CALENDAR / CALENDARAUTO
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn calendar_builds_the_inclusive_date_column() {
|
||||
let table = eval_table("CALENDAR(DATE(2024,2,27), DATE(2024,3,1))").expect("calendar table");
|
||||
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
|
||||
// 2024 is a leap year, so February 29 is included.
|
||||
assert_eq!(
|
||||
table.rows,
|
||||
vec![
|
||||
vec![Scalar::DateTime(serial(2024, 2, 27))],
|
||||
vec![Scalar::DateTime(serial(2024, 2, 28))],
|
||||
vec![Scalar::DateTime(serial(2024, 2, 29))],
|
||||
vec![Scalar::DateTime(serial(2024, 3, 1))],
|
||||
]
|
||||
);
|
||||
assert_eq!(eval_table("CALENDAR(DATE(2024,1,1), DATE(2024,1,31))").expect("january").rows.len(), 31);
|
||||
assert_eq!(value("COUNTROWS(CALENDAR(DATE(2024,1,1), DATE(2024,1,31)))"), Scalar::Integer(31));
|
||||
// Table functions are not scalars.
|
||||
assert!(eval("CALENDAR(DATE(2024,1,1), DATE(2024,1,2))").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_rejects_reversed_bounds() {
|
||||
assert!(eval_table("CALENDAR(DATE(2024,2,1), DATE(2024,1,1))").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_rejects_oversized_spans() {
|
||||
// The whole in-range span is 2,958,466 days, above the 1,000,000-row generation ceiling, so
|
||||
// it must fail instead of allocating the table.
|
||||
let error = eval_table("CALENDAR(DATE(1899,12,30), DATE(9999,12,31))").expect_err("oversized calendar");
|
||||
assert!(error.contains("too large"), "{error}");
|
||||
// 1900-01-01 is serial 2, so exactly 1,000,000 days end on 4637-11-27; the cap is inclusive
|
||||
// there and one day further fails.
|
||||
let largest = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,27))").expect("largest calendar");
|
||||
assert_eq!(largest.rows.len(), 1_000_000);
|
||||
assert_eq!(largest.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(4637, 11, 27))));
|
||||
let error = eval_table("CALENDAR(DATE(1900,1,1), DATE(4637,11,28))").expect_err("one day over the cap");
|
||||
assert!(error.contains("too large"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_covers_whole_fiscal_years() {
|
||||
// Sales spans 2023-06-15 .. 2024-03-10 and Date spans 2023-01-01 .. 2024-12-31.
|
||||
let table = eval_table("CALENDARAUTO()").expect("calendar auto");
|
||||
assert_eq!(table.columns, vec![TableColumn { name: "Date".into() }]);
|
||||
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
|
||||
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 12, 31))));
|
||||
assert_eq!(table.rows.len(), 731);
|
||||
assert_eq!(value("COUNTROWS(CALENDARAUTO())"), Scalar::Integer(731));
|
||||
|
||||
// Fiscal years ending in March: 2023-04-01 .. 2024-03-31, including leap day 2024-02-29.
|
||||
let fiscal = eval_table("CALENDARAUTO(3)").expect("fiscal calendar");
|
||||
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 4, 1))));
|
||||
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
|
||||
assert_eq!(fiscal.rows.len(), 366);
|
||||
assert!(fiscal.rows.iter().any(|row| row[0] == Scalar::DateTime(serial(2024, 2, 29))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_reads_date_typed_columns() {
|
||||
// 2023-03-31 .. 2023-06-15, in a column declared `Date`: the whole 2023 calendar year.
|
||||
let table = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO()").expect("calendar auto over Date columns");
|
||||
assert_eq!(table.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 1, 1))));
|
||||
assert_eq!(table.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2023, 12, 31))));
|
||||
assert_eq!(table.rows.len(), 365);
|
||||
// A fiscal year ending in March: two fiscal years, since June 2023 falls in FY2024.
|
||||
let fiscal = eval_table_in(&model_with_date_typed_columns(), "CALENDARAUTO(3)").expect("fiscal calendar over Date columns");
|
||||
assert_eq!(fiscal.rows.first().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2022, 4, 1))));
|
||||
assert_eq!(fiscal.rows.last().map(|row| row[0].clone()), Some(Scalar::DateTime(serial(2024, 3, 31))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendarauto_validates_arguments_and_model() {
|
||||
assert!(eval_table("CALENDARAUTO(0)").is_err());
|
||||
assert!(eval_table("CALENDARAUTO(13)").is_err());
|
||||
assert!(eval_table_in(&model_without_dates(), "CALENDARAUTO()").is_err());
|
||||
// Table functions are not scalars.
|
||||
assert!(eval("CALENDARAUTO()").is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Clock
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
// The test runs natively and needs an independent clock reference for the date serials.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn clock_functions_track_the_system_clock() {
|
||||
let clock = || {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs_f64() / 86_400.0 + 25_569.0)
|
||||
.expect("system clock")
|
||||
};
|
||||
let serial_of = |src: &str| match value(src) {
|
||||
Scalar::DateTime(serial) => serial,
|
||||
other => panic!("{src} produced {other:?}"),
|
||||
};
|
||||
// Each function is a separate evaluation; retry if a local or UTC day boundary falls inside
|
||||
// the sampling window, so the floor comparisons cannot race midnight.
|
||||
let mut attempts = 0;
|
||||
let (today, now, utc_today, utc_now) = loop {
|
||||
let before = clock();
|
||||
let (today, now) = (serial_of("TODAY()"), serial_of("NOW()"));
|
||||
let (utc_today, utc_now) = (serial_of("UTCTODAY()"), serial_of("UTCNOW()"));
|
||||
let after = clock();
|
||||
if before.floor() == after.floor() && today == now.floor() && utc_today == utc_now.floor() {
|
||||
break (today, now, utc_today, utc_now);
|
||||
}
|
||||
attempts += 1;
|
||||
assert!(attempts < 5, "clock functions disagree: TODAY {today}, NOW {now}, UTCTODAY {utc_today}, UTCNOW {utc_now}");
|
||||
};
|
||||
let expected = clock();
|
||||
assert!((utc_now - expected).abs() < 1.0 / 86_400.0, "UTCNOW follows the system clock");
|
||||
assert!((0.0..1.0).contains(&now.fract()));
|
||||
// The host supplies one wall clock, so the local and UTC variants never differ by a day.
|
||||
assert!((now - utc_now).abs() < 1.0);
|
||||
assert!((today - utc_today).abs() <= 1.0);
|
||||
// Volatile functions take no arguments.
|
||||
assert!(eval("NOW(1)").is_err());
|
||||
assert!(eval("TODAY(1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edate_and_eomonth_survive_extreme_month_offsets() {
|
||||
// `months` is arbitrary input: the month arithmetic must saturate instead of overflowing.
|
||||
let model = model();
|
||||
for (formula, name) in [("EDATE(DATE(2024,1,15), 1E18)", "EDATE"), ("EOMONTH(DATE(2024,1,15), -1E18)", "EOMONTH")] {
|
||||
match eval_in(&model, formula) {
|
||||
// Out-of-range serials are reported, but the month arithmetic itself must not overflow.
|
||||
Ok(value) => assert!(matches!(value, Scalar::DateTime(serial) if serial.is_finite() || serial.is_nan()), "{name}: {value:?}"),
|
||||
Err(error) => assert!(!error.is_empty(), "{name} reported an empty error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Relocated regressions
|
||||
//
|
||||
// These pin documented results that the evaluator used to get wrong; they moved here from
|
||||
// `eval_audit_semantics.rs` and `eval_text.rs` because their functions live in this family.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// The single numeric value of an expression; panics when it is not numeric.
|
||||
fn number(src: &str) -> f64 {
|
||||
let evaluated = value(src);
|
||||
evaluated.to_number().unwrap_or_else(|| panic!("{src} is not numeric: {evaluated:?}"))
|
||||
}
|
||||
|
||||
/// The message of the error an expression raises.
|
||||
fn error(src: &str) -> String {
|
||||
match eval(src) {
|
||||
Err(message) => message,
|
||||
Ok(evaluated) => panic!("{src}: expected an error, got {evaluated:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text form of an expression, as produced by `& ""`.
|
||||
fn text(src: &str) -> String {
|
||||
match value(src) {
|
||||
Scalar::String(text) => text,
|
||||
other => panic!("{src} should return text, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mod_follows_the_divisor_sign() {
|
||||
// Microsoft Learn, MOD: "The result has the same sign as the divisor."
|
||||
assert_eq!(value("MOD(7, 3)"), Scalar::Integer(1));
|
||||
assert_eq!(value("MOD(-3, 2)"), Scalar::Integer(1));
|
||||
assert_eq!(value("MOD(3, -2)"), Scalar::Integer(-1));
|
||||
assert_eq!(value("MOD(-3, -2)"), Scalar::Integer(-1));
|
||||
assert_eq!(value("MOD(10, 5)"), Scalar::Integer(0));
|
||||
// A fractional operand keeps the Decimal result.
|
||||
assert_eq!(number("MOD(5.5, 2)"), 1.5);
|
||||
assert_eq!(number("MOD(-5.5, 2)"), 0.5);
|
||||
// A zero divisor is a division-by-zero error, not BLANK.
|
||||
assert!(error("MOD(1, 0)").contains("MOD divisor must not be zero"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundup_and_rounddown_follow_the_sign() {
|
||||
// Microsoft Learn: ROUNDDOWN rounds toward zero, ROUNDUP away from zero.
|
||||
assert_eq!(number("ROUNDDOWN(-2.9, 0)"), -2.0);
|
||||
assert_eq!(number("ROUNDDOWN(2.9, 0)"), 2.0);
|
||||
assert_eq!(number("ROUNDDOWN(-2.345, 2)"), -2.34);
|
||||
assert_eq!(number("ROUNDUP(-2.1, 0)"), -3.0);
|
||||
assert_eq!(number("ROUNDUP(2.1, 0)"), 3.0);
|
||||
assert_eq!(number("ROUNDUP(2.341, 2)"), 2.35);
|
||||
// ROUND still rounds half away from zero.
|
||||
assert_eq!(number("ROUND(2.5, 0)"), 3.0);
|
||||
assert_eq!(number("ROUND(-2.5, 0)"), -3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datediff_counts_interval_boundaries() {
|
||||
// The catalog: DATEDIFF counts the Interval boundaries crossed between two dates.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), DAY)"), Scalar::Integer(60));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), MONTH)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2025, 3, 1), YEAR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 7, 1), QUARTER)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), WEEK)"), Scalar::Integer(8));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), HOUR)"), Scalar::Integer(24));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 2), MINUTE)"), Scalar::Integer(1_440));
|
||||
// A month boundary is crossed even by a single day.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 31), DATE(2024, 2, 1), MONTH)"), Scalar::Integer(1));
|
||||
// The sign follows Date2 - Date1.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 3, 1), DATE(2024, 1, 1), MONTH)"), Scalar::Integer(-2));
|
||||
// A text argument keeps the time of day, exactly like a DateTime one: the sub-day intervals
|
||||
// must not be read as midnight on both sides.
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", MINUTE)"), Scalar::Integer(120));
|
||||
assert_eq!(value("DATEDIFF(\"2024-01-01 10:00:00\", \"2024-01-01 12:00:00\", SECOND)"), Scalar::Integer(7_200));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1) + 10/24, \"2024-01-01 12:00:00\", HOUR)"), Scalar::Integer(2));
|
||||
assert!(error("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 3, 1), FORTNIGHT)").contains("DATEDIFF interval"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_wraps_inside_one_day() {
|
||||
// The catalog: "Overflowing arguments wrap inside the same day instead of raising an error
|
||||
// (TIME ( 10, 90, 0 ) is 11:30 and TIME ( 50, 0, 0 ) is 02:00)".
|
||||
assert_eq!(number("TIME(10, 90, 0)"), 11.5 / 24.0);
|
||||
assert_eq!(number("TIME(50, 0, 0)"), 2.0 / 24.0);
|
||||
assert_eq!(number("TIME(25, 0, 0)"), 1.0 / 24.0);
|
||||
assert_eq!(number("TIME(0, 0, 0)"), 0.0);
|
||||
assert_eq!(number("TIME(1, 2, 3)"), (3_723.0) / 86_400.0);
|
||||
assert!(error("TIME(-1, 0, 0)").contains("TIME argument 1"));
|
||||
assert!(error("TIME(32768, 0, 0)").contains("TIME argument 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weekday_honours_the_return_type() {
|
||||
// 2024-01-01 is a Monday. Return type 1 numbers Sunday 1, 2 numbers Monday 1, 3 numbers
|
||||
// Monday 0, and 11-17 start the week on Monday through Sunday.
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1))"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 1)"), Scalar::Integer(2));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 2)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 3)"), Scalar::Integer(0));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 11)"), Scalar::Integer(1));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 12)"), Scalar::Integer(7));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 1), 17)"), Scalar::Integer(2));
|
||||
// 2024-01-07 is a Sunday.
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 2)"), Scalar::Integer(7));
|
||||
assert_eq!(value("WEEKDAY(DATE(2024, 1, 7), 3)"), Scalar::Integer(6));
|
||||
assert!(error("WEEKDAY(DATE(2024, 1, 1), 5)").contains("WEEKDAY return type"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datediff_counts_boundaries_for_sub_day_and_week_intervals() {
|
||||
// 10:59:59 to 11:00:01 crosses the 11:00 hour boundary even though two seconds passed.
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 1), HOUR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 58), TIME(10, 59, 59), SECOND)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 59, 59), TIME(11, 0, 0), MINUTE)"), Scalar::Integer(1));
|
||||
// Exactly one elapsed hour is still one boundary; 59 minutes is none.
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(11, 0, 0), HOUR)"), Scalar::Integer(1));
|
||||
assert_eq!(value("DATEDIFF(TIME(10, 0, 0), TIME(10, 59, 59), HOUR)"), Scalar::Integer(0));
|
||||
// Weeks are Sunday-based: 2024-01-01 is a Monday, so the week boundary is the Sunday before it.
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 6), WEEK)"), Scalar::Integer(0));
|
||||
assert_eq!(value("DATEDIFF(DATE(2024, 1, 1), DATE(2024, 1, 7), WEEK)"), Scalar::Integer(1));
|
||||
// The sign follows Date2 - Date1.
|
||||
assert_eq!(value("DATEDIFF(TIME(11, 0, 1), TIME(10, 59, 59), HOUR)"), Scalar::Integer(-1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_and_large_numbers_concatenate_in_dax_form() {
|
||||
assert_eq!(text("CURRENCY(10) & \"\""), "10");
|
||||
assert_eq!(text("CURRENCY(10.5) & \"\""), "10.5");
|
||||
assert_eq!(text("CONVERT(1, CURRENCY) & \"\""), "1");
|
||||
// Very large whole numbers use Excel's exponent text with the explicit sign.
|
||||
assert_eq!(text("1e15 & \"\""), "1E+15");
|
||||
// DAX prints 15 significant digits, so a floating-point residue does not surface.
|
||||
assert_eq!(text("0.1 + 0.2 & \"\""), "0.3");
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Evaluator tests for math and trigonometry functions.
|
||||
|
||||
use gridcraft_dax::model::DataModel;
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
DataModel { tables: vec![], relationships: vec![], measures: vec![] }
|
||||
}
|
||||
|
||||
fn eval_result(source: &str) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval(source: &str) -> Scalar {
|
||||
eval_result(source).expect("expression evaluates")
|
||||
}
|
||||
|
||||
fn assert_close(actual: Scalar, expected: f64) {
|
||||
match actual {
|
||||
Scalar::Decimal(value) => {
|
||||
let tolerance = 1e-9 * expected.abs().max(1.0);
|
||||
assert!((value - expected).abs() <= tolerance, "expected {expected}, got {value}");
|
||||
}
|
||||
other => panic!("expected Decimal({expected}), got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_trigonometry() {
|
||||
assert_close(eval("ACOS(0.5)"), std::f64::consts::FRAC_PI_3);
|
||||
assert_close(eval("ACOS(-1)"), std::f64::consts::PI);
|
||||
assert!(eval_result("ACOS(2)").is_err());
|
||||
assert!(eval_result("ACOS(-1.0001)").is_err());
|
||||
|
||||
assert_close(eval("ASIN(0.5)"), std::f64::consts::FRAC_PI_6);
|
||||
assert_close(eval("ASIN(-1)"), -std::f64::consts::FRAC_PI_2);
|
||||
assert!(eval_result("ASIN(1.5)").is_err());
|
||||
|
||||
assert_close(eval("ATAN(1)"), std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ATAN(0)"), 0.0);
|
||||
|
||||
assert_close(eval("ACOT(1)"), std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ACOT(-1)"), 3.0 * std::f64::consts::FRAC_PI_4);
|
||||
assert_close(eval("ACOT(0)"), std::f64::consts::FRAC_PI_2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperbolic_and_inverse_hyperbolic() {
|
||||
assert_close(eval("ACOSH(2)"), 1.316_957_896_924_816_6);
|
||||
assert!(eval_result("ACOSH(0.5)").is_err());
|
||||
|
||||
assert_close(eval("ASINH(1)"), 0.881_373_587_019_543);
|
||||
assert_close(eval("ATANH(0.5)"), 0.549_306_144_334_054_9);
|
||||
assert!(eval_result("ATANH(1)").is_err());
|
||||
assert!(eval_result("ATANH(-1)").is_err());
|
||||
|
||||
assert_close(eval("ACOTH(2)"), 0.549_306_144_334_054_9);
|
||||
assert_close(eval("ACOTH(-2)"), -0.549_306_144_334_054_9);
|
||||
assert!(eval_result("ACOTH(1)").is_err());
|
||||
assert!(eval_result("ACOTH(-0.5)").is_err());
|
||||
|
||||
assert_close(eval("COSH(1)"), 1.543_080_634_815_243_7);
|
||||
assert_close(eval("SINH(1)"), 1.175_201_193_643_801_4);
|
||||
assert_close(eval("TANH(1)"), 0.761_594_155_955_764_9);
|
||||
assert!(eval_result("SINH(1000)").is_err(), "overflow must be an error, not infinity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cotangent_family() {
|
||||
assert_close(eval("COT(PI() / 4)"), 1.0);
|
||||
assert_close(eval("COTH(1)"), 1.313_035_285_499_331_2);
|
||||
assert!(eval_result("COT(0)").is_err());
|
||||
assert!(eval_result("COTH(0)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_and_odd_round_away_from_zero() {
|
||||
assert_eq!(eval("EVEN(3.2)"), Scalar::Integer(4));
|
||||
assert_eq!(eval("EVEN(-3.2)"), Scalar::Integer(-4));
|
||||
assert_eq!(eval("EVEN(2)"), Scalar::Integer(2));
|
||||
assert_eq!(eval("EVEN(-2)"), Scalar::Integer(-2));
|
||||
assert_eq!(eval("EVEN(0)"), Scalar::Integer(0));
|
||||
|
||||
assert_eq!(eval("ODD(2.1)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("ODD(-2.1)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("ODD(2)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("ODD(0)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("ODD(-2)"), Scalar::Integer(-3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mround_sign_and_multiples() {
|
||||
assert_close(eval("MROUND(7.3, 0.5)"), 7.5);
|
||||
assert_close(eval("MROUND(10, 3)"), 9.0);
|
||||
assert_close(eval("MROUND(-7.3, -0.5)"), -7.5);
|
||||
// dax.guide documents the binary floating-point midpoints 6.0 and 7.1.
|
||||
assert_close(eval("MROUND(6.05, 0.1)"), 6.0);
|
||||
assert_close(eval("MROUND(7.05, 0.1)"), 7.1);
|
||||
// A digit count whose scale factor would overflow leaves the value unchanged.
|
||||
assert_close(eval("ROUND(1.5, 400)"), 1.5);
|
||||
assert_close(eval("MROUND(10, 0)"), 0.0);
|
||||
assert!(eval_result("MROUND(7, -2)").is_err());
|
||||
assert!(eval_result("MROUND(-7, 2)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotient_truncates_toward_zero() {
|
||||
assert_eq!(eval("QUOTIENT(7, 2)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("QUOTIENT(-7, 2)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("QUOTIENT(7, -2)"), Scalar::Integer(-3));
|
||||
assert_eq!(eval("QUOTIENT(0, 2)"), Scalar::Integer(0));
|
||||
assert!(eval_result("QUOTIENT(7, 0)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqrtpi_domain() {
|
||||
assert_close(eval("SQRTPI(2)"), 2.506_628_274_631_000_2);
|
||||
assert_close(eval("SQRTPI(0)"), 0.0);
|
||||
assert!(eval_result("SQRTPI(-1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_rounds_to_four_decimals() {
|
||||
assert_eq!(eval("CURRENCY(10.5)"), Scalar::Currency(105_000));
|
||||
assert_eq!(eval("CURRENCY(3.66666)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CURRENCY(-3.66666)"), Scalar::Currency(-36_667));
|
||||
assert_eq!(eval("CURRENCY(3.0123456789)"), Scalar::Currency(30_123));
|
||||
assert_eq!(eval("CURRENCY(\"3.66666\")"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CURRENCY(TRUE)"), Scalar::Currency(10_000));
|
||||
assert_eq!(eval("CURRENCY(FALSE)"), Scalar::Currency(0));
|
||||
assert!(eval_result("CURRENCY(\"not a number\")").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_functions_stay_in_range() {
|
||||
for _ in 0..64 {
|
||||
match eval("RAND()") {
|
||||
Scalar::Decimal(value) => assert!((0.0..1.0).contains(&value), "RAND out of range: {value}"),
|
||||
other => panic!("RAND returned {other:?}"),
|
||||
}
|
||||
match eval("RANDBETWEEN(1, 10)") {
|
||||
Scalar::Integer(value) => assert!((1..=10).contains(&value), "RANDBETWEEN out of range: {value}"),
|
||||
other => panic!("RANDBETWEEN returned {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(eval("RANDBETWEEN(5, 5)"), Scalar::Integer(5));
|
||||
assert_eq!(eval("RANDBETWEEN(-3, -3)"), Scalar::Integer(-3));
|
||||
assert!(eval_result("RANDBETWEEN(10, 1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_data_types() {
|
||||
assert_eq!(eval("CONVERT(32.34, INTEGER)"), Scalar::Integer(32));
|
||||
assert_eq!(eval("CONVERT(-32.34, INT64)"), Scalar::Integer(-32));
|
||||
assert_eq!(eval("CONVERT(\"123\", INTEGER)"), Scalar::Integer(123));
|
||||
assert_eq!(eval("CONVERT(1, DOUBLE)"), Scalar::Decimal(1.0));
|
||||
assert_eq!(eval("CONVERT(3.66666, CURRENCY)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CONVERT(3.66666, DECIMAL)"), Scalar::Currency(36_667));
|
||||
assert_eq!(eval("CONVERT(12345, DATETIME)"), Scalar::DateTime(12_345.0));
|
||||
assert_eq!(eval("CONVERT(\"1966-12-25\", DATETIME)"), Scalar::DateTime(24_466.0));
|
||||
assert_eq!(eval("CONVERT(TRUE, STRING)"), Scalar::String("TRUE".into()));
|
||||
assert_eq!(eval("CONVERT(\"TRUE\", BOOLEAN)"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("CONVERT(0, LOGICAL)"), Scalar::Boolean(false));
|
||||
assert!(eval_result("CONVERT(\"abc\", INTEGER)").is_err());
|
||||
assert!(eval_result("CONVERT(1, NONSENSE)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ceiling_floor_and_trunc_use_their_second_argument() {
|
||||
// The catalog's documented semantics: CEILING/FLOOR take a required Significance, TRUNC an
|
||||
// optional NumberOfDigits.
|
||||
assert_close(eval("CEILING(4.42, 0.05)"), 4.45);
|
||||
assert_close(eval("CEILING(10.2, 1)"), 11.0);
|
||||
assert_close(eval("CEILING(10.7, 0.5)"), 11.0);
|
||||
// A negative number with a negative significance rounds away from zero.
|
||||
assert_close(eval("CEILING(-2.5, -2)"), -4.0);
|
||||
// ISO.CEILING takes the significance's magnitude and always rounds up.
|
||||
assert_close(eval("ISO.CEILING(-2.5, 2)"), -2.0);
|
||||
assert!(eval_result("CEILING(2.5, -2)").is_err());
|
||||
|
||||
assert_close(eval("FLOOR(27, 5)"), 25.0);
|
||||
assert_close(eval("FLOOR(2.7, 1)"), 2.0);
|
||||
assert_close(eval("FLOOR(-2.7, -1)"), -2.0);
|
||||
assert!(eval_result("FLOOR(-2.7, 1)").is_err());
|
||||
assert!(eval_result("FLOOR(1, 0)").is_err());
|
||||
|
||||
assert_close(eval("TRUNC(1.239, 2)"), 1.23);
|
||||
assert_close(eval("TRUNC(2.71828)"), 2.0);
|
||||
assert_close(eval("TRUNC(-2.71828, 2)"), -2.71);
|
||||
assert_close(eval("TRUNC(1234.5, -2)"), 1200.0);
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
//! Time-intelligence range functions over an in-memory model.
|
||||
//!
|
||||
//! The fixture date table runs from 2022-01-01 to 2025-12-31 so that previous/next year windows
|
||||
//! always have a full calendar to draw from. `Date` is table 0 and `Sales` is table 1; the
|
||||
//! `Sales[Date]` -> `Date[Date]` relationship is the only cross-filtering path.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, TableValue};
|
||||
use gridcraft_dax::{Binder, BoundExpr, Evaluator, FilterContext, Literal, ScalarKey, parse_expression};
|
||||
|
||||
const DATE_TABLE: usize = 0;
|
||||
const DATE_COLUMN: usize = 0;
|
||||
const YEAR_COLUMN: usize = 1;
|
||||
const SALES_TABLE: usize = 1;
|
||||
const AMOUNT_COLUMN: usize = 1;
|
||||
|
||||
/// Excel/OLE date serial, computed with `chrono` independently of the evaluator.
|
||||
fn serial(year: i64, month: i64, day: i64) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn date_rows() -> Vec<Vec<Scalar>> {
|
||||
use chrono::Datelike;
|
||||
let start = chrono::NaiveDate::from_ymd_opt(2022, 1, 1).expect("the fixture start is a valid date");
|
||||
let end = chrono::NaiveDate::from_ymd_opt(2025, 12, 31).expect("the fixture end is a valid date");
|
||||
start
|
||||
.iter_days()
|
||||
.take_while(|date| *date <= end)
|
||||
.map(|date| {
|
||||
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
|
||||
vec![
|
||||
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
|
||||
Scalar::Integer(year),
|
||||
Scalar::Integer((month - 1) / 3 + 1),
|
||||
Scalar::Integer(month),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// (year, month, day, amount) for every sales row.
|
||||
const SALES: &[(i64, i64, i64, f64)] = &[
|
||||
(2023, 1, 10, 10.0),
|
||||
(2023, 3, 5, 20.0),
|
||||
(2023, 6, 15, 30.0),
|
||||
(2023, 9, 20, 40.0),
|
||||
(2023, 12, 31, 50.0),
|
||||
(2024, 1, 5, 100.0),
|
||||
(2024, 1, 31, 200.0),
|
||||
(2024, 2, 29, 300.0),
|
||||
(2024, 3, 15, 400.0),
|
||||
(2024, 4, 1, 500.0),
|
||||
(2024, 6, 30, 600.0),
|
||||
(2024, 9, 30, 700.0),
|
||||
(2024, 11, 11, 800.0),
|
||||
(2024, 12, 25, 900.0),
|
||||
(2024, 12, 31, 1000.0),
|
||||
];
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: date_rows(),
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: SALES
|
||||
.iter()
|
||||
.map(|(year, month, day, amount)| vec![Scalar::DateTime(serial(*year, *month, *day)), Scalar::Decimal(*amount)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Date".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![Measure {
|
||||
name: "Sales Amount".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
/// A three-day date table whose last row's date cell is BLANK: the axis must drop that row instead
|
||||
/// of reading BLANK as serial 0 (1899-12-30).
|
||||
fn model_with_blank_date() -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Day".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 3))],
|
||||
vec![Scalar::Blank],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate(source: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
evaluate_in(&model(), source, filters)
|
||||
}
|
||||
|
||||
fn evaluate_in(model: &DataModel, source: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_with(&bound, filters).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval_with(source: &str, filters: FilterContext) -> Scalar {
|
||||
evaluate(source, filters).expect("expression evaluates")
|
||||
}
|
||||
|
||||
fn eval_error(source: &str, filters: FilterContext) -> String {
|
||||
evaluate(source, filters).expect_err("expression must fail")
|
||||
}
|
||||
|
||||
fn evaluate_table(source: &str) -> Result<TableValue, String> {
|
||||
evaluate_table_in(&model(), source)
|
||||
}
|
||||
|
||||
fn evaluate_table_in(model: &DataModel, source: &str) -> Result<TableValue, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn table(source: &str) -> TableValue {
|
||||
evaluate_table(source).expect("table evaluates")
|
||||
}
|
||||
|
||||
/// Filter context selecting the date column between two inclusive calendar days.
|
||||
fn dates(from: (i64, i64, i64), to: (i64, i64, i64)) -> FilterContext {
|
||||
let mut filters = FilterContext::default();
|
||||
let mut keys = Vec::new();
|
||||
let start = serial(from.0, from.1, from.2) as i64;
|
||||
let end = serial(to.0, to.1, to.2) as i64;
|
||||
for day in start..=end {
|
||||
keys.push(ScalarKey::from(&Scalar::DateTime(day as f64)));
|
||||
}
|
||||
filters.set(DATE_TABLE, DATE_COLUMN, keys);
|
||||
filters
|
||||
}
|
||||
|
||||
fn year(year: i64) -> FilterContext {
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(DATE_TABLE, YEAR_COLUMN, [ScalarKey::from(&Scalar::Integer(year))]);
|
||||
filters
|
||||
}
|
||||
|
||||
/// Number of rows of a table expression evaluated under a filter context.
|
||||
fn row_count(source: &str, filters: FilterContext) -> i64 {
|
||||
let count = eval_with(&format!("COUNTROWS({source})"), filters);
|
||||
match count {
|
||||
Scalar::Blank => 0,
|
||||
other => other.to_number().expect("COUNTROWS is numeric") as i64,
|
||||
}
|
||||
}
|
||||
|
||||
/// (first, last) date of a table expression evaluated under a filter context.
|
||||
fn bounds(source: &str, filters: FilterContext) -> (f64, f64) {
|
||||
let first = eval_with(&format!("MINX({source}, 'Date'[Date])"), filters.clone());
|
||||
let last = eval_with(&format!("MAXX({source}, 'Date'[Date])"), filters);
|
||||
(first.to_number().expect("first date"), last.to_number().expect("last date"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_shifts_the_visible_period() {
|
||||
let march = dates((2024, 3, 1), (2024, 3, 31));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), 29);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", march.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
// A partial period keeps its day span.
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 10, \"DAY\")", dates((2024, 3, 25), (2024, 3, 31))), (serial(2024, 4, 4), serial(2024, 4, 10)));
|
||||
// A selection ending on the last day of its period extends to the whole target period.
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"QUARTER\")", dates((2024, 4, 1), (2024, 6, 30))), 91);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", dates((2024, 2, 25), (2024, 2, 29))), (serial(2024, 3, 25), serial(2024, 3, 31)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2024, 3, 1), (2024, 3, 31))), 31);
|
||||
|
||||
let error = eval_error("DATEADD('Date'[Date], 1, \"DECADE\")", FilterContext::default());
|
||||
assert!(error.contains("interval"), "{error}");
|
||||
let error = eval_error("DATEADD(Sales[Amount], 1, \"DAY\")", FilterContext::default());
|
||||
assert!(error.contains("DateTime"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_rejects_a_non_contiguous_selection() {
|
||||
// A complete date column filtered to May 1 and May 3 has a gap at May 2. Shifting the window
|
||||
// would sweep in May 3's source day (and any blocked day inside the range), which Microsoft's
|
||||
// date-column DATEADD contract forbids: the visible dates must be contiguous.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
DATE_TABLE,
|
||||
DATE_COLUMN,
|
||||
[ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 1))), ScalarKey::from(&Scalar::DateTime(serial(2024, 5, 3)))],
|
||||
);
|
||||
let error = eval_error("DATEADD('Date'[Date], 1, \"DAY\")", filters.clone());
|
||||
assert!(error.contains("contiguous"), "{error}");
|
||||
assert!(error.contains("5/1/2024") && error.contains("5/3/2024"), "{error}");
|
||||
// The contract covers every interval, not just days.
|
||||
for interval in ["MONTH", "QUARTER", "YEAR"] {
|
||||
let source = format!("DATEADD('Date'[Date], 1, \"{interval}\")");
|
||||
let error = eval_error(&source, filters.clone());
|
||||
assert!(error.contains("contiguous"), "{error}");
|
||||
}
|
||||
// A contiguous selection still shifts: May 1-2 to May 2-3, and a single day to its neighbour.
|
||||
let contiguous = dates((2024, 5, 1), (2024, 5, 2));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", contiguous.clone()), (serial(2024, 5, 2), serial(2024, 5, 3)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"DAY\")", contiguous), 2);
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"DAY\")", dates((2024, 5, 1), (2024, 5, 1))), (serial(2024, 5, 2), serial(2024, 5, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_date_cells_are_not_axis_dates() {
|
||||
let model = model_with_blank_date();
|
||||
// BLANK is not serial 0, so it must not become the first visible date (1899-12-30) or an axis
|
||||
// row that the range functions can select.
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Day'[Date])", FilterContext::default()).expect("first date"), Scalar::DateTime(serial(2024, 1, 1)));
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Day'[Date])", FilterContext::default()).expect("last date"), Scalar::DateTime(serial(2024, 1, 3)));
|
||||
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(1899,12,30), DATE(1899,12,30))").expect("epoch day").rows.len(), 0);
|
||||
assert_eq!(evaluate_table_in(&model, "DATESBETWEEN('Day'[Date], DATE(2024,1,1), DATE(2024,1,3))").expect("window").rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datesbetween_is_inclusive_and_accepts_blanks() {
|
||||
let between = table("DATESBETWEEN('Date'[Date], DATE(2024, 1, 15), DATE(2024, 2, 10))");
|
||||
assert_eq!(between.rows.len(), 27);
|
||||
assert_eq!(between.columns.len(), 1);
|
||||
assert_eq!(between.columns[0].name, "Date");
|
||||
assert_eq!(between.lineage, Some(DATE_TABLE));
|
||||
assert_eq!(between.rows[0][0], Scalar::DateTime(serial(2024, 1, 15)));
|
||||
assert_eq!(between.rows[26][0], Scalar::DateTime(serial(2024, 2, 10)));
|
||||
|
||||
// BLANK boundaries fall back to the visible range.
|
||||
assert_eq!(row_count("DATESBETWEEN('Date'[Date], BLANK(), DATE(2024, 1, 5))", FilterContext::default()), 735);
|
||||
assert_eq!(row_count("DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), BLANK())", FilterContext::default()), 731);
|
||||
|
||||
assert_eq!(table("DATESBETWEEN('Date'[Date], DATE(2024, 2, 1), DATE(2024, 1, 1))").rows.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datesinperiod_moves_backwards_from_the_start_date() {
|
||||
let backwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -1, \"MONTH\")");
|
||||
assert_eq!(backwards.rows.len(), 29);
|
||||
assert_eq!(backwards.rows[0][0], Scalar::DateTime(serial(2024, 2, 16)));
|
||||
assert_eq!(backwards.rows[28][0], Scalar::DateTime(serial(2024, 3, 15)));
|
||||
|
||||
let forwards = table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 3, \"DAY\")");
|
||||
assert_eq!(forwards.rows.len(), 3);
|
||||
assert_eq!(forwards.rows[2][0], Scalar::DateTime(serial(2024, 3, 17)));
|
||||
assert_eq!(table("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), 0, \"DAY\")").rows.len(), 0);
|
||||
assert_eq!(
|
||||
bounds("DATESINPERIOD('Date'[Date], DATE(2024, 3, 15), -2, \"WEEK\")", FilterContext::default()),
|
||||
(serial(2024, 3, 2), serial(2024, 3, 15))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_date_windows() {
|
||||
assert_eq!(bounds("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), (serial(2024, 3, 1), serial(2024, 3, 20)));
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 20))), 20);
|
||||
assert_eq!(row_count("DATESQTD('Date'[Date])", dates((2024, 5, 1), (2024, 5, 10))), 40);
|
||||
assert_eq!(row_count("DATESWTD('Date')", dates((2024, 3, 13), (2024, 3, 15))), 6);
|
||||
assert_eq!(row_count("DATESYTD('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), 75);
|
||||
// A fiscal year ending June 30 starts on July 1.
|
||||
assert_eq!(row_count("DATESYTD('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), 46);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_boundaries() {
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 5)));
|
||||
assert_eq!(eval_with("LASTDATE('Date'[Date])", dates((2024, 3, 5), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 20)));
|
||||
let first = table("FIRSTDATE('Date'[Date])");
|
||||
assert_eq!(first.rows.len(), 1);
|
||||
assert_eq!(first.lineage, Some(DATE_TABLE));
|
||||
|
||||
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 3, 1)));
|
||||
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", dates((2024, 2, 1), (2024, 2, 10))), Scalar::DateTime(serial(2024, 2, 29)));
|
||||
assert_eq!(eval_with("STARTOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 4, 1)));
|
||||
assert_eq!(eval_with("ENDOFQUARTER('Date'[Date])", dates((2024, 5, 20), (2024, 5, 20))), Scalar::DateTime(serial(2024, 6, 30)));
|
||||
assert_eq!(eval_with("STARTOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 10)));
|
||||
assert_eq!(eval_with("ENDOFWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
assert_eq!(eval_with("STARTOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 1, 1)));
|
||||
assert_eq!(eval_with("ENDOFYEAR('Date'[Date])", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2024, 12, 31)));
|
||||
assert_eq!(eval_with("STARTOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 3, 20), (2024, 3, 20))), Scalar::DateTime(serial(2023, 7, 1)));
|
||||
assert_eq!(eval_with("ENDOFYEAR('Date'[Date], \"6/30/2024\")", dates((2024, 8, 15), (2024, 8, 15))), Scalar::DateTime(serial(2025, 6, 30)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_periods() {
|
||||
assert_eq!(eval_with("NEXTDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
assert_eq!(eval_with("PREVIOUSDAY('Date'[Date])", dates((2024, 3, 15), (2024, 3, 15))), Scalar::DateTime(serial(2024, 3, 14)));
|
||||
|
||||
assert_eq!(bounds("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 4, 1), serial(2024, 4, 30)));
|
||||
assert_eq!(bounds("PREVIOUSMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 10))), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
assert_eq!(row_count("NEXTQUARTER('Date'[Date])", dates((2024, 2, 1), (2024, 2, 28))), 91);
|
||||
assert_eq!(row_count("PREVIOUSQUARTER('Date'[Date])", dates((2024, 5, 1), (2024, 5, 31))), 91);
|
||||
assert_eq!(bounds("NEXTWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 17), serial(2024, 3, 23)));
|
||||
assert_eq!(bounds("PREVIOUSWEEK('Date')", dates((2024, 3, 13), (2024, 3, 13))), (serial(2024, 3, 3), serial(2024, 3, 9)));
|
||||
assert_eq!(bounds("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2025, 1, 1), serial(2025, 12, 31)));
|
||||
assert_eq!(row_count("NEXTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 365);
|
||||
assert_eq!(bounds("PREVIOUSYEAR('Date'[Date])", dates((2024, 1, 10), (2024, 1, 20))), (serial(2023, 1, 1), serial(2023, 12, 31)));
|
||||
|
||||
// A partial period is expanded to the full parallel period.
|
||||
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], -1, \"MONTH\")", dates((2024, 3, 15), (2024, 3, 20))), 29);
|
||||
assert_eq!(row_count("PARALLELPERIOD('Date'[Date], 0, \"YEAR\")", dates((2024, 3, 15), (2024, 3, 20))), 366);
|
||||
assert_eq!(row_count("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), 31);
|
||||
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31))), (serial(2023, 3, 1), serial(2023, 3, 31)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonblank_scan_uses_the_value_expression() {
|
||||
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 1, 10)));
|
||||
assert_eq!(eval_with("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), Scalar::DateTime(serial(2023, 12, 31)));
|
||||
assert_eq!(row_count("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2023)), 1);
|
||||
// An aggregate expression works too: it is evaluated in the date row's context.
|
||||
assert_eq!(
|
||||
eval_with("LASTNONBLANK('Date'[Date], SUM(Sales[Amount]))", dates((2024, 1, 1), (2024, 6, 30))),
|
||||
Scalar::DateTime(serial(2024, 6, 30))
|
||||
);
|
||||
// No sales at all in 2025: nothing is non-blank.
|
||||
assert_eq!(eval_with("FIRSTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), Scalar::Blank);
|
||||
assert_eq!(row_count("LASTNONBLANK('Date'[Date], [Sales Amount])", year(2025)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_tables_drive_calculate() {
|
||||
let march = dates((2024, 3, 1), (2024, 3, 31));
|
||||
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), DATESMTD('Date'[Date]))", march.clone()), Scalar::Decimal(400.0));
|
||||
assert_eq!(eval_with("CALCULATE([Sales Amount], SAMEPERIODLASTYEAR('Date'[Date]))", march), Scalar::Decimal(20.0));
|
||||
assert_eq!(eval_with("CALCULATE([Sales Amount], PREVIOUSYEAR('Date'[Date]))", dates((2024, 1, 10), (2024, 1, 20))), Scalar::Decimal(150.0));
|
||||
assert_eq!(eval_with("CALCULATE(SUM(Sales[Amount]), ENDOFMONTH('Date'[Date]))", dates((2024, 2, 1), (2024, 2, 10))), Scalar::Decimal(300.0));
|
||||
assert_eq!(eval_with("CALCULATE(COUNTROWS('Date'), FIRSTDATE('Date'[Date]))", dates((2024, 3, 1), (2024, 3, 31))), Scalar::Integer(1));
|
||||
// Rolling twelve months ending December 31, 2024.
|
||||
assert_eq!(
|
||||
eval_with("CALCULATE(SUM(Sales[Amount]), DATESINPERIOD('Date'[Date], DATE(2024, 12, 31), -12, \"MONTH\"))", FilterContext::default()),
|
||||
Scalar::Decimal(5500.0)
|
||||
);
|
||||
assert_eq!(
|
||||
eval_with("CALCULATE(SUM(Sales[Amount]), DATESBETWEEN('Date'[Date], DATE(2024, 1, 1), DATE(2024, 3, 31)))", FilterContext::default()),
|
||||
Scalar::Decimal(1000.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_row_results_are_not_scalars() {
|
||||
let error = eval_error("DATESMTD('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
|
||||
assert!(error.contains("rows"), "{error}");
|
||||
let error = eval_error("NEXTMONTH('Date'[Date])", dates((2024, 3, 1), (2024, 3, 31)));
|
||||
assert!(error.contains("rows"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_results_are_scalars() {
|
||||
let filters = dates((2024, 3, 15), (2024, 3, 15));
|
||||
assert_eq!(eval_with("STARTOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 1)));
|
||||
assert_eq!(eval_with("ENDOFMONTH('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2024, 3, 31)));
|
||||
assert_eq!(eval_with("NEXTDAY('Date'[Date])", filters), Scalar::DateTime(serial(2024, 3, 16)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_filter_context_yields_empty_windows() {
|
||||
// An empty date-column filter leaves nothing visible.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(DATE_TABLE, DATE_COLUMN, Vec::<ScalarKey>::new());
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", filters.clone()), 0);
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::Blank);
|
||||
assert_eq!(eval_with("LASTDATE('Date'[Date])", filters), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_filters_do_not_narrow_the_date_axis() {
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(SALES_TABLE, AMOUNT_COLUMN, [ScalarKey::from(&Scalar::Decimal(400.0))]);
|
||||
// Only one sale matches, but the date table itself is unfiltered.
|
||||
assert_eq!(eval_with("FIRSTDATE('Date'[Date])", filters.clone()), Scalar::DateTime(serial(2022, 1, 1)));
|
||||
assert_eq!(row_count("DATESMTD('Date'[Date])", filters), 31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interval_keywords_reach_the_evaluator_as_keywords() {
|
||||
// The binder turns a bare interval keyword (DATEADD(..., MONTH)) into `BoundExpr::Keyword`;
|
||||
// build that shape directly so the evaluator path is covered independently of the binder.
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let dateadd = BoundExpr::Call {
|
||||
spec: gridcraft_dax::lookup("DATEADD").expect("DATEADD is catalogued"),
|
||||
args: vec![
|
||||
BoundExpr::Column { table: DATE_TABLE, column: DATE_COLUMN },
|
||||
BoundExpr::Literal(Literal::Integer(-1)),
|
||||
BoundExpr::Keyword("MONTH".into()),
|
||||
],
|
||||
};
|
||||
let countrows = BoundExpr::Call { spec: gridcraft_dax::lookup("COUNTROWS").expect("COUNTROWS is catalogued"), args: vec![dateadd] };
|
||||
let count = evaluator.evaluate_with(&countrows, dates((2024, 3, 1), (2024, 3, 31))).expect("count");
|
||||
assert_eq!(count, Scalar::Integer(29));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn week_functions_accept_a_table_reference() {
|
||||
let filters = dates((2024, 3, 13), (2024, 3, 13));
|
||||
assert_eq!(row_count("DATESWTD('Date')", filters.clone()), 4);
|
||||
assert_eq!(eval_with("STARTOFWEEK('Date')", filters), Scalar::DateTime(serial(2024, 3, 10)));
|
||||
let error = eval_error("DATESWTD('Date'[Date])", FilterContext::default());
|
||||
assert!(error.contains("table"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_and_sameperiodlastyear_keep_the_leap_day_of_a_full_month() {
|
||||
// A full February shifted back a year reaches 29 February 2024, not 28.
|
||||
let february = dates((2025, 2, 1), (2025, 2, 28));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", february.clone()), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
assert_eq!(bounds("SAMEPERIODLASTYEAR('Date'[Date])", february), (serial(2024, 2, 1), serial(2024, 2, 29)));
|
||||
// A selection ending mid-month keeps its day span.
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"YEAR\")", dates((2025, 2, 1), (2025, 2, 15))), (serial(2024, 2, 1), serial(2024, 2, 15)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_extend_a_selection_ending_on_the_penultimate_day() {
|
||||
// 29 April is its month's penultimate day, but the selection does not contain 30 April, so
|
||||
// the shifted window keeps its day span instead of reaching 31 March.
|
||||
let selection = dates((2024, 4, 1), (2024, 4, 29));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], -1, \"MONTH\")", selection.clone()), (serial(2024, 3, 1), serial(2024, 3, 29)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], -1, \"MONTH\")", selection), 29);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_extend_a_selection_ending_on_day_30_of_a_31_day_month() {
|
||||
// 30 July is one day before its month end, but 31 July is not visible, so the shifted window
|
||||
// stops on 30 August instead of extending to 31 August.
|
||||
let selection = dates((2024, 7, 1), (2024, 7, 30));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 8, 1), serial(2024, 8, 30)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dateadd_does_not_expand_a_single_month_end_date_to_the_target_period() {
|
||||
// Only 30 April 2024 is visible: the date shifts to 30 May and stays a single date instead of
|
||||
// expanding to the end of May (or the whole target period).
|
||||
let selection = dates((2024, 4, 30), (2024, 4, 30));
|
||||
assert_eq!(bounds("DATEADD('Date'[Date], 1, \"MONTH\")", selection.clone()), (serial(2024, 5, 30), serial(2024, 5, 30)));
|
||||
assert_eq!(row_count("DATEADD('Date'[Date], 1, \"MONTH\")", selection), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_day_timestamps_stay_in_the_date_axis() {
|
||||
// Two timestamps sharing a day are distinct cells of the column, and the range tables key
|
||||
// their filter on those exact values, so both rows have to survive the axis.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let table = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,2), DATE(2024,1,2))").expect("window");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(table.rows[0][0], Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
|
||||
assert_eq!(table.rows[1][0], Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0));
|
||||
// The other days are untouched by the value-level deduplication.
|
||||
let whole = evaluate_table_in(&model, "DATESBETWEEN('Log'[Stamp], DATE(2024,1,1), DATE(2024,1,2))").expect("whole window");
|
||||
assert_eq!(whole.rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_functions_pick_one_cell_of_a_day() {
|
||||
// A day can hold several timestamps; `FIRSTDATE`/`LASTDATE` are scalar conveniences and must
|
||||
// return one exact cell rather than every cell of the day.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)],
|
||||
vec![Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "LASTDATE('Log'[Stamp])", FilterContext::default()).expect("last date"),
|
||||
Scalar::DateTime(serial(2024, 1, 3) + 10.0 / 24.0)
|
||||
);
|
||||
|
||||
// Filtered to the first day, which holds two timestamps: `FIRSTDATE` still returns one value.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
0,
|
||||
0,
|
||||
[Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0), Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]
|
||||
.into_iter()
|
||||
.map(|value| ScalarKey::from(&value)),
|
||||
);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters).expect("first date"), Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_date_functions_stay_inside_the_visible_cells() {
|
||||
// A filter that selects one timestamp of a two-timestamp day: `FIRSTDATE`/`LASTDATE` must pick
|
||||
// from the selected cell, not from the other timestamp the same day holds.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0)]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let early = Scalar::DateTime(serial(2024, 1, 2) + 9.0 / 24.0);
|
||||
let late = Scalar::DateTime(serial(2024, 1, 2) + 14.0 / 24.0);
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(0, 0, [ScalarKey::from(&late)]);
|
||||
|
||||
// 14:00 is the only visible cell: the last date is it, even though 09:00 exists in the column.
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", filters.clone()).expect("last date"), late);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", filters.clone()).expect("first date"), late);
|
||||
|
||||
let mut early_filters = FilterContext::default();
|
||||
early_filters.set(0, 0, [ScalarKey::from(&early)]);
|
||||
assert_eq!(evaluate_in(&model, "LASTDATE('Log'[Stamp])", early_filters.clone()).expect("last date"), early);
|
||||
assert_eq!(evaluate_in(&model, "FIRSTDATE('Log'[Stamp])", early_filters).expect("first date"), early);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonblank_candidates_match_mixed_case_text_rows() {
|
||||
// The candidate filter is written through `FilterContext::set`, which folds text the same way
|
||||
// the filter's own comparison does: a candidate `"A"` has to select the `"A"` and `"a"` rows.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "T".into(),
|
||||
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("a".into())], vec![Scalar::String("B".into())]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![gridcraft_dax::model::Measure {
|
||||
name: "Rows".into(),
|
||||
formula: "COUNTROWS('T')".into(),
|
||||
table: Some("T".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
// Only the folded candidate filter leaves rows for the expression; an unfolded key would match
|
||||
// nothing and make every candidate blank.
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "FIRSTNONBLANK('T'[Text], IF([Rows] = 0, BLANK(), 1))", FilterContext::default()).expect("first non blank"),
|
||||
Scalar::String("A".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_ends_pick_the_latest_timestamp_of_a_day() {
|
||||
// A day may hold several timestamps; the axis orders them by their full serial, so `ENDOFMONTH`
|
||||
// returns the latest one even when the model stores it before or after its siblings.
|
||||
let model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Log".into(),
|
||||
columns: vec![ModelColumn { name: "Stamp".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)], vec![Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(
|
||||
0,
|
||||
0,
|
||||
[Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0), Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)]
|
||||
.into_iter()
|
||||
.map(|value| ScalarKey::from(&value)),
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "ENDOFMONTH('Log'[Stamp])", filters.clone()).expect("end of month"),
|
||||
Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate_in(&model, "STARTOFMONTH('Log'[Stamp])", filters).expect("start of month"),
|
||||
Scalar::DateTime(serial(2024, 3, 31) + 9.0 / 24.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_impossible_year_end_date_is_rejected_by_the_range_functions() {
|
||||
// The same validation the total functions use: `"2/30"` is not a date, while the documented
|
||||
// `"6/30/2024"` and `"6/30"` forms are.
|
||||
let model = model();
|
||||
let count = |argument: &str| evaluate_in(&model, &format!("COUNTROWS(DATESYTD('Date'[Date], \"{argument}\"))"), FilterContext::default());
|
||||
assert!(count("2/30").is_err());
|
||||
// An empty component is not a date either.
|
||||
assert!(count("6/-30").is_err());
|
||||
assert!(count("6/").is_err());
|
||||
assert!(count("6/30").is_ok());
|
||||
assert!(count("6/30/2024").is_ok());
|
||||
assert!(count("2/29").is_ok());
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
//! Integration tests for the time-intelligence totals and balance evaluator functions.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, ScalarKey};
|
||||
use gridcraft_dax::{BoundExpr, Evaluator, FilterContext, Literal, lookup};
|
||||
|
||||
/// The calendar date of a whole-day Excel/OLE serial, via `chrono`.
|
||||
fn date_of(value: f64) -> chrono::NaiveDate {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
epoch + chrono::Duration::days(value.floor() as i64)
|
||||
}
|
||||
|
||||
/// Excel/OLE date serial for a whole day, computed with `chrono`.
|
||||
fn serial(year: i64, month: i64, day: i64) -> f64 {
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).expect("the Excel epoch is a valid date");
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32).expect("the fixture date is valid");
|
||||
(date - epoch).num_days() as f64
|
||||
}
|
||||
|
||||
fn date(year: i64, month: i64, day: i64) -> Scalar {
|
||||
Scalar::DateTime(serial(year, month, day))
|
||||
}
|
||||
|
||||
/// The fixture shared with the worksheet/measure cases: Sales facts for 2023-2024 and a
|
||||
/// contiguous Date table covering both years.
|
||||
fn model() -> DataModel {
|
||||
use chrono::Datelike;
|
||||
let start = date_of(serial(2023, 1, 1));
|
||||
let end = date_of(serial(2024, 12, 31));
|
||||
let date_rows: Vec<Vec<Scalar>> = start
|
||||
.iter_days()
|
||||
.take_while(|date| *date <= end)
|
||||
.map(|date| {
|
||||
// Excel's weekday numbering is 1 = Sunday, matching the evaluator's WEEKDAY default.
|
||||
let (year, month) = (i64::from(date.year()), i64::from(date.month()));
|
||||
vec![
|
||||
Scalar::DateTime(serial(year, month, i64::from(date.day()))),
|
||||
Scalar::Integer(year),
|
||||
Scalar::Integer((month - 1) / 3 + 1),
|
||||
Scalar::Integer(month),
|
||||
Scalar::Integer(i64::from(date.weekday().num_days_from_sunday()) + 1),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(40), date(2024, 1, 3)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(100), date(2024, 1, 5)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(250), date(2024, 1, 12)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(75), date(2024, 2, 3)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(400), date(2024, 2, 20)],
|
||||
vec![Scalar::String("East".into()), Scalar::Blank, date(2024, 3, 15)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(150), date(2024, 4, 1)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(300), date(2024, 6, 18)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(50), date(2024, 7, 7)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(220), date(2024, 9, 9)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(90), date(2024, 11, 11)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(180), date(2024, 12, 1)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(310), date(2024, 12, 25)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(60), date(2023, 3, 10)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(140), date(2023, 6, 15)],
|
||||
vec![Scalar::String("North".into()), Scalar::Integer(200), date(2023, 9, 20)],
|
||||
vec![Scalar::String("South".into()), Scalar::Integer(80), date(2023, 12, 5)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quarter".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Month".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Weekday".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: date_rows,
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Date".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
measure("Total Amount", "SUM(Sales[Amount])"),
|
||||
measure("MTD", "TOTALMTD([Total Amount], 'Date'[Date])"),
|
||||
measure("QTD", "TOTALQTD([Total Amount], 'Date'[Date])"),
|
||||
measure("WTD", "TOTALWTD([Total Amount], Date)"),
|
||||
measure("YTD", "TOTALYTD([Total Amount], 'Date'[Date])"),
|
||||
measure("YTD June", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("YTD All", "TOTALYTD([Total Amount], 'Date'[Date], ALL ())"),
|
||||
measure("QTD Remove All", "TOTALQTD([Total Amount], 'Date'[Date], REMOVEFILTERS ())"),
|
||||
measure("YTD Region All", "TOTALYTD([Total Amount], 'Date'[Date], ALL([Region]))"),
|
||||
measure("YTD Over Ten", "TOTALYTD(SUM(Sales[Amount]), 'Date'[Date], Sales[Amount] > 100)"),
|
||||
measure("YTD Unqualified", "TOTALYTD([Total Amount], 'Date'[Date], [Region] = \"East\")"),
|
||||
measure("OB Month", "OPENINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Month", "CLOSINGBALANCEMONTH([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Quarter", "OPENINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Quarter", "CLOSINGBALANCEQUARTER([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Week", "OPENINGBALANCEWEEK([Total Amount], Date)"),
|
||||
measure("CB Week", "CLOSINGBALANCEWEEK([Total Amount], Date)"),
|
||||
measure("OB Year", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
|
||||
measure("CB Year", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date])"),
|
||||
measure("OB Year June", "OPENINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("CB Year June", "CLOSINGBALANCEYEAR([Total Amount], 'Date'[Date], ALL(Sales), \"6/30/2024\")"),
|
||||
measure("First Non Blank", "FIRSTNONBLANKVALUE('Date'[Date], [Total Amount])"),
|
||||
measure("Last Non Blank", "LASTNONBLANKVALUE('Date'[Date], [Total Amount])"),
|
||||
measure("Bad Date Column", "TOTALMTD([Total Amount], Sales[Amount])"),
|
||||
measure("Bad Filter", "TOTALMTD([Total Amount], 'Date'[Date], 1)"),
|
||||
measure("Bad Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"not a date\")"),
|
||||
measure("Impossible Year End", "TOTALYTD([Total Amount], 'Date'[Date], ALL(Sales), \"2/30\")"),
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
model
|
||||
}
|
||||
|
||||
fn measure(name: &str, formula: &str) -> Measure {
|
||||
Measure { name: name.into(), formula: formula.into(), table: Some("Sales".into()), format: None, expr: None }
|
||||
}
|
||||
|
||||
fn filters(model: &DataModel, pairs: &[(&str, &str, Scalar)]) -> FilterContext {
|
||||
let mut context = FilterContext::default();
|
||||
for (table, column, value) in pairs {
|
||||
let table_index = model.table_index(table).expect("table exists");
|
||||
let column_index = model.column_index(table_index, column).expect("column exists");
|
||||
context.set(table_index, column_index, [ScalarKey::from(value)]);
|
||||
}
|
||||
context
|
||||
}
|
||||
|
||||
fn date_filter(model: &DataModel, dates: &[Scalar]) -> FilterContext {
|
||||
let table = model.table_index("Date").expect("Date table");
|
||||
let column = model.column_index(table, "Date").expect("Date column");
|
||||
let mut context = FilterContext::default();
|
||||
context.set(table, column, dates.iter().map(ScalarKey::from));
|
||||
context
|
||||
}
|
||||
|
||||
fn eval_measure(model: &DataModel, name: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_measure(name, filters).map_err(|error| format!("{name}: {error}"))
|
||||
}
|
||||
|
||||
fn assert_number(result: Result<Scalar, String>, expected: f64) {
|
||||
match result {
|
||||
Ok(value) => {
|
||||
let actual = value.to_number().expect("numeric result");
|
||||
assert!((actual - expected).abs() < 1e-9, "expected {expected}, got {actual} ({value:?})");
|
||||
}
|
||||
Err(error) => panic!("unexpected error: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn february_filter(model: &DataModel) -> FilterContext {
|
||||
filters(model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn period_to_date_totals() {
|
||||
let model = model();
|
||||
let february = february_filter(&model);
|
||||
// February 2024: 2024-02-03 (75) + 2024-02-20 (400); January 2024: 40 + 100 + 250.
|
||||
assert_number(eval_measure(&model, "MTD", february.clone()), 475.0);
|
||||
assert_number(eval_measure(&model, "QTD", february.clone()), 865.0);
|
||||
assert_number(eval_measure(&model, "YTD", february.clone()), 865.0);
|
||||
// Fiscal year ending June 30: H2 2023 (200 + 80) plus the 2024 YTD window.
|
||||
assert_number(eval_measure(&model, "YTD June", february), 1145.0);
|
||||
|
||||
let january = date_filter(&model, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&model, "MTD", january.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "QTD", january.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "YTD", january.clone()), 140.0);
|
||||
// 2024-01-05 is a Friday: the DAX week starts on Sunday 2023-12-31.
|
||||
assert_number(eval_measure(&model, "WTD", january), 140.0);
|
||||
|
||||
let second_friday = date_filter(&model, &[date(2024, 1, 12)]);
|
||||
assert_number(eval_measure(&model, "WTD", second_friday), 250.0);
|
||||
|
||||
// The last visible date anchors the window: Feb 28 only, not the whole month.
|
||||
let partial = date_filter(&model, &[date(2024, 1, 5), date(2024, 2, 28)]);
|
||||
assert_number(eval_measure(&model, "MTD", partial.clone()), 475.0);
|
||||
assert_number(eval_measure(&model, "QTD", partial.clone()), 865.0);
|
||||
// No sale in the week of 2024-02-28 (Sunday 25th to Saturday 2nd), so the sum is blank.
|
||||
assert_eq!(eval_measure(&model, "WTD", partial), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_and_closing_balances() {
|
||||
// Boundary dates need facts: add one sale on every date the balance functions select.
|
||||
let mut facts = model();
|
||||
let boundaries = [
|
||||
(2023, 6, 30, 900),
|
||||
(2023, 12, 30, 450),
|
||||
(2023, 12, 31, 500),
|
||||
(2024, 1, 6, 550),
|
||||
(2024, 1, 13, 650),
|
||||
(2024, 1, 31, 600),
|
||||
(2024, 2, 29, 700),
|
||||
(2024, 3, 31, 800),
|
||||
(2024, 6, 30, 950),
|
||||
(2024, 12, 31, 1000),
|
||||
];
|
||||
let sales = &mut facts.tables[0].rows;
|
||||
for (year, month, day, amount) in boundaries {
|
||||
sales.push(vec![Scalar::String("Boundary".into()), Scalar::Integer(amount), date(year, month, day)]);
|
||||
}
|
||||
|
||||
let february = february_filter(&facts);
|
||||
// EXCEL: CLOSINGBALANCEMONTH = CALCULATE(expr, ENDOFMONTH(dates)), OPENING = previous day.
|
||||
assert_number(eval_measure(&facts, "OB Month", february.clone()), 600.0);
|
||||
assert_number(eval_measure(&facts, "CB Month", february.clone()), 700.0);
|
||||
assert_number(eval_measure(&facts, "OB Quarter", february.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Quarter", february.clone()), 800.0);
|
||||
assert_number(eval_measure(&facts, "OB Year", february.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Year", february.clone()), 1000.0);
|
||||
// Fiscal year July 2023 - June 2024: opening is 2023-06-30, closing is 2024-06-30.
|
||||
assert_number(eval_measure(&facts, "OB Year June", february.clone()), 900.0);
|
||||
assert_number(eval_measure(&facts, "CB Year June", february), 950.0);
|
||||
|
||||
let january = date_filter(&facts, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&facts, "OB Month", january.clone()), 500.0);
|
||||
assert_number(eval_measure(&facts, "CB Month", january.clone()), 600.0);
|
||||
// The DAX week starts on Sunday 2023-12-31, so the opening date is 2023-12-30.
|
||||
assert_number(eval_measure(&facts, "OB Week", january.clone()), 450.0);
|
||||
assert_number(eval_measure(&facts, "CB Week", january), 550.0);
|
||||
|
||||
let second_week = date_filter(&facts, &[date(2024, 1, 12)]);
|
||||
assert_number(eval_measure(&facts, "OB Week", second_week.clone()), 550.0);
|
||||
assert_number(eval_measure(&facts, "CB Week", second_week), 650.0);
|
||||
|
||||
// March 31 carries a boundary fact, so the closing balance is that day's value.
|
||||
let march = filters(&facts, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
|
||||
assert_eq!(eval_measure(&facts, "CB Month", march), Ok(Scalar::Decimal(800.0)));
|
||||
|
||||
// Without a fact on the boundary date Excel returns BLANK, not a scan backwards.
|
||||
let sparse = model();
|
||||
let february = february_filter(&sparse);
|
||||
assert_eq!(eval_measure(&sparse, "OB Month", february.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&sparse, "CB Month", february), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_and_last_non_blank_values() {
|
||||
let model = model();
|
||||
let february = february_filter(&model);
|
||||
assert_number(eval_measure(&model, "First Non Blank", february.clone()), 75.0);
|
||||
assert_number(eval_measure(&model, "Last Non Blank", february.clone()), 400.0);
|
||||
|
||||
let january = date_filter(&model, &[date(2024, 1, 5)]);
|
||||
assert_number(eval_measure(&model, "First Non Blank", january.clone()), 100.0);
|
||||
assert_number(eval_measure(&model, "Last Non Blank", january), 100.0);
|
||||
|
||||
let march = filters(&model, &[("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(3))]);
|
||||
assert_eq!(eval_measure(&model, "First Non Blank", march.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "Last Non Blank", march), Ok(Scalar::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_clears_the_outer_filter_context() {
|
||||
let model = model();
|
||||
// February 2024 restricted to the East region: the outer filter sits on the fact table, the
|
||||
// date filters only anchor the window.
|
||||
let east_february = filters(
|
||||
&model,
|
||||
&[("Sales", "Region", Scalar::String("East".into())), ("Date", "Year", Scalar::Integer(2024)), ("Date", "Month", Scalar::Integer(2))],
|
||||
);
|
||||
// Without a filter argument the region filter still applies: East only, January + February.
|
||||
assert_number(eval_measure(&model, "YTD", east_february.clone()), 140.0);
|
||||
assert_number(eval_measure(&model, "QTD", east_february.clone()), 140.0);
|
||||
|
||||
// `ALL ()` clears the whole filter context, so every region is visible again over the same
|
||||
// year-to-date window (40 + 100 + 250 + 75 + 400 = 865).
|
||||
assert_number(eval_measure(&model, "YTD All", east_february.clone()), 865.0);
|
||||
// `REMOVEFILTERS ()` is the same modifier.
|
||||
assert_number(eval_measure(&model, "QTD Remove All", east_february.clone()), 865.0);
|
||||
// An unqualified column argument clears just that column: `[Region]` resolves to Sales[Region].
|
||||
assert_number(eval_measure(&model, "YTD Region All", east_february), 865.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_window_and_invalid_arguments() {
|
||||
let model = model();
|
||||
|
||||
// A date filter outside the model's date range leaves nothing visible.
|
||||
let outside = date_filter(&model, &[date(2030, 1, 1)]);
|
||||
assert_eq!(eval_measure(&model, "MTD", outside.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "CB Month", outside.clone()), Ok(Scalar::Blank));
|
||||
assert_eq!(eval_measure(&model, "First Non Blank", outside), Ok(Scalar::Blank));
|
||||
|
||||
let error = eval_measure(&model, "Bad Date Column", FilterContext::default()).expect_err("amount is not a date");
|
||||
assert!(error.contains("not a date column"), "{error}");
|
||||
|
||||
let error = eval_measure(&model, "Bad Filter", FilterContext::default()).expect_err("invalid filter");
|
||||
assert!(error.contains("table expression"), "{error}");
|
||||
|
||||
let error = eval_measure(&model, "Bad Year End", FilterContext::default()).expect_err("invalid year end");
|
||||
assert!(error.contains("YearEndDate"), "{error}");
|
||||
// The range functions share the parser, so an impossible day is rejected here too.
|
||||
let error = eval_measure(&model, "Impossible Year End", FilterContext::default()).expect_err("2/30 is not a date");
|
||||
assert!(error.contains("YearEndDate"), "{error}");
|
||||
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let spec = lookup("TOTALMTD").expect("catalog entry");
|
||||
let error = evaluator.evaluate(&BoundExpr::Call { spec, args: Vec::new() }).expect_err("arity");
|
||||
assert!(error.message.contains("between 2 and 3"), "{}", error.message);
|
||||
|
||||
let spec = lookup("FIRSTNONBLANKVALUE").expect("catalog entry");
|
||||
let measure_index = model.measure_index("Total Amount").expect("measure");
|
||||
let expr = BoundExpr::Call { spec, args: vec![BoundExpr::Literal(Literal::Integer(1)), BoundExpr::Measure(measure_index)] };
|
||||
let error = evaluator.evaluate(&expr).expect_err("non-column argument");
|
||||
assert!(error.message.contains("column reference"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_and_unqualified_column_filters_are_applied() {
|
||||
// `TOTALYTD(expr, dates, filter)` is CALCULATE sugar: a comparison and an unqualified column
|
||||
// are filter arguments too, not table expressions.
|
||||
let model = model();
|
||||
let february = date_filter(&model, &[Scalar::DateTime(serial(2024, 2, 1)), Scalar::DateTime(serial(2024, 2, 29))]);
|
||||
let plain = eval_measure(&model, "YTD", february.clone()).expect("YTD");
|
||||
let filtered = eval_measure(&model, "YTD Over Ten", february).expect("YTD Over Ten");
|
||||
// Exact totals, so a filter argument the evaluator ignored could not pass: every 2024
|
||||
// January-February amount is above 10 but only two are above 100.
|
||||
assert_eq!(plain.to_number(), Some(865.0));
|
||||
assert_eq!(filtered.to_number(), Some(650.0));
|
||||
let east = eval_measure(&model, "YTD Unqualified", FilterContext::default()).expect("YTD Unqualified");
|
||||
assert_eq!(east.to_number(), Some(360.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_dimension_filters_reach_the_visible_date_range() {
|
||||
// Snowflaked calendar: `Date` is many-to-one against a `Year` dimension on its one side.
|
||||
// Filtering `Year` propagates to `Date`, so the dates visible to the range functions narrow
|
||||
// to the filtered year instead of spanning the whole model calendar.
|
||||
let mut model = model();
|
||||
model.tables.push(ModelTable {
|
||||
name: "Year".into(),
|
||||
columns: vec![ModelColumn { name: "Year".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(2023)], vec![Scalar::Integer(2024)]],
|
||||
});
|
||||
model.relationships.push(Relationship {
|
||||
from_table: "Date".into(),
|
||||
from_column: "Year".into(),
|
||||
to_table: "Year".into(),
|
||||
to_column: "Year".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
});
|
||||
model.measures.push(measure("Last Date", "LASTDATE('Date'[Date])"));
|
||||
model.measures.push(measure("First Date", "FIRSTDATE('Date'[Date])"));
|
||||
model.measures.push(measure("Dates YTD Rows", "COUNTROWS(DATESYTD('Date'[Date]))"));
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
let y2023 = filters(&model, &[("Year", "Year", Scalar::Integer(2023))]);
|
||||
// The axis ends on the last date of the year the relationship selects, not on the model's
|
||||
// overall last date (2024-12-31).
|
||||
assert_eq!(eval_measure(&model, "Last Date", y2023.clone()), Ok(date(2023, 12, 31)));
|
||||
assert_eq!(eval_measure(&model, "First Date", y2023.clone()), Ok(date(2023, 1, 1)));
|
||||
// 2023 is not a leap year: 365 days in the year-to-date window, not the 366 of 2024.
|
||||
assert_number(eval_measure(&model, "Dates YTD Rows", y2023.clone()), 365.0);
|
||||
// The year-to-date total is 2023's own facts: 60 + 140 + 200 + 80.
|
||||
assert_number(eval_measure(&model, "YTD", y2023.clone()), 480.0);
|
||||
|
||||
let y2024 = filters(&model, &[("Year", "Year", Scalar::Integer(2024))]);
|
||||
assert_eq!(eval_measure(&model, "Last Date", y2024.clone()), Ok(date(2024, 12, 31)));
|
||||
assert_number(eval_measure(&model, "Dates YTD Rows", y2024.clone()), 366.0);
|
||||
// 2024's facts: 40 + 100 + 250 + 75 + 400 + 150 + 300 + 50 + 220 + 90 + 180 + 310.
|
||||
assert_number(eval_measure(&model, "YTD", y2024), 2165.0);
|
||||
}
|
||||
|
||||
/// Fixtures for the two fact-table cases: a model whose date column is a fact column, so there is
|
||||
/// no date dimension whose filters the window may replace.
|
||||
fn fact_date_model(mut measures: Vec<Measure>, rows: Vec<Vec<Scalar>>, amount_type: &str) -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some(amount_type.into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows,
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: std::mem::take(&mut measures),
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
model
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_date_totals_keep_the_other_fact_filters() {
|
||||
// The date column is a fact column, so the window replaces only that column's filter: the
|
||||
// Region slice has to keep applying, as it would to `CALCULATE ( SUM (…), DATESYTD (…) )`.
|
||||
let model = fact_date_model(
|
||||
vec![measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"), measure("MTD Fact", "TOTALMTD(SUM(Sales[Amount]), Sales[Date])")],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), date(2024, 1, 10)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(20), date(2024, 3, 10)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(100), date(2024, 1, 20)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
let east = filters(&model, &[("Sales", "Region", Scalar::String("East".into()))]);
|
||||
// East's own year-to-date facts: 10 + 20. Dropping the Region filter would return 130.
|
||||
assert_number(eval_measure(&model, "YTD Fact", east.clone()), 30.0);
|
||||
assert_number(eval_measure(&model, "MTD Fact", east.clone()), 20.0);
|
||||
|
||||
// A filter on the fact date column itself is replaced by the window, not intersected with it:
|
||||
// anchoring on 2024-03-10 makes the year-to-date window run from 2024-01-01, so both East rows
|
||||
// count (30). Keeping and intersecting the filter would return only 2024-03-10's 20.
|
||||
let east_march = filters(&model, &[("Sales", "Region", Scalar::String("East".into())), ("Sales", "Date", date(2024, 3, 10))]);
|
||||
assert_number(eval_measure(&model, "YTD Fact", east_march), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_date_totals_match_cells_that_carry_a_time_of_day() {
|
||||
// DateTime cells may store a time of day, and a day may hold more than one timestamp; every
|
||||
// cell of the period still has to count, not just the first one found for its day.
|
||||
let model = fact_date_model(
|
||||
vec![
|
||||
measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
|
||||
measure("OB Month", "OPENINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])"),
|
||||
measure("YTD Fact", "TOTALYTD(SUM(Sales[Amount]), Sales[Date])"),
|
||||
],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(5), Scalar::DateTime(serial(2024, 1, 1))],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(7), Scalar::DateTime(serial(2024, 2, 29) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
// March's closing balance covers both 2024-03-31 timestamps, not the earlier February date.
|
||||
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
|
||||
// March's opening balance is the day before its start: 2024-02-29 09:30.
|
||||
assert_number(eval_measure(&model, "OB Month", FilterContext::default()), 7.0);
|
||||
// The year-to-date window keeps every cell: 5 + 7 + 3 + 10, including both March 31 rows.
|
||||
assert_number(eval_measure(&model, "YTD Fact", FilterContext::default()), 25.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_filters_intersect_the_boundary_day() {
|
||||
// The boundary day holds two timestamps; a filter argument that keeps only one of them has to
|
||||
// intersect with the boundary keys, exactly like `TOTAL*`, instead of being dropped.
|
||||
let mut model = fact_date_model(
|
||||
vec![measure("CB Month", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date])")],
|
||||
vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(3), Scalar::DateTime(serial(2024, 3, 31) + 9.5 / 24.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::DateTime(serial(2024, 3, 31) + 14.0 / 24.0)],
|
||||
],
|
||||
"Int64",
|
||||
);
|
||||
model.measures.push(measure("CB Month Filtered", "CLOSINGBALANCEMONTH(SUM(Sales[Amount]), Sales[Date], Sales[Date] > DATE(2024,3,31) + 10/24)"));
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
// Without a filter both same-day cells are the boundary.
|
||||
assert_number(eval_measure(&model, "CB Month", FilterContext::default()), 13.0);
|
||||
// With a filter that keeps only the 14:00 cell the boundary is one cell: 10, not 13.
|
||||
assert_number(eval_measure(&model, "CB Month Filtered", FilterContext::default()), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_table_argument_uses_its_typed_date_column() {
|
||||
// `TOTALWTD(…, Calendar)` must resolve the calendar's date column exactly like `DATESWTD`:
|
||||
// the declared date type wins over an earlier untyped column.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Label".into(), data_type: None },
|
||||
ModelColumn { name: "Day".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::String("first".into()), date(2024, 1, 1)], vec![Scalar::String("second".into()), date(2024, 1, 2)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
|
||||
.into_iter()
|
||||
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
|
||||
// 2024-01-02 is a Tuesday, so the week starts on Sunday 2023-12-31: both calendar days are in
|
||||
// the window and the sum is 30. Binding the untyped `Label` column would return BLANK.
|
||||
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_with_one_untyped_column_is_still_a_calendar() {
|
||||
// A calendar whose only date column is untyped keeps working: the unambiguous untyped column
|
||||
// is the fallback once no typed date column and no `Date` column exist.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![ModelColumn { name: "Day".into(), data_type: None }],
|
||||
rows: vec![vec![date(2024, 1, 1)], vec![date(2024, 1, 2)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![[10.0, serial(2024, 1, 1)], [20.0, serial(2024, 1, 2)]]
|
||||
.into_iter()
|
||||
.map(|[amount, serial]| vec![Scalar::Decimal(amount), Scalar::DateTime(serial)])
|
||||
.collect(),
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
assert_number(eval_measure(&model, "Week To Date", FilterContext::default()), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_calendar_date_column_declared_as_a_non_date_type_is_rejected() {
|
||||
// An integer `Date` column (YYYYMMDD keys) is not a date axis: report the model, do not read
|
||||
// its numbers as OLE serials.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Calendar".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("Int64".into()) }],
|
||||
rows: vec![vec![Scalar::Integer(20_240_101)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }],
|
||||
rows: vec![vec![Scalar::Decimal(10.0)]],
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![measure("Week To Date", "TOTALWTD(SUM(Sales[Amount]), Calendar)")],
|
||||
};
|
||||
model.parse_formulas().expect("model formulas parse");
|
||||
let error = eval_measure(&model, "Week To Date", FilterContext::default()).expect_err("an Int64 Date column is not a date axis");
|
||||
assert!(error.contains("has no date column"), "{error}");
|
||||
}
|
||||
@@ -29,7 +29,14 @@ gridcraft-math = { workspace = true }
|
||||
image = { workspace = true }
|
||||
unicode-segmentation = "=1.13.3"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
cap-std = "4.0.3"
|
||||
getrandom = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
gridcraft-xlsx = { workspace = true, features = ["test-support"] }
|
||||
gridcraft-model = { workspace = true, features = ["test-support"] }
|
||||
zip = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
tempfile = "3.27"
|
||||
|
||||
@@ -210,6 +210,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
super::extra::keep_page_breaks(d, &now);
|
||||
d.calc.rebuild(&d.wb);
|
||||
d.revision += 1;
|
||||
Ok(json!({"undone": label}))
|
||||
@@ -232,6 +233,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
super::extra::keep_page_breaks(d, &now);
|
||||
d.calc.rebuild(&d.wb);
|
||||
d.revision += 1;
|
||||
Ok(json!({"redone": label}))
|
||||
|
||||
@@ -28,7 +28,7 @@ use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}
|
||||
pub(crate) use scripts::has_scripts;
|
||||
use scripts::{all_scripts, delete_script, new_script, record, run_script, stop_action, trust_scripts};
|
||||
use window::{arrange_all, custom_views, hide_window, new_window, ruler, set_view, split, switch_windows, unhide_window, watch_window};
|
||||
pub(crate) use window::{keep_view_modes, keep_watch_list, window_param};
|
||||
pub(crate) use window::{keep_page_breaks, keep_view_modes, keep_watch_list, window_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
|
||||
@@ -72,9 +72,19 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Query field identity follows the surviving physical column, even if its header was renamed.
|
||||
let query_field_id = c.checked_sub(old.start.col).and_then(|i| old_cols.get(i as usize)).and_then(|x| x.query_field_id);
|
||||
cols.push(match existing {
|
||||
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
|
||||
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
Some(x) => TableColumn { name: name.clone(), query_field_id, ..x.clone() },
|
||||
None => TableColumn {
|
||||
name: name.clone(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id,
|
||||
xml: None,
|
||||
},
|
||||
});
|
||||
}
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
|
||||
@@ -4,7 +4,8 @@ use super::{
|
||||
};
|
||||
|
||||
/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it
|
||||
/// neither records an undo step nor marks a clean workbook as changed.
|
||||
/// neither records an undo step nor marks a clean workbook as changed. Page Break Preview also
|
||||
/// turns on the sheet's page breaks, which Normal view then keeps showing (as in Excel).
|
||||
pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result<Json> {
|
||||
let si = target_sheet(s, p)?;
|
||||
let d = s.doc_mut()?;
|
||||
@@ -12,6 +13,9 @@ pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
if let Some(sh) = wb.sheet_mut(si) {
|
||||
sh.view = mode;
|
||||
if mode == SheetViewMode::PageBreakPreview {
|
||||
sh.show_page_breaks = true;
|
||||
}
|
||||
}
|
||||
if !dirty {
|
||||
d.saved = d.wb.clone();
|
||||
@@ -38,6 +42,35 @@ pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>
|
||||
wb.names.extend(keep);
|
||||
}
|
||||
|
||||
/// Show page breaks is a view setting: keep it on each surviving sheet across undo and redo.
|
||||
/// Sheet identities persist through renames and moves; a restored sheet with no current identity
|
||||
/// keeps its own snapshot value. A kept setting does not make a saved workbook dirty.
|
||||
pub(crate) fn keep_page_breaks(d: &mut crate::DocState, from: &Workbook) {
|
||||
let changed: Vec<_> =
|
||||
d.wb.sheets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, sh)| {
|
||||
let on = from.sheets.iter().find(|f| f.uid.get() == sh.uid.get()).map_or(sh.show_page_breaks, |f| f.show_page_breaks);
|
||||
(sh.show_page_breaks != on).then_some((i, on))
|
||||
})
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let dirty = d.is_dirty();
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
// Only the sheets that differ are copied (`sheet_mut` unshares the sheet).
|
||||
for (i, on) in changed {
|
||||
if let Some(sh) = wb.sheet_mut(i) {
|
||||
sh.show_page_breaks = on;
|
||||
}
|
||||
}
|
||||
if !dirty {
|
||||
d.saved = d.wb.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Normal, Page Layout and Page Break Preview belong to the window, not to the edits: Excel doesn't
|
||||
/// undo a switch between them, and `set_view` is no undo step. So undo and redo keep each sheet's
|
||||
/// current view when they swap in another snapshot of the workbook, and a view kept this way
|
||||
|
||||
@@ -413,7 +413,15 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
totals_row: false,
|
||||
columns: headers
|
||||
.iter()
|
||||
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|h| TableColumn {
|
||||
name: h.clone(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
@@ -424,6 +432,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let q = gridcraft_formula::quote_sheet(&sheet_name);
|
||||
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
|
||||
|
||||
@@ -1057,7 +1057,7 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// values change as soon as it is switched on or off.
|
||||
let precision_changed = c.precision_as_displayed != before.precision_as_displayed;
|
||||
if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) || precision_changed {
|
||||
cx.structural = true;
|
||||
cx.recalc_all = true;
|
||||
}
|
||||
Ok(json!({
|
||||
"mode": format!("{:?}", c.mode),
|
||||
@@ -1073,6 +1073,42 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn calculation_options_preserve_numeric_table_headers() {
|
||||
for (mode, precision, params) in [
|
||||
(CalcMode::Automatic, false, json!({"mode": "automatic"})),
|
||||
(CalcMode::Manual, false, json!({"mode": "automatic"})),
|
||||
(CalcMode::Automatic, false, json!({"iterative": true})),
|
||||
(CalcMode::Manual, false, json!({"precisionAsDisplayed": true})),
|
||||
(CalcMode::Manual, true, json!({"precisionAsDisplayed": false})),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Price", "Qty"], [7, 1]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:B2", "header": true})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=SUM(Table1[Price])"})).unwrap();
|
||||
|
||||
let header = CellRef::new(0, 0);
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
wb.calc.mode = mode;
|
||||
wb.calc.precision_as_displayed = precision;
|
||||
let sheet = wb.sheet_mut(0).unwrap();
|
||||
// A workbook can import a numeric cell with a different table column name.
|
||||
sheet.set_value(header, Value::Number(123.0));
|
||||
sheet.set_value(CellRef::new(1, 0), Value::Number(9.0));
|
||||
assert_eq!(sheet.value(CellRef::new(0, 3)), Value::Number(7.0));
|
||||
|
||||
s.execute("formulas.calculationOptions", params.clone()).unwrap();
|
||||
|
||||
let sheet = s.doc().unwrap().wb.sheet(0).unwrap();
|
||||
assert_eq!(sheet.value(header), Value::Number(123.0), "{params}");
|
||||
assert_eq!(sheet.tables[0].columns[0].name, "Price", "{params}");
|
||||
let result = s.execute("cell.get", json!({"cell": "D1"})).unwrap();
|
||||
assert_eq!(result["formula"], "=SUM(Table1[Price])", "{params}");
|
||||
assert_eq!(result["value"], json!(9.0), "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_with_relative_references() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Chart",
|
||||
["Insert", "Charts"],
|
||||
None,
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|pareto|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
|
||||
has_doc,
|
||||
insert_chart
|
||||
),
|
||||
|
||||
@@ -59,6 +59,7 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
|
||||
("bubble", _) => ChartKind::Bubble,
|
||||
("radar", _) => ChartKind::Radar,
|
||||
("histogram", _) => ChartKind::Histogram,
|
||||
("pareto", _) => ChartKind::Pareto,
|
||||
("waterfall", _) => ChartKind::Waterfall,
|
||||
("funnel", _) => ChartKind::Funnel,
|
||||
("treemap", _) => ChartKind::Treemap,
|
||||
@@ -285,7 +286,11 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
|
||||
},
|
||||
title,
|
||||
series,
|
||||
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
|
||||
legend: match kind {
|
||||
ChartKind::Pie | ChartKind::Doughnut => LegendPos::Right,
|
||||
ChartKind::Pareto => LegendPos::None,
|
||||
_ => LegendPos::Bottom,
|
||||
},
|
||||
data_labels: false,
|
||||
data_table: None,
|
||||
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
|
||||
|
||||
@@ -112,7 +112,15 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
totals_row: false,
|
||||
columns: names
|
||||
.into_iter()
|
||||
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.map(|n| TableColumn {
|
||||
name: n,
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
})
|
||||
.collect(),
|
||||
style,
|
||||
banded_rows: true,
|
||||
@@ -123,6 +131,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
cx.structural = true;
|
||||
Ok(json!({"table": name, "range": r.a1()}))
|
||||
|
||||
@@ -56,7 +56,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
|
||||
#[cfg(test)]
|
||||
use layout::bands;
|
||||
pub(crate) use layout::split_bands;
|
||||
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
|
||||
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, page_break_bands, paper_size, print_range};
|
||||
use layout::{seg_size, segments};
|
||||
use objects::{PicCache, draw_objects};
|
||||
#[cfg(test)]
|
||||
@@ -96,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Page Setup…",
|
||||
["Page Layout", "Page Setup"],
|
||||
None,
|
||||
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
|
||||
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
|
||||
has_doc,
|
||||
page_setup
|
||||
),
|
||||
|
||||
@@ -353,7 +353,7 @@ pub(crate) fn page_sequence(rows: usize, cols: usize, order: PageOrder, cap: usi
|
||||
}
|
||||
|
||||
/// Inclusive-start/end index spans of the pages along one axis.
|
||||
pub(crate) type Bands = Vec<(u32, u32)>;
|
||||
pub type Bands = Vec<(u32, u32)>;
|
||||
|
||||
/// Splits a layout's area into row and column bands that fit its pages (at most `cap` of each),
|
||||
/// honouring manual breaks (when `lay.manual_breaks`), print headings and repeated titles. The
|
||||
@@ -386,6 +386,24 @@ pub(crate) fn split_bands(sh: &Sheet, lay: &SheetLayout, cap: usize) -> (Bands,
|
||||
(rows, cols)
|
||||
}
|
||||
|
||||
/// Page bands for the grid's editing overlay, extending only the last printed bands to their
|
||||
/// actual printable capacity. The original layout, print area, scale and page sequence stay intact.
|
||||
pub fn page_break_bands(sh: &Sheet, lay: &SheetLayout) -> (Bands, Bands) {
|
||||
let (Some(row), Some(col)) = (lay.row_bands.last(), lay.col_bands.last()) else { return (Vec::new(), Vec::new()) };
|
||||
let mut tail = lay.clone();
|
||||
tail.area = RangeRef::new(CellRef::new(row.0, col.0), CellRef::new(MAX_ROWS - 1, MAX_COLS - 1));
|
||||
let (rows, cols) = split_bands(sh, &tail, 1);
|
||||
let mut out_rows = lay.row_bands.clone();
|
||||
let mut out_cols = lay.col_bands.clone();
|
||||
if let (Some(last), Some(extended)) = (out_rows.last_mut(), rows.first()) {
|
||||
*last = *extended;
|
||||
}
|
||||
if let (Some(last), Some(extended)) = (out_cols.last_mut(), cols.first()) {
|
||||
*last = *extended;
|
||||
}
|
||||
(out_rows, out_cols)
|
||||
}
|
||||
|
||||
/// Lays out every sheet a print command covers.
|
||||
pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -22,6 +22,29 @@ fn arabic_face_available() -> bool {
|
||||
!doc.missing_arabic_font()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_page_boundaries_follow_paper_and_orientation_without_changing_print_range() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheet_mut(0).unwrap().print.paper = "A4".into();
|
||||
let overlay = |wb: &Workbook| {
|
||||
let layout = layout_sheet(wb, 0, &PrintOptions::default(), None).unwrap();
|
||||
let original = (layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone());
|
||||
let (rows, cols) = page_break_bands(wb.sheet(0).unwrap(), &layout);
|
||||
assert_eq!((layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone()), original);
|
||||
assert_eq!(layout.row_bands.len(), 1);
|
||||
assert_eq!(layout.col_bands.len(), 1);
|
||||
(rows[0].1, cols[0].1)
|
||||
};
|
||||
let portrait = overlay(&wb);
|
||||
assert!(portrait.0 > 0 && portrait.1 > 0, "an empty one-page sheet still shows its capacity");
|
||||
wb.sheet_mut(0).unwrap().print.orientation = Orientation::Landscape;
|
||||
let landscape = overlay(&wb);
|
||||
assert!(landscape.1 > portrait.1 && landscape.0 < portrait.0);
|
||||
wb.sheet_mut(0).unwrap().print.paper = "A3".into();
|
||||
let larger = overlay(&wb);
|
||||
assert!(larger.0 > landscape.0 && larger.1 > landscape.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_sheets_mirror_link_rectangles_and_targets() {
|
||||
fn numbers_after(pdf: &[u8], key: &str, n: usize) -> Vec<f32> {
|
||||
@@ -942,6 +965,9 @@ fn page_setup_edits_settings() {
|
||||
fn japanese_paper_sizes_are_jis() {
|
||||
for (name, w, h) in [
|
||||
("A4", 595.28, 841.89), // unchanged
|
||||
("A2", 1190.55, 1683.78),
|
||||
("a1", 1683.78, 2383.94),
|
||||
("A0", 2383.94, 3370.39),
|
||||
("B4", 728.50, 1031.81),
|
||||
("B5", 515.91, 728.50),
|
||||
("B6", 362.83, 515.91),
|
||||
|
||||
@@ -727,17 +727,80 @@ fn check_lines_protection(s: &Session, p: &Json, axis: Axis, at: u32, count: u32
|
||||
return Ok(());
|
||||
}
|
||||
let end = at.saturating_add(count - 1).min(if axis == Axis::Rows { MAX_ROWS - 1 } else { MAX_COLS - 1 });
|
||||
let infos = if axis == Axis::Rows { &sh.rows } else { &sh.cols };
|
||||
if (at..=end).any(|i| locked(infos.get(&i).and_then(|x| x.style).unwrap_or_default())) {
|
||||
return Err(refuse());
|
||||
}
|
||||
let block = if axis == Axis::Rows { RangeRef::rows(at, end) } else { RangeRef::cols(at, end) };
|
||||
if sh.cells.iter_range(block).any(|(_, cell)| locked(cell.style)) {
|
||||
let lines = LockedLines::of(sh, axis, &locked);
|
||||
if !(at..=end).all(|i| lines.unlocked(sh, i, &locked)) {
|
||||
return Err(refuse());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether every cell of a row or column is unlocked, which Excel requires before it deletes the
|
||||
/// line on a protected sheet ("You are trying to delete a row that contains a locked cell"),
|
||||
/// however the Delete Rows or Delete Columns permission is set.
|
||||
///
|
||||
/// A cell the sheet does not store is judged by the style `Sheet::style_id` gives it: its row's
|
||||
/// format, then its column's, then the default: the workbook's Normal style, locked unless the
|
||||
/// file unlocked it (see `unlocked`). Reading a line with no format of
|
||||
/// its own as the default refused every delete, even over a row the user had unlocked through
|
||||
/// its columns; reading it as unlocked passed a blank row whose cells are all locked by default.
|
||||
/// The cross lines' formats are summarised once here, since a delete can span a million rows.
|
||||
struct LockedLines {
|
||||
axis: Axis,
|
||||
/// Cross lines (columns for a row, rows for a column) whose own format is locked.
|
||||
locked_cross: Vec<u32>,
|
||||
/// How many cross lines have no format of their own, and so no say over a cell they cross.
|
||||
plain_count: u32,
|
||||
}
|
||||
|
||||
impl LockedLines {
|
||||
fn of(sh: &Sheet, axis: Axis, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> Self {
|
||||
let (cross, cross_len) = if axis == Axis::Rows { (&sh.cols, MAX_COLS) } else { (&sh.rows, MAX_ROWS) };
|
||||
let styled: Vec<_> = cross.iter().filter_map(|(k, x)| x.style.map(|st| (*k, st))).collect();
|
||||
let locked_cross = styled.iter().filter(|(_, st)| locked(*st)).map(|(k, _)| *k).collect();
|
||||
Self { axis, locked_cross, plain_count: cross_len - styled.len() as u32 }
|
||||
}
|
||||
|
||||
fn unlocked(&self, sh: &Sheet, i: u32, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> bool {
|
||||
let rows = self.axis == Axis::Rows;
|
||||
let (line, cross_len) = if rows { (RangeRef::rows(i, i), MAX_COLS) } else { (RangeRef::cols(i, i), MAX_ROWS) };
|
||||
let mut stored = std::collections::HashSet::new();
|
||||
for (at, cell) in sh.cells.iter_range(line) {
|
||||
if locked(cell.style) {
|
||||
return false;
|
||||
}
|
||||
stored.insert(if rows { at.col } else { at.row });
|
||||
}
|
||||
if stored.len() as u32 == cross_len {
|
||||
return true;
|
||||
}
|
||||
let (own_lines, cross) = if rows { (&sh.rows, &sh.cols) } else { (&sh.cols, &sh.rows) };
|
||||
let own = own_lines.get(&i).and_then(|x| x.style);
|
||||
// A row's own format is the first one its empty cells take, so it decides alone.
|
||||
if rows && let Some(st) = own {
|
||||
return !locked(st);
|
||||
}
|
||||
// Otherwise a cross line's locked format reaches every cell of this line it crosses
|
||||
// (for a column, a row's format comes before the column's own).
|
||||
if self.locked_cross.iter().any(|k| !stored.contains(k)) {
|
||||
return false;
|
||||
}
|
||||
// The cells left are those under a cross line with no format. Deleting a column, they take
|
||||
// the column's own format, which may unlock them all. Deleting a row, neither line has a
|
||||
// format, so they take the default; when it is locked, each has to be a stored cell, and
|
||||
// the stored ones were all checked above.
|
||||
if !rows && own.is_some_and(|st| !locked(st)) {
|
||||
return true;
|
||||
}
|
||||
// Neither line has a format, so the cells take the workbook's Normal style, which a file
|
||||
// may have unlocked: then they all are.
|
||||
if own.is_none() && !locked(gridcraft_model::StyleId::DEFAULT) {
|
||||
return true;
|
||||
}
|
||||
let plain = stored.iter().filter(|k| !cross.get(k).is_some_and(|x| x.style.is_some())).count();
|
||||
plain as u32 == self.plain_count
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a range of the edited sheet goes after a structural edit (`None` = deleted).
|
||||
pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
|
||||
let expr = gridcraft_formula::Expr::Ref(gridcraft_formula::Reference {
|
||||
@@ -895,6 +958,7 @@ fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, inse
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
t.columns.insert((idx + k).min(t.columns.len()), col);
|
||||
|
||||
@@ -38,6 +38,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("view.gridlines", "Gridlines", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "gridlines")),
|
||||
cmd!("view.headings", "Headings", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "headings")),
|
||||
cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")),
|
||||
cmd!(
|
||||
noundo "view.showPageBreaks",
|
||||
"Show Page Breaks",
|
||||
[],
|
||||
None,
|
||||
"{sheet?, on?} → {on}: dashed page boundaries in Normal view (a display option, not saved with the file)",
|
||||
has_doc,
|
||||
show_page_breaks
|
||||
),
|
||||
cmd!("view.showOutlineSymbols", "Show Outline Symbols", [], Some("Ctrl+8"), "{on?}", has_doc, |s, p| sheet_flag(s, p, "outlineSymbols")),
|
||||
cmd!("view.showObjects", "Show Objects", [], Some("Ctrl+6"), "{on?}", has_doc, show_objects),
|
||||
cmd!(
|
||||
@@ -84,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Size",
|
||||
["Page Layout", "Page Setup"],
|
||||
None,
|
||||
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
|
||||
"{paper: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
|
||||
has_doc,
|
||||
paper
|
||||
),
|
||||
@@ -225,6 +234,26 @@ fn workbook_view_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Excel's Show page breaks: a display option of the sheet, so it neither records an undo step
|
||||
/// nor marks a clean workbook as changed (like `set_view`).
|
||||
fn show_page_breaks(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let si = target_sheet(s, p)?;
|
||||
let d = s.doc_mut()?;
|
||||
let dirty = d.is_dirty();
|
||||
let current = d.wb.sheet(si).is_some_and(|sh| sh.show_page_breaks);
|
||||
let on = bool_param(p, "on").unwrap_or(!current);
|
||||
if on != current {
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
if let Some(sh) = wb.sheet_mut(si) {
|
||||
sh.show_page_breaks = on;
|
||||
}
|
||||
if !dirty {
|
||||
d.saved = d.wb.clone();
|
||||
}
|
||||
}
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
/// Ctrl+6: hides every object, or shows them again. Placeholders (from a file) count as shown.
|
||||
fn show_objects(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
use gridcraft_model::ShowObjects;
|
||||
|
||||
@@ -0,0 +1,678 @@
|
||||
//! The folders automation may read and write (#445, #2172).
|
||||
//!
|
||||
//! Adapted from Isaac Levine's PR #480 (20bc9432a773689698190e0b32067a7863e0cf22).
|
||||
//!
|
||||
//! `gridcraft-cli mcp --headless --automation-read-root <dir> --automation-write-root <dir>`
|
||||
//! confines the files an agent's commands reach (in the open window, the agent folders of its
|
||||
//! Agents page apply instead). [`AutomationRoots`] holds the two folders. While they are in
|
||||
//! force, every document open and save applies their read or write policy. The checks sit behind
|
||||
//! [`crate::io::read_file`] and [`crate::io::write_file`], the
|
||||
//! only functions the engine opens user-named files with (`file.open`, `file.saveAs`,
|
||||
//! `file.export`, `file.exportPdf`, `insert.picture`, CSV and text import), so a new command that
|
||||
//! reads or writes through them is confined without further work.
|
||||
//!
|
||||
//! - The path is made absolute against the working directory, as the file system reads it. Its
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`), using their canonical spellings rather than Unicode case folding.
|
||||
//! - Read and write access are separate: a root given alone grants only its own kind of access.
|
||||
//!
|
||||
//! Roots are in force on a thread inside [`confine`], and in the whole process after
|
||||
//! [`confine_process`] (`gridcraft-cli mcp`), except inside [`unconfined`] (what the person at the
|
||||
//! keyboard does). Without roots nothing is checked.
|
||||
//!
|
||||
//! Native I/O resolves each checked path relative to an open root directory. Opens and atomic
|
||||
//! saves use capability-relative operations, so replacing a checked component with an escaping
|
||||
//! symlink cannot redirect them. This is a document-I/O policy, not a process sandbox.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Read access or write access.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Access {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
/// The folders automation may read and write; a root left out grants no access of its kind.
|
||||
#[derive(Debug)]
|
||||
pub struct AutomationRoots {
|
||||
read: Option<Root>,
|
||||
write: Option<Root>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Root {
|
||||
/// The folder made absolute, links followed: what paths are compared with.
|
||||
resolved: PathBuf,
|
||||
/// The same without Windows' `\\?\` prefix, for people.
|
||||
shown: PathBuf,
|
||||
/// Retain the authorized directory object instead of reopening its ambient path for I/O.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
dir: cap_std::fs::Dir,
|
||||
}
|
||||
|
||||
impl Root {
|
||||
/// The folder at `path`, which must exist.
|
||||
fn open(path: &Path, access: Access) -> Result<Self, String> {
|
||||
Self::open_resolving(path, access, |p| std::fs::canonicalize(p))
|
||||
}
|
||||
|
||||
fn open_resolving(path: &Path, access: Access, resolve: impl FnOnce(&Path) -> std::io::Result<PathBuf>) -> Result<Self, String> {
|
||||
let kind = match access {
|
||||
Access::Read => "read",
|
||||
Access::Write => "write",
|
||||
};
|
||||
// Capture the operator-selected directory before resolving its display/check name.
|
||||
// A rename or symlink swap during resolution must not change the retained authority:
|
||||
// later I/O always uses this handle, never reopens the resolved ambient pathname.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let dir = cap_std::fs::Dir::open_ambient_dir(path, cap_std::ambient_authority())
|
||||
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?;
|
||||
let resolved = resolve(path)
|
||||
.and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) })
|
||||
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?;
|
||||
Ok(Self {
|
||||
shown: plain(resolved.clone()),
|
||||
resolved,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
dir,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` without the `\\?\` prefix `canonicalize` gives on Windows (`\\?\C:\x` becomes `C:\x`,
|
||||
/// `\\?\UNC\server\share` becomes `\\server\share`); other paths are returned as they are.
|
||||
fn plain(path: PathBuf) -> PathBuf {
|
||||
if !cfg!(windows) {
|
||||
return path;
|
||||
}
|
||||
let Some(text) = path.to_str() else { return path };
|
||||
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
|
||||
return PathBuf::from(format!(r"\\{rest}"));
|
||||
}
|
||||
match text.strip_prefix(r"\\?\") {
|
||||
Some(rest) if rest.as_bytes().get(1) == Some(&b':') => PathBuf::from(rest),
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
impl AutomationRoots {
|
||||
/// The roots `read` and `write`, which must be existing folders; `None` when neither is given
|
||||
/// (nothing is confined then).
|
||||
pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result<Option<Arc<Self>>, String> {
|
||||
if read.is_none() && write.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = read.map(|p| Root::open(p, Access::Read)).transpose()?;
|
||||
let write = write.map(|p| Root::open(p, Access::Write)).transpose()?;
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// Roots that grant nothing: every open and save is refused. An agent session whose folders
|
||||
/// can't be used gets these rather than no roots, which would confine nothing.
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: None, write: None })
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_ref().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The write root, absolute with its links followed.
|
||||
pub fn write_root(&self) -> Option<&Path> {
|
||||
self.write.as_ref().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// May the file or folder at `path` be read (or written)? `Err` says why not.
|
||||
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
self.checked(path, access).map(|_| ())
|
||||
}
|
||||
|
||||
/// Resolve a path to the selected root plus a relative name; native I/O uses that root's
|
||||
/// retained handle, so the ambient pathname is never reopened after this check.
|
||||
fn checked(&self, path: &str, access: Access) -> Result<(&Root, PathBuf), String> {
|
||||
let root = match access {
|
||||
Access::Read => self.read.as_ref(),
|
||||
Access::Write => self.write.as_ref(),
|
||||
};
|
||||
let Some(root) = root else {
|
||||
return match access {
|
||||
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
|
||||
};
|
||||
};
|
||||
let resolved = resolve(path)?;
|
||||
if inside(&resolved, &root.resolved) {
|
||||
return resolved
|
||||
.strip_prefix(&root.resolved)
|
||||
.map(|p| (root, p.to_path_buf()))
|
||||
.map_err(|e| format!("automation path rejected: {path}: {e}"));
|
||||
}
|
||||
let shown = root.shown.display();
|
||||
match access {
|
||||
Access::Read => Err(format!("automation path rejected: outside the read root {shown}: {path}")),
|
||||
Access::Write => Err(format!("automation path rejected: outside the write root {shown}: {path}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
|
||||
#[derive(Clone, Debug)]
|
||||
enum Scope {
|
||||
Confined(Arc<AutomationRoots>),
|
||||
Unconfined,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// This thread's scope; `None`: the process's roots ([`confine_process`]).
|
||||
static SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The roots in force in every thread outside [`confine`] and [`unconfined`].
|
||||
static PROCESS: OnceLock<Arc<AutomationRoots>> = OnceLock::new();
|
||||
|
||||
/// Put `roots` in force in the whole process, for good. `false` when roots were in force already
|
||||
/// (they stay as they were).
|
||||
pub fn confine_process(roots: Arc<AutomationRoots>) -> bool {
|
||||
PROCESS.set(roots).is_ok()
|
||||
}
|
||||
|
||||
/// Puts the scope it replaced back when dropped (also when `f` panics).
|
||||
struct Restore(Option<Scope>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
SCOPE.with(|s| *s.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = Restore(SCOPE.with(|s| s.replace(scope)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
match roots {
|
||||
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with no roots in force on this thread: what the person at the keyboard does.
|
||||
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_scope(Some(Scope::Unconfined), f)
|
||||
}
|
||||
|
||||
/// The roots in force on this thread, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
match SCOPE.with(|s| s.borrow().clone()) {
|
||||
Some(Scope::Confined(r)) => Some(r),
|
||||
Some(Scope::Unconfined) => None,
|
||||
None => PROCESS.get().cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
pub fn check_read(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))
|
||||
}
|
||||
|
||||
/// Open a document relative to the retained read root, or use ordinary I/O when unconfined.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn open_read(path: &str) -> Result<std::fs::File, String> {
|
||||
let result = match current() {
|
||||
Some(roots) => {
|
||||
let (root, relative) = roots.checked(path, Access::Read)?;
|
||||
// Check through the retained authority: a FIFO must not block the GUI thread.
|
||||
// As in ordinary I/O, a type swap between metadata and open still needs O_NONBLOCK.
|
||||
if !root.dir.metadata(&relative).map_err(|e| format!("{path}: {e}"))?.is_file() {
|
||||
return Err(format!("{path}: only regular files can be opened"));
|
||||
}
|
||||
root.dir.open(relative).map(cap_std::fs::File::into_std)
|
||||
}
|
||||
None => {
|
||||
if !std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?.is_file() {
|
||||
return Err(format!("{path}: only regular files can be opened"));
|
||||
}
|
||||
std::fs::File::open(path)
|
||||
}
|
||||
};
|
||||
result.map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
/// Pin the save's parent directory before creating its temporary file. Both creation and
|
||||
/// rename are relative to this same handle, even if its ambient path is replaced meanwhile.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn write_parent(path: &str, roots: Option<&AutomationRoots>) -> Result<(cap_std::fs::Dir, OsString), String> {
|
||||
// Path::file_name normalizes these final components before splitting off the parent.
|
||||
if matches!(path.rsplit(std::path::is_separator).next(), Some("" | "." | "..")) {
|
||||
return Err(format!("{path}: not a file path"));
|
||||
}
|
||||
let result = match roots {
|
||||
Some(roots) => {
|
||||
let (root, _) = roots.checked(path, Access::Write)?;
|
||||
// Atomic rename replaces the requested leaf, not its symlink target. Resolve only
|
||||
// the parent here, after also checking the leaf above, to preserve that behavior.
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let name = absolute.file_name().ok_or_else(|| format!("{path}: not a file path"))?;
|
||||
let parent = absolute.parent().ok_or_else(|| format!("{path}: no parent directory"))?;
|
||||
let parent = std::fs::canonicalize(parent).map_err(|e| format!("{path}: {e}"))?;
|
||||
let relative = parent
|
||||
.strip_prefix(&root.resolved)
|
||||
.map_err(|_| format!("automation path rejected: outside the write root {}: {path}", root.shown.display()))?
|
||||
.join(name);
|
||||
parent_in(&root.dir, &relative)
|
||||
}
|
||||
None => {
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let name = absolute.file_name().ok_or_else(|| format!("{path}: not a file path"))?.to_os_string();
|
||||
let parent = absolute.parent().ok_or_else(|| format!("{path}: no parent directory"))?;
|
||||
cap_std::fs::Dir::open_ambient_dir(parent, cap_std::ambient_authority()).map(|dir| (dir, name))
|
||||
}
|
||||
};
|
||||
result.map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn parent_in(dir: &cap_std::fs::Dir, relative: &Path) -> std::io::Result<(cap_std::fs::Dir, OsString)> {
|
||||
let name = relative.file_name().ok_or(std::io::ErrorKind::InvalidInput)?.to_os_string();
|
||||
let parent = relative.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
|
||||
dir.open_dir(parent).map(|dir| (dir, name))
|
||||
}
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
fn resolve(path: &str) -> Result<PathBuf, String> {
|
||||
if path.is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
// Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows.
|
||||
if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {path}"));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?;
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
loop {
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
found.extend(missing.iter().rev());
|
||||
return Ok(found);
|
||||
}
|
||||
Err(e) => match std::fs::symlink_metadata(at) {
|
||||
Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {path}")),
|
||||
// There, yet its real path can't be had (no permission): nothing to compare.
|
||||
Ok(_) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")),
|
||||
},
|
||||
}
|
||||
let parent = at.parent();
|
||||
match (at.components().next_back(), parent) {
|
||||
(Some(Component::Normal(name)), Some(parent)) => {
|
||||
missing.push(name.to_os_string());
|
||||
at = parent;
|
||||
}
|
||||
(Some(Component::ParentDir), _) => {
|
||||
return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {path}"));
|
||||
}
|
||||
// Down to the root (or drive) and it doesn't exist either.
|
||||
_ => {
|
||||
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
return Err(format!("automation path rejected: cannot resolve {path}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component?
|
||||
///
|
||||
/// Compare canonical spellings exactly. Manual Unicode case folding can conflate distinct
|
||||
/// directories on case-sensitive Windows volumes; a mismatch must fail closed.
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
path.starts_with(root)
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
/// A fresh folder holding `in` (read root), `out` (write root) and `outside`.
|
||||
fn folders(name: &str) -> (PathBuf, Arc<AutomationRoots>) {
|
||||
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let base = std::env::temp_dir().join(format!("gc-file-access-{name}-{}-{stamp}", std::process::id()));
|
||||
for d in ["in/sub", "out", "outside", "in2"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("in/a.csv"), "a,b").unwrap();
|
||||
std::fs::write(base.join("outside/secret.csv"), "x").unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap();
|
||||
(base, roots)
|
||||
}
|
||||
|
||||
fn s(p: PathBuf) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_inside_the_roots_pass_and_others_dont() {
|
||||
let (base, roots) = folders("inside");
|
||||
assert_eq!(roots.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("in")), Access::Read), Ok(()), "the root itself");
|
||||
assert_eq!(roots.check(&s(base.join("in/sub/new.csv")), Access::Read), Ok(()), "missing files are checked by their folder");
|
||||
assert_eq!(roots.check(&s(base.join("out/new/deeper/x.xlsx")), Access::Write), Ok(()), "and by their nearest folder");
|
||||
let e = roots.check(&s(base.join("outside/secret.csv")), Access::Read).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the read root"), "{e}");
|
||||
// Read and write access are separate.
|
||||
let e = roots.check(&s(base.join("in/a.csv")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/x.xlsx")), Access::Read).unwrap_err().contains("outside the read root"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_roots_may_be_the_same_folder() {
|
||||
let (base, _) = folders("same");
|
||||
let both = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("in"))).unwrap().unwrap();
|
||||
assert_eq!(both.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
|
||||
assert_eq!(both.check(&s(base.join("in/new.xlsx")), Access::Write), Ok(()));
|
||||
assert!(both.check(&s(base.join("out/new.xlsx")), Access::Write).is_err());
|
||||
}
|
||||
|
||||
/// A nested write root permits output without granting writes to the surrounding inputs.
|
||||
#[test]
|
||||
fn write_root_may_be_a_subfolder_of_the_read_root() {
|
||||
let (base, _) = folders("nested");
|
||||
let read = base.join("in");
|
||||
let write = read.join("_artcraft");
|
||||
std::fs::create_dir_all(&write).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&read), Some(&write)).unwrap().unwrap();
|
||||
for path in [read.join("a.csv"), write.join("new.xlsx"), write.join("deeper/new.xlsx")] {
|
||||
assert_eq!(roots.check(&s(path), Access::Read), Ok(()));
|
||||
}
|
||||
for path in [write.clone(), write.join("new.xlsx"), write.join("deeper/new.xlsx")] {
|
||||
assert_eq!(roots.check(&s(path), Access::Write), Ok(()));
|
||||
}
|
||||
for path in [read.join("a.csv"), read.join("new.xlsx"), read.join("_artcraft2/new.xlsx"), write.join("../new.xlsx")] {
|
||||
assert!(roots.check(&s(path), Access::Write).unwrap_err().contains("outside the write root"));
|
||||
}
|
||||
assert!(roots.check(&s(base.join("outside/secret.csv")), Access::Read).is_err());
|
||||
assert_eq!(std::fs::read_to_string(read.join("a.csv")).unwrap(), "a,b");
|
||||
}
|
||||
|
||||
/// Existing case aliases use the filesystem's canonical spelling on macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_existing_case_aliases_follow_the_filesystem() {
|
||||
let (base, roots) = folders("macos-case");
|
||||
let original = base.join("in/MixedCase");
|
||||
std::fs::create_dir_all(&original).unwrap();
|
||||
std::fs::write(original.join("Input.csv"), "synthetic,7").unwrap();
|
||||
let alias = base.join("IN/mixedcase/input.CSV");
|
||||
if alias.exists() {
|
||||
assert_eq!(roots.check(&s(alias), Access::Read), Ok(()));
|
||||
} else {
|
||||
assert!(roots.check(&s(alias), Access::Read).is_err());
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(original.join("Input.csv")).unwrap(), "synthetic,7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sibling_with_the_same_prefix_is_outside() {
|
||||
let (base, roots) = folders("prefix");
|
||||
std::fs::write(base.join("in2/b.csv"), "b").unwrap();
|
||||
assert!(roots.check(&s(base.join("in2/b.csv")), Access::Read).is_err(), "in2 is not inside in");
|
||||
assert!(roots.check(&format!("{}2/c.csv", s(base.join("in"))), Access::Read).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_traversal_is_resolved_or_refused() {
|
||||
let (base, roots) = folders("dotdot");
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
let up = format!("{}{sep}..{sep}outside{sep}secret.csv", s(base.join("in")));
|
||||
assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root");
|
||||
let back = format!("{}{sep}..{sep}a.csv", s(base.join("in/sub")));
|
||||
assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside");
|
||||
let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.csv", s(base.join("out")));
|
||||
let e = roots.check(&missing, Access::Write).unwrap_err();
|
||||
// Windows resolves `..` by name first (so does opening the file there): then it's outside.
|
||||
assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_and_empty_paths() {
|
||||
let (_base, roots) = folders("relative");
|
||||
// The tests' working directory is the crate's folder: not inside the roots.
|
||||
assert!(roots.check("a.csv", Access::Read).unwrap_err().contains("outside the read root"));
|
||||
assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_root_is_an_error_and_none_is_no_confinement() {
|
||||
let (base, _) = folders("missing");
|
||||
let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err();
|
||||
assert!(e.starts_with("cannot open the automation read root"), "{e}");
|
||||
let e = AutomationRoots::new(None, Some(&base.join("in/a.csv"))).unwrap_err();
|
||||
assert!(e.starts_with("cannot open the automation write root"), "{e}");
|
||||
assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``"));
|
||||
assert!(AutomationRoots::new(None, None).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_left_out_grants_none_of_its_access() {
|
||||
let (base, _) = folders("one-root");
|
||||
let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
|
||||
assert_eq!(read_only.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
|
||||
let e = read_only.check(&s(base.join("in/x.xlsx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("write authority is absent"), "{e}");
|
||||
let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap();
|
||||
assert_eq!(write_only.check(&s(base.join("out/x.xlsx")), Access::Write), Ok(()));
|
||||
let e = write_only.check(&s(base.join("out/x.xlsx")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("read authority is absent"), "{e}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let (base, roots) = folders("links");
|
||||
symlink(base.join("outside/secret.csv"), base.join("in/leak.csv")).unwrap();
|
||||
assert!(roots.check(&s(base.join("in/leak.csv")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out");
|
||||
symlink(base.join("outside"), base.join("out/away")).unwrap();
|
||||
let e = roots.check(&s(base.join("out/away/new.xlsx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "a folder link out: {e}");
|
||||
symlink(base.join("outside/gone.csv"), base.join("out/dangling.xlsx")).unwrap();
|
||||
let e = roots.check(&s(base.join("out/dangling.xlsx")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}");
|
||||
// A link to a folder inside the root stays inside.
|
||||
symlink(base.join("in/sub"), base.join("in/alias")).unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/alias/x.csv")), Access::Read), Ok(()));
|
||||
// A root given through a link is the folder it leads to.
|
||||
symlink(base.join("in"), base.join("in-link")).unwrap();
|
||||
let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap();
|
||||
assert_eq!(linked.check(&s(base.join("in/a.csv")), Access::Read), Ok(()));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_resolves_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
assert_eq!(roots.check(&s(base.join("IN/A.CSV")), Access::Read), Ok(()));
|
||||
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scopes_nest_and_restore() {
|
||||
let (base, roots) = folders("scopes");
|
||||
let outside = s(base.join("outside/secret.csv"));
|
||||
assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default");
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_read(&outside).is_err());
|
||||
assert_eq!(unconfined(|| check_read(&outside)), Ok(()));
|
||||
assert!(check_read(&outside).is_err(), "restored after unconfined");
|
||||
let o = outside.clone();
|
||||
assert!(std::thread::spawn(move || check_read(&o).is_ok()).join().unwrap(), "another thread is not in this thread's scope");
|
||||
});
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after confine");
|
||||
let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom")));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after a panic");
|
||||
assert_eq!(confine(None, || check_read(&outside)), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_components_are_not_case_folded() {
|
||||
assert!(inside(Path::new("scope/Case/child"), Path::new("scope/Case")));
|
||||
assert!(!inside(Path::new("scope/case/child"), Path::new("scope/Case")));
|
||||
assert!(!inside(Path::new("scope/Case2/child"), Path::new("scope/Case")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.csv", "NUL "] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.csv", "nul-x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A root replaced during name resolution must never replace the captured authority.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn root_handle_is_captured_before_resolving_its_name() {
|
||||
for access in [Access::Read, Access::Write] {
|
||||
for swap_before_resolution in [false, true] {
|
||||
let (base, _) = folders("root-setup-swap");
|
||||
let requested = base.join("in");
|
||||
let retained = base.join("retained-root");
|
||||
std::fs::write(requested.join("secret.csv"), "authorized sentinel").unwrap();
|
||||
let root = Root::open_resolving(&requested, access, |path| {
|
||||
let swap = || {
|
||||
std::fs::rename(&requested, &retained).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside"), &requested).unwrap();
|
||||
};
|
||||
if swap_before_resolution {
|
||||
swap();
|
||||
}
|
||||
let resolved = std::fs::canonicalize(path);
|
||||
if !swap_before_resolution {
|
||||
swap();
|
||||
}
|
||||
resolved
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
root.dir.read("secret.csv").unwrap(),
|
||||
b"authorized sentinel",
|
||||
"{access:?}, swap before resolution: {swap_before_resolution}"
|
||||
);
|
||||
root.dir.write("new.csv", "authorized output").unwrap();
|
||||
assert_eq!(std::fs::read(retained.join("new.csv")).unwrap(), b"authorized output");
|
||||
assert!(!base.join("outside/new.csv").exists());
|
||||
assert_eq!(std::fs::read(base.join("outside/secret.csv")).unwrap(), b"x");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// cap-std's Windows handle prevents replacing the root while its name is resolved.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn root_handle_prevents_replacement_during_name_resolution() {
|
||||
let (base, _) = folders("root-setup-lock");
|
||||
let requested = base.join("in");
|
||||
let root = Root::open_resolving(&requested, Access::Read, |path| {
|
||||
assert!(std::fs::rename(&requested, base.join("retained-root")).is_err());
|
||||
std::fs::canonicalize(path)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(root.dir.read("a.csv").unwrap(), b"a,b");
|
||||
assert!(requested.is_dir());
|
||||
}
|
||||
|
||||
/// Replacing a checked path component must not redirect the later capability-relative open.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn checked_read_and_save_parent_reject_a_subsequent_escaping_symlink() {
|
||||
let (base, roots) = folders("checked-swap");
|
||||
std::fs::write(base.join("in/sub/secret.csv"), "inside").unwrap();
|
||||
std::fs::create_dir_all(base.join("out/sub")).unwrap();
|
||||
let input = s(base.join("in/sub/secret.csv"));
|
||||
let output = s(base.join("out/sub/book.xlsx"));
|
||||
let (read, relative_read) = roots.checked(&input, Access::Read).unwrap();
|
||||
let (write, relative_write) = roots.checked(&output, Access::Write).unwrap();
|
||||
for kind in ["in", "out"] {
|
||||
std::fs::rename(base.join(kind).join("sub"), base.join(kind).join("retained-sub")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside"), base.join(kind).join("sub")).unwrap();
|
||||
}
|
||||
assert!(read.dir.open(relative_read).is_err());
|
||||
assert!(parent_in(&write.dir, &relative_write).is_err());
|
||||
assert_eq!(std::fs::read_to_string(base.join("outside/secret.csv")).unwrap(), "x");
|
||||
assert!(!base.join("outside/book.xlsx").exists());
|
||||
assert_eq!(std::fs::read_to_string(base.join("in/retained-sub/secret.csv")).unwrap(), "inside");
|
||||
}
|
||||
|
||||
/// An outside symlink into the write root cannot authorize replacing that outside entry.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn write_parent_rejects_an_outside_leaf_alias_into_the_root() {
|
||||
let (base, roots) = folders("outside-alias");
|
||||
let target = base.join("out/book.xlsx");
|
||||
std::fs::write(&target, "inside sentinel").unwrap();
|
||||
let alias = base.join("outside/alias.xlsx");
|
||||
std::os::unix::fs::symlink(&target, &alias).unwrap();
|
||||
let result = confine(Some(&roots), || crate::io::write_file(alias.to_str().unwrap(), b"must not be saved"));
|
||||
assert!(result.is_err());
|
||||
assert!(std::fs::symlink_metadata(&alias).unwrap().file_type().is_symlink());
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), "inside sentinel");
|
||||
}
|
||||
|
||||
/// Ordinary inside-pointing links remain usable after resolving them to root-relative names.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn native_read_accepts_an_inside_pointing_symlink() {
|
||||
let (base, roots) = folders("inside-alias");
|
||||
let alias = base.join("in/sub/link.csv");
|
||||
std::os::unix::fs::symlink(base.join("in/a.csv"), &alias).unwrap();
|
||||
let bytes = confine(Some(&roots), || crate::io::read_file(alias.to_str().unwrap())).unwrap();
|
||||
assert_eq!(bytes, b"a,b");
|
||||
}
|
||||
|
||||
/// Confined reads reject a FIFO through their retained root before an open can block.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn confined_fifo_is_refused_before_opening() {
|
||||
let (base, roots) = folders("fifo");
|
||||
let fifo = base.join("in/pipe.xlsx");
|
||||
let made = std::process::Command::new("mkfifo").arg(&fifo).status();
|
||||
assert!(made.as_ref().is_ok_and(|s| s.success()), "mkfifo could not make the fixture: {made:?}");
|
||||
let error = confine(Some(&roots), || crate::io::read_file(fifo.to_str().unwrap())).unwrap_err().to_string();
|
||||
assert!(error.contains("only regular files"), "{error}");
|
||||
}
|
||||
}
|
||||
+103
-77
@@ -1055,13 +1055,7 @@ const MAX_READ_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||
pub fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
script_sandbox_check(path)?;
|
||||
// Checked before opening: opening a FIFO nobody writes to blocks the calling (GUI) thread.
|
||||
// shortcut: a FIFO swapped in between this check and the open still blocks; close that with
|
||||
// O_NONBLOCK when the crate takes a libc dependency.
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: only regular files can be opened")));
|
||||
}
|
||||
let f = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let f = crate::file_access::open_read(path).map_err(EngineError::Other)?;
|
||||
// A symlink to an endless device reports length 0 but streams forever, so metadata
|
||||
// alone never bounds the read: require a real file and cap the bytes actually taken.
|
||||
if !f.metadata().map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
@@ -1084,81 +1078,113 @@ pub fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
script_sandbox_check(path)?;
|
||||
// Write to a temporary file, then rename: a crash never leaves a half-written workbook.
|
||||
// The temporary file is created exclusively, so an existing file or symlink at that
|
||||
// path (planted by another local user) makes the save fail instead of truncating the
|
||||
// link's target; and it inherits the destination's access restrictions, so saving a
|
||||
// private workbook doesn't widen who can read it.
|
||||
let tmp = format!("{path}.sctmp");
|
||||
let prior_meta = std::fs::metadata(path).ok();
|
||||
let prior = prior_meta.as_ref().map(std::fs::Metadata::permissions);
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
let roots = crate::file_access::current();
|
||||
let (dir, name) = crate::file_access::write_parent(path, roots.as_deref()).map_err(EngineError::Other)?;
|
||||
let metadata = dir.metadata(&name).or_else(|err| {
|
||||
// A desktop save may replace a symlink to a file outside its immediate parent.
|
||||
// Only follow that link with ambient authority when no automation roots are active.
|
||||
if roots.is_none() && dir.symlink_metadata(&name).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
std::fs::metadata(path).map(cap_std::fs::Metadata::from_just_metadata)
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
});
|
||||
atomic_write(&dir, &name, bytes, metadata).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// Each save owns an exclusively created, unpredictable temporary name. A stale temporary
|
||||
/// file never blocks a later save; creation, cleanup and rename stay on the pinned directory.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn atomic_write(
|
||||
dir: &cap_std::fs::Dir,
|
||||
name: &std::ffi::OsStr,
|
||||
bytes: &[u8],
|
||||
metadata: std::io::Result<cap_std::fs::Metadata>,
|
||||
) -> std::io::Result<()> {
|
||||
use std::io::Write;
|
||||
let prior_meta = match metadata {
|
||||
Ok(meta) => Some(meta),
|
||||
// Only an absent leaf is new. A dangling or unresolvable symlink is not permission
|
||||
// to replace an existing destination with the ordinary creation mode. A regular file that
|
||||
// appeared since the first look (another save published first) is an existing destination.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => match dir.symlink_metadata(name) {
|
||||
Err(leaf) if leaf.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Ok(leaf) if leaf.is_file() => Some(leaf),
|
||||
_ => return Err(e),
|
||||
},
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let prior = prior_meta.as_ref().map(|m| m.permissions());
|
||||
let mut opts = cap_std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
// Over an existing file the replacement starts owner-only, whatever the umask: its group is
|
||||
// still the saving user's primary one until it is changed below, and a member of that group
|
||||
// must not be able to open it (and keep the descriptor) before then.
|
||||
#[cfg(unix)]
|
||||
if prior.is_some() {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
// A brand-new file gets the restrictive default: no group/other write, whatever the umask.
|
||||
#[cfg(unix)]
|
||||
if prior.is_none() {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o644);
|
||||
}
|
||||
let mut f = opts.open(&tmp).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})?;
|
||||
// The replacement belongs to the saving user's primary group: restore the old file's group and
|
||||
// then its mode. When the group can't be restored its access is dropped rather than handed to a
|
||||
// different group; failing to read that back is a failed save.
|
||||
#[cfg(unix)]
|
||||
if let Some(m) = &prior_meta {
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
let _ = std::os::unix::fs::fchown(&f, None, Some(m.gid()));
|
||||
let group_kept = f.metadata().map(|now| now.gid() == m.gid()).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})?;
|
||||
// Best effort: a file system that can't change modes keeps the owner-only one. Without the
|
||||
// group, the old owner and other bits are kept and the group, setuid and setgid bits dropped.
|
||||
let _ = f.set_permissions(std::fs::Permissions::from_mode(restored_mode(m.mode(), group_kept)));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
if let Some(p) = &prior {
|
||||
let _ = f.set_permissions(p.clone());
|
||||
}
|
||||
// `sync_all` before the rename: without it a power loss right after the rename can leave
|
||||
// the new name pointing at an empty or truncated file while the old workbook is gone.
|
||||
// A file system that cannot flush at all (some network mounts; on Apple targets std asks
|
||||
// for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename.
|
||||
let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) });
|
||||
f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})?;
|
||||
drop(f);
|
||||
std::fs::rename(&tmp, path).map_err(|e| {
|
||||
// A write or rename that fails (full disk, the workbook locked by another app) leaves
|
||||
// no temporary file beside the user's workbook.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})?;
|
||||
// Make the rename itself durable. Best effort: the workbook is already in place, so a
|
||||
// directory that can't be opened or synced (some file systems) is not a failed save.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
|
||||
if let Ok(d) = std::fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
use cap_std::fs::OpenOptionsExt;
|
||||
opts.mode(if prior_meta.is_some() { 0o600 } else { 0o644 });
|
||||
}
|
||||
let mut created = None;
|
||||
for _ in 0..32 {
|
||||
let mut random = [0u8; 16];
|
||||
getrandom::fill(&mut random).map_err(std::io::Error::other)?;
|
||||
let suffix = u128::from_le_bytes(random);
|
||||
let tmp = format!(".gridcraft-{suffix:032x}.sctmp");
|
||||
match dir.open_with(&tmp, &opts) {
|
||||
Ok(file) => {
|
||||
created = Some((tmp, file));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
let (tmp, file) = created.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::AlreadyExists, "cannot create a unique save file"))?;
|
||||
#[cfg(unix)]
|
||||
let mut file = file.into_std();
|
||||
// Restore the old group before its mode; a failed group restore must not grant access to
|
||||
// the saving user's different group. The temporary file starts owner-only until this point.
|
||||
#[cfg(unix)]
|
||||
if let Some(m) = &prior_meta {
|
||||
use cap_std::fs::MetadataExt as _;
|
||||
use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
|
||||
let _ = std::os::unix::fs::fchown(&file, None, Some(m.gid()));
|
||||
let group_kept = file.metadata().map(|now| now.gid() == m.gid()).inspect_err(|_| {
|
||||
let _ = dir.remove_file(&tmp);
|
||||
})?;
|
||||
if let Some(mode) = restored_mode(m.mode(), group_kept) {
|
||||
let _ = file.set_permissions(std::fs::Permissions::from_mode(mode));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let mut file = file;
|
||||
#[cfg(not(unix))]
|
||||
if let Some(p) = prior {
|
||||
let _ = file.set_permissions(p);
|
||||
}
|
||||
// Flush before rename, preserving the unsupported-filesystem fallback.
|
||||
let result = file
|
||||
.write_all(bytes)
|
||||
.and_then(|()| file.flush())
|
||||
.and_then(|()| file.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) }));
|
||||
// Close before rename, including on Windows; no other attempt ever owns this name.
|
||||
drop(file);
|
||||
let result = result.and_then(|()| dir.rename(&tmp, dir, name));
|
||||
if result.is_err() {
|
||||
let _ = dir.remove_file(&tmp);
|
||||
}
|
||||
// The held directory remains the authority for the best-effort directory flush.
|
||||
#[cfg(unix)]
|
||||
if result.is_ok()
|
||||
&& let Ok(directory) = dir.open(".")
|
||||
{
|
||||
let _ = directory.sync_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what
|
||||
@@ -1179,11 +1205,11 @@ fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool {
|
||||
(unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported
|
||||
}
|
||||
|
||||
/// The mode a saved file gets from the file it replaces (`old`): all of it when its group was
|
||||
/// restored; without the group, the owner and other bits only.
|
||||
/// Restore the saved mode only when the old group is kept. Otherwise leave the temporary
|
||||
/// file's restrictive permissions unchanged: old group members could now match the other class.
|
||||
#[cfg(unix)]
|
||||
fn restored_mode(old: u32, group_kept: bool) -> u32 {
|
||||
if group_kept { old & 0o7777 } else { old & 0o707 }
|
||||
fn restored_mode(old: u32, group_kept: bool) -> Option<u32> {
|
||||
group_kept.then_some(old & 0o7777)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
+163
-17
@@ -18,23 +18,107 @@ fn copied(wb: &Workbook, range: &str) -> String {
|
||||
range_html(wb, 0, r, &crate::display::range_text(wb, 0, r)).unwrap()
|
||||
}
|
||||
|
||||
/// Isolate each native save fixture and clean it on normal return or unwinding. Set
|
||||
/// `GRIDCRAFT_RETAIN_TEST_FIXTURES` to retain diagnostics on workstations that forbid cleanup.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save_fixture(label: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new()
|
||||
.prefix(&format!("gridcraft-save-{label}-"))
|
||||
.disable_cleanup(std::env::var_os("GRIDCRAFT_RETAIN_TEST_FIXTURES").is_some())
|
||||
.tempdir()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// New saves inherit the process umask just like an ordinary newly created file.
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix))]
|
||||
#[test]
|
||||
fn new_workbook_save_keeps_default_creation_permissions() {
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
|
||||
let fixture = save_fixture("new-permissions");
|
||||
let reference = fixture.path().join("ordinary.txt");
|
||||
// The save asks for 0644; the reference asks for the same, so both meet the same umask.
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).mode(0o644).open(&reference).unwrap();
|
||||
let saved = fixture.path().join("synthetic.xlsx");
|
||||
write_file(saved.to_str().unwrap(), b"synthetic workbook bytes").unwrap();
|
||||
let expected = std::fs::metadata(&reference).unwrap().permissions().mode() & 0o777;
|
||||
let actual = std::fs::metadata(&saved).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(actual, expected, "a new save must use the save creation mode (0644) after umask");
|
||||
assert_eq!(std::fs::read(saved).unwrap(), b"synthetic workbook bytes");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_fails_upfront_when_the_temp_name_is_taken() {
|
||||
// Another local user who can write the directory must not be able to point the
|
||||
// save's predictable temporary name at their own file: creation is exclusive.
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-temp-name-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
fn stale_temporary_file_does_not_block_save_or_get_removed() {
|
||||
let fixture = save_fixture("stale");
|
||||
let dir = fixture.path();
|
||||
let stale = dir.join("book.xlsx.sctmp");
|
||||
std::fs::write(&stale, b"stale contents").unwrap();
|
||||
let dest = dir.join("book.xlsx");
|
||||
write_file(dest.to_str().unwrap(), b"new").unwrap();
|
||||
assert_eq!(std::fs::read(dest).unwrap(), b"new");
|
||||
assert_eq!(std::fs::read(stale).unwrap(), b"stale contents");
|
||||
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 2);
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix))]
|
||||
#[test]
|
||||
fn planted_temporary_symlink_does_not_block_save_or_modify_its_target() {
|
||||
let fixture = save_fixture("planted");
|
||||
let dir = fixture.path();
|
||||
let victim = dir.join("victim.txt");
|
||||
std::fs::write(&victim, b"original").unwrap();
|
||||
let dest = dir.join("book.xlsx");
|
||||
std::os::unix::fs::symlink(&victim, dir.join("book.xlsx.sctmp")).unwrap();
|
||||
let err = write_file(dest.to_str().unwrap(), b"new").unwrap_err();
|
||||
assert_eq!(std::fs::read(&victim).unwrap(), b"original");
|
||||
assert!(!dir.join("book.xlsx").exists(), "{err}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let planted = dir.join("book.xlsx.sctmp");
|
||||
std::os::unix::fs::symlink(&victim, &planted).unwrap();
|
||||
write_file(dest.to_str().unwrap(), b"new").unwrap();
|
||||
assert_eq!(std::fs::read(victim).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(dest).unwrap(), b"new");
|
||||
assert!(std::fs::symlink_metadata(planted).unwrap().file_type().is_symlink());
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix))]
|
||||
#[test]
|
||||
fn atomic_save_uses_the_pinned_parent_after_a_directory_swap() {
|
||||
let fixture = save_fixture("parent-swap");
|
||||
let dir = fixture.path();
|
||||
for sub in ["allowed/sub", "outside"] {
|
||||
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("outside/book.xlsx"), b"outside sentinel").unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(None, Some(&dir.join("allowed"))).unwrap();
|
||||
let dest = dir.join("allowed/sub/book.xlsx");
|
||||
let (parent, name) = crate::file_access::write_parent(dest.to_str().unwrap(), roots.as_deref()).unwrap();
|
||||
std::fs::rename(dir.join("allowed/sub"), dir.join("allowed/retained-sub")).unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("outside"), dir.join("allowed/sub")).unwrap();
|
||||
atomic_write(&parent, &name, b"inside saved", parent.metadata(&name)).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join("outside/book.xlsx")).unwrap(), b"outside sentinel");
|
||||
assert_eq!(std::fs::read(dir.join("allowed/retained-sub/book.xlsx")).unwrap(), b"inside saved");
|
||||
assert_eq!(std::fs::read_dir(dir.join("outside")).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn simultaneous_atomic_saves_do_not_share_temporary_names() {
|
||||
let fixture = save_fixture("parallel");
|
||||
let dir = fixture.path();
|
||||
let destination = dir.join("book.xlsx");
|
||||
let barrier = std::sync::Barrier::new(8);
|
||||
std::thread::scope(|scope| {
|
||||
for n in 0..8u8 {
|
||||
let destination = &destination;
|
||||
let barrier = &barrier;
|
||||
scope.spawn(move || {
|
||||
barrier.wait();
|
||||
write_file(destination.to_str().unwrap(), &[n; 64]).unwrap();
|
||||
});
|
||||
}
|
||||
});
|
||||
let saved = std::fs::read(destination).unwrap();
|
||||
assert_eq!(saved.len(), 64);
|
||||
assert!(saved.iter().all(|v| *v == saved[0]));
|
||||
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -67,15 +151,17 @@ fn save_keeps_the_destination_access_restrictions() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Without the old group, a saved file keeps the old owner and other bits and nothing for a group.
|
||||
/// Without the old group, a saved file keeps the restrictive temporary mode.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() {
|
||||
assert_eq!(super::restored_mode(0o100_664, true), 0o664);
|
||||
assert_eq!(super::restored_mode(0o100_664, false), 0o604);
|
||||
assert_eq!(super::restored_mode(0o102_444, false), 0o404, "an original read-only file stays read-only, setgid is dropped");
|
||||
assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped");
|
||||
fn restored_mode_keeps_restrictive_permissions_when_the_group_is_lost() {
|
||||
assert_eq!(super::restored_mode(0o100_664, true), Some(0o664));
|
||||
assert_eq!(super::restored_mode(0o100_664, false), None);
|
||||
assert_eq!(super::restored_mode(0o102_444, false), None, "leave the restrictive temporary mode; do not copy setgid");
|
||||
assert_eq!(super::restored_mode(0o104_755, false), None, "do not copy setuid or other-class access");
|
||||
assert_eq!(super::restored_mode(0o100_604, false), None, "members of a lost group must not gain the old other-class read access");
|
||||
assert_eq!(super::restored_mode(0o100_604, true), Some(0o604));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1101,6 +1187,66 @@ fn the_merge_index_holds_a_bounded_number_of_cells() {
|
||||
assert!(merge_index(&sh, rect).is_none());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn desktop_save_rejects_file_names_spelled_as_directories() {
|
||||
let fixture = save_fixture("trailing-separator");
|
||||
let file = fixture.path().join("book.xlsx");
|
||||
std::fs::write(&file, b"original").unwrap();
|
||||
for suffix in ["", ".", ".."] {
|
||||
let spelling = format!("{}{}{suffix}", file.display(), std::path::MAIN_SEPARATOR);
|
||||
assert!(crate::file_access::unconfined(|| write_file(&spelling, b"new")).is_err());
|
||||
}
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"original");
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix))]
|
||||
#[test]
|
||||
fn desktop_save_replaces_a_valid_relative_symlink_and_keeps_the_target_mode() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let fixture = save_fixture("desktop-alias");
|
||||
let parent = fixture.path().join("sub");
|
||||
std::fs::create_dir(&parent).unwrap();
|
||||
let target = fixture.path().join("original.xlsx");
|
||||
std::fs::write(&target, b"original").unwrap();
|
||||
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let alias = parent.join("book.xlsx");
|
||||
std::os::unix::fs::symlink("../original.xlsx", &alias).unwrap();
|
||||
crate::file_access::unconfined(|| write_file(alias.to_str().unwrap(), b"new")).unwrap();
|
||||
assert!(std::fs::symlink_metadata(&alias).unwrap().is_file());
|
||||
assert_eq!(std::fs::read(&alias).unwrap(), b"new");
|
||||
assert_eq!(std::fs::metadata(alias).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"original");
|
||||
}
|
||||
|
||||
/// A target inside the write root can still be outside a narrower retained parent handle.
|
||||
/// Metadata refusal must not replace its symlink with a more widely readable saved copy.
|
||||
#[cfg(all(not(target_arch = "wasm32"), unix))]
|
||||
#[test]
|
||||
fn failed_destination_metadata_does_not_widen_a_saved_copy() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let fixture = save_fixture("metadata-refused");
|
||||
let selected = fixture.path().join("selected");
|
||||
std::fs::create_dir_all(selected.join("sub")).unwrap();
|
||||
let private = selected.join("private.xlsx");
|
||||
std::fs::write(&private, b"private sentinel").unwrap();
|
||||
std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let alias = selected.join("sub/book.xlsx");
|
||||
std::os::unix::fs::symlink("../private.xlsx", &alias).unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(None, Some(&selected)).unwrap();
|
||||
let result = crate::file_access::confine(roots.as_ref(), || write_file(alias.to_str().unwrap(), b"new saved copy"));
|
||||
assert!(result.is_err(), "a refused metadata lookup cannot be treated as a new file");
|
||||
assert!(std::fs::symlink_metadata(&alias).unwrap().file_type().is_symlink());
|
||||
assert_eq!(std::fs::read(&private).unwrap(), b"private sentinel");
|
||||
assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
// Also refuse a leaf whose target disappeared after an earlier path check.
|
||||
let dangling = selected.join("sub/lost.xlsx");
|
||||
std::os::unix::fs::symlink("missing.xlsx", &dangling).unwrap();
|
||||
let dir = cap_std::fs::Dir::open_ambient_dir(selected.join("sub"), cap_std::ambient_authority()).unwrap();
|
||||
assert!(atomic_write(&dir, std::ffi::OsStr::new("lost.xlsx"), b"new saved copy", dir.metadata("lost.xlsx")).is_err());
|
||||
assert!(std::fs::symlink_metadata(dangling).unwrap().file_type().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_without_sheets_keeps_its_text_defaults() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
// Saved and opened as GridCraft JSON, with the sheet list emptied in between: the reset to a
|
||||
|
||||
@@ -13,6 +13,7 @@ mod chart_svg;
|
||||
mod clip_html;
|
||||
pub mod cmd;
|
||||
pub mod display;
|
||||
pub mod file_access;
|
||||
pub mod fill;
|
||||
pub mod io;
|
||||
pub mod links;
|
||||
|
||||
@@ -904,6 +904,7 @@ mod tests {
|
||||
filter: Vec::new(),
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)];
|
||||
let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None };
|
||||
|
||||
@@ -695,6 +695,7 @@ fn grow_right(
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
});
|
||||
cx.rebuild_deps = true;
|
||||
|
||||
@@ -3947,6 +3947,84 @@ fn show_outline_symbols_toggles() {
|
||||
assert!(!on(&s));
|
||||
}
|
||||
|
||||
/// Show page breaks (Excel: Options › Advanced, per worksheet): off on a new sheet, turned on by
|
||||
/// Page Break Preview and kept in Normal view, switched without making the workbook dirty.
|
||||
#[test]
|
||||
fn page_break_preview_turns_on_show_page_breaks_for_its_sheet() {
|
||||
let mut s = s();
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
let wb = s.doc().unwrap().wb.clone();
|
||||
s.doc_mut().unwrap().saved = wb;
|
||||
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|x| x.name == name).unwrap().show_page_breaks;
|
||||
assert!(!on(&s, "Two"));
|
||||
s.execute("view.pageBreakPreview", json!({})).unwrap();
|
||||
s.execute("view.normal", json!({})).unwrap();
|
||||
assert!(on(&s, "Two"), "Normal view keeps the page breaks Page Break Preview showed");
|
||||
assert!(!on(&s, "Sheet1"), "only the previewed sheet");
|
||||
assert_eq!(s.execute("view.showPageBreaks", json!({})).unwrap(), json!({"on": false}));
|
||||
assert!(!on(&s, "Two"));
|
||||
assert_eq!(s.execute("view.showPageBreaks", json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
assert!(on(&s, "Two"));
|
||||
assert!(!s.doc().unwrap().is_dirty(), "a display option, not an edit");
|
||||
}
|
||||
|
||||
/// Undo and redo swap in another snapshot of the workbook; the page breaks shown stay as they are
|
||||
/// (a display option isn't undone), matched by sheet name.
|
||||
#[test]
|
||||
fn undo_and_redo_keep_show_page_breaks() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
s.execute("view.pageBreakPreview", json!({})).unwrap();
|
||||
s.execute("view.normal", json!({})).unwrap();
|
||||
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
|
||||
assert!(on(&s));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(on(&s), "undoing the typing leaves the page breaks on");
|
||||
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert!(!on(&s), "redo doesn't bring back the snapshot's page breaks either");
|
||||
assert!(s.active().unwrap().wb.active().unwrap().cell(CellRef::new(0, 0)).is_some(), "the redo itself happened");
|
||||
}
|
||||
|
||||
/// Undoing a rename brings back a sheet name the current workbook doesn't have: its page breaks
|
||||
/// stay as the snapshot has them, not off.
|
||||
#[test]
|
||||
fn undoing_a_rename_keeps_show_page_breaks() {
|
||||
let mut s = s();
|
||||
s.execute("view.pageBreakPreview", json!({})).unwrap();
|
||||
s.execute("view.normal", json!({})).unwrap();
|
||||
s.execute("sheet.rename", json!({"name": "Renamed"})).unwrap();
|
||||
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
|
||||
assert!(on(&s));
|
||||
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_ne!(s.active().unwrap().wb.active().unwrap().name, "Renamed", "the rename was undone");
|
||||
assert!(!on(&s), "the current setting survives the undone rename");
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert!(!on(&s), "the current setting survives the redone rename");
|
||||
}
|
||||
|
||||
/// A grouped rename can reuse another sheet's name. View state follows identity, not that name.
|
||||
#[test]
|
||||
fn grouped_renames_keep_page_breaks_on_the_same_sheets() {
|
||||
let mut s = s();
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
s.grouped("Rename sheets", |s| {
|
||||
s.execute("sheet.rename", json!({"sheet": "Sheet1", "name": "Temp"}))?;
|
||||
s.execute("sheet.rename", json!({"sheet": "Two", "name": "Sheet1"}))?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("view.showPageBreaks", json!({"sheet": "Temp", "on": true})).unwrap();
|
||||
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|sh| sh.name == name).unwrap().show_page_breaks;
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(on(&s, "Sheet1"));
|
||||
assert!(!on(&s, "Two"));
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert!(on(&s, "Temp"));
|
||||
assert!(!on(&s, "Sheet1"));
|
||||
}
|
||||
|
||||
fn reopen(s: &mut Session) {
|
||||
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
let b64 = r["base64"].as_str().unwrap().to_string();
|
||||
@@ -4042,6 +4120,7 @@ fn every_chart_kind_survives_xlsx() {
|
||||
("combo", ChartKind::Combo),
|
||||
("stock", ChartKind::Stock),
|
||||
("histogram", ChartKind::Histogram),
|
||||
("pareto", ChartKind::Pareto),
|
||||
("boxWhisker", ChartKind::BoxWhisker),
|
||||
("waterfall", ChartKind::Waterfall),
|
||||
("funnel", ChartKind::Funnel),
|
||||
@@ -4073,6 +4152,16 @@ fn every_chart_kind_survives_xlsx() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pareto_chart_has_no_legend() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Item", "Count"], ["A", 3], ["B", 2], ["C", 1]]})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "pareto", "range": "A1:B4"})).unwrap();
|
||||
let c = &s.doc().unwrap().wb.active().unwrap().charts[0];
|
||||
assert_eq!(c.kind, gridcraft_model::ChartKind::Pareto);
|
||||
assert_eq!(c.legend, gridcraft_model::LegendPos::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_set_doughnut_hole_and_angle() {
|
||||
let mut s = s();
|
||||
@@ -7522,6 +7611,120 @@ fn unique_nonce() -> u64 {
|
||||
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Protect Sheet's Delete Rows and Delete Columns delete a line only when every cell in it is
|
||||
/// unlocked, as Excel does ("You are trying to delete a row that contains a locked cell"). The
|
||||
/// line-level check read a line without a format of its own as carrying the default style, which
|
||||
/// is locked, so every delete was refused however the permission was set; a cell the sheet does
|
||||
/// not store is judged by the format it shows, its row's, then its column's, then the default.
|
||||
#[test]
|
||||
fn a_protected_sheet_deletes_blank_lines_when_the_normal_style_is_unlocked() {
|
||||
// A file whose Normal style is unlocked leaves every unformatted cell unlocked, stored or not.
|
||||
let mut sess = s();
|
||||
sess.execute("review.protectSheet", json!({})).unwrap();
|
||||
{
|
||||
let d = sess.doc_mut().unwrap();
|
||||
let mut wb = (*d.wb).clone();
|
||||
let mut normal = wb.styles.get(gridcraft_model::StyleId::DEFAULT).clone();
|
||||
normal.protection.locked = false;
|
||||
wb.styles = gridcraft_model::StyleTable::with_default(normal);
|
||||
// The sheet must be protected, or the deletes below would pass without checking anything.
|
||||
let p = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()).expect("review.protectSheet protected sheet 0");
|
||||
p.delete_rows = true;
|
||||
p.delete_columns = true;
|
||||
d.wb = std::sync::Arc::new(wb);
|
||||
}
|
||||
sess.execute("selection.set", json!({"range": "A7:A7"})).unwrap();
|
||||
assert!(sess.execute("home.deleteRows", json!({})).is_ok(), "a blank row of unlocked default cells");
|
||||
sess.execute("selection.set", json!({"range": "F1:F1"})).unwrap();
|
||||
assert!(sess.execute("home.deleteColumns", json!({})).is_ok(), "a blank column of unlocked default cells");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_protected_sheet_deletes_lines_when_it_says_so() {
|
||||
fn grant(sess: &mut Session) {
|
||||
let d = sess.doc_mut().unwrap();
|
||||
let mut wb = (*d.wb).clone();
|
||||
if let Some(p) = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()) {
|
||||
p.delete_rows = true;
|
||||
p.delete_columns = true;
|
||||
}
|
||||
d.wb = std::sync::Arc::new(wb);
|
||||
}
|
||||
// Values in A1:A3, the given ranges unlocked (or locked again) in order, then protected.
|
||||
let book = |locks: &[(&str, bool)], granted: bool| {
|
||||
let mut sess = s();
|
||||
for (c, v) in [("A1", "1"), ("A2", "2"), ("A3", "3")] {
|
||||
sess.execute("cell.set", json!({"cell": c, "input": v})).unwrap();
|
||||
}
|
||||
for (range, on) in locks {
|
||||
sess.execute("home.lockCell", json!({"range": range, "on": on})).unwrap();
|
||||
}
|
||||
sess.execute("review.protectSheet", json!({})).unwrap();
|
||||
if granted {
|
||||
grant(&mut sess);
|
||||
}
|
||||
sess
|
||||
};
|
||||
let delete = |sess: &mut Session, what: &str, at: &str| {
|
||||
sess.execute("selection.set", json!({"range": format!("{at}:{at}")})).unwrap();
|
||||
sess.execute(what, json!({})).is_ok()
|
||||
};
|
||||
let (rows, cols) = ("home.deleteRows", "home.deleteColumns");
|
||||
const SHEET: &str = "A1:XFD1048576";
|
||||
|
||||
// Granted, over whole rows the user unlocked: the row goes, and the rows below move up.
|
||||
let mut sess = book(&[("A1:XFD10", false)], true);
|
||||
assert!(delete(&mut sess, rows, "A1"), "an unlocked row is deleted");
|
||||
assert_eq!((v(&sess, "A1"), v(&sess, "A2")), (Value::Number(2.0), Value::Number(3.0)));
|
||||
// Its columns still have locked cells below row 10, so a column is not deleted.
|
||||
assert!(!delete(&mut sess, cols, "A1"), "a column with locked cells stays");
|
||||
|
||||
// Granted, over a whole column the user unlocked: the column goes.
|
||||
let mut sess = book(&[("A1:A1048576", false)], true);
|
||||
assert!(delete(&mut sess, cols, "A1"), "an unlocked column is deleted");
|
||||
assert_eq!(v(&sess, "A1"), Value::Empty);
|
||||
|
||||
// Granted, with the whole sheet unlocked: blank lines go too, judged by their columns' format.
|
||||
let mut sess = book(&[(SHEET, false)], true);
|
||||
assert!(delete(&mut sess, rows, "A7"), "a blank row under unlocked columns");
|
||||
assert!(delete(&mut sess, cols, "F1"), "a blank unlocked column");
|
||||
|
||||
// Not granted: refused, and the rows stay.
|
||||
let mut sess = book(&[(SHEET, false)], false);
|
||||
assert!(!delete(&mut sess, rows, "A1"), "Delete rows is off");
|
||||
assert!(!delete(&mut sess, cols, "A1"), "Delete columns is off");
|
||||
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
|
||||
|
||||
// Granted, but only a block of cells is unlocked: the rest of each line is locked by default,
|
||||
// so neither its rows nor its columns are deleted.
|
||||
let mut sess = book(&[("A1:D10", false)], true);
|
||||
assert!(!delete(&mut sess, rows, "A1"), "E1 onwards are locked");
|
||||
assert!(!delete(&mut sess, cols, "A1"), "A11 onwards are locked");
|
||||
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
|
||||
|
||||
// Granted, nothing unlocked: a blank line is locked by the default like any other, and a line
|
||||
// with a locked value in it is refused by that cell.
|
||||
let mut sess = book(&[], true);
|
||||
assert!(!delete(&mut sess, rows, "A7"), "a blank row of default cells is locked");
|
||||
assert!(!delete(&mut sess, cols, "F1"), "a blank column of default cells is locked");
|
||||
assert!(!delete(&mut sess, rows, "A1"), "locked cells are not deleted");
|
||||
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
|
||||
|
||||
// Granted, the sheet unlocked but row 5 locked again by a format of its own: row 5 is refused,
|
||||
// and so is every column, since row 5's format comes before a column's in each cell it crosses.
|
||||
// The format has to go on before the sheet is protected, since changing a format on a
|
||||
// protected sheet is itself refused.
|
||||
let mut sess = book(&[(SHEET, false), ("A5:XFD5", true)], true);
|
||||
assert!(!delete(&mut sess, rows, "A5"), "a locked row format refuses");
|
||||
assert!(!delete(&mut sess, cols, "B1"), "B5 is locked by its row");
|
||||
assert!(delete(&mut sess, rows, "A6"), "the rows beside it are not");
|
||||
|
||||
// An unprotected sheet is untouched by any of this.
|
||||
let mut sess = s();
|
||||
sess.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
sess.execute("home.deleteRows", json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// Normal, Page Layout and Page Break Preview are not undo steps (as in Excel), so undoing or
|
||||
/// redoing an edit keeps each sheet in the view it is in now, instead of putting back the view
|
||||
/// of the snapshot it swaps in. Found through the command-sequence fuzz (seed 177).
|
||||
|
||||
@@ -317,6 +317,327 @@ fn a_python_cell_without_its_code_keeps_its_whole_cached_result_as_values() {
|
||||
}
|
||||
}
|
||||
|
||||
fn long_warning(n: u64) -> String {
|
||||
format!("sheet \"Sheet1\": {n} cell text(s) longer than Excel's limit of 32767 UTF-16 units were read; they were not cut to that length")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_in_a_python_spill_is_kept_and_warned_about() {
|
||||
// A Python cell's spilled values are its result, kept and saved, so text in them longer than
|
||||
// Excel allows in a cell is kept whole with the warning a plain cell's gets; at the limit, no warning.
|
||||
let most = gridcraft_core::MAX_CELL_CHARS as usize;
|
||||
let book = |n: usize| {
|
||||
let data = format!(
|
||||
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A2\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c></row></sheetData>",
|
||||
"a".repeat(n)
|
||||
);
|
||||
crate::io::open_bytes("long.xlsx", &excel_shaped(&data, Some(&["[1, 'text']"]))).unwrap()
|
||||
};
|
||||
let long = |warnings: &[String]| warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>();
|
||||
let (wb, warnings) = book(most);
|
||||
assert!(long(&warnings).is_empty(), "{warnings:?}");
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most).into())));
|
||||
let (wb, warnings) = book(most + 1);
|
||||
assert_eq!(long(&warnings), [long_warning(1)], "{warnings:?}");
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Text("a".repeat(most + 1).into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_address_in_a_python_spill_keeps_the_last_value_with_a_warning() {
|
||||
// A2 lies in A1's spill and has the default style, so its value is kept only as part of the
|
||||
// result, in the spill and not in a cell; a second A2, after B2, replaces it there, as on any
|
||||
// cell, and is counted as a repeat, found by the column bitmap of row 2's element (the next
|
||||
// test puts the second A2 in a later element, after another row's, where the spill finds it).
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c><c r=\"A2\"><v>9</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
|
||||
assert_eq!(wb.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(5.0));
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w
|
||||
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(!warnings.iter().any(|w| w.contains("out of column order")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_address_in_a_python_spill_in_a_later_row_element_is_found_in_the_spill() {
|
||||
// As above, but the second A2 sits in a second row element for row 2, after row 3's: the
|
||||
// column bitmap has been cleared and A2 is not the furthest cell, so only the spill finds the
|
||||
// repeat.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>2</v></c><c r=\"B2\"><v>5</v></c></row><row r=\"3\"><c r=\"C3\"><v>7</v></c></row>\
|
||||
<row r=\"2\"><c r=\"A2\"><v>9</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().spill.get(&CellRef::parse("A2").unwrap()), Some(&Value::Number(9.0)));
|
||||
assert!(
|
||||
warnings
|
||||
.iter()
|
||||
.any(|w| w
|
||||
== "sheet \"Sheet1\": 1 cell(s), or a row's properties, repeated an address or row already read; the later ones were read again"),
|
||||
"{warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_spilled_text_is_counted_when_read_even_where_a_repeat_replaces_it() {
|
||||
// A long A2 in A1's spill, then a second A2: the long text is counted as it is read, so a
|
||||
// plain value replacing it leaves the count at one, and a second long one makes it two.
|
||||
let long = format!("<c r=\"A2\" t=\"inlineStr\"><is><t>{}</t></is></c>", "a".repeat(gridcraft_core::MAX_CELL_CHARS as usize + 1));
|
||||
let count = |second: &str| {
|
||||
let data = format!(
|
||||
"<sheetData><row r=\"1\"><c r=\"A1\" cm=\"1\"><f t=\"array\" ref=\"A1:A3\">_xlfn._xlws.PY(0,0)</f><v>1</v></c></row>\
|
||||
<row r=\"2\">{long}{second}</row></sheetData>"
|
||||
);
|
||||
let (_, warnings) = crate::io::open_bytes("repeat.xlsx", &excel_shaped(&data, Some(&["[1, 2, 3]"]))).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("already read")), "{warnings:?}");
|
||||
warnings.iter().filter(|w| w.contains("longer than Excel's")).cloned().collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(count("<c r=\"A2\"><v>9</v></c>"), [long_warning(1)]);
|
||||
assert_eq!(count(&long), [long_warning(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_code_dropped_at_the_element_cap_leaves_its_cells_with_their_values() {
|
||||
// The first script's code holds a million elements. With the `environmentDefinition` before
|
||||
// the scripts in the tree, the last of them crosses the reader's element cap for a part, and
|
||||
// the code element is dropped with the 999,999 it held: 1,000,001 elements. A script whose
|
||||
// code was dropped is treated as missing, so A1, naming it, keeps its cached value and no
|
||||
// Python code, through a save too. The second script is read whole, and the third, an empty
|
||||
// `code` in the file, is empty code, as before.
|
||||
let crowded = format!("x = 1{}", "<pad/>".repeat(1_000_000));
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c>\
|
||||
<c r=\"C1\"><f>_xlfn._xlws.PY(2,0)</f><v>3</v></c></row></sheetData>";
|
||||
let bytes = excel_shaped(data, Some(&[&crowded, "y = 2", ""]));
|
||||
let (_, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.starts_with("the Python part: dropped 1000001 element(s)")
|
||||
&& w.ends_with("a script that lost its code and kept no code after it counts as missing")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(warnings.iter().any(|w| w.starts_with("1 Python cell(s) name code the file's Python part doesn't hold")), "{warnings:?}");
|
||||
let mut s = s();
|
||||
open(&mut s, "crowded.xlsx", &bytes);
|
||||
let check = |s: &Session, when: &str| {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
let a1 = sh.cell(CellRef::parse("A1").unwrap()).unwrap_or_else(|| panic!("{when}: A1 is stored"));
|
||||
assert_eq!(a1.value, Value::Number(1.0), "{when}");
|
||||
assert!(a1.py.is_none() && a1.formula.is_none(), "{when}: A1 is a plain value");
|
||||
assert_eq!(code(s, "B1").map(|p| p.code), Some("y = 2".to_string()), "{when}");
|
||||
assert_eq!(code(s, "C1").map(|p| p.code), Some(String::new()), "{when}");
|
||||
};
|
||||
check(&s, "after open");
|
||||
let saved = save(&mut s, "xlsx");
|
||||
open(&mut s, "saved.xlsx", &saved);
|
||||
check(&s, "after a save");
|
||||
}
|
||||
|
||||
/// A1 naming the one script, `script` (a whole `pythonScript` element), read: A1's Python code, if
|
||||
/// any, and the warnings.
|
||||
fn a1_code_with_script(script: &str) -> (Option<String>, Vec<String>) {
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["MARKER"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| {
|
||||
if name == "xl/python/python1.xml" { text.replace("<pythonScript><code>MARKER</code></pythonScript>", script) } else { text.to_string() }
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("script.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).cloned();
|
||||
(a1.and_then(|c| c.py.map(|p| p.code.clone())), warnings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_without_code_reads_as_empty_code_also_when_an_unknown_element_crosses_the_cap() {
|
||||
// A script with no code reads as empty code. An unknown element in it that crosses the
|
||||
// element cap is dropped and counted, but holds nothing the reader reads: the script still
|
||||
// reads as empty code, not as missing.
|
||||
for (script, dropped) in [
|
||||
("<pythonScript><other/></pythonScript>".to_string(), false),
|
||||
(format!("<pythonScript><other>{}</other></pythonScript>", "<pad/>".repeat(1_000_001)), true),
|
||||
] {
|
||||
let (code, warnings) = a1_code_with_script(&script);
|
||||
assert_eq!(code.as_deref(), Some(""), "{warnings:?}");
|
||||
assert_eq!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), dropped, "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_whose_first_code_is_dropped_at_the_element_cap_takes_its_second_code() {
|
||||
// The first code crosses the element cap and is dropped whole: it took no place in the
|
||||
// script's allowance of one code, so the second code is read, and A1 takes it.
|
||||
let (code, warnings) =
|
||||
a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code>y = 2</code></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_whose_code_is_dropped_at_the_element_cap_before_an_empty_code_counts_as_missing() {
|
||||
// The first code crosses the element cap and is dropped whole, and the code after it is empty:
|
||||
// the script lost its code and kept none, so A1 keeps only its value, as when no code follows.
|
||||
let (code, warnings) = a1_code_with_script(&format!("<pythonScript><code>x = 1{}</code><code/></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code, None, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_that_keeps_its_code_and_loses_a_second_one_past_the_element_cap_keeps_its_code() {
|
||||
// The second code crosses the element cap; it is one more than a script holds, so it is
|
||||
// dropped for that, and the script, which lost no code it reads, keeps its first code, empty
|
||||
// or not.
|
||||
for kept in ["y = 2", ""] {
|
||||
let (code, warnings) =
|
||||
a1_code_with_script(&format!("<pythonScript><code>{kept}</code><code>x = 1{}</code></pythonScript>", "<pad/>".repeat(1_000_001)));
|
||||
assert_eq!(code.as_deref(), Some(kept), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_that_loses_an_unknown_element_at_the_element_cap_keeps_its_code() {
|
||||
// The script's code comes first; an unknown element after it crosses the element cap and is
|
||||
// dropped whole. The code was kept, so A1 keeps it.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let crowded = format!("</code><extra>{}</extra></pythonScript>", "<pad/>".repeat(1_000_001));
|
||||
let good = excel_shaped(data, Some(&["y = 2"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</code></pythonScript>", &crowded) } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("crowded.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("y = 2"), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_script_with_the_element_cap_full_is_read_and_the_part_fails_when_its_scripts_close() {
|
||||
// The `environmentDefinition` and the filler before `pythonScripts` fill the part's element
|
||||
// cap of a million. An empty script holds no element, so it is handed out as on main and
|
||||
// reads as empty code; `pythonScripts` itself is then one element past the cap, so the part
|
||||
// fails as it closes, and the warning counts the empty script among those kept. A1, naming
|
||||
// it, keeps the empty code. With one element less of filler the part is whole.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["MARKER"]));
|
||||
for (filler, script, damaged) in
|
||||
[(999_999, "<pythonScript/>", true), (999_999, "<pythonScript></pythonScript>", true), (999_998, "<pythonScript/>", false)]
|
||||
{
|
||||
let scripts = format!("{}<pythonScripts>{script}</pythonScripts>", "<pad/>".repeat(filler));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| {
|
||||
if name == "xl/python/python1.xml" {
|
||||
text.replace("<pythonScripts><pythonScript><code>MARKER</code></pythonScript></pythonScripts>", &scripts)
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("full.xlsx", &bytes).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some(""), "{script} after {filler}: {warnings:?}");
|
||||
let failed: Vec<&String> = warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).collect();
|
||||
let expected = "the Python part is damaged (the file contains invalid XML: the part holds more than 1000000 elements); kept 1 scripts";
|
||||
assert_eq!(failed, if damaged { vec![expected] } else { vec![] }, "{script} after {filler}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("doesn't hold") || w.starts_with("the Python part: dropped")), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_python_part_still_reports_what_it_dropped_before_the_damage() {
|
||||
// The script's second code is dropped, then the part ends in an unclosed comment: both the
|
||||
// damage and the dropped element are warned about.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["x = 1</code><code>y = 2"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (_, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
|
||||
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_code_in_a_python_script_is_dropped_with_a_warning() {
|
||||
// A script holds one code: the first is read, the second dropped and counted.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let (wb, warnings) = crate::io::open_bytes("twice.xlsx", &excel_shaped(data, Some(&["x = 1</code><code>y = 2"]))).unwrap();
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"));
|
||||
assert!(warnings.iter().any(|w| w.starts_with("the Python part: dropped 1 element(s)")), "{warnings:?}");
|
||||
}
|
||||
|
||||
fn unknown_warning(n: u64) -> String {
|
||||
format!("the Python part: {n} element(s) GridCraft does not read (unknown elements) were left out and will not be saved")
|
||||
}
|
||||
|
||||
fn unknown_warnings(warnings: &[String]) -> Vec<String> {
|
||||
warnings.iter().filter(|w| w.contains("does not read")).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_with_an_unknown_child_keeps_its_code_and_warns_that_it_will_not_be_saved() {
|
||||
// The unknown child is small, so nothing reaches an allowance or the element cap and nothing
|
||||
// is dropped: the code is read, and the child, which a save does not write, is warned about.
|
||||
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code><extra>note</extra></pythonScript>");
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.starts_with("the Python part: dropped ")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_children_across_two_scripts_are_counted_in_one_warning() {
|
||||
// Two unknown children in the first script and one in the second: one warning, counting three.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c><c r=\"B1\"><f>_xlfn._xlws.PY(1,0)</f><v>2</v></c></row></sheetData>";
|
||||
let scripts = ["x = 1</code><extra/><other>text</other><code>unread", "y = 2</code><extra/><code>unread"];
|
||||
let (wb, warnings) = crate::io::open_bytes("unknown.xlsx", &excel_shaped(data, Some(&scripts))).unwrap();
|
||||
let sheet = wb.sheet(0).unwrap();
|
||||
let code = |cell: &str| sheet.cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_ref().map(|p| p.code.clone()));
|
||||
assert_eq!(code("A1").as_deref(), Some("x = 1"), "{warnings:?}");
|
||||
assert_eq!(code("B1").as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(3)], "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_without_unknown_children_gives_no_unknown_element_warning() {
|
||||
let (code, warnings) = a1_code_with_script("<pythonScript><code>y = 2</code></pythonScript>");
|
||||
assert_eq!(code.as_deref(), Some("y = 2"), "{warnings:?}");
|
||||
assert!(unknown_warnings(&warnings).is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_python_part_still_reports_unknown_children_read_before_the_damage() {
|
||||
// The script, with one unknown child, closes before the part ends in an unclosed comment: both
|
||||
// the damage and the unknown child are warned about, and the script's code is kept.
|
||||
let data = "<sheetData><row r=\"1\"><c r=\"A1\"><f>_xlfn._xlws.PY(0,0)</f><v>1</v></c></row></sheetData>";
|
||||
let good = excel_shaped(data, Some(&["x = 1</code><extra/><code>unread"]));
|
||||
let bytes = with_parts(
|
||||
&good,
|
||||
|name, text| if name == "xl/python/python1.xml" { text.replace("</pythonScripts></python>", "<!-- ") } else { text.to_string() },
|
||||
&[],
|
||||
);
|
||||
let (wb, warnings) = crate::io::open_bytes("damaged.xlsx", &bytes).unwrap();
|
||||
assert_eq!(warnings.iter().filter(|w| w.starts_with("the Python part is damaged")).count(), 1, "{warnings:?}");
|
||||
assert_eq!(unknown_warnings(&warnings), [unknown_warning(1)], "{warnings:?}");
|
||||
let a1 = wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().clone();
|
||||
assert_eq!(a1.py.as_ref().map(|p| p.code.as_str()), Some("x = 1"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_python_spill_whose_blank_cells_have_no_records_is_still_a_spill() {
|
||||
// A1's result spills over A1:A3, and the file holds no records for the blank A2 and A3.
|
||||
|
||||
@@ -530,7 +530,7 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
|
||||
}
|
||||
|
||||
/// The workbook with view state (active sheet, scroll, active cell, zoom, Normal / Page Layout /
|
||||
/// Page Break Preview) and the Watch Window list reset: undo restores view state as it was, but
|
||||
/// Page Break Preview, Show page breaks) and the Watch Window list reset: undo restores view state as it was, but
|
||||
/// switching sheets, zooming or switching views isn't an undoable edit.
|
||||
fn canonical(wb: &Workbook) -> Workbook {
|
||||
let mut wb = wb.clone();
|
||||
@@ -542,6 +542,8 @@ fn canonical(wb: &Workbook) -> Workbook {
|
||||
sh.view_top_left = CellRef::default();
|
||||
sh.zoom = 100;
|
||||
sh.view = SheetViewMode::Normal;
|
||||
// Page Break Preview turns Show page breaks on, a display option that isn't an edit either.
|
||||
sh.show_page_breaks = false;
|
||||
}
|
||||
wb
|
||||
}
|
||||
|
||||
@@ -600,8 +600,15 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let col =
|
||||
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
let col = |name: &str| TableColumn {
|
||||
name: name.into(),
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
query_field_id: None,
|
||||
xml: None,
|
||||
};
|
||||
sh.tables.push(Table {
|
||||
id: 1,
|
||||
name: "LeftTable".into(),
|
||||
@@ -618,6 +625,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.tables.push(Table {
|
||||
id: 2,
|
||||
@@ -635,6 +643,7 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
query_table: None,
|
||||
});
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(2).or_default().hidden = true;
|
||||
|
||||
@@ -55,6 +55,31 @@ fn resize_next_to_another_table_still_works() {
|
||||
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_keeps_a_renamed_column_query_field() {
|
||||
let mut s = table();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let si = d.wb.active_sheet();
|
||||
std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns[1].query_field_id = Some(7);
|
||||
s.execute("range.setValues", json!({"range":"B1", "values":[["Amount"]]})).unwrap();
|
||||
s.execute("table.resize", json!({"table":"T", "range":"A1:B3"})).unwrap();
|
||||
let col = &s.doc().unwrap().wb.active().unwrap().tables[0].columns[1];
|
||||
assert_eq!((col.name.as_str(), col.query_field_id), ("Amount", Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_preserves_query_fields_only_for_surviving_addresses() {
|
||||
let mut s = table();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let si = d.wb.active_sheet();
|
||||
let columns = &mut std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns;
|
||||
columns[0].query_field_id = Some(3);
|
||||
columns[1].query_field_id = Some(7);
|
||||
s.execute("table.resize", json!({"table":"T", "range":"B1:C3"})).unwrap();
|
||||
let cols = &s.doc().unwrap().wb.active().unwrap().tables[0].columns;
|
||||
assert_eq!(cols.iter().map(|c| c.query_field_id).collect::<Vec<_>>(), [Some(7), None]);
|
||||
}
|
||||
|
||||
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
|
||||
s.doc().unwrap().wb.active().unwrap()
|
||||
}
|
||||
|
||||
@@ -23,6 +23,19 @@ fn needle(args: &[Arg], i: usize) -> R<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The lookup value of XLOOKUP and XMATCH. Unlike the older lookups, a reference to a blank cell is
|
||||
/// blank rather than numeric zero: it matches a blank entry and nothing else (#4044). A written
|
||||
/// blank argument (`XMATCH(, array)`) still becomes zero, as MATCH does.
|
||||
fn xneedle(args: &[Arg], i: usize) -> R<Value> {
|
||||
let a = arg(args, i)?;
|
||||
match a.value.scalar() {
|
||||
Value::Error(e) => Err(e),
|
||||
Value::Empty if a.from_ref || a.blank_value => Ok(Value::Empty),
|
||||
Value::Empty => Ok(Value::Number(0.0)),
|
||||
v => Ok(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// Order of two values for the approximate and binary searches: [`compare`], except that numbers
|
||||
/// compare exactly. Excel's `=` treats numbers equal to 15 significant digits as equal, but its
|
||||
/// lookups don't. Observed in Excel 365 with A1 holding
|
||||
@@ -233,6 +246,12 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
if search_mode.abs() == 2 {
|
||||
let desc = search_mode == -2;
|
||||
// A blank needle only matches a blank entry. The coercing comparison would read it as
|
||||
// numeric zero, so the exact result stands even when it finds nothing: the approximate
|
||||
// probes must not fall through to a zero (#4044).
|
||||
if matches!(x, Value::Empty) {
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
}
|
||||
if match_mode == 2 {
|
||||
// Wildcards are not supported with binary search: Excel falls back to exact.
|
||||
return Ok(bsearch_exact(x, hay, desc));
|
||||
@@ -292,13 +311,20 @@ fn xsearch(x: &Value, hay: &[Value], match_mode: i64, search_mode: i64) -> R<Opt
|
||||
}
|
||||
|
||||
fn bsearch_exact(x: &Value, hay: &[Value], desc: bool) -> Option<usize> {
|
||||
if matches!(x, Value::Empty) {
|
||||
// A blank needle only matches a blank entry. The coercing comparison below would read it
|
||||
// as numeric zero, so handle it here: blanks sort last in both directions, so the first
|
||||
// blank entry is the only possible exact match.
|
||||
let p = hay.partition_point(|v| !matches!(v, Value::Empty));
|
||||
return matches!(hay.get(p)?, Value::Empty).then_some(p);
|
||||
}
|
||||
let p = bsearch_first(x, hay, desc)?;
|
||||
let v = hay.get(p)?;
|
||||
if binary_order(v, x, desc) == Ordering::Equal { Some(p) } else { None }
|
||||
}
|
||||
|
||||
fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -344,7 +370,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
}
|
||||
|
||||
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let x = needle(args, 0)?;
|
||||
let x = xneedle(args, 0)?;
|
||||
let lv = &arg(args, 1)?.value;
|
||||
if let Value::Error(e) = lv {
|
||||
return Err(*e);
|
||||
@@ -567,6 +593,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
mod tests {
|
||||
use gridcraft_core::{CellError, Value};
|
||||
|
||||
use crate::Arg;
|
||||
use crate::util::testutil::*;
|
||||
|
||||
fn table() -> Value {
|
||||
@@ -759,6 +786,49 @@ mod tests {
|
||||
assert_eq!(rows_of(&r), vec![vec![nv(3.0), nv(1.0)]]);
|
||||
}
|
||||
|
||||
/// A reference to a blank cell is a blank lookup value, not numeric zero, for XMATCH and
|
||||
/// XLOOKUP: it finds a blank entry and misses numbers. MATCH keeps Excel's zero coercion (#4044).
|
||||
#[test]
|
||||
fn xmatch_and_xlookup_treat_a_blank_reference_as_blank() {
|
||||
let numbers = || av(row(&[0.0, 1.0, 3.0]));
|
||||
let blank = || Arg::reference(Value::Empty);
|
||||
is_err(ev("XMATCH", vec![blank(), numbers()]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), rf(arr(vec![vec![Value::Empty], vec![nv(2.0)]]))]), 1.0);
|
||||
let keys = || rf(col(&[0.0, 1.0, 3.0]));
|
||||
let values = || av(col(&[10.0, 20.0, 30.0]));
|
||||
close(ev("XLOOKUP", vec![blank(), keys(), values(), n(999.0), n(0.0)]), 999.0);
|
||||
// Binary exact search (search mode 2 ascending, -2 descending) does not coerce the blank
|
||||
// needle to zero either: {0} has no blank entry, {0;blank} has one last.
|
||||
let zero = || rf(col(&[0.0]));
|
||||
let zero_then_blank = || rf(arr(vec![vec![nv(0.0)], vec![Value::Empty]]));
|
||||
let just_blank = || rf(arr(vec![vec![Value::Empty]]));
|
||||
for mode in [2.0, -2.0] {
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(0.0), n(mode)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(0.0), n(mode)]), 2.0);
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(0.0), n(mode)]), 1.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 999.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(0.0), n(mode)]), 10.0);
|
||||
// The approximate binary modes (-1 next smaller, 1 next larger) still take a present
|
||||
// exact blank before their fallback, in both search directions.
|
||||
for mm in [-1.0, 1.0] {
|
||||
close(ev("XMATCH", vec![blank(), just_blank(), n(mm), n(mode)]), 1.0);
|
||||
close(ev("XMATCH", vec![blank(), zero_then_blank(), n(mm), n(mode)]), 2.0);
|
||||
close(ev("XLOOKUP", vec![blank(), just_blank(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 10.0);
|
||||
close(ev("XLOOKUP", vec![blank(), zero_then_blank(), av(col(&[10.0, 20.0])), n(999.0), n(mm), n(mode)]), 20.0);
|
||||
// Without a blank entry the approximate probes must not read the blank as zero.
|
||||
is_err(ev("XMATCH", vec![blank(), zero(), n(mm), n(mode)]), CellError::NA);
|
||||
close(ev("XLOOKUP", vec![blank(), zero(), av(col(&[10.0])), n(999.0), n(mm), n(mode)]), 999.0);
|
||||
}
|
||||
}
|
||||
// Controls: numeric zero is still a key, and a written blank stays zero.
|
||||
close(ev("XMATCH", vec![n(0.0), numbers()]), 1.0);
|
||||
close(ev("XLOOKUP", vec![n(0.0), keys(), values(), n(999.0), n(0.0)]), 10.0);
|
||||
is_err(ev("XMATCH", vec![n(0.0), just_blank(), n(0.0), n(2.0)]), CellError::NA);
|
||||
close(ev("XMATCH", vec![empty(), zero(), n(0.0), n(2.0)]), 1.0);
|
||||
close(ev("MATCH", vec![blank(), numbers(), n(0.0)]), 1.0);
|
||||
close(ev("XMATCH", vec![empty(), numbers()]), 1.0);
|
||||
}
|
||||
|
||||
/// Lookups compare numbers exactly, unlike `=` (15 significant digits). Observed in Excel 365.
|
||||
#[test]
|
||||
fn lookups_compare_numbers_exactly() {
|
||||
|
||||
@@ -23,8 +23,8 @@ use descriptive::{
|
||||
use distributions::{
|
||||
beta_dist, beta_inv, betadist_legacy, binom_dist, binom_dist_range, binom_inv, chisq_dist, chisq_dist_rt, chisq_inv, chisq_inv_rt, chisq_test,
|
||||
confidence_norm, confidence_t, expon_dist, f_dist, f_dist_rt, f_inv, f_inv_rt, f_test, fisher, gamma_dist, gamma_fn, gamma_inv, gammaln, gauss,
|
||||
hypgeom_dist, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist, t_dist, t_dist_2t,
|
||||
t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
|
||||
hypgeom_dist, hypgeomdist_legacy, lognorm_dist, lognorm_inv, negbinom_dist, norm_dist, norm_inv_fn, norm_s_dist, norm_s_inv, poisson_dist,
|
||||
t_dist, t_dist_2t, t_dist_rt, t_inv, t_inv_2t, t_test, tdist_legacy, weibull_dist, z_test,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use regression::{MAX_REGRESSORS, check_regression_size};
|
||||
@@ -649,7 +649,7 @@ pub(crate) fn specs() -> Vec<FnSpec> {
|
||||
S,
|
||||
"HYPGEOMDIST(sample_s, number_sample, population_s, number_pop)",
|
||||
"Hypergeometric probability of an exact count.",
|
||||
hypgeom_dist
|
||||
hypgeomdist_legacy
|
||||
),
|
||||
f!(
|
||||
"NEGBINOM.DIST",
|
||||
|
||||
@@ -804,15 +804,27 @@ pub(super) fn weibull_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
num_val(if cum { -(-t).exp_m1() } else { al / be.powf(al) * x.powf(al - 1.0) * (-t).exp() })
|
||||
}
|
||||
|
||||
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
fn hypgeom_common(a: &[Arg], strict: bool) -> R<Value> {
|
||||
let k = num(a, 0)?.trunc();
|
||||
let n = num(a, 1)?.trunc();
|
||||
let kk = num(a, 2)?.trunc();
|
||||
let nn = num(a, 3)?.trunc();
|
||||
let cum = if a.len() > 4 { boolean(a, 4)? } else { false };
|
||||
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn || k > n.min(kk) || k < (n - nn + kk).max(0.0) {
|
||||
if k < 0.0 || n <= 0.0 || kk <= 0.0 || nn <= 0.0 || n > nn || kk > nn {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let lo = (n - nn + kk).max(0.0);
|
||||
let hi = n.min(kk);
|
||||
if k < lo || k > hi {
|
||||
// Above the support the mass is zero and the cumulative form is 1, as
|
||||
// Excel returns (#4032). Below the support Excel returns #NUM!, so both
|
||||
// forms stay strict there. The legacy compatibility form is strict on
|
||||
// both sides.
|
||||
if strict || k < lo {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
return num_val(if cum { 1.0 } else { 0.0 });
|
||||
}
|
||||
let pmf = |i: f64| (ln_comb(kk, i) + ln_comb(nn - kk, n - i) - ln_comb(nn, n)).exp();
|
||||
if !cum {
|
||||
return num_val(pmf(k));
|
||||
@@ -829,6 +841,14 @@ pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
num_val(s.min(1.0))
|
||||
}
|
||||
|
||||
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
hypgeom_common(a, false)
|
||||
}
|
||||
|
||||
pub(super) fn hypgeomdist_legacy(a: &[Arg], _: C) -> R<Value> {
|
||||
hypgeom_common(a, true)
|
||||
}
|
||||
|
||||
pub(super) fn negbinom_dist(a: &[Arg], _: C) -> R<Value> {
|
||||
let f = num(a, 0)?.trunc();
|
||||
let s = num(a, 1)?.trunc();
|
||||
|
||||
@@ -821,6 +821,25 @@ fn discrete() {
|
||||
close_tol(ev("NEGBINOMDIST", vec![n(10.0), n(5.0), n(0.25)]), 0.0550487, D7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hypgeom_dist_out_of_support_clamps() {
|
||||
// Support is [max(0, n - nn + kk), min(n, kk)].
|
||||
// Above support: k=2, n=1, kk=1, nn=3 -> high = min(1, 1) = 1, so 2 is above.
|
||||
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(false)]), Value::Number(0.0));
|
||||
assert_eq!(ev("HYPGEOM.DIST", vec![n(2.0), n(1.0), n(1.0), n(3.0), b(true)]), Value::Number(1.0));
|
||||
// Controls inside the support (low = max(0, 1 - 3 + 1) = 0, high = 1).
|
||||
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(false)]), 1.0 / 3.0);
|
||||
close(ev("HYPGEOM.DIST", vec![n(1.0), n(1.0), n(1.0), n(3.0), b(true)]), 1.0);
|
||||
// Below support stays #NUM!, as Excel documents: k=0, n=4, kk=8, nn=10
|
||||
// -> low = max(0, 4 - 10 + 8) = 2, so 0 is below.
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(false)]), CellError::Num);
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(0.0), n(4.0), n(8.0), n(10.0), b(true)]), CellError::Num);
|
||||
// Legacy compatibility form stays strict outside the support.
|
||||
is_err(ev("HYPGEOMDIST", vec![n(5.0), n(4.0), n(8.0), n(20.0)]), CellError::Num);
|
||||
// Invalid population arguments stay #NUM! (number_sample > number_pop here).
|
||||
is_err(ev("HYPGEOM.DIST", vec![n(1.0), n(5.0), n(2.0), n(3.0), b(false)]), CellError::Num);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous() {
|
||||
close_tol(ev("EXPON.DIST", vec![n(0.2), n(10.0), b(true)]), 0.86466472, D7);
|
||||
|
||||
@@ -10,6 +10,16 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-mcp-server = { workspace = true }
|
||||
# The ArtCraft Launcher's switch, the connection file and the live client (`agents`), and the
|
||||
# challenge handshake's proofs (`security`): plain `mcp` finds the open window with them.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
craft-automation = { workspace = true, features = ["agents"] }
|
||||
gridcraft-engine = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The framework's control server, which the desktop app's agent link runs, for the window tests.
|
||||
craft-automation = { workspace = true, features = ["agents", "ui"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
egui = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//! Agents in the open window: GridCraft's side of the ArtCraft Launcher's switch.
|
||||
//!
|
||||
//! While the launcher's *Settings › AI agents* switch names GridCraft (behind the suite's `AI-MCP`
|
||||
//! flag), the desktop app serves its control channel on loopback and publishes where in its
|
||||
//! settings folder (`craft_automation::agents::AgentLink`). Plain `gridcraft-cli mcp` reads that
|
||||
//! file on every tool call ([`LiveBackend`], over the shared `craft_control::agents::Live`), so an
|
||||
//! MCP client's configuration holds no port and no token, and the app may start, quit or move to
|
||||
//! another port while the client stays connected. Adding GridCraft to MCP clients is the
|
||||
//! launcher's job (one entry for every Craft app); GridCraft writes no client configuration.
|
||||
//!
|
||||
//! What is GridCraft's here: its launcher id, its agent settings file ([`SETTINGS_FILE`]), its
|
||||
//! window client ([`Window`], which authenticates the app before it proves it holds the token)
|
||||
//! and its headless session ([`Headless`] with the agent folders as automation roots).
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::security::{self, ProofRole};
|
||||
use craft_control::agents::{self as shared, AgentFolders, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
|
||||
use gridcraft_engine::file_access::AutomationRoots;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::headless::Headless;
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names GridCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "gridcraft";
|
||||
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/GridCraft`).
|
||||
pub const APP_NAME: &str = "GridCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
pub const APP_EXE: &str = "gridcraft";
|
||||
/// The agent settings in the settings folder: `{"controlPort", "readRoot", "writeRoot",
|
||||
/// "whenAppClosed", "allowAgentControl"}` (`craft_control::agents::AgentSettings`). The app writes it
|
||||
/// when they change, so `gridcraft-cli mcp` reads the current choice on every tool call.
|
||||
pub const SETTINGS_FILE: &str = "agents.json";
|
||||
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
|
||||
pub const FOLDERS_METHOD: &str = "agent.folders";
|
||||
|
||||
/// The largest settings file read; the settings are a few short strings.
|
||||
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
|
||||
|
||||
/// GridCraft's settings folder for the platform `platform` (`std::env::consts::OS`), with
|
||||
/// environment variables from `env`: `%APPDATA%\GridCraft`, `~/Library/Application Support/GridCraft`,
|
||||
/// else `$XDG_CONFIG_HOME/gridcraft` (`~/.config/gridcraft`). The desktop app keeps `ui.json`,
|
||||
/// `prefs.json` and its agent files there; `gridcraft-cli mcp` looks for the open window there.
|
||||
pub fn settings_dir_for(platform: &str, env: &impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
match platform {
|
||||
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
|
||||
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
|
||||
_ => env("XDG_CONFIG_HOME")
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.map(|c| c.join("gridcraft")),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`settings_dir_for`] this system.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
settings_dir_for(std::env::consts::OS, &|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be
|
||||
/// read, so neither the app nor the CLI fails over them. One bad value resets only itself.
|
||||
pub fn read_settings(dir: &Path) -> AgentSettings {
|
||||
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
|
||||
let mut text = String::new();
|
||||
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
|
||||
return AgentSettings::default();
|
||||
}
|
||||
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
|
||||
let mut settings = AgentSettings::default();
|
||||
for (key, value) in saved {
|
||||
let mut one = serde_json::to_value(&settings).unwrap_or_default();
|
||||
if let Some(o) = one.as_object_mut()
|
||||
&& o.contains_key(&key)
|
||||
{
|
||||
o.insert(key, value);
|
||||
if let Ok(next) = serde_json::from_value(one) {
|
||||
settings = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Saves `settings` in `dir` (created when missing), replacing the file in one step so a
|
||||
/// `gridcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
|
||||
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
|
||||
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&partial, text)?;
|
||||
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the person lets agents use GridCraft now: with the suite's `AI-MCP` flag, the
|
||||
/// launcher's switch. GridCraft had no agent consent of its own before the switch, so without the
|
||||
/// flag agents get a headless session, as `mcp` always gave them.
|
||||
pub fn allowed_now() -> bool {
|
||||
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// The automation roots for `folders`: what a session with these folders may open and save. A
|
||||
/// direction without a folder is refused, and so is everything when there is no folder at all.
|
||||
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
|
||||
Ok(AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref())?.unwrap_or_else(AutomationRoots::none))
|
||||
}
|
||||
|
||||
/// The `agent_folders` answer for these roots.
|
||||
pub fn folders_answer(roots: Option<&AutomationRoots>) -> Value {
|
||||
match roots {
|
||||
Some(roots) => {
|
||||
let mut folders = AgentFolders::default();
|
||||
folders.read = roots.read_root().map(Path::to_path_buf);
|
||||
folders.write = roots.write_root().map(Path::to_path_buf);
|
||||
shared::folders_answer(&folders)
|
||||
}
|
||||
// A session started with no automation roots (`--headless` without them, or with the
|
||||
// agents switch off) isn't confined: say so rather than claim it has no folders.
|
||||
None => json!({
|
||||
"read_folder": null,
|
||||
"write_folder": null,
|
||||
"unrestricted": true,
|
||||
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- The open window ---------------------------------------------------------------------------
|
||||
|
||||
/// How long connecting to the window may take: it is on loopback.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_millis(800);
|
||||
/// How long a reply may take: the app's own deadline (60 s) plus a margin, so its timeout error
|
||||
/// arrives first.
|
||||
const CALL_TIMEOUT: Duration = Duration::from_secs(65);
|
||||
/// Longest reply line read from the app.
|
||||
const MAX_REPLY: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// One authenticated connection to the open window. The app proves it holds the token first
|
||||
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
|
||||
/// wire, and a program that took a stale port learns nothing derived from it.
|
||||
pub struct Window {
|
||||
addr: SocketAddr,
|
||||
token: String,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
|
||||
pub fn new(port: u16, token: String) -> Self {
|
||||
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
|
||||
}
|
||||
|
||||
/// Connects and runs the challenge handshake.
|
||||
pub fn connect(&mut self) -> Result<(), String> {
|
||||
self.conn = None;
|
||||
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
|
||||
stream.set_nodelay(true).ok();
|
||||
stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
|
||||
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
|
||||
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
|
||||
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
|
||||
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?
|
||||
.map_err(|e| format!("{} refused challenge authentication ({e}); the control token was not used", self.addr))?;
|
||||
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
|
||||
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
|
||||
return Err(format!("{} answered the challenge without a proof; the control token was not used", self.addr));
|
||||
};
|
||||
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(format!("{} could not prove it holds GridCraft's agent token; nothing was sent to it", self.addr));
|
||||
}
|
||||
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
|
||||
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}))?.map_err(|e| format!("GridCraft refused the agent token: {e}"))?;
|
||||
self.conn = Some(conn);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends one request and reads its reply: `Err` when the connection failed, `Ok(Err)` when the app
|
||||
/// answered with an error.
|
||||
fn round_trip(conn: &mut (BufReader<TcpStream>, TcpStream), id: u64, method: &str, params: Value) -> Result<Result<Value, String>, String> {
|
||||
let (reader, writer) = conn;
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
|
||||
let mut reply = String::new();
|
||||
let n = reader.by_ref().take(MAX_REPLY).read_line(&mut reply).map_err(|e| e.to_string())?;
|
||||
if n == 0 || !reply.ends_with('\n') {
|
||||
return Err("the window closed the connection".into());
|
||||
}
|
||||
let v: Value = serde_json::from_str(reply.trim()).map_err(|e| format!("bad reply from the window: {e}"))?;
|
||||
if v.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
return Err("the window answered another request".into());
|
||||
}
|
||||
Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
impl Backend for Window {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
if self.conn.is_none() {
|
||||
self.connect()?;
|
||||
}
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1).max(1);
|
||||
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
|
||||
match round_trip(conn, id, method, params) {
|
||||
Ok(answer) => answer,
|
||||
// Never sent again: the request may have run (#5000). The next call reconnects.
|
||||
Err(e) => {
|
||||
self.conn = None;
|
||||
Err(format!("lost the connection to the GridCraft window ({e}); the request may or may not have run"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
format!("the open GridCraft window ({})", self.addr)
|
||||
}
|
||||
}
|
||||
|
||||
/// The environment variable a client takes the control token from instead of the settings folder.
|
||||
pub const TOKEN_ENV: &str = "GRIDCRAFT_CONTROL_TOKEN";
|
||||
|
||||
/// The client for a `gridcraft --control` window at `addr` (`7979`, `127.0.0.1:7979` or
|
||||
/// `localhost:7979`; loopback only, as the server is), with the token from [`TOKEN_ENV`] or the
|
||||
/// window's `agent-control.token` in the settings folder. The window authenticates first (the
|
||||
/// challenge handshake), so nothing derived from the token goes to another program on that port.
|
||||
pub fn control_window(addr: &str) -> Result<Window, String> {
|
||||
let port = match addr.rsplit_once(':') {
|
||||
None => addr.trim().parse::<u16>().ok(),
|
||||
Some(("127.0.0.1" | "localhost", port)) => port.trim().parse::<u16>().ok(),
|
||||
Some(_) => return Err(format!("{addr} is not a loopback address: GridCraft's control server listens on 127.0.0.1 only")),
|
||||
}
|
||||
.ok_or_else(|| format!("expected a port, 0-65535 (or 127.0.0.1:<port>), not `{addr}`"))?;
|
||||
let supplied = std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty());
|
||||
let file = settings_dir().map(|d| d.join(shared::TOKEN_FILE));
|
||||
let names = craft_automation::args::EnvNames::for_app("GRIDCRAFT");
|
||||
let token = match supplied {
|
||||
Some(t) => security::client_token(Some(t.trim()), None, &craft_automation::args::FlagNames::default(), &names),
|
||||
None => security::client_token(None, file.as_deref(), &craft_automation::args::FlagNames::default(), &names),
|
||||
}
|
||||
.map_err(|e| format!("no control token: {e} (start GridCraft with --control on this machine and user, or set {TOKEN_ENV})"))?;
|
||||
let mut window = Window::new(port, token);
|
||||
window.connect().map_err(|e| format!("cannot reach the GridCraft app on 127.0.0.1:{port}: {e} (start it with `gridcraft --control {port}`)"))?;
|
||||
Ok(window)
|
||||
}
|
||||
|
||||
// ---- The live backend --------------------------------------------------------------------------
|
||||
|
||||
type SharedWindow = Arc<Mutex<Window>>;
|
||||
type SharedHeadless = Arc<Mutex<Headless>>;
|
||||
|
||||
/// Prepares a fresh headless session (the CLI's `--in` / `--sample`).
|
||||
pub type PrepareFn = Box<dyn Fn(&mut Headless) -> Result<(), String> + Send + Sync>;
|
||||
|
||||
/// What plain `gridcraft-cli mcp` needs to find the window.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: connection file, token file and agent settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Overrides the app's closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't.
|
||||
pub launch: Option<shared::LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The default agent folder for an empty folder setting; tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
/// Prepares each new headless session.
|
||||
pub prepare: Option<PrepareFn>,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The settings in `config_dir`, the launcher's switch, the default agent folder.
|
||||
pub fn new(config_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
config_dir,
|
||||
when_closed: None,
|
||||
read_root: None,
|
||||
write_root: None,
|
||||
launch: None,
|
||||
launch_timeout: shared::LAUNCH_TIMEOUT,
|
||||
allowed: allowed_now,
|
||||
default_folder: shared::default_folder(APP_NAME),
|
||||
prepare: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain `gridcraft-cli mcp`: every call goes to the open window while the person lets agents use
|
||||
/// it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup is
|
||||
/// the shared `craft_control::agents::Live`; a session that went headless stays headless.
|
||||
pub struct LiveBackend {
|
||||
live: shared::Live<SharedWindow, SharedHeadless>,
|
||||
}
|
||||
|
||||
impl LiveBackend {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder, prepare } = cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
|
||||
let mut window = Window::new(w.port, w.token.clone());
|
||||
window.connect()?;
|
||||
Ok(Arc::new(Mutex::new(window)))
|
||||
};
|
||||
let headless = move |folders: &HeadlessFolders| -> Result<SharedHeadless, String> {
|
||||
// Each folder grants its direction and a missing one denies it, as in every Craft
|
||||
// app: with no folder at all (none given, or an agent folder that couldn't be made)
|
||||
// nothing may be opened or saved.
|
||||
let roots = if folders.read.is_empty() && folders.write.is_none() {
|
||||
Some(AutomationRoots::none())
|
||||
} else {
|
||||
let mut wanted = AgentFolders::default();
|
||||
wanted.read = folders.read.first().cloned();
|
||||
wanted.write = folders.write.clone();
|
||||
Some(roots_for(&wanted)?)
|
||||
};
|
||||
let mut session = Headless::new().with_automation_roots(roots);
|
||||
if let Some(prepare) = &prepare {
|
||||
prepare(&mut session)?;
|
||||
}
|
||||
Ok(Arc::new(Mutex::new(session)))
|
||||
};
|
||||
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
|
||||
shared_cfg.when_closed = when_closed;
|
||||
shared_cfg.read_roots = read_root.into_iter().collect();
|
||||
shared_cfg.write_root = write_root;
|
||||
shared_cfg.launch = launch;
|
||||
shared_cfg.launch_timeout = launch_timeout;
|
||||
shared_cfg.default_folder = default_folder;
|
||||
Self { live: shared::Live::new(shared_cfg) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(h) => h.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
matches!(self.live.resolve(), Ok(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open GridCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window".into()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Plain `mcp` and the open window: the switch, the closed-app choice, the token handshake and the
|
||||
//! agent folders, against the framework's own control server.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::agents::{Connection, TOKEN_FILE, write_connection};
|
||||
use craft_automation::control::ControlRequest;
|
||||
use craft_automation::server::Listening;
|
||||
use craft_control::agents::WhenAppClosed;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Backend;
|
||||
use crate::agents::{LiveBackend, LiveConfig, Window, write_settings};
|
||||
|
||||
fn temp(label: &str) -> PathBuf {
|
||||
#[allow(clippy::disallowed_methods)] // native-only fixture
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-agents-{label}-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn config(dir: &Path, allowed: fn() -> bool, when_closed: WhenAppClosed) -> LiveConfig {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf());
|
||||
cfg.allowed = allowed;
|
||||
cfg.when_closed = Some(when_closed);
|
||||
cfg.default_folder = None;
|
||||
cfg
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn no() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// A window: the framework's control server with the token in `dir`, published in `dir` as an
|
||||
/// app publishes it. The returned receiver gets the requests the "app" runs.
|
||||
fn window(dir: &Path) -> (Listening, Receiver<ControlRequest>) {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
let token = craft_automation::security::server_token(None, Some(&token_file)).unwrap();
|
||||
let host = craft_ui::runtime::windows::WindowHost::of(&egui::Context::default());
|
||||
let (requests, server) = craft_automation::server::listen(0, token, host).unwrap();
|
||||
write_connection(dir, &Connection::new(server.addr.port(), token_file, "GridCraft test")).unwrap();
|
||||
(server, requests)
|
||||
}
|
||||
|
||||
/// Answers requests on another thread: `ping` with the method name, so a reply shows it came
|
||||
/// from the window.
|
||||
fn serve(requests: Receiver<ControlRequest>) {
|
||||
std::thread::spawn(move || {
|
||||
while let Ok(req) = requests.recv() {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": format!("window {}", req.method)}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_off_serves_headless_without_the_apps_folders_or_a_start() {
|
||||
let dir = temp("off");
|
||||
// The person chose to start the app and set agent folders; with the switch off neither applies
|
||||
// (the app doesn't listen then either: `agents_link_follows_the_switch` in the app).
|
||||
let mut settings = craft_control::agents::AgentSettings::default();
|
||||
settings.read_root = dir.display().to_string();
|
||||
write_settings(&dir, &settings).unwrap();
|
||||
let mut cfg = config(&dir, no, WhenAppClosed::Launch);
|
||||
cfg.launch = Some(Box::new(|| panic!("the switch is off: the app must not be started")));
|
||||
let mut live = LiveBackend::new(cfg);
|
||||
assert_eq!(live.call("ping", json!({})).unwrap(), json!("pong"));
|
||||
assert!(!live.has_ui());
|
||||
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
|
||||
// The command gave no folders, and the app's are only for agents let in: nothing is granted.
|
||||
assert_eq!((folders["read_folder"].clone(), folders["write_folder"].clone()), (Value::Null, Value::Null), "{folders}");
|
||||
assert!(folders.get("unrestricted").is_none(), "{folders}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_on_reaches_the_window() {
|
||||
let dir = temp("on");
|
||||
let (_server, requests) = window(&dir);
|
||||
serve(requests);
|
||||
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Error));
|
||||
assert_eq!(live.call("ping", json!({})).unwrap(), json!("window ping"));
|
||||
assert!(live.has_ui());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_app_follows_the_closed_app_choice() {
|
||||
let dir = temp("closed");
|
||||
// A connection file a crashed app left behind: nothing listens on its port.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
write_connection(&dir, &Connection::new(port, dir.join(TOKEN_FILE), "GridCraft test")).unwrap();
|
||||
let err = LiveBackend::new(config(&dir, yes, WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
|
||||
assert!(err.contains("isn't running"), "{err}");
|
||||
|
||||
// Headless with the app's agent folders: file commands stay inside them.
|
||||
let folder = dir.join("agent folder");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut settings = craft_control::agents::AgentSettings::default();
|
||||
settings.read_root = folder.display().to_string();
|
||||
settings.write_root = folder.display().to_string();
|
||||
write_settings(&dir, &settings).unwrap();
|
||||
std::fs::write(dir.join("outside.csv"), "secret,1\n").unwrap();
|
||||
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Headless));
|
||||
assert_eq!(live.call("ping", json!({})).unwrap(), json!("pong"));
|
||||
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
|
||||
let shown = folders["read_folder"].as_str().unwrap();
|
||||
assert!(Path::new(shown).ends_with("agent folder"), "{folders}");
|
||||
let refused = live.call("engine.execute", json!({"command": "file.open", "params": {"path": dir.join("outside.csv")}})).unwrap_err();
|
||||
assert!(refused.contains("outside the read root"), "{refused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agents_let_in_without_any_folder_may_open_and_save_nothing() {
|
||||
// Agents are let in, the app is closed, the choice is headless, and neither a folder setting nor
|
||||
// a default agent folder exists: the session gets no file access, never unconfined access.
|
||||
let dir = temp("nofolder");
|
||||
std::fs::write(
|
||||
dir.join("any.csv"),
|
||||
"secret,1
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
let mut live = LiveBackend::new(config(&dir, yes, WhenAppClosed::Headless));
|
||||
let folders = live.call(crate::agents::FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!((folders["read_folder"].clone(), folders["unrestricted"].clone()), (Value::Null, Value::Null), "{folders}");
|
||||
let refused = live.call("engine.execute", json!({"command": "file.open", "params": {"path": dir.join("any.csv")}})).unwrap_err();
|
||||
assert!(refused.contains("not granted"), "{refused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_must_prove_it_holds_the_token_before_anything_is_sent() {
|
||||
let dir = temp("token");
|
||||
let (server, requests) = window(&dir);
|
||||
let port = server.addr.port();
|
||||
// A different token than the window's: as a program on a stale port would hold.
|
||||
let wrong = "0".repeat(64);
|
||||
let err = Window::new(port, wrong).connect().unwrap_err();
|
||||
assert!(err.contains("could not prove"), "{err}");
|
||||
assert!(requests.recv_timeout(Duration::from_millis(200)).is_err(), "no request may reach the window");
|
||||
|
||||
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_owned();
|
||||
serve(requests);
|
||||
let mut ok = Window::new(port, token);
|
||||
assert_eq!(ok.call("ping", Value::Null).unwrap(), json!("window ping"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_client_reaches_only_loopback() {
|
||||
// Refused before any token is read, so no token can go to another machine.
|
||||
for addr in ["192.0.2.1:7979", "example.com:7979", "[::ffff:192.0.2.1]:7979"] {
|
||||
let err = crate::agents::control_window(addr).err().unwrap();
|
||||
assert!(err.contains("not a loopback address"), "{addr}: {err}");
|
||||
}
|
||||
assert!(crate::agents::control_window("not a port").is_err());
|
||||
}
|
||||
+1
-138
@@ -1,10 +1,6 @@
|
||||
//! Where MCP tool calls end up: a control-channel method call.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Something that answers control-channel methods (`engine.execute`, `engine.commands`,
|
||||
/// `document.inspect`, `sheet.read`, `ui.screenshot`, …).
|
||||
@@ -16,136 +12,3 @@ pub trait Backend {
|
||||
/// Short human description ("headless", "connected to 127.0.0.1:7979").
|
||||
fn describe(&self) -> String;
|
||||
}
|
||||
|
||||
/// Read/write timeout on the control connection.
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Longest reply line accepted from the app (guards against a runaway peer).
|
||||
const MAX_REPLY: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// A running GridCraft app, reached through its loopback control port.
|
||||
pub struct Remote {
|
||||
addr: String,
|
||||
token: String,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Remote {
|
||||
/// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. The app
|
||||
/// requires a token (#777): `GRIDCRAFT_CONTROL_TOKEN`, else the file the app wrote for this port.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let token = crate::control_auth::client_token(addr).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
Self::connect_with_token(addr, token)
|
||||
}
|
||||
|
||||
/// Like [`Remote::connect`] with a token the caller already has.
|
||||
pub fn connect_with_token(addr: &str, token: String) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), token, conn: None, next_id: 1 };
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn addr(&self) -> &str {
|
||||
&self.addr
|
||||
}
|
||||
|
||||
fn reconnect(&mut self) -> std::io::Result<()> {
|
||||
self.conn = None;
|
||||
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
|
||||
for sa in self.addr.to_socket_addrs()? {
|
||||
// The token goes over plain TCP, so only to this machine: a network peer could read it,
|
||||
// and the app's control port listens on loopback only.
|
||||
if !sa.ip().is_loopback() {
|
||||
last = std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!("{sa} is not a loopback address: the control token is sent only to 127.0.0.1 or ::1"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
match TcpStream::connect_timeout(&sa, Duration::from_secs(2)) {
|
||||
Ok(s) => {
|
||||
s.set_nodelay(true).ok();
|
||||
s.set_read_timeout(Some(IO_TIMEOUT)).ok();
|
||||
s.set_write_timeout(Some(IO_TIMEOUT)).ok();
|
||||
let read = s.try_clone()?;
|
||||
let mut conn = (BufReader::new(read), s);
|
||||
Self::authenticate(&mut conn, &self.token)?;
|
||||
self.conn = Some(conn);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
|
||||
/// The handshake every connection starts with: the app closes one that doesn't send the token first.
|
||||
fn authenticate(conn: &mut (BufReader<TcpStream>, TcpStream), token: &str) -> std::io::Result<()> {
|
||||
let (reader, writer) = conn;
|
||||
writer.write_all(crate::control_auth::auth_line(0, token).as_bytes())?;
|
||||
writer.write_all(b"\n")?;
|
||||
writer.flush()?;
|
||||
let mut reply = String::new();
|
||||
let n = std::io::Read::take(reader, 64 * 1024).read_line(&mut reply)?;
|
||||
let ok = n > 0 && serde_json::from_str::<Value>(reply.trim()).ok().and_then(|v| v.get("ok").and_then(Value::as_bool)) == Some(true);
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"the app refused the control token (is GRIDCRAFT_CONTROL_TOKEN or the app's token file for this port out of date?)",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn roundtrip(&mut self, line: &str) -> std::io::Result<String> {
|
||||
if self.conn.is_none() {
|
||||
self.reconnect()?;
|
||||
}
|
||||
let Some((reader, writer)) = self.conn.as_mut() else {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"));
|
||||
};
|
||||
writer.write_all(line.as_bytes())?;
|
||||
writer.write_all(b"\n")?;
|
||||
writer.flush()?;
|
||||
let mut reply = String::new();
|
||||
let n = std::io::Read::take(reader, MAX_REPLY).read_line(&mut reply)?;
|
||||
if n == 0 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed"));
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Remote {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
// One retry with a fresh connection (the app may have restarted).
|
||||
let reply = match self.roundtrip(&line) {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
self.conn = None;
|
||||
self.roundtrip(&line).map_err(|e| {
|
||||
self.conn = None;
|
||||
format!("GridCraft app at {} is not reachable: {e}", self.addr)
|
||||
})?
|
||||
}
|
||||
};
|
||||
let v: Value = serde_json::from_str(reply.trim()).map_err(|e| format!("bad reply from app: {e}"))?;
|
||||
if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
format!("connected to the GridCraft app at {}", self.addr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
//! Authentication of the control channel (#777).
|
||||
//!
|
||||
//! Anything on the machine, and a web page that POSTs `text/plain` to `127.0.0.1:<port>`, can
|
||||
//! reach a loopback port. So the first line of every connection must be
|
||||
//! `{"id":…,"method":"auth","params":{"token":"…"}}`, with the secret the app made at start. The
|
||||
//! app keeps it in memory and writes it to a file only the user can read (or the user chooses it
|
||||
//! with `GRIDCRAFT_CONTROL_TOKEN`); [`Remote`](crate::Remote) reads it from the same places.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Environment variable holding a token chosen by the user. The app uses it instead of making
|
||||
/// one (and writes no file); clients use it instead of reading the file.
|
||||
pub const TOKEN_ENV: &str = "GRIDCRAFT_CONTROL_TOKEN";
|
||||
/// The method of the handshake line.
|
||||
pub const AUTH_METHOD: &str = "auth";
|
||||
/// Shortest token the app accepts from the user (a made one has 256 bits).
|
||||
pub const MIN_TOKEN_LEN: usize = 16;
|
||||
/// Longest first line the app reads from a peer that hasn't authenticated yet.
|
||||
pub const MAX_AUTH_LINE: usize = 4096;
|
||||
|
||||
/// Compare two secrets without stopping at the first difference. Unequal lengths are unequal
|
||||
/// at once (the length of a token isn't secret).
|
||||
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
// Keep the optimiser from turning the loop into an early exit.
|
||||
std::hint::black_box(diff) == 0
|
||||
}
|
||||
|
||||
/// A made token as lowercase hex (two characters per byte).
|
||||
pub fn hex(bytes: &[u8]) -> String {
|
||||
const DIGITS: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut s = String::with_capacity(bytes.len().saturating_mul(2));
|
||||
for b in bytes {
|
||||
s.push(char::from(DIGITS[usize::from(b >> 4)]));
|
||||
s.push(char::from(DIGITS[usize::from(b & 15)]));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The handshake line a client sends first.
|
||||
pub fn auth_line(id: u64, token: &str) -> String {
|
||||
json!({"id": id, "method": AUTH_METHOD, "params": {"token": token}}).to_string()
|
||||
}
|
||||
|
||||
/// Check a connection's first line. `Ok` is the reply to send before serving further requests;
|
||||
/// `Err` is the reply for a refused connection, which the caller sends and then closes. The
|
||||
/// refusal is the same whatever was wrong, so it tells a stranger nothing.
|
||||
pub fn check_first_line(line: &str, token: &str) -> Result<Value, Value> {
|
||||
let refused = || json!({"ok": false, "error": "authentication required"});
|
||||
let msg: Value = serde_json::from_str(line.trim()).map_err(|_| refused())?;
|
||||
if msg.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
|
||||
return Err(refused());
|
||||
}
|
||||
let given = msg.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or("");
|
||||
// Always compare, so a missing token costs the same as a wrong one.
|
||||
if constant_time_eq(given.as_bytes(), token.as_bytes()) && !token.is_empty() {
|
||||
Ok(json!({"id": msg.get("id").cloned().unwrap_or(Value::Null), "ok": true, "result": {"authenticated": true}}))
|
||||
} else {
|
||||
Err(refused())
|
||||
}
|
||||
}
|
||||
|
||||
/// An app-selected folder for the tokens, set once before any window exists. The nightly channel
|
||||
/// points it at its own private profile, so a nightly control server can never write the stable
|
||||
/// app's token (and two channels can never authenticate each other).
|
||||
static TOKEN_ROOT: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
|
||||
|
||||
/// Choose the token folder for this process. Only a desktop app that owns its data root calls
|
||||
/// this; a client (`gridcraft-cli`, the MCP bridge) keeps reading the app's own folder.
|
||||
pub fn set_token_root(dir: PathBuf) -> Result<(), String> {
|
||||
if !dir.is_absolute() {
|
||||
return Err("the control token folder must be absolute".into());
|
||||
}
|
||||
TOKEN_ROOT.set(dir).map_err(|_| "the control token folder was already selected".to_string())
|
||||
}
|
||||
|
||||
/// The folder tokens go in: [`set_token_root`]'s when an app chose one, else the user's own.
|
||||
pub fn token_root() -> Option<PathBuf> {
|
||||
TOKEN_ROOT.get().cloned().or_else(default_token_root)
|
||||
}
|
||||
|
||||
fn default_token_root() -> Option<PathBuf> {
|
||||
let dir = if cfg!(windows) {
|
||||
PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft")
|
||||
} else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) {
|
||||
PathBuf::from(run).join("gridcraft")
|
||||
} else {
|
||||
PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft")
|
||||
};
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
/// Where the app writes the token it made for `port`, and where clients look for it: a folder
|
||||
/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows
|
||||
/// `%USERPROFILE%\.gridcraft`), file `control-<port>.token`. `None` when no such folder is known.
|
||||
pub fn token_path(port: u16) -> Option<PathBuf> {
|
||||
Some(token_root()?.join(format!("control-{port}.token")))
|
||||
}
|
||||
|
||||
/// The port of a control address (`127.0.0.1:7979` → 7979).
|
||||
fn port_of(addr: &str) -> Option<u16> {
|
||||
addr.rsplit(':').next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The token a client uses for `addr`: [`TOKEN_ENV`] if set, else the file the app wrote.
|
||||
pub fn client_token(addr: &str) -> Result<String, String> {
|
||||
if let Ok(t) = std::env::var(TOKEN_ENV)
|
||||
&& !t.trim().is_empty()
|
||||
{
|
||||
return Ok(t.trim().to_string());
|
||||
}
|
||||
let path = port_of(addr).and_then(token_path).ok_or_else(|| format!("no control token: set {TOKEN_ENV}"))?;
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(t) if !t.trim().is_empty() => Ok(t.trim().to_string()),
|
||||
_ => Err(format!("no control token: set {TOKEN_ENV}, or start the app on this machine and user (it writes {})", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `token` to [`token_path`] for the app: the folder is made private (mode 0700 on Unix),
|
||||
/// an older file is replaced, and the new one is created readable by the user only (mode 0600).
|
||||
/// Returns the path.
|
||||
pub fn write_token_file(port: u16, token: &str) -> std::io::Result<PathBuf> {
|
||||
use std::io::Write;
|
||||
let path = token_path(port).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no user folder for the control token"))?;
|
||||
let dir = path.parent().ok_or_else(|| std::io::Error::other("token path has no folder"))?;
|
||||
std::fs::create_dir_all(dir)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
// Only our own folder: leave a shared one (`$XDG_RUNTIME_DIR` itself) as it is.
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
// Replace rather than open: a leftover file may have looser permissions, or be a link.
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let mut f = opts.open(&path)?;
|
||||
f.write_all(token.as_bytes())?;
|
||||
f.write_all(b"\n")?;
|
||||
Ok(path)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Synthetic end-to-end regressions for confined MCP. Fixtures are retained for inspection.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use crate::{Backend, Headless, Server};
|
||||
use gridcraft_engine::{Session, file_access::AutomationRoots};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn fixture(label: &str) -> PathBuf {
|
||||
#[allow(clippy::disallowed_methods)] // Native-only filesystem fixture; retain every run.
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let base = std::env::temp_dir().join(format!("gridcraft-confined-{label}-{}-{stamp}", std::process::id()));
|
||||
for sub in ["allowed", "allowed2", "outside"] {
|
||||
std::fs::create_dir_all(base.join(sub)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("allowed/in.csv"), "inside,7\n").unwrap();
|
||||
std::fs::write(base.join("outside/private.csv"), "outside,91\n").unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn confined(base: &Path, write: bool) -> Headless {
|
||||
let read = base.join("allowed");
|
||||
let roots = AutomationRoots::new(Some(&read), write.then_some(read.as_path())).unwrap();
|
||||
Headless::new().with_automation_roots(roots)
|
||||
}
|
||||
|
||||
fn execute(b: &mut Headless, command: &str, params: Value) -> Result<Value, String> {
|
||||
b.call("engine.execute", json!({"command":command,"params":params}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_confinement_import_and_generic_commands_reject_existing_outside_files() {
|
||||
let base = fixture("reads");
|
||||
let mut b = confined(&base, true);
|
||||
execute(&mut b, "file.open", json!({"path":base.join("allowed/in.csv")})).unwrap();
|
||||
let before = b.call("sheet.read", json!({"range":"A1:B1"})).unwrap();
|
||||
for command in ["file.open", "data.fromTextCsv", "data.getData", "insert.picture"] {
|
||||
let err = execute(&mut b, command, json!({"path":base.join("outside/private.csv"),"placement":"overCells"})).unwrap_err();
|
||||
assert!(err.contains("outside the read root"), "{command}: {err}");
|
||||
assert_eq!(b.call("sheet.read", json!({"range":"A1:B1"})).unwrap(), before);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_confinement_mcp_protocol_rejects_traversal_and_prefix_siblings() {
|
||||
let base = fixture("rpc");
|
||||
std::fs::write(base.join("allowed2/private.csv"), "sibling,91\n").unwrap();
|
||||
let mut s = Server::new(Box::new(confined(&base, true)));
|
||||
for path in [base.join("outside/private.csv"), base.join("allowed/../outside/private.csv"), base.join("allowed2/private.csv")] {
|
||||
let result =
|
||||
s.handle(json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"open_workbook","arguments":{"path":path}}})).unwrap();
|
||||
assert_eq!(result["result"]["isError"], true, "{result}");
|
||||
assert!(result.to_string().contains("outside the read root"), "{result}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_confinement_all_exports_and_implicit_save_are_checked() {
|
||||
let base = fixture("writes");
|
||||
let mut b = confined(&base, true);
|
||||
execute(&mut b, "cell.set", json!({"cell":"A1","input":"7"})).unwrap();
|
||||
for (command, extension) in [
|
||||
("file.save", "xlsx"),
|
||||
("file.saveAs", "xlsx"),
|
||||
("file.exportCsv", "csv"),
|
||||
("file.exportHtml", "html"),
|
||||
("file.exportPdf", "pdf"),
|
||||
("file.print", "pdf"),
|
||||
] {
|
||||
let path = base.join("outside").join(format!("{command}.{extension}"));
|
||||
let err = execute(&mut b, command, json!({"path":path})).unwrap_err();
|
||||
assert!(err.contains("outside the write root"), "{command}: {err}");
|
||||
assert!(!path.exists());
|
||||
assert!(!PathBuf::from(format!("{}.sctmp", path.display())).exists());
|
||||
}
|
||||
let destination = base.join("allowed/new.xlsx");
|
||||
execute(&mut b, "file.save", json!({"path":destination})).unwrap();
|
||||
assert!(destination.is_file());
|
||||
let mut session = Session::new();
|
||||
session.execute_headless("file.open", json!({"path":base.join("outside/private.csv")})).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("allowed")), Some(&base.join("allowed"))).unwrap();
|
||||
let mut outside = Headless::with_session(session).with_automation_roots(roots);
|
||||
let err = execute(&mut outside, "file.save", json!({})).unwrap_err();
|
||||
assert!(err.contains("outside the write root"), "{err}");
|
||||
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_confinement_read_only_and_in_memory_export() {
|
||||
let base = fixture("read-only");
|
||||
let mut b = confined(&base, false);
|
||||
execute(&mut b, "file.open", json!({"path":base.join("allowed/in.csv")})).unwrap();
|
||||
let err = execute(&mut b, "file.save", json!({"path":base.join("allowed/new.xlsx")})).unwrap_err();
|
||||
assert!(err.contains("write authority is absent"), "{err}");
|
||||
let bytes = execute(&mut b, "file.saveBytes", json!({"format":"xlsx"})).unwrap();
|
||||
assert!(bytes["base64"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_confinement_symlinks_and_temporary_save_paths_are_checked() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let base = fixture("links");
|
||||
symlink(base.join("outside/private.csv"), base.join("allowed/link.csv")).unwrap();
|
||||
symlink(base.join("outside"), base.join("allowed/away")).unwrap();
|
||||
symlink(base.join("outside/missing.xlsx"), base.join("allowed/dangling.xlsx")).unwrap();
|
||||
symlink(base.join("outside/private.csv"), base.join("allowed/new.xlsx.sctmp")).unwrap();
|
||||
let mut b = confined(&base, true);
|
||||
assert!(execute(&mut b, "file.open", json!({"path":base.join("allowed/link.csv")})).unwrap_err().contains("outside the read root"));
|
||||
for name in ["away/new.xlsx", "dangling.xlsx"] {
|
||||
let err = execute(&mut b, "file.save", json!({"path":base.join("allowed").join(name)})).unwrap_err();
|
||||
assert!(err.contains("outside the write root") || err.contains("link that leads nowhere"), "{err}");
|
||||
}
|
||||
execute(&mut b, "file.save", json!({"path":base.join("allowed/new.xlsx")})).unwrap();
|
||||
assert!(std::fs::symlink_metadata(base.join("allowed/new.xlsx.sctmp")).unwrap().file_type().is_symlink());
|
||||
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_confinement_existing_temporary_file_survives_successful_save() {
|
||||
let base = fixture("existing-temporary");
|
||||
let destination = base.join("allowed/new.xlsx");
|
||||
let temporary = base.join("allowed/new.xlsx.sctmp");
|
||||
std::fs::write(&temporary, b"existing temporary content").unwrap();
|
||||
let mut b = confined(&base, true);
|
||||
execute(&mut b, "file.save", json!({"path":destination})).unwrap();
|
||||
assert_eq!(std::fs::read(&temporary).unwrap(), b"existing temporary content");
|
||||
assert!(destination.is_file());
|
||||
execute(&mut b, "file.open", json!({"path":destination})).unwrap();
|
||||
}
|
||||
|
||||
/// The operator may keep inputs readable while allowing writes only to a nested output folder.
|
||||
#[test]
|
||||
fn folder_confinement_nested_write_root_preserves_inputs() {
|
||||
let base = fixture("nested");
|
||||
let read = base.join("allowed");
|
||||
let write = read.join("_artcraft");
|
||||
std::fs::create_dir_all(&write).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&read), Some(&write)).unwrap();
|
||||
let mut b = Headless::new().with_automation_roots(roots);
|
||||
let input = read.join("in.csv");
|
||||
execute(&mut b, "file.open", json!({"path":input})).unwrap();
|
||||
execute(&mut b, "cell.set", json!({"cell":"B1","input":"42"})).unwrap();
|
||||
// Implicit Save still points at the input, outside the narrower write root.
|
||||
assert!(execute(&mut b, "file.save", json!({})).unwrap_err().contains("outside the write root"));
|
||||
for path in [read.join("new.xlsx"), read.join("_artcraft2/new.xlsx"), write.join("../new.xlsx"), base.join("outside/new.xlsx")] {
|
||||
assert!(execute(&mut b, "file.saveAs", json!({"path":path})).unwrap_err().contains("outside the write root"));
|
||||
assert!(!path.exists());
|
||||
}
|
||||
let destination = write.join("result.xlsx");
|
||||
execute(&mut b, "file.saveAs", json!({"path":destination})).unwrap();
|
||||
execute(&mut b, "file.open", json!({"path":destination})).unwrap();
|
||||
let sheet = b.call("sheet.read", json!({"range":"A1:B1"})).unwrap();
|
||||
assert!(sheet.to_string().contains("42"), "{sheet}");
|
||||
execute(&mut b, "file.exportCsv", json!({"path":write.join("result.csv")})).unwrap();
|
||||
assert!(std::fs::read_to_string(write.join("result.csv")).unwrap().contains("42"));
|
||||
assert!(execute(&mut b, "file.open", json!({"path":base.join("outside/private.csv")})).unwrap_err().contains("outside the read root"));
|
||||
assert_eq!(std::fs::read_to_string(input).unwrap(), "inside,7\n");
|
||||
assert_eq!(std::fs::read_to_string(base.join("outside/private.csv")).unwrap(), "outside,91\n");
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
//! An in-process engine session that answers the engine-level control-channel methods itself.
|
||||
|
||||
use gridcraft_engine::{Session, Target};
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_engine::{
|
||||
Session, Target,
|
||||
file_access::{self, AutomationRoots},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::backend::Backend;
|
||||
|
||||
/// Error for methods that need a window.
|
||||
pub(crate) const NO_UI: &str = "no UI in headless mode: start the app with `gridcraft --control 7979` and run the MCP server \
|
||||
with `gridcraft-cli mcp --connect 7979`";
|
||||
pub(crate) const NO_UI: &str = "no window in this session: open GridCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `gridcraft-cli mcp` without --headless";
|
||||
|
||||
/// Headless backend: a [`Session`] with one blank workbook to start with.
|
||||
pub struct Headless {
|
||||
pub session: Session,
|
||||
roots: Option<Arc<AutomationRoots>>,
|
||||
}
|
||||
|
||||
impl Default for Headless {
|
||||
@@ -25,17 +30,23 @@ impl Headless {
|
||||
pub fn new() -> Self {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
Self { session }
|
||||
Self { session, roots: None }
|
||||
}
|
||||
|
||||
/// A session wrapping an existing one (e.g. with a file already open).
|
||||
pub fn with_session(session: Session) -> Self {
|
||||
Self { session }
|
||||
Self { session, roots: None }
|
||||
}
|
||||
|
||||
/// Apply read/write roots to every command, including generic and nested dispatch.
|
||||
pub fn with_automation_roots(mut self, roots: Option<Arc<AutomationRoots>>) -> Self {
|
||||
self.roots = roots;
|
||||
self
|
||||
}
|
||||
|
||||
fn execute(&mut self, target: Target, id: &str, params: Value) -> Result<Value, String> {
|
||||
// Programmatic calls never open dialogs; anything a command queued for a UI is dropped.
|
||||
self.session.execute_headless_in(target, id, params).map_err(|e| e.to_string())
|
||||
file_access::confine(self.roots.as_ref(), || self.session.execute_headless_in(target, id, params)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn commands(&self, params: &Value) -> Value {
|
||||
@@ -62,6 +73,7 @@ impl Backend for Headless {
|
||||
let params = if params.is_null() { json!({}) } else { params };
|
||||
match method {
|
||||
"ping" => Ok(json!("pong")),
|
||||
crate::agents::FOLDERS_METHOD => Ok(crate::agents::folders_answer(self.roots.as_deref())),
|
||||
"engine.execute" => {
|
||||
let id = params.get("command").and_then(Value::as_str).ok_or("engine.execute: missing `command`")?.to_string();
|
||||
let p = params.get("params").cloned().unwrap_or_else(|| json!({}));
|
||||
@@ -99,6 +111,13 @@ impl Backend for Headless {
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"headless (in-process engine, no window)".to_string()
|
||||
match &self.roots {
|
||||
None => "headless (in-process engine, no window; unrestricted filesystem)".to_string(),
|
||||
Some(roots) => format!(
|
||||
"headless (read root: {}; write root: {})",
|
||||
roots.read_root().map(|p| p.display().to_string()).unwrap_or_else(|| "none".into()),
|
||||
roots.write_root().map(|p| p.display().to_string()).unwrap_or_else(|| "none".into())
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -4,9 +4,11 @@
|
||||
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes GridCraft as MCP tools and
|
||||
//! resources and forwards everything to a [`Backend`]:
|
||||
//!
|
||||
//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel
|
||||
//! (`gridcraft --control 7979`): one `{"id","method","params"}` line in, one
|
||||
//! `{"id","ok","result"|"error"}` line out (see `docs/control-protocol.md`).
|
||||
//! - [`agents::Window`] talks to the open desktop app through its loopback JSON-lines control
|
||||
//! channel (the framework's server, found through the agent connection file, or a
|
||||
//! `gridcraft --control 7979` app): one `{"id","method","params"}` line in, one
|
||||
//! `{"id","ok","result"|"error"}` line out, after the challenge handshake (see
|
||||
//! `docs/control-protocol.md`).
|
||||
//! - [`Headless`] hosts an in-process [`gridcraft_engine::Session`] and implements the
|
||||
//! engine-level control-channel methods itself, so agents can build workbooks without a window.
|
||||
//!
|
||||
@@ -14,24 +16,22 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod agents;
|
||||
mod backend;
|
||||
pub mod control_auth;
|
||||
mod headless;
|
||||
mod server;
|
||||
mod tools;
|
||||
|
||||
pub use backend::{Backend, Remote};
|
||||
pub use backend::Backend;
|
||||
pub use headless::Headless;
|
||||
pub use server::{COMMANDS_URI, FUNCTIONS_URI, PROTOCOL_VERSION, SUPPORTED_VERSIONS, Server, WORKBOOK_URI};
|
||||
pub use tools::{ToolResult, call_tool, tool_definitions};
|
||||
|
||||
/// Default control-channel port of the desktop app.
|
||||
pub const DEFAULT_PORT: u16 = 7979;
|
||||
|
||||
/// `"7979"` → `"127.0.0.1:7979"`; `"host:port"` is kept as is.
|
||||
pub fn control_addr(s: &str) -> String {
|
||||
if s.parse::<u16>().is_ok() { format!("127.0.0.1:{s}") } else { s.to_string() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod folder_confinement_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod agents_tests;
|
||||
|
||||
+2
-106
@@ -1,10 +1,8 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, control_addr, tool_definitions};
|
||||
use crate::{Headless, PROTOCOL_VERSION, Server, tool_definitions};
|
||||
|
||||
fn server() -> Server {
|
||||
Server::new(Box::new(Headless::new()))
|
||||
@@ -159,7 +157,7 @@ fn malformed_input_never_panics() {
|
||||
fails(&mut s, "sort_range", json!({"keys": []}));
|
||||
fails(&mut s, "open_workbook", json!({"path": "/definitely/not/here.xlsx"}));
|
||||
fails(&mut s, "save_workbook", json!({}));
|
||||
assert!(fails(&mut s, "screenshot", json!({"path": "/tmp/x.png"})).contains("no UI in headless mode"));
|
||||
assert!(fails(&mut s, "screenshot", json!({"path": "/tmp/x.png"})).contains("no window in this session"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -436,108 +434,6 @@ fn cell_set_without_input_is_error() {
|
||||
assert_eq!(ok(&mut s, "get_cell", json!({"cell": "B2"}))["text"], "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_backend_over_tcp() {
|
||||
// A fake app: answers engine.execute by running a headless session; closes after the first
|
||||
// request to exercise the reconnect path.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let handle = std::thread::spawn(move || {
|
||||
let mut h = Headless::new();
|
||||
for (i, stream) in listener.incoming().take(2).enumerate() {
|
||||
let stream = stream.unwrap();
|
||||
let mut w = stream.try_clone().unwrap();
|
||||
let mut r = BufReader::new(stream);
|
||||
// Every connection starts with the token, as the app requires.
|
||||
let mut first = String::new();
|
||||
r.read_line(&mut first).unwrap();
|
||||
let hello = crate::control_auth::check_first_line(&first, "secret-token-0123456789").unwrap();
|
||||
w.write_all(format!("{hello}\n").as_bytes()).unwrap();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if r.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
break;
|
||||
}
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let reply = match h.call(req["method"].as_str().unwrap(), req["params"].clone()) {
|
||||
Ok(v) => json!({"id": req["id"], "ok": true, "result": v}),
|
||||
Err(e) => json!({"id": req["id"], "ok": false, "error": e}),
|
||||
};
|
||||
w.write_all(format!("{reply}\n").as_bytes()).unwrap();
|
||||
if i == 0 {
|
||||
break; // drop the first connection
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let addr = control_addr(&port.to_string());
|
||||
assert_eq!(addr, format!("127.0.0.1:{port}"));
|
||||
let mut s = Server::new(Box::new(Remote::connect_with_token(&addr, "secret-token-0123456789".into()).unwrap()));
|
||||
assert_eq!(ok(&mut s, "evaluate_formula", json!({"formula": "=1+1"}))["result"], json!(2.0));
|
||||
// Second call reconnects transparently.
|
||||
ok(&mut s, "set_cell", json!({"cell": "A1", "input": "7"}));
|
||||
assert_eq!(ok(&mut s, "get_cell", json!({"cell": "A1"}))["value"], json!(7.0));
|
||||
let msg = fails(&mut s, "execute_command", json!({"command": "nope"}));
|
||||
assert!(msg.contains("unknown command"), "{msg}");
|
||||
drop(s);
|
||||
handle.join().unwrap();
|
||||
assert!(Remote::connect_with_token("127.0.0.1:1", "x".into()).is_err());
|
||||
// A network address is refused before anything, the token included, is sent.
|
||||
let err = Remote::connect_with_token("192.0.2.1:7979", "x".into()).err().unwrap();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_auth_handshake_and_compare() {
|
||||
use crate::control_auth::{auth_line, check_first_line, constant_time_eq, hex};
|
||||
let token = "0123456789abcdef0123456789abcdef";
|
||||
let ok = check_first_line(&auth_line(7, token), token).unwrap();
|
||||
assert_eq!((ok["id"].clone(), ok["ok"].clone()), (json!(7), json!(true)));
|
||||
// Wrong or missing token, another method, and non-JSON are all refused the same way.
|
||||
let wrong = check_first_line(&auth_line(1, "0123456789abcdef0123456789abcdee"), token).unwrap_err();
|
||||
for bad in [
|
||||
auth_line(1, ""),
|
||||
r#"{"id":1,"method":"auth","params":{}}"#.into(),
|
||||
r#"{"id":1,"method":"app.save","params":{"path":"/tmp/x","token":"0123456789abcdef0123456789abcdef"}}"#.into(),
|
||||
"POST / HTTP/1.1".into(),
|
||||
String::new(),
|
||||
] {
|
||||
assert_eq!(check_first_line(&bad, token).unwrap_err(), wrong, "{bad}");
|
||||
}
|
||||
// An empty configured token never matches an empty given one.
|
||||
assert!(check_first_line(&auth_line(1, ""), "").is_err());
|
||||
assert!(constant_time_eq(b"abc", b"abc"));
|
||||
assert!(!constant_time_eq(b"abc", b"abd"));
|
||||
assert!(!constant_time_eq(b"abc", b"abcd"));
|
||||
assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_token_root_is_refused_before_it_is_selected() {
|
||||
// The app may point the tokens at its own private profile, but only at an absolute folder: a
|
||||
// relative one would resolve against whatever directory the process was started in. (A
|
||||
// successful selection is process-wide, so this test only exercises the refusal.)
|
||||
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("relative/tokens")).is_err());
|
||||
assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn control_token_file_is_private() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
// Unique port per run so parallel tests don't share a file; the folder is the real one.
|
||||
let port = 40_000 + (std::process::id() % 20_000) as u16;
|
||||
let path = crate::control_auth::write_token_file(port, "tok-0123456789abcdef").unwrap();
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(std::fs::metadata(path.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
// A looser leftover is replaced, not reused.
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
|
||||
crate::control_auth::write_token_file(port, "tok-1123456789abcdef").unwrap();
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "tok-1123456789abcdef");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_commands_without_a_file_fail() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -107,7 +107,8 @@ const BORDER_PRESETS: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Tools that don't act on one workbook, so they take no `window`/`doc` target.
|
||||
const UNTARGETED: &[&str] = &["list_commands", "list_functions", "list_windows", "new_workbook", "open_workbook", "screenshot"];
|
||||
const UNTARGETED: &[&str] =
|
||||
&["list_commands", "list_functions", "list_windows", "new_workbook", "open_workbook", "screenshot", craft_control::agents::FOLDERS_TOOL];
|
||||
|
||||
/// All tools, in `tools/list` order. Tools that act on a workbook take an optional `window` or
|
||||
/// `doc` id (from list_windows) and default to the active window.
|
||||
@@ -388,7 +389,7 @@ fn base_tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"screenshot",
|
||||
"Screenshot",
|
||||
"Save a PNG screenshot of the GridCraft window to `path`. Desktop app only (`gridcraft-cli mcp --connect 7979`).",
|
||||
"Save a PNG screenshot of the GridCraft window to `path` (inside the agent folders: see agent_folders). Needs the open window: AI agents on in ArtCraft Launcher › Settings › AI agents.",
|
||||
obj(json!({"path": string("Output PNG path")}), &["path"]),
|
||||
true,
|
||||
),
|
||||
@@ -402,6 +403,7 @@ fn base_tool_definitions() -> Vec<Value> {
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(craft_control::agents::FOLDERS_TOOL, "Agent folders", craft_control::agents::FOLDERS_TOOL_DESCRIPTION, obj(json!({}), &[]), true),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -663,6 +665,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<Value, String>
|
||||
"redo" => exec(b, "edit.redo", pick(a, &["steps"])),
|
||||
"screenshot" => screenshot(b, a),
|
||||
"list_functions" => exec(b, "formulas.functions", pick(a, &["search", "category"])),
|
||||
craft_control::agents::FOLDERS_TOOL => b.call(crate::agents::FOLDERS_METHOD, json!({})),
|
||||
other => Err(format!("unknown tool `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,10 @@ pub struct TableColumn {
|
||||
/// `uniqueName`: the name XML maps know the column by.
|
||||
#[serde(default)]
|
||||
pub unique_name: Option<String>,
|
||||
/// `queryTableFieldId`: the field of the table's query table this column shows. It moves with
|
||||
/// the column; inserted columns have none.
|
||||
#[serde(default)]
|
||||
pub query_field_id: Option<u32>,
|
||||
/// Binding to an element of an XML map. It moves with the column and goes when the column is
|
||||
/// deleted; inserted columns are unmapped.
|
||||
#[serde(default)]
|
||||
@@ -102,6 +106,10 @@ pub struct Table {
|
||||
/// The connection (`xl/connections.xml`) an XML table is bound through.
|
||||
#[serde(default)]
|
||||
pub connection_id: Option<u32>,
|
||||
/// The XML of the table's query table part (`xl/queryTables/…`), kept as read so the table
|
||||
/// stays attached to its data connection. Never refreshed.
|
||||
#[serde(default)]
|
||||
pub query_table: Option<String>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
@@ -513,6 +521,7 @@ pub enum ChartKind {
|
||||
Bubble,
|
||||
Radar,
|
||||
Histogram,
|
||||
Pareto,
|
||||
Waterfall,
|
||||
Funnel,
|
||||
Treemap,
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and
|
||||
/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and
|
||||
/// envelopes are the JIS ones too.
|
||||
pub const PAPERS: [(&str, f32, f32); 24] = [
|
||||
pub const PAPERS: [(&str, f32, f32); 27] = [
|
||||
("Letter", 612.0, 792.0),
|
||||
("Legal", 612.0, 1008.0),
|
||||
("A4", 595.28, 841.89),
|
||||
("A3", 841.89, 1190.55),
|
||||
("A2", 1190.55, 1683.78),
|
||||
("A1", 1683.78, 2383.94),
|
||||
("A0", 2383.94, 3370.39),
|
||||
("A5", 419.53, 595.28),
|
||||
("A6", 297.64, 419.53),
|
||||
("Tabloid", 792.0, 1224.0),
|
||||
|
||||
@@ -131,6 +131,10 @@ pub struct Sheet {
|
||||
#[serde(default = "yes")]
|
||||
pub summary_right: bool,
|
||||
pub right_to_left: bool,
|
||||
/// Excel's Show page breaks (Options › Advanced, "Display options for this worksheet"): dashed
|
||||
/// page boundaries in Normal view. Page Break Preview turns it on; not saved with the file.
|
||||
#[serde(skip)]
|
||||
pub show_page_breaks: bool,
|
||||
pub zoom: u16,
|
||||
pub cond_formats: Vec<CondFormat>,
|
||||
pub validations: Vec<Validation>,
|
||||
@@ -211,6 +215,7 @@ impl Sheet {
|
||||
show_formulas: false,
|
||||
show_zeros: true,
|
||||
right_to_left: false,
|
||||
show_page_breaks: false,
|
||||
zoom: 100,
|
||||
cond_formats: vec![],
|
||||
validations: vec![],
|
||||
|
||||
@@ -46,6 +46,10 @@ gridcraft-xlsx = { workspace = true, features = ["test-support"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# Agents in the open window (`agents`): the ArtCraft Launcher's switch, the link host with its
|
||||
# control server, and the Agents page of File › Options.
|
||||
craft-automation = { workspace = true, features = ["agents", "ui"] }
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
# The desktop's preferred language for the first-run interface language.
|
||||
sys-locale = { workspace = true }
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Agents in the open window: the ArtCraft Launcher's switch lets agents into this window.
|
||||
//!
|
||||
//! The switch, the control server, its token and the connection file `gridcraft-cli mcp` finds
|
||||
//! the window by are the framework's (`craft_automation::agents::AgentSwitch` and `AgentLink`).
|
||||
//! GridCraft supplies its agent settings (saved by the app, `options.agents`), runs the requests
|
||||
//! that arrive with its own control methods (`control::poll`), and confines their file commands to
|
||||
//! the agent folders: the folders set on the Agents page of File › Options, or
|
||||
//! `Documents/ArtCraft/Agents/GridCraft` for an empty one.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
|
||||
use craft_automation::control::{ControlChannel, ControlRequest};
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use gridcraft_engine::file_access::AutomationRoots;
|
||||
|
||||
/// The control method `gridcraft-cli mcp`'s `agent_folders` tool calls.
|
||||
pub const FOLDERS_METHOD: &str = "agent.folders";
|
||||
|
||||
/// The `agent_folders` answer for the folders agent requests may use now: `null` for a direction
|
||||
/// they may not use (the folder couldn't be opened, or the link doesn't run).
|
||||
pub fn folders_answer(roots: &AutomationRoots) -> serde_json::Value {
|
||||
let mut folders = craft_control::agents::AgentFolders::default();
|
||||
folders.read = roots.read_root().map(std::path::Path::to_path_buf);
|
||||
folders.write = roots.write_root().map(std::path::Path::to_path_buf);
|
||||
craft_control::agents::folders_answer(&folders)
|
||||
}
|
||||
|
||||
/// Saves the agent settings where `gridcraft-cli mcp` reads them; `Err` says why it couldn't.
|
||||
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
|
||||
|
||||
/// The agents link of the open window.
|
||||
pub struct Agents {
|
||||
link: AgentLink,
|
||||
switch: AgentSwitch,
|
||||
settings: AgentSettings,
|
||||
save: SaveFn,
|
||||
channel: Option<ControlChannel>,
|
||||
/// What agent requests may open and save: nothing until the link runs.
|
||||
roots: Arc<AutomationRoots>,
|
||||
default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Agents {
|
||||
/// The link for the window, keeping its token and connection file in `settings_dir`, naming
|
||||
/// `app` (the version string) in the connection file, following `switch` with the saved
|
||||
/// `settings`; `save` stores the settings when the Agents page changes them.
|
||||
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self {
|
||||
Self {
|
||||
link: AgentLink::new(settings_dir, app),
|
||||
switch,
|
||||
settings,
|
||||
save,
|
||||
channel: None,
|
||||
roots: AutomationRoots::none(),
|
||||
default_folder: craft_control::agents::default_folder("GridCraft"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The window was started with `--control`: `server` (the framework's control server, bound to
|
||||
/// that port) serves the whole run, the switch and the settings change nothing, and the Agents
|
||||
/// page says the launch options manage it. Its requests are confined like an agent's: to
|
||||
/// `folders` when the launch named them (`--automation-read-root`, `--automation-write-root`),
|
||||
/// otherwise to the agent folders.
|
||||
pub fn launched_with_control(
|
||||
mut self,
|
||||
server: craft_automation::server::Listening,
|
||||
requests: std::sync::mpsc::Receiver<ControlRequest>,
|
||||
folders: Option<craft_control::agents::AgentFolders>,
|
||||
) -> Self {
|
||||
self.link = AgentLink::from_launch(server);
|
||||
self.channel = Some(ControlChannel::new(requests));
|
||||
let folders = folders.unwrap_or_else(|| self.settings.folders_with(self.default_folder.as_deref()));
|
||||
self.open_roots(&folders);
|
||||
self
|
||||
}
|
||||
|
||||
/// Opens `folders` as the roots agent requests may use; a folder that can't be opened leaves
|
||||
/// no file access and is named on the Agents page.
|
||||
fn open_roots(&mut self, folders: &craft_control::agents::AgentFolders) {
|
||||
self.roots = match AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref()) {
|
||||
Ok(roots) => roots.unwrap_or_else(AutomationRoots::none),
|
||||
Err(e) => {
|
||||
self.link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
|
||||
AutomationRoots::none()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// `default` replaces the default agent folder (tests).
|
||||
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
|
||||
self.default_folder = default;
|
||||
self
|
||||
}
|
||||
|
||||
/// The saved agent settings.
|
||||
pub fn settings(&self) -> &AgentSettings {
|
||||
&self.settings
|
||||
}
|
||||
|
||||
/// Where the link stands, for the Agents page and `ui.inspect`.
|
||||
pub fn status(&self) -> &AgentLinkStatus {
|
||||
self.link.status()
|
||||
}
|
||||
|
||||
/// The suite's `AI-MCP` flag: the launcher's switch decides, and the Agents page shows.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.switch.mcp_flag()
|
||||
}
|
||||
|
||||
/// Whether the launcher's switch lets agents use GridCraft now.
|
||||
pub fn allowed(&self) -> bool {
|
||||
// GridCraft had no agent consent of its own before the switch.
|
||||
self.switch.allows(false)
|
||||
}
|
||||
|
||||
/// Saves `settings` and applies them on the next [`Self::sync`].
|
||||
pub fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
|
||||
(self.save)(&settings)?;
|
||||
self.settings = settings;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Brings the link in line with the switch and the settings: the control server starts, moves
|
||||
/// or stops, and the agent folders are opened again when they changed.
|
||||
pub fn sync(&mut self, host: &WindowHost) {
|
||||
let allowed = self.allowed();
|
||||
let update = self.link.sync(allowed.then_some(&self.settings), host);
|
||||
if update.stopped {
|
||||
self.channel = None;
|
||||
}
|
||||
if let Some(requests) = update.requests {
|
||||
self.channel = Some(ControlChannel::new(requests));
|
||||
}
|
||||
if !update.changed {
|
||||
return;
|
||||
}
|
||||
if self.link.status().port.is_none() {
|
||||
self.roots = AutomationRoots::none();
|
||||
return;
|
||||
}
|
||||
let folders = self.settings.folders_with(self.default_folder.as_deref());
|
||||
self.open_roots(&folders);
|
||||
}
|
||||
|
||||
/// The next agent request to run this frame, with the folders it may use. Requests whose
|
||||
/// client stopped waiting are answered and skipped.
|
||||
pub fn next_request(&mut self) -> Option<(ControlRequest, Arc<AutomationRoots>)> {
|
||||
let request = self.channel.as_mut()?.next_request()?;
|
||||
Some((request, self.roots.clone()))
|
||||
}
|
||||
|
||||
/// The folders agent requests may open from and save to now.
|
||||
pub fn roots(&self) -> &Arc<AutomationRoots> {
|
||||
&self.roots
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::SheetApp {
|
||||
/// Runs one of the app's passes (`logic`, a window's `ui`): while input an agent queued is
|
||||
/// still being applied (`SheetApp::agent_input`), confined to that agent's folders, so a key
|
||||
/// or click it sent can't save outside them or change the agent settings.
|
||||
pub fn with_agent_input<T>(&mut self, pass: impl FnOnce(&mut Self) -> T) -> T {
|
||||
let roots = self.agent_input.clone();
|
||||
gridcraft_engine::file_access::confine(roots.as_ref(), || pass(self))
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,18 @@ impl SheetApp {
|
||||
synthetic_pending: false,
|
||||
synthetic_injected_at_pass: None,
|
||||
control_rx: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agent_input: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agent_changed: Default::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agent_seen: Vec::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agent_draft: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agent_seen_draft: None,
|
||||
grid: grid::GridState {
|
||||
last_border: "bottom".into(),
|
||||
last_fill: "#FFFF00".into(),
|
||||
@@ -141,6 +153,8 @@ impl SheetApp {
|
||||
// issues the capture command (after every widget, so a command cannot be missed).
|
||||
control::drain_screenshots(self, ctx);
|
||||
control::poll(self, ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
control::poll_agents(self, ctx);
|
||||
// Printing feedback is polled once per frame, here, so hidden windows and logic-only
|
||||
// frames still see worker completion. `ui` and the desktop app no longer poll it.
|
||||
self.poll_printing(ctx);
|
||||
|
||||
@@ -273,6 +273,7 @@ impl SheetApp {
|
||||
self.ui.autocomplete = p.get("on").and_then(Json::as_bool).unwrap_or(!self.ui.autocomplete);
|
||||
Ok(json!({"on": self.ui.autocomplete}))
|
||||
}
|
||||
"options.agents" => self.agents_option(p),
|
||||
"options.highlightActiveRow" => {
|
||||
self.ui.highlight_active_row = p.get("on").and_then(Json::as_bool).unwrap_or(!self.ui.highlight_active_row);
|
||||
Ok(json!({"on": self.ui.highlight_active_row}))
|
||||
@@ -298,6 +299,8 @@ impl SheetApp {
|
||||
match i18n::Language::parse(code) {
|
||||
Some(l) => {
|
||||
self.ui.language = l;
|
||||
// Chart text is translated: cached primitives hold the old language.
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": l}))
|
||||
}
|
||||
None => Err(format!("unknown language {code:?} (use one of {})", i18n::Language::code_list(", "))),
|
||||
@@ -305,10 +308,12 @@ impl SheetApp {
|
||||
}
|
||||
"app.language.english" => {
|
||||
self.ui.language = i18n::Language::En;
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": i18n::Language::En}))
|
||||
}
|
||||
"app.language.japanese" => {
|
||||
self.ui.language = i18n::Language::Ja;
|
||||
self.chart_cache.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner).clear();
|
||||
Ok(json!({"language": i18n::Language::Ja}))
|
||||
}
|
||||
"ui.quickAnalysis" => crate::quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)),
|
||||
@@ -523,3 +528,39 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SheetApp {
|
||||
/// `options.agents`: the agent settings of File › Options, the agents link's status and the
|
||||
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves
|
||||
/// those settings first. Agents can't change them: their requests run confined to the agent
|
||||
/// folders, and widening those is the person's choice.
|
||||
fn agents_option(&mut self, p: &Json) -> Result<Json, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = p;
|
||||
Err("agents in the open window need the desktop app".into())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"];
|
||||
let Some(agents) = self.agents.as_mut() else {
|
||||
return Err("agents can't use this window: it has no settings folder, or it is a nightly".into());
|
||||
};
|
||||
if let Some(unknown) = p.as_object().and_then(|o| o.keys().find(|k| !KEYS.contains(&k.as_str()))) {
|
||||
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
|
||||
}
|
||||
if p.as_object().is_some_and(|o| !o.is_empty()) {
|
||||
if gridcraft_engine::file_access::current().is_some() {
|
||||
return Err("agents can't change the agent settings: the person sets them in File › Options".into());
|
||||
}
|
||||
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
|
||||
if let (Some(next), Some(given)) = (next.as_object_mut(), p.as_object()) {
|
||||
next.extend(given.clone());
|
||||
}
|
||||
let next = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?;
|
||||
agents.set(next)?;
|
||||
}
|
||||
Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +113,12 @@ impl SheetApp {
|
||||
/// forced hidden UI pass from saving the same change twice.
|
||||
pub(super) fn autosave(&mut self, ctx: &egui::Context) {
|
||||
let dirty_xlsx = self.session.active().is_some_and(|d| d.is_dirty() && d.path.as_deref().is_some_and(|p| p.ends_with(".xlsx")));
|
||||
// A workbook saved since an agent changed it is the person's again.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let session = &self.session;
|
||||
self.agent_changed.retain(|uid, _| session.documents().iter().any(|d| d.uid == *uid && d.is_dirty()));
|
||||
}
|
||||
if !(self.ui.autosave && dirty_xlsx) {
|
||||
self.end_autosave_hold();
|
||||
}
|
||||
@@ -134,6 +140,15 @@ impl SheetApp {
|
||||
}
|
||||
self.end_autosave_hold();
|
||||
self.store_view_state();
|
||||
// Changes an agent made are saved only inside its folders (an agent's edit to a workbook
|
||||
// the person opened elsewhere waits for the person's own Save).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let roots = self.session.active().and_then(|d| self.agent_changed.get(&d.uid).cloned());
|
||||
let session = &mut self.session;
|
||||
let _ = gridcraft_engine::file_access::confine(roots.as_ref(), || session.run("file.save", json!({})));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = self.session.run("file.save", json!({}));
|
||||
} else if self.ui.autosave && dirty_xlsx {
|
||||
// Keep checking even when no input arrives while the window is hidden.
|
||||
|
||||
@@ -31,6 +31,8 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
if ui.checkbox(&mut autosave, lang.tr("Save .xlsx workbooks automatically after every change")).changed() {
|
||||
app.toggle_autosave();
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents_options(app, ui, lang);
|
||||
let Some((calc, view)) = app.session.active().map(|d| (d.wb.calc.clone(), d.wb.view)) else { return };
|
||||
ui.add_space(18.0);
|
||||
// Excel's Advanced › Display options for this workbook: saved with the workbook (#3101).
|
||||
@@ -46,6 +48,12 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Display options for this worksheet");
|
||||
let mut page_breaks = app.session.active().and_then(|d| d.wb.active().map(|s| s.show_page_breaks)).unwrap_or(false);
|
||||
if ui.checkbox(&mut page_breaks, lang.tr("Show page breaks")).changed() {
|
||||
app.run_or_alert("view.showPageBreaks", json!({"on": page_breaks}));
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Formulas");
|
||||
ui.label(lang.tr("Workbook calculation"));
|
||||
calc_options(app, ui, lang, &calc);
|
||||
@@ -53,6 +61,34 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
dim(ui, lang.tr("Calculation settings are saved with the workbook."));
|
||||
}
|
||||
|
||||
/// The Agents section: the shared Agents page over the saved agent settings, with the suite's
|
||||
/// `AI-MCP` flag (the ArtCraft Launcher's switch decides; the page has no switch of its own).
|
||||
/// A change runs `options.agents`, which saves it where `gridcraft-cli mcp` reads it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
|
||||
use craft_automation::agents::AgentSettings;
|
||||
use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
const PAGE: &str = "integrations";
|
||||
let Some(agents) = app.agents.as_ref().filter(|a| a.mcp_flag()) else { return };
|
||||
let (settings, status) = (agents.settings().clone(), agents.status().clone());
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Agents");
|
||||
let mut draft = SettingsDraft::default();
|
||||
if draft.replace(&json!({ PAGE: &settings })).is_err() {
|
||||
return;
|
||||
}
|
||||
let out = AgentsPage::new(PAGE, &mut draft, &status).mcp_flag(true).show(ui);
|
||||
if !out.changed {
|
||||
return;
|
||||
}
|
||||
let Some(next) = draft.get::<AgentSettings>(PAGE).filter(|next| *next != settings) else { return };
|
||||
app.run_or_alert(
|
||||
"options.agents",
|
||||
json!({"controlPort": next.control_port, "readRoot": next.read_root, "writeRoot": next.write_root, "whenAppClosed": next.when_app_closed}),
|
||||
);
|
||||
}
|
||||
|
||||
/// The display theme and interface language controls of the General section.
|
||||
fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
|
||||
egui::Grid::new("backstage_options_general").num_columns(2).spacing(vec2(18.0, 10.0)).show(ui, |ui| {
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
|
||||
use egui::epaint::{PathShape, PathStroke};
|
||||
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
|
||||
use gridcraft_chart::{HAlign, Prim, VAlign};
|
||||
use gridcraft_chart::{ChartLabels, HAlign, Prim, VAlign};
|
||||
use gridcraft_engine::model::{Anchor, ObjKind, ObjRef, ShapeKind, Sheet, Workbook};
|
||||
|
||||
use crate::SheetApp;
|
||||
@@ -39,7 +39,8 @@ pub fn paint_chart(p: &Painter, rect: Rect, wb: &Workbook, sheet: usize, chart:
|
||||
let origin = rect.center() - vec2(w * z, h * z) / 2.0;
|
||||
let data = gridcraft_chart::resolve(wb, sheet, chart);
|
||||
let m = EguiMeasure { painter: p, z };
|
||||
let prims = gridcraft_chart::render(chart, &data, w, h, &m);
|
||||
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
|
||||
let prims = gridcraft_chart::render_with_labels(chart, &data, w, h, &m, &labels);
|
||||
paint_prims(&p.with_clip_rect(rect.intersect(p.clip_rect())), origin, &prims, z);
|
||||
}
|
||||
|
||||
@@ -254,7 +255,8 @@ fn render_chart(p: &Painter, z: f32, wb: &Workbook, si: usize, ch: &gridcraft_en
|
||||
tests::RENDERS.with(|c| c.set(c.get() + 1));
|
||||
let data = gridcraft_chart::resolve(wb, si, ch);
|
||||
let m = EguiMeasure { painter: p, z };
|
||||
gridcraft_chart::render(ch, &data, ch.anchor.width, ch.anchor.height, &m)
|
||||
let labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
|
||||
gridcraft_chart::render_with_labels(ch, &data, ch.anchor.width, ch.anchor.height, &m, &labels)
|
||||
}
|
||||
|
||||
/// The primitives of chart `ci` of sheet `si`: from the frame cache when the workbook, zoom and
|
||||
|
||||
@@ -279,6 +279,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
("view.animations", "Animations", "{on?: bool} (toggles without it) → {on}"),
|
||||
("options.autoComplete", "Enable AutoComplete for cell values", "{on?: bool} (toggles without it) → {on}"),
|
||||
("options.highlightActiveRow", "Highlight the active cell's row", "{on?: bool} (toggles without it) → {on}"),
|
||||
(
|
||||
"options.agents",
|
||||
"Agents",
|
||||
"{controlPort?: int, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} saves those settings → {settings, status, allowed, mcpFlag}",
|
||||
),
|
||||
("view.interfaceScale", "Interface Size", "{percent: 75–200 | \"auto\"} (100 = auto; clamped)"),
|
||||
("ui.window.minimize", "Minimize Window", ""),
|
||||
("ui.window.maximize", "Maximize Window", "{on: bool}"),
|
||||
@@ -534,7 +539,7 @@ pub fn poll(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
Outcome::Done(v) => {
|
||||
let _ = req.reply.send(v);
|
||||
}
|
||||
Outcome::Screenshot { path } => admit(app, ctx, path, req.reply),
|
||||
Outcome::Screenshot { path } => admit(app, ctx, path, req.reply, None),
|
||||
}
|
||||
}
|
||||
app.control_rx = Some(rx);
|
||||
@@ -543,6 +548,111 @@ pub fn poll(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the requests agents sent through the ArtCraft Launcher's switch (`crate::agents`): the same
|
||||
/// methods as the `--control` channel, with file commands confined to the agent folders. A
|
||||
/// screenshot is written only inside the write folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn poll_agents(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
use gridcraft_engine::file_access;
|
||||
let Some(agents) = app.agents.as_mut() else { return };
|
||||
agents.sync(&craft_ui::runtime::windows::WindowHost::of(ctx));
|
||||
// What the agent's queued input changed in the frames since the last look is the agent's too,
|
||||
// and so is a cell draft it left open: committed later by anyone, it is still the agent's edit.
|
||||
if let Some(roots) = app.agent_input.clone() {
|
||||
let seen = std::mem::take(&mut app.agent_seen);
|
||||
mark_agent_changes(app, &seen, &roots);
|
||||
// Only a draft the input opened or changed is the agent's; a pointer move over the person's
|
||||
// open draft leaves it theirs.
|
||||
let draft = app.editor.as_ref().map(|e| e.text.clone());
|
||||
if draft.is_some() && draft != app.agent_seen_draft && app.agent_draft.is_none() {
|
||||
app.agent_draft = Some((roots, workbooks(app)));
|
||||
}
|
||||
app.agent_seen_draft = draft;
|
||||
}
|
||||
if let Some((roots, before)) = app.agent_draft.take() {
|
||||
if app.editor.is_some() {
|
||||
app.agent_draft = Some((roots, before));
|
||||
} else {
|
||||
mark_agent_changes(app, &before, &roots);
|
||||
}
|
||||
}
|
||||
// The agent's queued input has been applied: the frames that follow are the person's again,
|
||||
// and the workbook snapshots kept to compare against are let go.
|
||||
if app.synthetic.is_empty() && !app.synthetic_pending {
|
||||
app.agent_input = None;
|
||||
app.agent_seen.clear();
|
||||
app.agent_seen_draft = None;
|
||||
}
|
||||
while let Some((req, roots)) = app.agents.as_mut().and_then(crate::agents::Agents::next_request) {
|
||||
if req.method == crate::agents::FOLDERS_METHOD {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": crate::agents::folders_answer(&roots)}));
|
||||
continue;
|
||||
}
|
||||
let queued = app.synthetic.len();
|
||||
let before = workbooks(app);
|
||||
let draft_before = app.editor.as_ref().map(|e| e.text.clone());
|
||||
let outcome = file_access::confine(Some(&roots), || handle(app, ctx, &req.method, &req.params));
|
||||
mark_agent_changes(app, &before, &roots);
|
||||
// A cell draft this request opened or changed (`ui.edit.begin`, `ui.edit.text`) is the
|
||||
// agent's, whoever commits it later. A draft the person opened stays theirs until an agent
|
||||
// request really changes it; a refused one leaves it as it was.
|
||||
let draft_after = app.editor.as_ref().map(|e| e.text.clone());
|
||||
if app.agent_draft.is_none() && draft_after.is_some() && draft_after != draft_before {
|
||||
app.agent_draft = Some((roots.clone(), before));
|
||||
}
|
||||
// Input an agent queued is applied in later passes, outside this call: those passes run
|
||||
// with the agent folders too (`SheetApp::agent_input`), so a key or click the agent sends
|
||||
// can't save outside them or change the agent settings.
|
||||
if app.synthetic.len() > queued {
|
||||
if app.agent_input.is_none() {
|
||||
app.agent_seen_draft = app.editor.as_ref().map(|e| e.text.clone());
|
||||
}
|
||||
app.agent_input = Some(roots.clone());
|
||||
app.agent_seen = workbooks(app);
|
||||
}
|
||||
match outcome {
|
||||
Outcome::Done(v) => {
|
||||
let _ = req.reply.send(v);
|
||||
}
|
||||
Outcome::Screenshot { path } => match path.as_deref().map(|p| roots.check(p, file_access::Access::Write)) {
|
||||
Some(Err(e)) => {
|
||||
let _ = req.reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
_ => admit(app, ctx, path, req.reply, Some(roots.clone())),
|
||||
},
|
||||
}
|
||||
}
|
||||
if !app.synthetic.is_empty() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Each open workbook by document uid, to see later which ones changed.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn workbooks(app: &SheetApp) -> Vec<(u64, std::sync::Arc<gridcraft_engine::model::Workbook>)> {
|
||||
app.session.documents().iter().map(|d| (d.uid, d.wb.clone())).collect()
|
||||
}
|
||||
|
||||
/// Workbooks that changed since `before` are an agent's changes: AutoSave writes them only inside
|
||||
/// `roots` until they are saved (`SheetApp::agent_changed`). While queued agent input remains, the
|
||||
/// current state is kept for the next look.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mark_agent_changes(
|
||||
app: &mut SheetApp,
|
||||
before: &[(u64, std::sync::Arc<gridcraft_engine::model::Workbook>)],
|
||||
roots: &std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>,
|
||||
) {
|
||||
for d in app.session.documents() {
|
||||
let unchanged = before.iter().any(|(uid, wb)| *uid == d.uid && std::sync::Arc::ptr_eq(wb, &d.wb));
|
||||
if !unchanged && d.is_dirty() {
|
||||
app.agent_changed.insert(d.uid, roots.clone());
|
||||
}
|
||||
}
|
||||
if app.agent_input.is_some() {
|
||||
app.agent_seen = workbooks(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the request token on every screenshot reply (success, rejection, timeout), so a client can
|
||||
/// correlate an asynchronous capture even when the reply order differs from the request order.
|
||||
fn with_token(mut reply: Json, token: u64) -> Json {
|
||||
@@ -564,7 +674,15 @@ fn next_token(app: &mut SheetApp) -> u64 {
|
||||
|
||||
/// Admit one screenshot request against the count and byte budgets **before** any capture is
|
||||
/// issued. A rejected request gets one error reply and never evicts an earlier request.
|
||||
fn admit(app: &mut SheetApp, ctx: &egui::Context, path: Option<String>, reply: Sender<ControlResponse>) {
|
||||
/// Queues a screenshot. `roots` are an agent's folders: its PNG is written through them when the
|
||||
/// capture completes, not by reopening the path (`save_image`).
|
||||
fn admit(
|
||||
app: &mut SheetApp,
|
||||
ctx: &egui::Context,
|
||||
path: Option<String>,
|
||||
reply: Sender<ControlResponse>,
|
||||
roots: Option<std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
|
||||
) {
|
||||
let token = next_token(app);
|
||||
let geometry = current_capture_geometry(app, ctx);
|
||||
let expected = geometry.expected_size();
|
||||
@@ -628,6 +746,7 @@ fn admit(app: &mut SheetApp, ctx: &egui::Context, path: Option<String>, reply: S
|
||||
app.shots.requests.push(Shot {
|
||||
token,
|
||||
path,
|
||||
roots,
|
||||
reply,
|
||||
deadline: now + 8000.0,
|
||||
ready_at: now + 100.0,
|
||||
|
||||
@@ -255,6 +255,8 @@ pub(super) fn check_peak_budget(reserved: usize, expected: [usize; 2], base64: b
|
||||
pub(super) struct Shot {
|
||||
pub(super) token: u64,
|
||||
pub(super) path: Option<String>,
|
||||
/// An agent's folders: the PNG is written through them (`save_image`).
|
||||
pub(super) roots: Option<std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
|
||||
pub(super) reply: Sender<ControlResponse>,
|
||||
/// Monotonic deadline for the whole request, including retries.
|
||||
pub(super) deadline: f64,
|
||||
@@ -624,7 +626,7 @@ fn drain_image(r: &mut Shot, image: std::sync::Arc<egui::ColorImage>, now: f64,
|
||||
drop(image);
|
||||
DrainAction::Restart
|
||||
}
|
||||
Ok(()) => DrainAction::Remove(save_image(image, r.path.as_deref())),
|
||||
Ok(()) => DrainAction::Remove(save_image(image, r.path.as_deref(), r.roots.as_ref())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,7 +690,15 @@ fn retry_capture(app: &mut SheetApp, i: usize, geometry: CaptureGeometry, epoch:
|
||||
/// straight to the file. A base64 reply is length-checked against
|
||||
/// [`SCREENSHOT_MAX_BASE64_BYTES`] *before* the string is allocated, so one admitted capture cannot
|
||||
/// retain an unbounded reply alongside its image.
|
||||
pub fn save_image(image: std::sync::Arc<egui::ColorImage>, path: Option<&str>) -> Json {
|
||||
///
|
||||
/// With an agent's `roots`, the PNG is encoded first and written through the engine's confined
|
||||
/// writer, relative to the write folder it opened: the path is checked again as it is written, so
|
||||
/// an entry replaced after admission (a link to somewhere else) can't redirect it.
|
||||
pub fn save_image(
|
||||
image: std::sync::Arc<egui::ColorImage>,
|
||||
path: Option<&str>,
|
||||
roots: Option<&std::sync::Arc<gridcraft_engine::file_access::AutomationRoots>>,
|
||||
) -> Json {
|
||||
use image::ImageEncoder as _;
|
||||
let [w, h] = image.size;
|
||||
let Some(capacity) = w.checked_mul(h).and_then(|p| p.checked_mul(4)) else { return json!({"ok": false, "error": "bad image"}) };
|
||||
@@ -703,6 +713,18 @@ pub fn save_image(image: std::sync::Arc<egui::ColorImage>, path: Option<&str>) -
|
||||
rgba.extend_from_slice(&p.to_array());
|
||||
}
|
||||
drop(image);
|
||||
if let (Some(p), Some(roots)) = (path, roots) {
|
||||
let mut png = Vec::new();
|
||||
let encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
if let Err(e) = encoder.write_image(&rgba, width, height, image::ExtendedColorType::Rgba8) {
|
||||
return json!({"ok": false, "error": e.to_string()});
|
||||
}
|
||||
drop(rgba);
|
||||
return match gridcraft_engine::file_access::confine(Some(roots), || gridcraft_engine::io::write_file(p, &png)) {
|
||||
Ok(()) => json!({"ok": true, "result": {"path": p, "width": w, "height": h}}),
|
||||
Err(e) => json!({"ok": false, "error": e.to_string()}),
|
||||
};
|
||||
}
|
||||
match path {
|
||||
Some(p) => match std::fs::File::create(p) {
|
||||
Ok(file) => {
|
||||
|
||||
@@ -178,13 +178,13 @@ fn screenshot_admission_stops_on_the_count_budget_without_evicting() {
|
||||
let mut replies = Vec::new();
|
||||
for _ in 0..SCREENSHOT_MAX_REQUESTS {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
replies.push(rx);
|
||||
}
|
||||
assert_eq!(app.shots.requests.len(), SCREENSHOT_MAX_REQUESTS);
|
||||
assert!(replies.iter_mut().all(|r| r.try_recv().is_err()), "admitted requests do not reply early");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
let reply = rx.try_recv().expect("the over-count request is rejected");
|
||||
assert_eq!(reply["ok"], false);
|
||||
assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit 4")), "{reply}");
|
||||
@@ -202,7 +202,7 @@ fn screenshot_admission_stops_on_aggregate_bytes_before_the_count() {
|
||||
for _ in 0..3 {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
// A path capture (not base64) isolates the retained-image aggregate budget.
|
||||
admit(&mut app, &ctx, Some(path.clone()), tx);
|
||||
admit(&mut app, &ctx, Some(path.clone()), tx, None);
|
||||
if let Ok(reply) = rx.try_recv() {
|
||||
rejected = Some(reply);
|
||||
}
|
||||
@@ -218,7 +218,7 @@ fn requests_without_a_size_stay_queued_and_time_out() {
|
||||
let ctx = sized_context(egui::Vec2::ZERO);
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
assert!(rx.try_recv().is_err(), "an unknown size is queued, not refused with an overflow error");
|
||||
assert_eq!(app.shots.requests[0].bytes, UNKNOWN_CAPTURE_BYTES, "the largest possible image is reserved meanwhile");
|
||||
// Settling passes without a size neither issue nor fail the request.
|
||||
@@ -244,7 +244,7 @@ fn a_queued_capture_requests_hidden_paint_until_it_is_issued() {
|
||||
let ctx = sized_context(egui::vec2(64.0, 48.0));
|
||||
let mut app = test_app();
|
||||
let (tx, _rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
let queued = ctx.run_logic(&raw_of(egui::vec2(64.0, 48.0)), |ctx| app.logic(ctx));
|
||||
assert_eq!(hidden_paints(&queued), 1, "a queued capture needs a real `ui` pass");
|
||||
|
||||
@@ -267,7 +267,7 @@ fn a_minimized_capture_does_not_force_hidden_frames_while_it_waits() {
|
||||
}
|
||||
app.raw_input_hook(&ctx, &mut raw);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
assert!(rx.try_recv().is_err());
|
||||
let waited = ctx.run_logic(&raw, |ctx| app.logic(ctx));
|
||||
assert_eq!(hidden_paints(&waited), 0, "a minimized request cannot issue until it is restored");
|
||||
@@ -304,7 +304,7 @@ fn one_admitted_capture_issues_one_callback_and_replies_once() {
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(h.state_mut(), &ctx, None, tx);
|
||||
admit(h.state_mut(), &ctx, None, tx, None);
|
||||
let token = h.state().shots.requests[0].token;
|
||||
h.state_mut().shots.requests[0].ready_at = 0.0;
|
||||
let mut callbacks = Vec::new();
|
||||
@@ -334,10 +334,10 @@ fn out_of_order_completions_reply_on_their_own_request() {
|
||||
let p1 = temp_png("order-1");
|
||||
let p2 = temp_png("order-2");
|
||||
let (tx1, rx1) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1);
|
||||
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1, None);
|
||||
let token1 = app.shots.requests[0].token;
|
||||
let (tx2, rx2) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2);
|
||||
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2, None);
|
||||
let token2 = app.shots.requests[1].token;
|
||||
for request in &mut app.shots.requests {
|
||||
request.ready_at = 0.0;
|
||||
@@ -370,7 +370,7 @@ fn a_timed_out_capture_replies_once_and_never_writes() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("timeout");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].deadline = 0.0;
|
||||
let _ = ui_pass(&ctx, egui::RawInput::default(), |ui| drain_screenshots(&mut app, ui.ctx()));
|
||||
let reply = rx.try_recv().expect("the timeout replies");
|
||||
@@ -389,7 +389,7 @@ fn a_capture_completed_after_its_deadline_writes_nothing() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("late");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
let token = app.shots.requests[0].token;
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
@@ -414,7 +414,7 @@ fn a_callback_after_the_request_is_removed_is_inert() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("removed");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
assert_eq!(callbacks.len(), 1);
|
||||
@@ -433,7 +433,7 @@ fn a_resize_between_admission_and_issuance_does_not_cost_a_retry() {
|
||||
let ctx = sized_context(egui::vec2(64.0, 48.0));
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let admitted_epoch = app.shots.requests[0].epoch;
|
||||
let resized = raw_of(egui::vec2(32.0, 24.0));
|
||||
@@ -458,7 +458,7 @@ fn the_retained_reservation_is_the_slot_bound() {
|
||||
let ctx = sized_context(egui::vec2(10.0, 8.0));
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
// validate_image accepts one pixel of rounding per axis: an 11x9 image is the largest.
|
||||
assert_eq!(app.shots.requests[0].bytes, 11 * 9 * 4);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
@@ -480,9 +480,9 @@ fn an_image_beyond_the_reservation_is_released_without_writing() {
|
||||
let p1 = temp_png("over-1");
|
||||
let p2 = temp_png("over-2");
|
||||
let (tx1, rx1) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1);
|
||||
admit(&mut app, &ctx, Some(p1.to_string_lossy().into_owned()), tx1, None);
|
||||
let (tx2, rx2) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2);
|
||||
admit(&mut app, &ctx, Some(p2.to_string_lossy().into_owned()), tx2, None);
|
||||
for request in &mut app.shots.requests {
|
||||
request.ready_at = 0.0;
|
||||
}
|
||||
@@ -521,7 +521,7 @@ fn settling_counts_one_real_pass_and_skips_a_discarded_one() {
|
||||
let ctx = sized_context(egui::vec2(64.0, 48.0));
|
||||
let mut app = test_app();
|
||||
let (tx, _rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
// Two `ui` calls in one pass are one settling frame.
|
||||
let _ = ui_pass(&ctx, egui::RawInput::default(), |ui| {
|
||||
issue_screenshots(&mut app, ui.ctx());
|
||||
@@ -547,7 +547,7 @@ fn a_discard_requested_after_issuance_still_issues_and_writes_once() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("discard-after-issue");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let mut asked = false;
|
||||
let mut callbacks = Vec::new();
|
||||
@@ -580,7 +580,7 @@ fn an_image_larger_than_the_reservation_retries_like_a_smaller_one() {
|
||||
let ctx = sized_context(egui::vec2(10.0, 8.0));
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
assert_eq!(callbacks.len(), 1);
|
||||
@@ -618,7 +618,7 @@ fn a_minimize_retry_without_a_size_still_checks_the_aggregate_budget() {
|
||||
let path = temp_png(&format!("minimize-retry-{n}"));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
// A path capture isolates the retained-image aggregate budget.
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
paths.push(path);
|
||||
receivers.push(rx);
|
||||
}
|
||||
@@ -695,7 +695,7 @@ fn a_hidden_resize_rejects_an_image_issued_before_it_and_reissues() {
|
||||
let ctx = sized_context(egui::vec2(64.0, 48.0));
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
assert_eq!(callbacks.len(), 1);
|
||||
@@ -737,7 +737,7 @@ fn a_drained_capture_frees_its_slot_for_the_next_admission() {
|
||||
let mut receivers = Vec::new();
|
||||
for _ in 0..SCREENSHOT_MAX_REQUESTS {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
receivers.push(rx);
|
||||
}
|
||||
for request in &mut app.shots.requests {
|
||||
@@ -753,7 +753,7 @@ fn a_drained_capture_frees_its_slot_for_the_next_admission() {
|
||||
assert_eq!(app.shots.requests.len(), 0);
|
||||
assert!(receivers.iter_mut().all(|rx| rx.try_recv().is_ok()));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
assert!(rx.try_recv().is_err(), "a new request is admitted once the drained slots are free");
|
||||
assert_eq!(app.shots.requests.len(), 1);
|
||||
}
|
||||
@@ -809,7 +809,7 @@ fn minimized_geometry_has_no_size_and_restore_bumps_the_epoch() {
|
||||
|
||||
// Admission while minimized reserves the unknown-size maximum and waits.
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
assert_eq!(app.shots.requests[0].bytes, UNKNOWN_CAPTURE_BYTES);
|
||||
assert!(rx.try_recv().is_err());
|
||||
let epoch = app.capture_epoch;
|
||||
@@ -834,7 +834,7 @@ fn a_document_switch_before_issuance_cancels_without_writing() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("doc-queued");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let admitted = app.shots.requests[0].document;
|
||||
assert!(app.run("file.new", json!({})).is_ok());
|
||||
@@ -855,7 +855,7 @@ fn a_document_switch_after_issuance_rejects_the_completed_image() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("doc-issued");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
assert_eq!(callbacks.len(), 1);
|
||||
@@ -875,7 +875,7 @@ fn a_completion_for_another_viewport_is_rejected() {
|
||||
let mut app = test_app();
|
||||
let path = temp_png("viewport");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx, None);
|
||||
app.shots.requests[0].ready_at = 0.0;
|
||||
let callbacks = issue_with(&ctx, &mut app, egui::RawInput::default());
|
||||
assert_eq!(callbacks.len(), 1);
|
||||
@@ -922,7 +922,7 @@ fn base64_capture_over_the_encoding_budget_is_rejected_before_admission() {
|
||||
let ctx = sized_context(egui::vec2(5000.0, 4000.0));
|
||||
let mut app = test_app();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, None, tx);
|
||||
admit(&mut app, &ctx, None, tx, None);
|
||||
let reply = rx.try_recv().expect("an oversized base64 capture is refused at admission");
|
||||
assert_eq!(reply["ok"], false, "{reply}");
|
||||
assert!(reply["error"].as_str().is_some_and(|e| e.contains("encoding") || e.contains("base64")), "the error names the encoding budget: {reply}");
|
||||
@@ -931,7 +931,7 @@ fn base64_capture_over_the_encoding_budget_is_rejected_before_admission() {
|
||||
// The same capture as a file is admitted within the per-image and encoding budgets.
|
||||
let path = temp_png("encoding-path");
|
||||
let (tx2, rx2) = std::sync::mpsc::channel();
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx2);
|
||||
admit(&mut app, &ctx, Some(path.to_string_lossy().into_owned()), tx2, None);
|
||||
assert!(rx2.try_recv().is_err(), "the path form is admitted");
|
||||
assert_eq!(app.shots.requests.len(), 1);
|
||||
app.shots.cancel_all();
|
||||
@@ -1255,3 +1255,463 @@ fn python_mode_does_not_start_on_a_draft_typed_inside_a_spill() {
|
||||
let a2 = app.session.active().and_then(|d| d.wb.sheet(0)).and_then(|sh| sh.cell(gridcraft_engine::core::CellRef::new(1, 0)).cloned());
|
||||
assert_eq!(a2.map(|c| (c.input_text(), c.py.is_some())), Some(("5".to_string(), false)));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod agents_support {
|
||||
use super::*;
|
||||
use craft_control::agents::{AgentSettings, AgentSwitch, read_connection};
|
||||
|
||||
pub(super) fn temp(label: &str) -> std::path::PathBuf {
|
||||
#[allow(clippy::disallowed_methods)] // native-only fixture
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-ui-agents-{label}-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
pub(super) fn agents(dir: &std::path::Path, launcher: bool, folder: &std::path::Path) -> crate::agents::Agents {
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.read_root = folder.display().to_string();
|
||||
settings.write_root = folder.display().to_string();
|
||||
crate::agents::Agents::new(
|
||||
Some(dir.to_path_buf()),
|
||||
"GridCraft test".into(),
|
||||
AgentSwitch::fixed(true, launcher),
|
||||
settings,
|
||||
Box::new(|_| Ok(())),
|
||||
)
|
||||
.with_default_folder(None)
|
||||
}
|
||||
|
||||
/// Runs `calls` from another thread over the window's agent connection while this thread runs
|
||||
/// the app's frames, as the app's loop would.
|
||||
pub(super) fn agent_calls(
|
||||
app: &mut SheetApp,
|
||||
ctx: &egui::Context,
|
||||
dir: &std::path::Path,
|
||||
calls: Vec<(&'static str, Json)>,
|
||||
) -> Vec<Result<Json, String>> {
|
||||
let connection = read_connection(dir).unwrap().expect("the window publishes its connection while agents may use it");
|
||||
let token = std::fs::read_to_string(&connection.token_file).unwrap().trim().to_owned();
|
||||
let addr: std::net::SocketAddr = connection.addr().parse().unwrap();
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut c = craft_automation::client::ControlClient::connect(addr, &token).unwrap();
|
||||
calls.into_iter().map(|(m, p)| c.call(m, p)).collect::<Vec<_>>()
|
||||
});
|
||||
while !client.is_finished() {
|
||||
poll_agents(app, ctx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
client.join().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod agents {
|
||||
use super::agents_support::*;
|
||||
use super::*;
|
||||
use craft_control::agents::read_connection;
|
||||
|
||||
#[test]
|
||||
fn agents_link_follows_the_switch() {
|
||||
let dir = temp("switch");
|
||||
let mut app = test_app();
|
||||
app.agents = Some(agents(&dir, false, &dir));
|
||||
let ctx = egui::Context::default();
|
||||
poll_agents(&mut app, &ctx);
|
||||
assert!(read_connection(&dir).unwrap().is_none(), "the switch is off: nothing may be published");
|
||||
assert!(app.agents.as_ref().unwrap().status().port.is_none());
|
||||
|
||||
app.agents = Some(agents(&dir, true, &dir));
|
||||
poll_agents(&mut app, &ctx);
|
||||
let port = app.agents.as_ref().unwrap().status().port.expect("the switch is on: agents can connect");
|
||||
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(port));
|
||||
app.agents = None;
|
||||
assert!(read_connection(&dir).unwrap().is_none(), "closing the link removes its connection file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_requests_stay_in_the_agent_folders() {
|
||||
let dir = temp("folders");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
std::fs::write(folder.join("in.csv"), "inside,7\n").unwrap();
|
||||
std::fs::write(dir.join("private.csv"), "outside,91\n").unwrap();
|
||||
let mut app = test_app();
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
poll_agents(&mut app, &ctx);
|
||||
let outside = dir.join("private.csv").display().to_string();
|
||||
let replies = agent_calls(
|
||||
&mut app,
|
||||
&ctx,
|
||||
&dir,
|
||||
vec![
|
||||
("app.open", json!({"path": outside})),
|
||||
("app.open", json!({"path": folder.join("in.csv")})),
|
||||
("ui.screenshot", json!({"path": dir.join("shot.png")})),
|
||||
("engine.execute", json!({"command": "options.agents", "params": {"readRoot": dir}})),
|
||||
("agent.folders", json!({})),
|
||||
("ui.text", json!({"text": "x"})),
|
||||
],
|
||||
);
|
||||
let refused = replies[0].as_ref().unwrap_err();
|
||||
assert!(refused.contains("outside the read root"), "{refused}");
|
||||
assert!(replies[1].is_ok(), "{:?}", replies[1]);
|
||||
assert!(replies[2].as_ref().unwrap_err().contains("outside the write root"), "{:?}", replies[2]);
|
||||
assert!(replies[3].as_ref().unwrap_err().contains("can't change"), "{:?}", replies[3]);
|
||||
assert_eq!(app.agents.as_ref().unwrap().settings().read_root, folder.display().to_string());
|
||||
let answered = replies[4].as_ref().unwrap();
|
||||
assert!(answered["write_folder"].as_str().is_some_and(|f| std::path::Path::new(f).ends_with("agents")), "{answered}");
|
||||
// The text it typed is applied in later passes: those run with the agent folders too.
|
||||
assert!(app.agent_input.is_some(), "queued agent input must keep the agent folders");
|
||||
// Once that input is gone, the frames are the person's again and nothing is kept for it.
|
||||
app.synthetic.clear();
|
||||
app.synthetic_pending = false;
|
||||
poll_agents(&mut app, &ctx);
|
||||
assert!(app.agent_input.is_none() && app.agent_seen.is_empty());
|
||||
// The person at the keyboard isn't confined: the same open runs from the window.
|
||||
assert!(app.run("file.open", json!({"path": outside})).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod agent_autosave {
|
||||
use super::agents_support::*;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn autosave_keeps_an_agents_change_inside_the_agent_folders() {
|
||||
let dir = temp("autosave");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
// The person saved this workbook outside the agent folder and turned AutoSave on.
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("cell.set", json!({"cell": "A1", "input": "mine"})).unwrap();
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
poll_agents(&mut app, &ctx);
|
||||
let replies =
|
||||
agent_calls(&mut app, &ctx, &dir, vec![("engine.execute", json!({"command": "cell.set", "params": {"cell": "A1", "input": "agent"}}))]);
|
||||
assert!(replies[0].is_ok(), "{:?}", replies[0]);
|
||||
// AutoSave's two seconds have passed.
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
app.logic(&ctx);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote an agent's change outside the agent folders");
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
// The person's own Save still writes it, and the workbook is theirs again.
|
||||
app.run("file.save", json!({})).unwrap();
|
||||
assert_ne!(std::fs::read(&outside).unwrap(), saved);
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
app.logic(&ctx);
|
||||
assert!(app.agent_changed.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod agent_writes {
|
||||
use super::agents_support::*;
|
||||
use super::*;
|
||||
use gridcraft_engine::file_access::AutomationRoots;
|
||||
|
||||
#[test]
|
||||
fn an_agents_screenshot_is_written_through_its_folder_not_by_path() {
|
||||
let dir = temp("shot-write");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&folder), Some(&folder)).unwrap().unwrap();
|
||||
let image = || std::sync::Arc::new(egui::ColorImage::filled([4, 3], egui::Color32::RED));
|
||||
// Checked again as it is written: a path outside the folder writes nothing, even though
|
||||
// nothing checked it before.
|
||||
let outside = dir.join("outside.png");
|
||||
let refused = save_image(image(), outside.to_str(), Some(&roots));
|
||||
assert_eq!(refused["ok"], json!(false), "{refused}");
|
||||
assert!(!outside.exists());
|
||||
let inside = folder.join("shot.png");
|
||||
let written = save_image(image(), inside.to_str(), Some(&roots));
|
||||
assert_eq!(written["ok"], json!(true), "{written}");
|
||||
assert!(std::fs::read(&inside).unwrap().starts_with(b"\x89PNG"));
|
||||
}
|
||||
|
||||
/// An agent's typed input is applied by later passes; what it changes is the agent's for
|
||||
/// AutoSave, while the input is still queued and after the queue has emptied.
|
||||
#[test]
|
||||
fn autosave_keeps_changes_made_by_an_agents_queued_input_inside_its_folders() {
|
||||
for pending in [true, false] {
|
||||
let dir = temp(if pending { "input-pending" } else { "input-done" });
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
poll_agents(&mut app, &ctx);
|
||||
agent_calls(&mut app, &ctx, &dir, vec![("ui.text", json!({"text": "x"}))]);
|
||||
assert!(app.agent_input.is_some());
|
||||
// A later pass applies the agent's input: here, the edit it makes.
|
||||
app.run("cell.set", json!({"cell": "B2", "input": "typed by the agent"})).unwrap();
|
||||
if !pending {
|
||||
app.synthetic.clear();
|
||||
app.synthetic_pending = false;
|
||||
}
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
app.logic(&ctx);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved, "pending={pending}: AutoSave wrote the agent's input outside its folders");
|
||||
assert!(app.session.active().unwrap().is_dirty(), "pending={pending}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod launch_control {
|
||||
use super::agents_support::*;
|
||||
use super::*;
|
||||
use craft_control::agents::{AgentFolders, AgentSwitch};
|
||||
|
||||
/// `--control` runs the framework's server for the whole run, and its requests stay in the
|
||||
/// folders the launch named, as an agent's do.
|
||||
#[test]
|
||||
fn control_requests_are_confined_like_an_agents() {
|
||||
let dir = temp("launch");
|
||||
let folder = dir.join("roots");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
std::fs::write(folder.join("in.csv"), "inside,7\n").unwrap();
|
||||
std::fs::write(dir.join("private.csv"), "outside,91\n").unwrap();
|
||||
let token = "ab".repeat(32);
|
||||
let host = craft_ui::runtime::windows::WindowHost::of(&egui::Context::default());
|
||||
let (requests, server) = craft_automation::server::listen(0, token.clone(), host).unwrap();
|
||||
let addr = server.addr;
|
||||
let mut folders = AgentFolders::default();
|
||||
folders.read = Some(folder.clone());
|
||||
folders.write = Some(folder.clone());
|
||||
let mut app = test_app();
|
||||
// The switch is off: `--control` doesn't depend on it.
|
||||
let agents =
|
||||
crate::agents::Agents::new(None, "GridCraft test".into(), AgentSwitch::fixed(true, false), Default::default(), Box::new(|_| Ok(())))
|
||||
.with_default_folder(None)
|
||||
.launched_with_control(server, requests, Some(folders));
|
||||
assert!(agents.status().launch_flags);
|
||||
app.agents = Some(agents);
|
||||
let ctx = egui::Context::default();
|
||||
let outside = dir.join("private.csv");
|
||||
let inside = folder.join("in.csv");
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut c = craft_automation::client::ControlClient::connect(addr, &token).unwrap();
|
||||
vec![c.call("app.open", json!({"path": outside})), c.call("app.open", json!({"path": inside}))]
|
||||
});
|
||||
while !client.is_finished() {
|
||||
poll_agents(&mut app, &ctx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
let replies = client.join().unwrap();
|
||||
assert!(replies[0].as_ref().unwrap_err().contains("outside the read root"), "{:?}", replies[0]);
|
||||
assert!(replies[1].is_ok(), "{:?}", replies[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod agent_input_frames {
|
||||
use super::agents_support::*;
|
||||
use super::*;
|
||||
|
||||
/// One desktop frame: the agent's queued input goes into the raw input, then `logic` and `ui`
|
||||
/// run as the desktop app runs them (`SheetApp::with_agent_input`).
|
||||
fn frame(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let mut raw = raw_of(egui::vec2(1200.0, 800.0));
|
||||
app.raw_input_hook(ctx, &mut raw);
|
||||
app.with_agent_input(|app| app.logic(ctx));
|
||||
let _ = ui_pass(ctx, raw, |ui| app.with_agent_input(|app| app.ui(ui)));
|
||||
}
|
||||
|
||||
/// Text an agent types into the grid is applied by later UI passes. AutoSave doesn't write
|
||||
/// that change outside the agent folders: not while the input is still being applied, and not
|
||||
/// after the queue has emptied.
|
||||
#[test]
|
||||
fn autosave_keeps_an_agents_typed_input_inside_its_folders() {
|
||||
let dir = temp("typed");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
let replies = agent_calls(
|
||||
&mut app,
|
||||
&ctx,
|
||||
&dir,
|
||||
vec![
|
||||
("engine.execute", json!({"command": "selection.set", "params": {"range": "C3"}})),
|
||||
("ui.text", json!({"text": "typed by the agent"})),
|
||||
("ui.key", json!({"key": "Enter"})),
|
||||
],
|
||||
);
|
||||
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
|
||||
let mut applied = false;
|
||||
for _ in 0..40 {
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's typed input outside its folders");
|
||||
applied |= app.run("cell.get", json!({"cell": "C3"})).is_ok_and(|c| c["input"] == json!("typed by the agent"));
|
||||
if applied && app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(applied, "the typed input must reach the cell through the UI passes");
|
||||
assert!(app.agent_input.is_none(), "the queue emptied and the frames are the person's again");
|
||||
// After the queue emptied, AutoSave still keeps the agent's change inside its folders.
|
||||
for _ in 0..3 {
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved);
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
/// The agent types into a cell and stops before Enter; the person commits the draft later.
|
||||
/// The committed change is still the agent's: AutoSave keeps it inside the agent folders.
|
||||
#[test]
|
||||
fn a_draft_the_agent_left_open_stays_the_agents_when_the_person_commits_it() {
|
||||
let dir = temp("draft");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
let replies = agent_calls(
|
||||
&mut app,
|
||||
&ctx,
|
||||
&dir,
|
||||
vec![("engine.execute", json!({"command": "selection.set", "params": {"range": "D4"}})), ("ui.text", json!({"text": "left open"}))],
|
||||
);
|
||||
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
|
||||
for _ in 0..40 {
|
||||
frame(&mut app, &ctx);
|
||||
if app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(app.editor.is_some(), "the agent's draft is still open");
|
||||
assert!(app.agent_input.is_none(), "its input is all applied");
|
||||
// The person commits the draft (Enter in their own frame).
|
||||
assert!(app.commit_edit(1, 0, false, false));
|
||||
for _ in 0..3 {
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
assert!(app.run("cell.get", json!({"cell": "D4"})).is_ok_and(|c| c["input"] == json!("left open")));
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's draft outside its folders");
|
||||
}
|
||||
|
||||
/// A draft an agent opens directly (`ui.edit.begin` with text, no queued keys) and the person
|
||||
/// commits later is still the agent's edit for AutoSave.
|
||||
#[test]
|
||||
fn a_draft_the_agent_opened_directly_stays_the_agents_when_the_person_commits_it() {
|
||||
let dir = temp("direct-draft");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
let replies = agent_calls(
|
||||
&mut app,
|
||||
&ctx,
|
||||
&dir,
|
||||
vec![
|
||||
("engine.execute", json!({"command": "selection.set", "params": {"range": "D5"}})),
|
||||
("ui.edit.begin", json!({"text": "opened directly"})),
|
||||
],
|
||||
);
|
||||
assert!(replies.iter().all(Result::is_ok), "{replies:?}");
|
||||
assert!(app.editor.is_some() && app.agent_input.is_none(), "a direct draft, no queued input");
|
||||
assert!(app.commit_edit(1, 0, false, false));
|
||||
for _ in 0..3 {
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
}
|
||||
assert!(app.run("cell.get", json!({"cell": "D5"})).is_ok_and(|c| c["input"] == json!("opened directly")));
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), saved, "AutoSave wrote the agent's direct draft outside its folders");
|
||||
}
|
||||
|
||||
/// The person's own draft is saved by AutoSave as before, also when an agent request that
|
||||
/// didn't change it ran meanwhile.
|
||||
#[test]
|
||||
fn the_persons_own_draft_is_still_autosaved() {
|
||||
let dir = temp("own-draft");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx);
|
||||
app.begin_edit(Some("mine".into()), false);
|
||||
// An agent request that is refused, or only reads, leaves the person's draft theirs.
|
||||
let replies = agent_calls(&mut app, &ctx, &dir, vec![("ui.edit.unknown", json!({})), ("engine.commands", json!({}))]);
|
||||
assert!(replies[0].is_err(), "{replies:?}");
|
||||
assert!(app.commit_edit(1, 0, false, false));
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
assert_ne!(std::fs::read(&outside).unwrap(), saved, "the person's own edit must still be autosaved");
|
||||
}
|
||||
|
||||
/// A pointer move an agent queues over the person's open draft leaves the draft theirs: AutoSave
|
||||
/// still saves their commit.
|
||||
#[test]
|
||||
fn queued_input_that_leaves_the_persons_draft_alone_keeps_it_theirs() {
|
||||
let dir = temp("move-draft");
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = test_app();
|
||||
let outside = dir.join("person.xlsx");
|
||||
app.run("file.saveAs", json!({"path": outside})).unwrap();
|
||||
let saved = std::fs::read(&outside).unwrap();
|
||||
app.ui.autosave = true;
|
||||
app.agents = Some(agents(&dir, true, &folder));
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx);
|
||||
app.begin_edit(Some("mine".into()), false);
|
||||
let replies = agent_calls(&mut app, &ctx, &dir, vec![("ui.move", json!({"x": 900.0, "y": 700.0}))]);
|
||||
assert!(replies[0].is_ok(), "{replies:?}");
|
||||
for _ in 0..40 {
|
||||
frame(&mut app, &ctx);
|
||||
if app.synthetic.is_empty() && !app.synthetic_pending && app.agent_input.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(app.editor.is_some(), "the person's draft is still open");
|
||||
assert!(app.commit_edit(1, 0, false, false));
|
||||
app.grid.last_autosave = f64::MIN;
|
||||
frame(&mut app, &ctx);
|
||||
assert_ne!(std::fs::read(&outside).unwrap(), saved, "the person's own commit must still be autosaved");
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user