mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-01 22:20:13 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0d5f15861 | ||
|
|
226a5d3d26 | ||
|
|
585970c542 | ||
|
|
9ed28ba9ea | ||
|
|
4d94d3e27c | ||
|
|
9a1e05f442 | ||
|
|
be7732912b | ||
|
|
c869fdb23c | ||
|
|
be07bd69fd | ||
|
|
5f22c7c01c | ||
|
|
838c9104c0 | ||
|
|
ade107ab73 | ||
|
|
44b8fc5b52 | ||
|
|
331486148e | ||
|
|
684d86b78d | ||
|
|
5b43c2abc8 | ||
|
|
01c94182f5 | ||
|
|
0ff6f02485 | ||
|
|
f2934fd009 | ||
|
|
ba597305a1 | ||
|
|
b742816737 | ||
|
|
97f2754c1d | ||
|
|
f45c122e79 | ||
|
|
6868b7eb7b | ||
|
|
dd1ba0e33d | ||
|
|
810b95bf68 | ||
|
|
a85ee924d6 | ||
|
|
0d868b83df | ||
|
|
05b883379a | ||
|
|
ba6385b388 | ||
|
|
989782f1a0 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408285582,
|
||||
"producer_workflow_id": 429713469,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -8,14 +8,15 @@ workflows:
|
||||
'.github/workflows/house-rules.yml': []
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]2.4'
|
||||
- 'step-security/[email protected]3.0'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]2.4'
|
||||
- 'step-security/[email protected]3.0'
|
||||
'.github/workflows/release.yml': []
|
||||
'.github/workflows/sonarcloud.yml': []
|
||||
'.github/workflows/windows-arm64.yml': []
|
||||
@@ -25,8 +26,8 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'step-security/[email protected]2.4':
|
||||
ref: 'v2.22.4'
|
||||
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
|
||||
'step-security/[email protected]3.0':
|
||||
ref: 'v2.23.0'
|
||||
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
|
||||
owner_id: 88700172
|
||||
repo_id: 422287306
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]2.4
|
||||
uses: step-security/[email protected]3.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [GridCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/gridcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/gridcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/gridcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/gridcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'gridcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: GridCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,12 +23,13 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]2.4
|
||||
uses: step-security/[email protected]3.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/[email protected]2.4
|
||||
uses: step-security/[email protected]3.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/[email protected]
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -81,4 +81,5 @@ Paths and conventions:
|
||||
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
|
||||
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
|
||||
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
|
||||
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
|
||||
|
||||
Generated
+27
-18
@@ -1216,6 +1216,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
@@ -2841,10 +2849,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"chrono",
|
||||
"craft-nightly",
|
||||
"craft-print",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
@@ -2870,7 +2879,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-calc"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
@@ -2882,7 +2891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-chart"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-calc",
|
||||
"gridcraft-core",
|
||||
@@ -2893,7 +2902,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-cli"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
@@ -2906,7 +2915,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-core"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"js-sys",
|
||||
@@ -2917,7 +2926,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-engine"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-csv",
|
||||
"craft-gridcraft-format",
|
||||
@@ -2943,7 +2952,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-formula"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"serde",
|
||||
@@ -2952,7 +2961,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-functions"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"regex",
|
||||
@@ -2960,7 +2969,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-math"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"ratex-font",
|
||||
"ratex-layout",
|
||||
@@ -2970,7 +2979,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-mcp"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-mcp-server",
|
||||
"gridcraft-engine",
|
||||
@@ -2980,7 +2989,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-model"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
@@ -2994,14 +3003,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-numfmt"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-pdf"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"craft-stream-codecs",
|
||||
@@ -3013,7 +3022,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-sandbox"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"landlock",
|
||||
"libc",
|
||||
@@ -3024,7 +3033,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-ui-egui"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -3056,7 +3065,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-web"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
@@ -3075,7 +3084,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-xlsx"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-csv",
|
||||
@@ -8249,7 +8258,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"serde_json",
|
||||
|
||||
+2
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -53,6 +53,7 @@ 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" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
|
||||
@@ -187,7 +187,7 @@ impl Args {
|
||||
|
||||
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
|
||||
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
|
||||
if id == "file.open"
|
||||
if matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
|
||||
&& let Ok(value) = &r
|
||||
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
|
||||
{
|
||||
@@ -328,6 +328,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
|
||||
return Ok(());
|
||||
}
|
||||
for warning in gridcraft_engine::cmd::file::save_losses(&s, "file.save", &json!({"path": out})).messages() {
|
||||
eprintln!("Warning: {warning}");
|
||||
}
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
|
||||
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -30,6 +30,8 @@ winresource = "0.1"
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
|
||||
craft-nightly = { workspace = true }
|
||||
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
|
||||
# Cargo.toml).
|
||||
craft-print = { workspace = true }
|
||||
|
||||
@@ -1,24 +1,12 @@
|
||||
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
|
||||
//! stable build, and a nightly build cannot be talked out of its profile.
|
||||
use crate::launch_profile::Profile;
|
||||
//! stable build, and a nightly build always stays isolated in its nightly profile.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
@@ -36,7 +24,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, needs_native_error, version, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -45,22 +34,6 @@ mod tests {
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
|
||||
|
||||
@@ -1,131 +1,43 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches keep their original arguments and directory policy. No environment mutation.
|
||||
//!
|
||||
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
|
||||
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
|
||||
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
|
||||
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
|
||||
//! of this can create a directory, open a log or start a window.
|
||||
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
|
||||
//! state. Direct launches of a nightly build self-isolate into
|
||||
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
|
||||
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
|
||||
//! their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
pub use craft_nightly::Profile;
|
||||
|
||||
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
|
||||
/// [`Profile::Stable`] before startup selection.
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
craft_nightly::current().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
|
||||
/// runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
|
||||
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
|
||||
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
|
||||
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
|
||||
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
|
||||
if let Some(index) = separator_index
|
||||
&& raw_args.get(index).is_some_and(|arg| arg == "--")
|
||||
{
|
||||
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
|
||||
passthrough_args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
|
||||
};
|
||||
|
||||
use super::restore_launcher_separator;
|
||||
use crate::profile_root;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
@@ -136,88 +48,88 @@ mod tests {
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
launch_arguments(Path::new(absolute()), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
|
||||
let spec = profile_root::app_spec();
|
||||
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
|
||||
let argv = args(&["sales.xlsx", "--sample", "budget"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = profile_root::app_spec();
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
|
||||
assert_eq!(
|
||||
restore_launcher_separator(&argv, launch.passthrough_args),
|
||||
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
fn stable_build_refuses_nightly_launch_flags() {
|
||||
let spec = profile_root::app_spec();
|
||||
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
|
||||
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv.clone()).is_err(), "{argv:?}");
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
|
||||
}
|
||||
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
args(&["-V"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["--version"])),
|
||||
launch_arguments(Path::new(absolute()), &args(&["-V"])),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
for argv in [
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(!launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
|
||||
+47
-31
@@ -214,8 +214,13 @@ fn services() -> Services {
|
||||
let path = std::path::Path::new(suggested);
|
||||
let stem = path.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
|
||||
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
|
||||
const TYPES: [(&str, &str); 4] =
|
||||
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
|
||||
const TYPES: [(&str, &str); 5] = [
|
||||
("Excel Workbook (.xlsx)", "xlsx"),
|
||||
("CSV UTF-8 (.csv)", "csv"),
|
||||
("Web Page (.html)", "html"),
|
||||
("PDF (.pdf)", "pdf"),
|
||||
("GridCraft Workbook (.json)", "json"),
|
||||
];
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
|
||||
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
|
||||
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
|
||||
@@ -304,46 +309,47 @@ fn report_launch_profile_error(error: &str) {
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window (a dialog
|
||||
// here would hang a headless runner and fail a Linux build).
|
||||
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
|
||||
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
|
||||
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
|
||||
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
|
||||
if nightly_build && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
let spec = profile_root::app_spec();
|
||||
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
|
||||
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
|
||||
if nightly_build && launch.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let channel =
|
||||
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) =
|
||||
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
|
||||
{
|
||||
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
|
||||
}
|
||||
|
||||
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
|
||||
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
|
||||
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
|
||||
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
|
||||
/// opened as a file.
|
||||
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
|
||||
/// separator itself is never opened as a file.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
@@ -660,8 +666,9 @@ mod launch_separator_tests {
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
|
||||
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
|
||||
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
|
||||
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
|
||||
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
|
||||
/// these tests too.
|
||||
fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
@@ -671,15 +678,24 @@ mod launch_separator_tests {
|
||||
let mut argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
let launch = craft_nightly::parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&profile_root::app_spec(),
|
||||
argv.iter().cloned(),
|
||||
&craft_nightly::StartupOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_platforms_root_spelling_is_refused_as_relative() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
|
||||
let argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
|
||||
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
|
||||
assert!(
|
||||
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
|
||||
"a root that is not absolute on this platform must be refused"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+209
-419
@@ -1,35 +1,91 @@
|
||||
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
|
||||
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
|
||||
//! nightly root, in both directions, so the two channels can never share a file.
|
||||
//! GridCraft's nightly profile specification and control-directory boundary, backed by
|
||||
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
|
||||
//! so the two channels can never share a file.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
|
||||
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
|
||||
pub const CONTROL_DIR: &str = "Control";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
|
||||
|
||||
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
|
||||
/// token, Flatpak, and installer boundary.
|
||||
pub fn app_spec() -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: "gridcraft",
|
||||
display_name: "GridCraft",
|
||||
stable_dir_names: &["gridcraft", "GridCraft"],
|
||||
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
|
||||
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &[],
|
||||
portable_markers: &[],
|
||||
folder_only_entries: &PROFILE_FOLDERS,
|
||||
extra_forbidden_roots: extra_forbidden_roots(|key| std::env::var_os(key)),
|
||||
}
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
// FreeBSD, the BSDs and anything else have no nightly channel.
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
|
||||
}
|
||||
|
||||
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
|
||||
/// config/data/cache directories already fenced by `craft-nightly`.
|
||||
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
|
||||
// (`install-policy.wxi`).
|
||||
let mut roots = Vec::new();
|
||||
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
|
||||
roots.push(profile.join(".gridcraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
|
||||
roots.push(home.join("Applications/GridCraft.app"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,18 +96,6 @@ fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
|
||||
/// ancestor is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
@@ -74,102 +118,21 @@ fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
|
||||
// token folder, plus both MSI install folders (`install-policy.wxi`).
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
|
||||
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
|
||||
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
|
||||
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/GridCraft"),
|
||||
library.join("Caches/GridCraft"),
|
||||
library.join("Caches/ai.storyteller.gridcraft"),
|
||||
library.join("Preferences/GridCraft"),
|
||||
library.join("Preferences/ai.storyteller.gridcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
|
||||
home.join("Applications/GridCraft.app"),
|
||||
PathBuf::from("/Applications/GridCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
|
||||
/// so a link there cannot point Nightly's writes at the stable app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.file_type().is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(())
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
|
||||
@@ -178,351 +141,178 @@ pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
|
||||
private_subdirectory(root, CONTROL_DIR, "control folder")
|
||||
}
|
||||
|
||||
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
|
||||
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
// A crashed launch can leave a probe with this name behind: take the next one instead of
|
||||
// failing, and remove only the file this call created, never someone else's.
|
||||
loop {
|
||||
let probe =
|
||||
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(_) => return std::fs::remove_file(&probe),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
|
||||
/// starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
|
||||
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
|
||||
{
|
||||
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
|
||||
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
|
||||
// instance may carry a profile. Any other, the stable app's included, could point it at
|
||||
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
|
||||
return Err(format!(
|
||||
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
|
||||
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
id.to_string_lossy()
|
||||
));
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect a subfolder elsewhere.
|
||||
control_directory(&chosen)?;
|
||||
entries_stay_inside(&chosen)?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
control_directory(&confirmed)?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
|
||||
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
|
||||
|
||||
struct TempDir {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/gridcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
Self { root }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
self.check_with(platform, root, |_| Ok(()))
|
||||
}
|
||||
|
||||
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
|
||||
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
fn path(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_stable_data_root_is_refused_on_its_own_platform() {
|
||||
let mut fixture = Fixture::new();
|
||||
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
|
||||
// and per-machine install folders and the control-token folder.
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
|
||||
for candidate in [stable.clone(), stable.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
|
||||
}
|
||||
assert!(!stable.exists());
|
||||
fn failed_profile_preparation_does_not_start_with_stable() {
|
||||
let tmp = TempDir::new("file-root");
|
||||
let root = tmp.path().join("not-a-directory");
|
||||
std::fs::write(&root, b"an ordinary file").unwrap();
|
||||
let argv = craft_nightly::launch_arguments(&root, &[]);
|
||||
let result =
|
||||
craft_nightly::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, &app_spec(), argv, &craft_nightly::StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
|
||||
let spec = app_spec();
|
||||
assert_eq!(spec.app_id, "gridcraft");
|
||||
assert_eq!(spec.display_name, "GridCraft");
|
||||
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
|
||||
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
|
||||
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert!(spec.forbidden_env_vars.is_empty());
|
||||
assert!(spec.portable_markers.is_empty());
|
||||
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
|
||||
let tmp = TempDir::new("extra-roots");
|
||||
let home = tmp.path().join("home");
|
||||
let local = tmp.path().join("local");
|
||||
let program_files = tmp.path().join("program-files");
|
||||
let env: BTreeMap<&str, OsString> = [
|
||||
("HOME", home.clone().into_os_string()),
|
||||
("USERPROFILE", home.clone().into_os_string()),
|
||||
("LOCALAPPDATA", local.clone().into_os_string()),
|
||||
("ProgramFiles", program_files.clone().into_os_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
|
||||
assert!(roots.contains(&home.join(".gridcraft")));
|
||||
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
|
||||
}
|
||||
assert!(
|
||||
fixture
|
||||
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
|
||||
.is_err()
|
||||
);
|
||||
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
|
||||
assert!(!base.join("ArtCraft/GridCraft").exists());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
|
||||
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
|
||||
}
|
||||
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
|
||||
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
|
||||
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
let _ = (&local, &program_files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
|
||||
let tmp = TempDir::new("reopen");
|
||||
let private = tmp.path().join("nightly-profile");
|
||||
let spec = app_spec();
|
||||
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
|
||||
// macOS: the four Library rows and the bundle itself.
|
||||
for suffix in [
|
||||
"Application Support/GridCraft",
|
||||
"Caches/GridCraft",
|
||||
"Preferences/GridCraft",
|
||||
"Saved Application State/ai.storyteller.gridcraft.savedState",
|
||||
] {
|
||||
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(
|
||||
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
|
||||
"{name} must stay a directory"
|
||||
);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_profile_row_is_accepted_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert_eq!(fixture.check(platform, &data).unwrap(), data);
|
||||
}
|
||||
assert!(
|
||||
fixture
|
||||
.check(
|
||||
Platform::Linux,
|
||||
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
|
||||
)
|
||||
.is_ok(),
|
||||
"the Launcher's own folder is not GridCraft's install"
|
||||
);
|
||||
}
|
||||
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
|
||||
let tmp = TempDir::new("forbidden");
|
||||
let forbidden = tmp.path().join("stable-boundary");
|
||||
let mut spec = app_spec();
|
||||
spec.extra_forbidden_roots.push(forbidden.clone());
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/gridcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Control"), platform));
|
||||
assert!(overlaps(&root.join("Control"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(!forbidden.exists());
|
||||
|
||||
#[test]
|
||||
fn the_install_folder_of_the_running_build_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/gridcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
|
||||
let mut fixture = Fixture::new();
|
||||
let root = fixture.root.join("flatpak profile");
|
||||
for (id, accepted) in [
|
||||
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
|
||||
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
|
||||
("ai.storyteller.gridcraft", false),
|
||||
("ai.storyteller.gridcraft.nightly-v1", false),
|
||||
("io.github.other.Gridcraft", false),
|
||||
] {
|
||||
fixture.env.insert("FLATPAK_ID".into(), id.into());
|
||||
let result = fixture.check(Platform::Linux, &root);
|
||||
assert_eq!(result.is_ok(), accepted, "{id}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_write_probe_never_falls_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/gridcraft");
|
||||
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
|
||||
assert!(!fixture.home().join(".config/gridcraft").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_in_place_of_the_profile_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let candidate = fixture.root.join("not-a-directory");
|
||||
std::fs::write(&candidate, b"a file, not a profile").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &candidate).is_err());
|
||||
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn profile_entry_aliases_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/gridcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
|
||||
for name in ["ui.json", "logs", "Control", "profile"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = fixture.check_with(Platform::Linux, &private, |_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-logs")).unwrap();
|
||||
std::fs::write(private.join("ui.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let outside = fixture.home().join("shared-tokens");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = fixture.root.join("nightly-control");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
|
||||
assert!(control_directory(&private).is_err());
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
|
||||
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_folder_is_a_private_lazy_subfolder() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
|
||||
let tmp = TempDir::new("control");
|
||||
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
|
||||
let control = control_directory(&private).unwrap();
|
||||
assert!(control.starts_with(&private) && control != private);
|
||||
assert!(!control.exists(), "resolving it must not create it");
|
||||
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_writable_probe_leaves_nothing_behind() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
|
||||
ensure_writable(&private).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
|
||||
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
|
||||
let tmp = TempDir::new("control-symlink");
|
||||
let outside = tmp.path().join("shared-tokens");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = tmp.path().join("nightly-control");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
|
||||
|
||||
assert!(control_directory(&private).is_err());
|
||||
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"From Text/CSV",
|
||||
["Data", "Get & Transform Data"],
|
||||
None,
|
||||
"{path | text, delimiter?: \",\", sheet?: new sheet name} → imports into a new sheet as a table",
|
||||
"{path | text, delimiter?: one character (comma, semicolon or tab picked by the text without it; a JSON array of objects is read as records only without it), sheet?: new sheet name, at?: cell, `Sheet!`-qualified or on the active sheet} → imports into a new sheet as a table, or with `at` pastes the columns there (no table), keeping the number formats the reader gives dates, percents and currency",
|
||||
has_doc,
|
||||
from_csv
|
||||
),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
|
||||
use gridcraft_model::Cell;
|
||||
use gridcraft_model::{Cell, Workbook};
|
||||
|
||||
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
|
||||
@@ -166,79 +166,200 @@ pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
let at = paste_target(s, p)?;
|
||||
let delimiter = delimiter_param(p)?;
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
// JSON array of objects → rows.
|
||||
let rows: Vec<Vec<Json>> =
|
||||
if text.trim_start().starts_with('[') {
|
||||
let arr: Vec<Json> = serde_json::from_str(&text).map_err(|e| bad("data.getData", e.to_string()))?;
|
||||
let mut keys: Vec<String> = Vec::new();
|
||||
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
for o in &arr {
|
||||
if let Some(m) = o.as_object() {
|
||||
for k in m.keys() {
|
||||
if !seen.contains(k.as_str()) {
|
||||
// Stop collecting at the column limit.
|
||||
if keys.len() >= gridcraft_core::MAX_COLS as usize {
|
||||
return Err(EngineError::Other("The data has more fields than a sheet has columns.".into()));
|
||||
}
|
||||
seen.insert(k.as_str());
|
||||
keys.push(k.clone());
|
||||
}
|
||||
// A JSON array of objects is read as records, unless a separator says the text is delimited.
|
||||
// Any other text, such as a copied range whose first field is `[Draft]`, is delimited.
|
||||
if delimiter.is_none()
|
||||
&& let Some(records) = json_records(&text)
|
||||
{
|
||||
let rows = json_rows(&records)?;
|
||||
return write_json_rows(s, p, at, rows);
|
||||
}
|
||||
// With no separator given (0) the reader picks comma, semicolon or tab by the text. Dates are
|
||||
// read as serials of the workbook they go into.
|
||||
let opts = gridcraft_xlsx::CsvOptions {
|
||||
delimiter: delimiter.unwrap_or(0),
|
||||
date_system: s.doc()?.wb.date_system,
|
||||
max_used_cells: Some(MAX_IMPORT_CELLS),
|
||||
..Default::default()
|
||||
};
|
||||
// The cell limit is enforced while parsing, before an oversized file is stored.
|
||||
let (wb, report) = gridcraft_xlsx::read_csv_with_report(&bytes, &opts).map_err(|e| match e {
|
||||
gridcraft_xlsx::IoError::TooLarge(_) => too_many_cells(),
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
// Pasted at a cell, the text covers every field it has, blank ones included (all of them, for
|
||||
// text like `,`), so they clear what is under them; it must not lose records or fields past a
|
||||
// sheet's last row or column. Imported into a sheet of its own, it is its cells with data.
|
||||
let src = match (at, wb.sheet(0).and_then(|sh| sh.used_range())) {
|
||||
(Some(_), _) if report.truncated => return Err(EngineError::Other("The text has more rows or columns than a sheet has.".into())),
|
||||
(Some(_), _) if report.records > 0 => RangeRef::new(CellRef::new(0, 0), CellRef::new(report.records - 1, report.fields.saturating_sub(1))),
|
||||
(None, Some(used)) => used,
|
||||
_ => return Err(EngineError::Other("The file is empty.".into())),
|
||||
};
|
||||
if src.count() > MAX_IMPORT_CELLS {
|
||||
return Err(too_many_cells());
|
||||
}
|
||||
if let Some((sheet, cell)) = at {
|
||||
let range = write_parsed(s, sheet, cell, &wb, src)?;
|
||||
return pasted(s, sheet, range);
|
||||
}
|
||||
let name = new_sheet(s, p)?;
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
write_parsed(s, sheet, CellRef::new(0, 0), &wb, src)?;
|
||||
Ok(as_table(s, name, src.height(), src.width()))
|
||||
}
|
||||
|
||||
/// The `delimiter` parameter as the byte the CSV reader splits at: one character other than a
|
||||
/// quote or line break. The reader reads the byte back as a character, so U+0001–U+00FF all work.
|
||||
/// `None` without one.
|
||||
fn delimiter_param(p: &Json) -> Result<Option<u8>> {
|
||||
let Some(d) = str_param(p, "delimiter") else { return Ok(None) };
|
||||
let mut chars = d.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(c), None) if !matches!(c, '\0' | '"' | '\r' | '\n') => match u8::try_from(u32::from(c)) {
|
||||
Ok(byte) => Ok(Some(byte)),
|
||||
Err(_) => Err(EngineError::Other(format!("The separator can't be `{c}`: use a character such as , ; or |."))),
|
||||
},
|
||||
_ => Err(EngineError::Other("The separator must be one character, such as , ; or |, and not a quote or line break.".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste Data's `at`: a cell (or a range's top-left cell, as Paste takes a selection) on the sheet
|
||||
/// it names (`'My Sheet'!C5`), else on the active sheet.
|
||||
fn paste_target(s: &Session, p: &Json) -> Result<Option<(usize, CellRef)>> {
|
||||
let t = match p.get("at") {
|
||||
None | Some(Json::Null) => return Ok(None),
|
||||
Some(Json::String(t)) => t,
|
||||
Some(v) => return Err(bad("at", format!("invalid cell reference `{v}`"))),
|
||||
};
|
||||
let wb = &s.doc()?.wb;
|
||||
let (name, body) = crate::cmd::split_sheet(t);
|
||||
let sheet = match name {
|
||||
Some(n) => wb.sheet_index(&n).ok_or_else(|| bad("at", format!("no sheet named `{n}`")))?,
|
||||
None => wb.active_sheet(),
|
||||
};
|
||||
let cell =
|
||||
CellRef::parse(body).or_else(|| RangeRef::parse(body).map(|r| r.start)).ok_or_else(|| bad("at", format!("invalid cell reference `{t}`")))?;
|
||||
Ok(Some((sheet, cell)))
|
||||
}
|
||||
|
||||
fn doesnt_fit() -> EngineError {
|
||||
EngineError::Other("The data doesn't fit on the sheet from that cell.".into())
|
||||
}
|
||||
|
||||
/// The records of text that is a JSON array of objects (`[]` included); `None` for any other
|
||||
/// text, which is read as delimited text.
|
||||
fn json_records(text: &str) -> Option<Vec<Json>> {
|
||||
if !text.trim_start().starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_str::<Vec<Json>>(text).ok().filter(|arr| arr.iter().all(Json::is_object))
|
||||
}
|
||||
|
||||
/// JSON records as rows: a header row of every key, then one row per object.
|
||||
fn json_rows(arr: &[Json]) -> Result<Vec<Vec<Json>>> {
|
||||
let mut keys: Vec<String> = Vec::new();
|
||||
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
for o in arr {
|
||||
if let Some(m) = o.as_object() {
|
||||
for k in m.keys() {
|
||||
if !seen.contains(k.as_str()) {
|
||||
// Stop collecting at the column limit.
|
||||
if keys.len() >= gridcraft_core::MAX_COLS as usize {
|
||||
return Err(EngineError::Other("The data has more fields than a sheet has columns.".into()));
|
||||
}
|
||||
seen.insert(k.as_str());
|
||||
keys.push(k.clone());
|
||||
}
|
||||
}
|
||||
if arr.len() as u64 + 1 > u64::from(gridcraft_core::MAX_ROWS) {
|
||||
return Err(EngineError::Other("The data has more rows than a sheet has.".into()));
|
||||
}
|
||||
if (arr.len() as u64 + 1).saturating_mul(keys.len().max(1) as u64) > MAX_IMPORT_CELLS {
|
||||
return Err(too_many_cells());
|
||||
}
|
||||
let mut out = vec![keys.iter().map(|k| json!(k)).collect::<Vec<_>>()];
|
||||
for o in &arr {
|
||||
out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect());
|
||||
}
|
||||
out
|
||||
} else {
|
||||
let delim = str_param(p, "delimiter")
|
||||
.and_then(|d| d.chars().next())
|
||||
.unwrap_or(if text.lines().next().is_some_and(|l| l.contains('\t')) { '\t' } else { ',' });
|
||||
let opts = gridcraft_xlsx::CsvOptions { delimiter: delim as u8, max_used_cells: Some(MAX_IMPORT_CELLS), ..Default::default() };
|
||||
// The cell limit is enforced while parsing, before an oversized file is stored.
|
||||
let wb = gridcraft_xlsx::read_csv(&bytes, &opts).map_err(|e| match e {
|
||||
gridcraft_xlsx::IoError::TooLarge(_) => too_many_cells(),
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
let sh = wb.sheet(0).ok_or(EngineError::NoDocument)?;
|
||||
let Some(u) = sh.used_range() else { return Err(EngineError::Other("The file is empty.".into())) };
|
||||
if u.count() > MAX_IMPORT_CELLS {
|
||||
return Err(too_many_cells());
|
||||
}
|
||||
(u.start.row..=u.end.row)
|
||||
.map(|r| {
|
||||
(u.start.col..=u.end.col)
|
||||
.map(|c| match sh.value(CellRef::new(r, c)) {
|
||||
Value::Number(n) => json!(n),
|
||||
Value::Bool(b) => json!(b),
|
||||
Value::Empty => Json::Null,
|
||||
v => json!(v.display()),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if rows.is_empty() || rows.len() > 1_048_576 {
|
||||
}
|
||||
}
|
||||
if arr.is_empty() {
|
||||
return Err(EngineError::Other("Nothing to import.".into()));
|
||||
}
|
||||
if arr.len() as u64 + 1 > u64::from(gridcraft_core::MAX_ROWS) {
|
||||
return Err(EngineError::Other("The data has more rows than a sheet has.".into()));
|
||||
}
|
||||
if (arr.len() as u64 + 1).saturating_mul(keys.len().max(1) as u64) > MAX_IMPORT_CELLS {
|
||||
return Err(too_many_cells());
|
||||
}
|
||||
let mut out = vec![keys.iter().map(|k| json!(k)).collect::<Vec<_>>()];
|
||||
for o in arr {
|
||||
out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn write_json_rows(s: &mut Session, p: &Json, at: Option<(usize, CellRef)>, rows: Vec<Vec<Json>>) -> Result<Json> {
|
||||
let h = u32::try_from(rows.len()).map_err(|_| too_many_cells())?;
|
||||
let w = u32::try_from(rows.iter().map(Vec::len).max().unwrap_or(1).max(1)).map_err(|_| too_many_cells())?;
|
||||
if let Some((sheet, cell)) = at {
|
||||
let end = cell.offset(i64::from(h) - 1, i64::from(w) - 1).ok_or_else(doesnt_fit)?;
|
||||
s.execute("range.setValues", json!({"range": cell.a1(), "sheet": sheet, "values": rows}))?;
|
||||
return pasted(s, sheet, RangeRef::new(cell, end));
|
||||
}
|
||||
let name = new_sheet(s, p)?;
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows}))?;
|
||||
Ok(as_table(s, name, h, w))
|
||||
}
|
||||
|
||||
/// Writes the CSV reader's cells in `src` to `sheet` from `at`, as a paste replaces cells: each
|
||||
/// value as the reader typed it, with the number format it gave (a date stays a date, text it
|
||||
/// kept as text stays text), and a blank field clearing its cell. Returns the range written.
|
||||
fn write_parsed(s: &mut Session, sheet: usize, at: CellRef, read: &Workbook, src: RangeRef) -> Result<RangeRef> {
|
||||
let end = at.offset(i64::from(src.height()) - 1, i64::from(src.width()) - 1).ok_or_else(doesnt_fit)?;
|
||||
let from = read.sheet(0).ok_or(EngineError::NoDocument)?;
|
||||
edit(s, |cx| {
|
||||
for c in src.iter() {
|
||||
let dest = CellRef::new(at.row + (c.row - src.start.row), at.col + (c.col - src.start.col));
|
||||
match from.cell(c).filter(|cell| cell.value != Value::Empty) {
|
||||
Some(cell) => {
|
||||
let format = &read.styles.get(cell.style).num_fmt;
|
||||
let mut style = cx.wb.sheet(sheet).map(|sh| sh.style_id(dest)).unwrap_or_default();
|
||||
if format.as_str() != "General" {
|
||||
style = cx.wb.styles.derive(style, |st| st.num_fmt = format.clone());
|
||||
}
|
||||
cx.sheet_mut(sheet)?.set_cell(dest, Cell { value: cell.value.clone(), formula: None, style, py: None });
|
||||
}
|
||||
None => {
|
||||
cx.sheet_mut(sheet)?.remove_cell(dest);
|
||||
}
|
||||
}
|
||||
cx.changed.push((sheet, dest));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(RangeRef::new(at, end))
|
||||
}
|
||||
|
||||
/// After a paste at a cell: its sheet active and the pasted range selected, as Paste leaves them.
|
||||
fn pasted(s: &mut Session, sheet: usize, range: RangeRef) -> Result<Json> {
|
||||
if s.doc()?.wb.active_sheet() != sheet {
|
||||
s.execute("sheet.activate", json!({"sheet": sheet}))?;
|
||||
}
|
||||
s.execute("selection.set", json!({"range": range.a1()}))?;
|
||||
let name = s.doc()?.wb.sheet(sheet).map(|sh| sh.name.clone());
|
||||
Ok(json!({"sheet": name, "range": range.a1(), "rows": range.height(), "cols": range.width()}))
|
||||
}
|
||||
|
||||
/// A new sheet for an import, named by `sheet` or the file's name when that name is free.
|
||||
fn new_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = str_param(p, "sheet").map(str::to_string).or_else(|| {
|
||||
str_param(p, "path").and_then(|x| std::path::Path::new(x).file_stem().and_then(std::ffi::OsStr::to_str).map(|f| f.chars().take(31).collect()))
|
||||
});
|
||||
let r = s.execute("home.insertSheet", json!({"name": name})).or_else(|_| s.execute("home.insertSheet", json!({})))?;
|
||||
let w = rows.iter().map(Vec::len).max().unwrap_or(1).max(1);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows}))?;
|
||||
let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.len() as u32 - 1, w as u32 - 1));
|
||||
Ok(r["name"].clone())
|
||||
}
|
||||
|
||||
/// The imported block at A1 of the new sheet as a table with a header row, its columns fitted.
|
||||
fn as_table(s: &mut Session, name: Json, rows: u32, cols: u32) -> Json {
|
||||
let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(rows.saturating_sub(1), cols.saturating_sub(1)));
|
||||
let _ = s.execute("insert.table", json!({"range": range.a1(), "header": true}));
|
||||
let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, w as u32 - 1).a1()}));
|
||||
Ok(json!({"sheet": r["name"], "rows": rows.len(), "cols": w}))
|
||||
let _ = s.execute("home.autofitColumnWidth", json!({"cols": RangeRef::cols(0, cols.saturating_sub(1)).a1()}));
|
||||
json!({"sheet": name, "rows": rows, "cols": cols})
|
||||
}
|
||||
|
||||
pub(super) fn from_table_range(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
@@ -276,6 +397,94 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_text_keeps_its_place_formats_and_sheet() {
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "old"})).unwrap();
|
||||
// Another sheet is active when the paste aimed at Sheet1 runs.
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
// A separator rules out JSON (`[Draft]` is a field), and the blank first field keeps the
|
||||
// rest one column right of `at`.
|
||||
let text = "\t[Draft]\t2026-01-15\n\t\t15%";
|
||||
s.execute("data.fromTextCsv", json!({"text": text, "delimiter": "\t", "at": "Sheet1!B2"})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert_eq!(sh.name, "Sheet1", "the paste shows its sheet");
|
||||
let at = |a1: &str| CellRef::parse(a1).unwrap();
|
||||
assert_eq!(sh.value(at("B2")), Value::Empty, "a blank field clears what was there");
|
||||
assert_eq!(sh.value(at("C2")), Value::text("[Draft]"));
|
||||
for a1 in ["D2", "D3"] {
|
||||
assert!(matches!(sh.value(at(a1)), Value::Number(_)), "{a1}");
|
||||
assert_ne!(d.wb.styles.get(sh.style_id(at(a1))).num_fmt.as_str(), "General", "{a1} keeps the format the reader gave it");
|
||||
}
|
||||
let other = d.wb.sheet(d.wb.sheet_index("Other").unwrap()).unwrap();
|
||||
assert!(other.used_range().is_none(), "the active sheet at OK is left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_clears_under_trailing_blanks_and_dates_follow_the_workbooks_date_system() {
|
||||
use gridcraft_core::{CellRef, DateSystem, Value};
|
||||
let at = |a1: &str| CellRef::parse(a1).unwrap();
|
||||
let pasted = |system: DateSystem| {
|
||||
let mut s = s();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).date_system = system;
|
||||
s.execute("range.setValues", json!({"range": "B1", "values": [["x", "y"], ["z", "w"]]})).unwrap();
|
||||
// The second field and the second record are blank: they clear C1 and B2:C2.
|
||||
s.execute("data.fromTextCsv", json!({"text": "2026-01-15,\n,\n", "delimiter": ",", "at": "B1"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap().clone();
|
||||
for a1 in ["C1", "B2", "C2"] {
|
||||
assert_eq!(sh.value(at(a1)), Value::Empty, "{a1}");
|
||||
}
|
||||
match sh.value(at("B1")) {
|
||||
Value::Number(n) => n,
|
||||
v => panic!("{v:?}"),
|
||||
}
|
||||
};
|
||||
// The same day is 1,462 serials lower in the 1904 date system.
|
||||
assert_eq!(pasted(DateSystem::D1900) - pasted(DateSystem::D1904), 1462.0);
|
||||
|
||||
// Text of blank fields only clears the cells it covers.
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "B1", "values": [["x", "y", "z"]]})).unwrap();
|
||||
s.execute("data.fromTextCsv", json!({"text": ",", "delimiter": ",", "at": "B1"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!((sh.value(at("B1")), sh.value(at("C1"))), (Value::Empty, Value::Empty));
|
||||
assert_eq!(sh.value(at("D1")), Value::text("z"), "past the text's two fields");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_with_more_records_or_fields_than_a_sheet_has_is_refused() {
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, Value};
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "old"})).unwrap();
|
||||
// One record per line break, so a record past the last row; then a field past the last column.
|
||||
let long = format!("new{}", "\n".repeat(MAX_ROWS as usize + 1));
|
||||
let wide = format!("new{}", ",".repeat(MAX_COLS as usize));
|
||||
for text in [long, wide] {
|
||||
let err = s.execute("data.fromTextCsv", json!({"text": text, "delimiter": ",", "at": "A1"})).expect_err("too large");
|
||||
assert!(err.to_string().contains("more rows or columns"), "{err}");
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("A1").unwrap()), Value::text("old"), "nothing is written");
|
||||
}
|
||||
// A record exactly as wide as the sheet fits.
|
||||
let fits = format!("new{}x", ",".repeat(MAX_COLS as usize - 1));
|
||||
s.execute("data.fromTextCsv", json!({"text": fits, "delimiter": ",", "at": "A1"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::new(0, MAX_COLS - 1)), Value::text("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_separator_is_one_character_the_reader_can_split_at() {
|
||||
let mut s = s();
|
||||
for bad in ["||", "", "\"", "€"] {
|
||||
assert!(s.execute("data.fromTextCsv", json!({"text": "a||b", "delimiter": bad})).is_err(), "{bad:?}");
|
||||
}
|
||||
// Up to U+00FF the reader splits at the character itself.
|
||||
let out = s.execute("data.fromTextCsv", json!({"text": "a§b\n1§2", "delimiter": "§"})).unwrap();
|
||||
assert_eq!(out["cols"].as_u64(), Some(2), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_imports_are_refused_before_their_rows_are_built() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -5,13 +5,16 @@ use serde_json::{Value as Json, json};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param};
|
||||
use crate::{DocState, EngineError};
|
||||
|
||||
mod losses;
|
||||
pub use losses::{SaveLosses, save_losses, xlsx_save_losses};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook),
|
||||
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
|
||||
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
|
||||
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
|
||||
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
|
||||
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension) → {path, bytes, warnings?: what the format could not keep}", has_doc, |s, p| losses::reported(s, "file.save", p, save)),
|
||||
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet) → {path, bytes, warnings?: what the format could not keep}", has_doc, |s, p| losses::reported(s, "file.saveAs", p, save_as)),
|
||||
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64, warnings?: what the format could not keep}", has_doc, |s, p| losses::reported_bytes(s, p, save_bytes)),
|
||||
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool, document?: bool} (closes the active window, or with `document` the workbook and all its windows; the workbook closes with its last window)", has_doc, close),
|
||||
cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?, values?: bool} → {path, bytes}: writes the cells as displayed, like Excel's Save As CSV; `values: true` writes raw values instead (full-precision numbers, ISO 8601 dates and times, TRUE/FALSE)", has_doc, |s, p| export(s, p, "csv")),
|
||||
cmd!(noundo "file.exportHtml", "Save as Web Page", ["File", "Export"], None, "{path}", has_doc, |s, p| export(s, p, "html")),
|
||||
@@ -147,9 +150,8 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return super::print::export_pdf(s, &json!({"path": path}));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
// The document's own file keeps the format its content had when opened; any other path
|
||||
// goes by its extension. Relative paths to linked workbooks are rewritten for the new folder.
|
||||
let kind = crate::io::FileKind::from_path(&path).or(d.content_kind.filter(|_| d.path.as_deref() == Some(path.as_str())));
|
||||
// Relative paths to linked workbooks are rewritten for the new folder.
|
||||
let kind = save_kind(d, &path);
|
||||
let rebased = crate::io::source_dir(&path).and_then(|f| gridcraft_xlsx::rebase_links(&d.wb, &f));
|
||||
let wb = rebased.as_ref().unwrap_or(&d.wb);
|
||||
let bytes = match kind {
|
||||
@@ -182,6 +184,12 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// The format saving `d` at `path` writes: the document's own file keeps the format its content
|
||||
/// had when opened; any other path goes by its extension.
|
||||
fn save_kind(d: &DocState, path: &str) -> Option<crate::io::FileKind> {
|
||||
crate::io::FileKind::from_path(path).or(d.content_kind.filter(|_| d.path.as_deref() == Some(path)))
|
||||
}
|
||||
|
||||
/// Shown when a workbook with a Distinct Count PivotTable value field is saved as .xlsx for the first time (#3336): the
|
||||
/// file stores a plain Count that only GridCraft's private marker turns back into Distinct Count.
|
||||
const DISTINCT_COUNT_NOTICE: &str = "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count.";
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! What saving the workbook would lose: the notice an interactive save asks about first, and the
|
||||
//! `warnings` of a programmatic one.
|
||||
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{Result, Session, str_param};
|
||||
use crate::io::FileKind;
|
||||
|
||||
/// Sheet names a warning spells out before it only counts the rest.
|
||||
const MAX_NAMES: usize = 10;
|
||||
|
||||
/// What a save would lose. Equal when the same sheets lose something, whatever they are called or
|
||||
/// wherever they are, so agreeing to a loss is agreeing to exactly these sheets; the messages name
|
||||
/// only some of them.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SaveLosses {
|
||||
/// The sheets left out of whole-workbook printing: their identity and name, in tab order.
|
||||
excluded: Vec<(u64, String)>,
|
||||
}
|
||||
|
||||
impl PartialEq for SaveLosses {
|
||||
fn eq(&self, other: &SaveLosses) -> bool {
|
||||
let sheets = |l: &SaveLosses| l.excluded.iter().map(|(uid, _)| *uid).collect::<std::collections::BTreeSet<_>>();
|
||||
sheets(self) == sheets(other)
|
||||
}
|
||||
}
|
||||
|
||||
impl SaveLosses {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.excluded.is_empty()
|
||||
}
|
||||
|
||||
/// What to tell the user, one message for each kind of loss.
|
||||
pub fn messages(&self) -> Vec<String> {
|
||||
if self.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let mut list = self.excluded.iter().take(MAX_NAMES).map(|(_, name)| name.as_str()).collect::<Vec<_>>().join(", ");
|
||||
if let Some(more) = self.excluded.len().checked_sub(MAX_NAMES).filter(|n| *n > 0) {
|
||||
list.push_str(&format!(" (and {more} more)"));
|
||||
}
|
||||
vec![format!(
|
||||
"An .xlsx file can't keep that a sheet is left out of whole-workbook printing. Once the file is opened again, these sheets print with the others: {list}. A GridCraft workbook (.json) keeps it."
|
||||
)]
|
||||
}
|
||||
}
|
||||
|
||||
/// What the save command `id` (`file.save`, `file.saveAs`) with these params would lose; nothing
|
||||
/// when the format keeps everything, and when the command would ask for a file first (Save As
|
||||
/// with no path always does, so nothing is known about what it writes). CSV and HTML are copies
|
||||
/// that never become the workbook's file, so only the .xlsx family is asked about.
|
||||
pub fn save_losses(s: &Session, id: &str, p: &Json) -> SaveLosses {
|
||||
let Some(d) = s.active() else { return SaveLosses::default() };
|
||||
let own = d.path.as_deref().filter(|_| id != "file.saveAs");
|
||||
let Some(path) = str_param(p, "path").or(own) else { return SaveLosses::default() };
|
||||
if super::save_kind(d, path) == Some(FileKind::Xlsx) { xlsx_losses(&d.wb) } else { SaveLosses::default() }
|
||||
}
|
||||
|
||||
/// What encoding the active workbook as .xlsx (a download) would lose.
|
||||
pub fn xlsx_save_losses(s: &Session) -> SaveLosses {
|
||||
s.active().map(|d| xlsx_losses(&d.wb)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn xlsx_losses(wb: &gridcraft_model::Workbook) -> SaveLosses {
|
||||
SaveLosses { excluded: wb.sheets.iter().filter(|sh| sh.print.excluded).map(|sh| (sh.uid.get(), sh.name.clone())).collect() }
|
||||
}
|
||||
|
||||
/// Runs a save and adds what it lost to the result as `warnings`. A save with no loss, and one
|
||||
/// that only asked for a file, return what they did before.
|
||||
pub(super) fn reported(s: &mut Session, id: &str, p: &Json, save: fn(&mut Session, &Json) -> Result<Json>) -> Result<Json> {
|
||||
let losses = save_losses(s, id, p);
|
||||
with_warnings(save(s, p)?, losses)
|
||||
}
|
||||
|
||||
/// [`reported`] for `file.saveBytes`, whose format is named instead of a path.
|
||||
pub(super) fn reported_bytes(s: &mut Session, p: &Json, save: fn(&mut Session, &Json) -> Result<Json>) -> Result<Json> {
|
||||
let name = format!("Book.{}", str_param(p, "format").unwrap_or("xlsx"));
|
||||
let losses = if FileKind::from_path(&name) == Some(FileKind::Xlsx) { xlsx_losses(&s.doc()?.wb) } else { SaveLosses::default() };
|
||||
with_warnings(save(s, p)?, losses)
|
||||
}
|
||||
|
||||
fn with_warnings(mut r: Json, losses: SaveLosses) -> Result<Json> {
|
||||
if let Some(o) = r.as_object_mut().filter(|_| !losses.is_empty()) {
|
||||
o.insert("warnings".into(), json!(losses.messages()));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
@@ -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} → the sheet's print settings",
|
||||
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
|
||||
has_doc,
|
||||
page_setup
|
||||
),
|
||||
@@ -390,7 +390,7 @@ fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let fit_page = bool_param(p, "fitToPage");
|
||||
let header = str_param(p, "header").map(|t| t.chars().take(255).collect::<String>());
|
||||
let footer = str_param(p, "footer").map(|t| t.chars().take(255).collect::<String>());
|
||||
let flags = [("centerH", 0usize), ("centerV", 1), ("gridlines", 2), ("headings", 3)].map(|(k, i)| (i, bool_param(p, k)));
|
||||
let flags = [("centerH", 0usize), ("centerV", 1), ("gridlines", 2), ("headings", 3), ("excluded", 4)].map(|(k, i)| (i, bool_param(p, k)));
|
||||
edit(s, |cx| {
|
||||
let pr = &mut cx.sheet_mut(si)?.print;
|
||||
if let Some(o) = orientation {
|
||||
@@ -423,7 +423,8 @@ fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
0 => pr.center_h = v,
|
||||
1 => pr.center_v = v,
|
||||
2 => pr.gridlines = v,
|
||||
_ => pr.headings = v,
|
||||
3 => pr.headings = v,
|
||||
_ => pr.excluded = v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,10 +335,21 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
let mut out = Vec::new();
|
||||
let mut pages = 0usize;
|
||||
let sheets: Vec<usize> = if opts.all_sheets {
|
||||
(0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|s| s.visibility == Visibility::Visible)).collect()
|
||||
let visible: Vec<usize> = (0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|s| s.visibility == Visibility::Visible)).collect();
|
||||
// Sheets left out of workbook printing are skipped, unless that would leave none. A range
|
||||
// given for the active sheet is asked for explicitly, so that sheet prints regardless.
|
||||
if visible.iter().all(|i| wb.sheet(*i).is_some_and(|s| s.print.excluded)) {
|
||||
visible
|
||||
} else {
|
||||
let keep = |i: usize| (i == wb.active_sheet() && !opts.ranges.is_empty()) || wb.sheet(i).is_some_and(|s| !s.print.excluded);
|
||||
visible.into_iter().filter(|i| keep(*i)).collect()
|
||||
}
|
||||
} else {
|
||||
vec![wb.active_sheet()]
|
||||
};
|
||||
// When every sheet is empty, one blank page: the active sheet's if it would print, else the
|
||||
// first sheet that would (never one left out of workbook printing).
|
||||
let fallback = if sheets.contains(&wb.active_sheet()) { wb.active_sheet() } else { sheets.first().copied().unwrap_or(wb.active_sheet()) };
|
||||
for si in sheets {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
@@ -360,7 +371,7 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
}
|
||||
}
|
||||
if out.is_empty() && opts.all_sheets {
|
||||
out.extend(layout_sheet(wb, wb.active_sheet(), opts, None));
|
||||
out.extend(layout_sheet(wb, fallback, opts, None));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1361,6 +1361,97 @@ fn equations_print_with_the_symbol_font() {
|
||||
assert!(contains(&pdf, "(?) Tj"));
|
||||
}
|
||||
|
||||
/// Printing the workbook leaves out sheets marked not to print, unless every sheet is.
|
||||
#[test]
|
||||
fn workbook_printing_skips_excluded_sheets() {
|
||||
use gridcraft_core::Value;
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
wb.sheets.clear();
|
||||
for name in ["One", "Two"] {
|
||||
let mut sh = gridcraft_model::Sheet::new(name);
|
||||
sh.set_value(CellRef::new(0, 0), Value::Text(name.into()));
|
||||
wb.sheets.push(std::sync::Arc::new(sh));
|
||||
}
|
||||
let all = super::layout::PrintOptions { all_sheets: true, ..Default::default() };
|
||||
let printed = |wb: &gridcraft_model::Workbook| super::layout::layouts(wb, &all).iter().map(|l| l.sheet).collect::<Vec<_>>();
|
||||
assert_eq!(printed(&wb), vec![0, 1]);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).print.excluded = true;
|
||||
assert_eq!(printed(&wb), vec![1]);
|
||||
// Printing the active sheet alone still prints it.
|
||||
let active = super::layout::PrintOptions::default();
|
||||
assert_eq!(super::layout::layouts(&wb, &active).iter().map(|l| l.sheet).collect::<Vec<_>>(), vec![0]);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[1]).print.excluded = true;
|
||||
assert_eq!(printed(&wb), vec![0, 1]);
|
||||
}
|
||||
|
||||
/// Page Setup's `excluded` marks the sheet; whole-workbook PDF export then skips it.
|
||||
#[test]
|
||||
fn page_setup_excluded_leaves_the_sheet_out_of_workbook_export() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "one"})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "two"})).unwrap();
|
||||
let (_, both) = pdf_of(&mut s, json!({"sheets": "all"}));
|
||||
assert_eq!(both, 2);
|
||||
assert!(s.execute("pageLayout.pageSetup", json!({})).unwrap().get("excluded").is_none());
|
||||
let r = s.execute("pageLayout.pageSetup", json!({"sheet": "Two", "excluded": true})).unwrap();
|
||||
assert_eq!(r["excluded"], true);
|
||||
let (pdf, one) = pdf_of(&mut s, json!({"sheets": "all"}));
|
||||
assert_eq!(one, 1);
|
||||
assert!(contains(&pdf, "(one) Tj") && !contains(&pdf, "(two) Tj"));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(pdf_of(&mut s, json!({"sheets": "all"})).1, 2);
|
||||
}
|
||||
|
||||
/// Workbook printing never falls back to an excluded sheet when every other sheet is empty, and a
|
||||
/// range given for an excluded active sheet still prints.
|
||||
#[test]
|
||||
fn excluded_active_sheet_is_not_the_empty_fallback_but_prints_an_explicit_range() {
|
||||
use gridcraft_core::Value;
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
wb.sheets.clear();
|
||||
let mut one = gridcraft_model::Sheet::new("One");
|
||||
one.set_value(CellRef::new(0, 0), Value::Text("One".into()));
|
||||
one.print.excluded = true;
|
||||
wb.sheets.push(std::sync::Arc::new(one));
|
||||
wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Two")));
|
||||
assert_eq!(wb.active_sheet(), 0);
|
||||
let sheets_of = |opts: &super::layout::PrintOptions| super::layout::layouts(&wb, opts).iter().map(|l| l.sheet).collect::<Vec<_>>();
|
||||
// One is excluded, Two is blank: Two's blank page, not One.
|
||||
let all = super::layout::PrintOptions { all_sheets: true, ..Default::default() };
|
||||
assert_eq!(sheets_of(&all), vec![1]);
|
||||
// An explicit range for the (excluded) active sheet prints it.
|
||||
let ranged = super::layout::PrintOptions {
|
||||
all_sheets: true,
|
||||
ranges: gridcraft_core::RangeRef::parse("A1:B2").into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let lays = super::layout::layouts(&wb, &ranged);
|
||||
assert_eq!(lays.iter().map(|l| (l.sheet, l.area)).collect::<Vec<_>>(), vec![(0, gridcraft_core::RangeRef::parse("A1:B2").unwrap())]);
|
||||
}
|
||||
|
||||
/// When every visible sheet is excluded they all print, with or without a range for the active one.
|
||||
#[test]
|
||||
fn every_sheet_excluded_prints_them_all_also_with_a_range() {
|
||||
use gridcraft_core::Value;
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
wb.sheets.clear();
|
||||
for name in ["One", "Two"] {
|
||||
let mut sh = gridcraft_model::Sheet::new(name);
|
||||
sh.set_value(CellRef::new(0, 0), Value::Text(name.into()));
|
||||
sh.print.excluded = true;
|
||||
wb.sheets.push(std::sync::Arc::new(sh));
|
||||
}
|
||||
let sheets_of = |opts: &super::layout::PrintOptions| super::layout::layouts(&wb, opts).iter().map(|l| l.sheet).collect::<Vec<_>>();
|
||||
assert_eq!(sheets_of(&super::layout::PrintOptions { all_sheets: true, ..Default::default() }), vec![0, 1]);
|
||||
let ranged = super::layout::PrintOptions {
|
||||
all_sheets: true,
|
||||
ranges: gridcraft_core::RangeRef::parse("A1:B2").into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(sheets_of(&ranged), vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
|
||||
use gridcraft_chart::Prim;
|
||||
@@ -1387,6 +1478,43 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
|
||||
assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1)));
|
||||
}
|
||||
|
||||
/// Saving as .xlsx, which can't hold the `excluded` mark, says so in the result; the format that
|
||||
/// keeps it, a plain copy, and a workbook without the mark save quietly.
|
||||
#[test]
|
||||
fn saving_reports_an_excluded_mark_the_format_drops() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-save-losses-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |name: &str| dir.join(name).to_string_lossy().into_owned();
|
||||
let excluded = |path: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", json!({"path": path})).unwrap();
|
||||
s.doc().unwrap().wb.sheets.iter().any(|sh| sh.print.excluded)
|
||||
};
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "one"})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
for r in [s.execute("file.saveAs", json!({"path": at("plain.xlsx")})), s.execute("file.save", json!({})), s.execute("file.saveBytes", json!({}))]
|
||||
{
|
||||
assert!(r.unwrap().get("warnings").is_none(), "nothing is lost");
|
||||
}
|
||||
s.execute("pageLayout.pageSetup", json!({"sheet": "Two", "excluded": true})).unwrap();
|
||||
let saved = s.execute("file.save", json!({})).unwrap();
|
||||
assert!(saved["warnings"][0].as_str().is_some_and(|w| w.contains("Two")), "{saved}");
|
||||
assert!(!excluded(&at("plain.xlsx")), "the mark is gone once the file is reopened");
|
||||
for r in [
|
||||
s.execute("file.saveAs", json!({"path": at("marked.xlsm")})),
|
||||
s.execute("file.saveBytes", json!({"format": "xlsx"})),
|
||||
s.execute_headless("file.save", json!({"path": at("headless.xlsx")})),
|
||||
] {
|
||||
assert!(r.unwrap()["warnings"][0].as_str().is_some_and(|w| w.contains("Two")));
|
||||
}
|
||||
assert!(s.take_ui_requests().is_empty(), "a programmatic save never asks");
|
||||
assert!(s.execute("file.saveAs", json!({"path": at("copy.csv")})).unwrap().get("warnings").is_none());
|
||||
assert!(s.execute("file.saveAs", json!({"path": at("kept.json")})).unwrap().get("warnings").is_none());
|
||||
assert!(excluded(&at("kept.json")), "GridCraft's own format keeps it");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn preview_ranges(s: &mut Session, p: Json) -> Vec<String> {
|
||||
let r = s.execute("file.printPreview", p).unwrap();
|
||||
r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect()
|
||||
|
||||
+10
-1
@@ -324,10 +324,13 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
|
||||
let mut wb: Workbook = craft_gridcraft_format::read(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
wb.styles.rebuild_index();
|
||||
if wb.sheets.is_empty() {
|
||||
// The file's macros are read after this (`macros::load`), so they come along.
|
||||
// The file's macros are read after this (`macros::load`), so they come along, and
|
||||
// so do its text defaults: a save would otherwise lose them.
|
||||
let macros = std::mem::take(&mut wb.macros_read);
|
||||
let text_defaults = std::mem::take(&mut wb.text_defaults);
|
||||
wb = Workbook::new();
|
||||
wb.macros_read = macros;
|
||||
wb.text_defaults = text_defaults;
|
||||
}
|
||||
// The file's band placement and cell count are derived state: rebuild them from the
|
||||
// cells themselves, dropping what is outside the sheet grid (#1008).
|
||||
@@ -1193,3 +1196,9 @@ pub fn image_size(data: &[u8]) -> Option<(u32, u32)> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The separator delimited text uses: comma, semicolon or tab, picked as the CSV reader picks it
|
||||
/// when none is given (consistent field counts over its first records; comma when none fits).
|
||||
pub fn guess_separator(text: &str) -> char {
|
||||
char::from(craft_csv::sniff_delimiter(text, '"'))
|
||||
}
|
||||
|
||||
@@ -1100,3 +1100,25 @@ fn the_merge_index_holds_a_bounded_number_of_cells() {
|
||||
sh.merges = vec![RangeRef::new(CellRef::new(0, 0), CellRef::new(1_000_000, 0))];
|
||||
assert!(merge_index(&sh, rect).is_none());
|
||||
}
|
||||
|
||||
#[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
|
||||
// new workbook carries the text defaults across with the macros.
|
||||
let mut saved = Workbook::new();
|
||||
saved.text_defaults.asian = gridcraft_model::ScriptDefault {
|
||||
language: Some("ja".into()),
|
||||
country: Some("JP".into()),
|
||||
font: Some("Noto Sans CJK JP".into()),
|
||||
..Default::default()
|
||||
};
|
||||
saved.macros.push(gridcraft_model::Macro { name: "Totals".into(), ..Default::default() });
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&save_bytes(&saved, "book.json")?)?;
|
||||
v["sheets"] = serde_json::json!([]);
|
||||
let (wb, warnings) = open_bytes("book.json", v.to_string().as_bytes())?;
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(!wb.sheets.is_empty(), "a workbook without sheets opens as a new one");
|
||||
assert_eq!(wb.text_defaults, saved.text_defaults);
|
||||
assert_eq!(wb.macros, saved.macros);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ use gridcraft_core::CellError;
|
||||
|
||||
use crate::ast::TrimMode;
|
||||
|
||||
/// A formula token. More kinds may be added (another syntax's tokenizer can need one), so a
|
||||
/// match outside this crate keeps a catch-all arm.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Tok {
|
||||
Number(f64),
|
||||
Text(String),
|
||||
@@ -31,6 +34,9 @@ pub enum Tok {
|
||||
Colon,
|
||||
/// Trim reference range operator `.:`, `:.` or `.:.`.
|
||||
Trim(TrimMode),
|
||||
/// A reference another syntax's tokenizer has already read (OpenFormula's `[.A1:.B2]`). The
|
||||
/// A1 tokenizer never produces it.
|
||||
Ref(crate::ast::Reference),
|
||||
Space,
|
||||
Eof,
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ pub mod printer;
|
||||
|
||||
pub use ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, TrimMode, UnOp};
|
||||
pub use input::{FormulaLocale, parse_input, print_input};
|
||||
pub use parser::{MAX_FORMULA_LEN, ParseError, normalize_function_name, parse, parse_closing_parens, parse_name};
|
||||
pub use printer::{print, print_r1c1, quote_sheet};
|
||||
pub use parser::{MAX_FORMULA_LEN, ParseError, normalize_function_name, parse, parse_closing_parens, parse_name, parse_tokens};
|
||||
pub use printer::{Dialect, print, print_r1c1, print_with, quote_sheet};
|
||||
|
||||
/// Whether two LET/LAMBDA names are the same: case-insensitive in any script, as in Excel
|
||||
/// (`dług` = `DŁUG`, `ß` = `ẞ`). Close to Unicode's default case folding: lower case, plus the
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_core::addr::{letters_to_col, parse_a1_prefix};
|
||||
use gridcraft_core::{CellError, MAX_ROWS};
|
||||
use gridcraft_core::{CellError, MAX_COLS, MAX_ROWS};
|
||||
|
||||
use crate::ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, TrimMode, UnOp};
|
||||
use crate::lexer::{Tok, Token, tokenize_locale};
|
||||
@@ -55,6 +55,131 @@ pub fn parse_closing_parens<T>(src: &str, parse: impl Fn(&str) -> Result<T, Pars
|
||||
Err(typed)
|
||||
}
|
||||
|
||||
/// Parses tokens another syntax's tokenizer produced (OpenFormula, say) with this grammar, so a
|
||||
/// caller with its own lexer builds the same [`Expr`]. A [`Tok::Space`] is the intersection
|
||||
/// operator where it stands between the end of one operand and the start of another; anywhere
|
||||
/// else it is dropped, as the text parser drops it. A [`Tok::Ref`] is a reference the tokenizer
|
||||
/// has already read; it must lie on the grid (rows and columns within Excel's limits) or the
|
||||
/// tokens are refused. Its ends are kept in the order given, as the text parser keeps `B2:A1`.
|
||||
/// The token list need not end with [`Tok::Eof`]; one anywhere else is an error.
|
||||
///
|
||||
/// The tokens are bounded as text is: at most [`MAX_FORMULA_LEN`] tokens, at most
|
||||
/// [`MAX_FORMULA_LEN`] characters of text, names, sheet names and structured-reference bodies
|
||||
/// in all, and the same nesting limits. Every token must print as text that parses back to the
|
||||
/// same tree, so these are refused: a number that is negative (a minus is [`Tok::Op`]) or not
|
||||
/// finite; a sheet name that is empty or holds `:`; a [`Tok::Word`] or [`Tok::Func`] the A1
|
||||
/// tokenizer would not read from its text (an empty one, `A!1`, or a row number such as the `1`
|
||||
/// of `1:3`: pass rows as a [`Tok::Ref`]); a word directly before `(`; [`Tok::Trim`], which
|
||||
/// only Excel's syntax has; and any other tree whose printed text reads back differently (an
|
||||
/// operand next to `:` that would regroup or read as rows: put it in parentheses). A number
|
||||
/// longer than the 15 significant digits text keeps is accepted as it is. The printed text is
|
||||
/// bounded as typed text is, so a string that only fits without its quotes is refused.
|
||||
///
|
||||
/// Only this grammar's operators are read: OpenFormula's `~` union is not handled here, so a
|
||||
/// tokenizer for that syntax translates it itself.
|
||||
pub fn parse_tokens(toks: Vec<Token>) -> Result<Expr, ParseError> {
|
||||
if toks.len() > MAX_FORMULA_LEN {
|
||||
return Err(ParseError { msg: format!("formula has more than {MAX_FORMULA_LEN} tokens"), pos: 0 });
|
||||
}
|
||||
let mut chars = 0usize;
|
||||
for t in &toks {
|
||||
chars = chars.saturating_add(token_chars(&t.tok));
|
||||
if chars > MAX_FORMULA_LEN {
|
||||
return Err(ParseError { msg: format!("formula is longer than {MAX_FORMULA_LEN} characters"), pos: t.start });
|
||||
}
|
||||
let bad = match &t.tok {
|
||||
Tok::Ref(r) if !reference_on_grid(r) => Some("reference is outside the sheet"),
|
||||
Tok::Ref(Reference { sheet: SheetSel::Named(a), .. }) if !sheet_name_ok(a) => Some(BAD_SHEET),
|
||||
Tok::Ref(Reference { sheet: SheetSel::Span(a, b), .. }) if !sheet_name_ok(a) || !sheet_name_ok(b) => Some(BAD_SHEET),
|
||||
Tok::Sheet(a, b) if !sheet_name_ok(a) || b.as_deref().is_some_and(|b| !sheet_name_ok(b)) => Some(BAD_SHEET),
|
||||
Tok::Number(n) if !n.is_finite() => Some("number too large"),
|
||||
// `-1` prints as text that reads back as negation of 1, a different tree.
|
||||
Tok::Number(n) if n.is_sign_negative() => Some("negative number (a minus is an operator)"),
|
||||
Tok::Trim(_) => Some("trim range operator"),
|
||||
Tok::Word(w) if !lexes_as(w, &t.tok) => Some("not a name or reference"),
|
||||
Tok::Func(f) if !lexes_as(&format!("{f}("), &t.tok) => Some("not a function name"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(msg) = bad {
|
||||
return Err(ParseError { msg: msg.into(), pos: t.start });
|
||||
}
|
||||
}
|
||||
// The end token may only close the list: anything after it would be dropped unread.
|
||||
if let Some(i) = toks.iter().position(|t| t.tok == Tok::Eof)
|
||||
&& i + 1 < toks.len()
|
||||
{
|
||||
return Err(ParseError { msg: "tokens after the end of the formula".into(), pos: toks.get(i + 1).map_or(0, |t| t.start) });
|
||||
}
|
||||
// A name before `(` is a function name to the A1 tokenizer, so `Word` + `(` has no text form.
|
||||
if let Some(w) = toks.windows(2).find(|w| matches!(w, [a, b] if matches!(a.tok, Tok::Word(_)) && b.tok == Tok::LParen)) {
|
||||
return Err(ParseError { msg: "name directly before `(`".into(), pos: w.first().map_or(0, |t| t.start) });
|
||||
}
|
||||
let toks = significant_spaces(toks);
|
||||
let mut p = Parser { toks, i: 0, depth: 0, input: false };
|
||||
let e = p.expr(0, false)?;
|
||||
let e = finish(&mut p, e)?;
|
||||
prints_back(e)
|
||||
}
|
||||
|
||||
/// Refuses a tree whose printed text reads back as a different tree. The checks above refuse
|
||||
/// the token shapes known to have no text form with a precise message; this catches the rest
|
||||
/// (an operand next to `:` that regroups, such as `A1` `:` `B2:C3` printed as `A1:B2:C3`, or
|
||||
/// numbers either side of `:` read back as rows). A number is compared as it prints: text keeps
|
||||
/// 15 significant digits, so a longer literal still reads back as the same formula.
|
||||
fn prints_back(e: Expr) -> Result<Expr, ParseError> {
|
||||
let as_printed = e.clone().map(&mut |n| match n {
|
||||
Expr::Number(v) => Expr::Number(crate::printer::number(v).parse().unwrap_or(v)),
|
||||
other => other,
|
||||
});
|
||||
match parse_syntax(&crate::printer::print(&e), crate::FormulaLocale::En) {
|
||||
Ok(back) if back == as_printed => Ok(e),
|
||||
_ => Err(ParseError { msg: "tokens with no formula text that reads back the same".into(), pos: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
const BAD_SHEET: &str = "sheet name empty or holding `:`";
|
||||
|
||||
/// A sheet name prints as text that reads back as the same name: not empty, and no `:`, which
|
||||
/// would read back as a span of sheets.
|
||||
fn sheet_name_ok(name: &str) -> bool {
|
||||
!name.is_empty() && !name.contains(':')
|
||||
}
|
||||
|
||||
/// The characters of text a token carries (its strings and sheet names).
|
||||
fn token_chars(t: &Tok) -> usize {
|
||||
let sheet = |s: &SheetSel| match s {
|
||||
SheetSel::Current => 0,
|
||||
SheetSel::Named(n) => n.chars().count(),
|
||||
SheetSel::Span(a, b) => a.chars().count().saturating_add(b.chars().count()),
|
||||
};
|
||||
match t {
|
||||
Tok::Text(s) | Tok::Word(s) | Tok::Func(s) | Tok::Struct(s) => s.chars().count(),
|
||||
Tok::Sheet(a, b) => a.chars().count().saturating_add(b.as_deref().map_or(0, |b| b.chars().count())),
|
||||
Tok::Ref(r) => sheet(&r.sheet),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the A1 tokenizer reads `src` as exactly the one token `tok`: a word or function name
|
||||
/// from another tokenizer must print as text that parses back to it.
|
||||
fn lexes_as(src: &str, tok: &Tok) -> bool {
|
||||
match tokenize_locale(src, crate::FormulaLocale::En) {
|
||||
Ok(toks) => matches!(toks.as_slice(), [only] | [only, Token { tok: Tok::Eof, .. }] if only.tok == *tok),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every row and column a reference names is on the grid.
|
||||
fn reference_on_grid(r: &Reference) -> bool {
|
||||
let anchor = |a: &Anchor| a.row < MAX_ROWS && a.col < MAX_COLS;
|
||||
match &r.kind {
|
||||
RefKind::Cell(a) => anchor(a),
|
||||
RefKind::Range(a, b) => anchor(a) && anchor(b),
|
||||
RefKind::Rows(r0, _, r1, _) => *r0 < MAX_ROWS && *r1 < MAX_ROWS,
|
||||
RefKind::Cols(c0, _, c1, _) => *c0 < MAX_COLS && *c1 < MAX_COLS,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_syntax(src: &str, locale: crate::FormulaLocale) -> Result<Expr, ParseError> {
|
||||
parse_top(src, locale, false)
|
||||
}
|
||||
@@ -68,6 +193,11 @@ fn parse_top(src: &str, locale: crate::FormulaLocale, allow_union: bool) -> Resu
|
||||
let toks = significant_spaces(toks);
|
||||
let mut p = Parser { toks, i: 0, depth: 0, input: locale == crate::FormulaLocale::Es };
|
||||
let e = p.expr(0, allow_union)?;
|
||||
finish(&mut p, e)
|
||||
}
|
||||
|
||||
/// Checks that the parser stopped at the end and that `e` is not nested too deeply as a whole.
|
||||
fn finish(p: &mut Parser, e: Expr) -> Result<Expr, ParseError> {
|
||||
match p.peek() {
|
||||
Tok::Eof if wrapper_height(&e) > MAX_DEPTH => Err(ParseError { msg: "formula is nested too deeply".into(), pos: 0 }),
|
||||
Tok::Eof => Ok(e),
|
||||
@@ -113,9 +243,11 @@ fn significant_spaces(toks: Vec<Token>) -> Vec<Token> {
|
||||
let mut out: Vec<Token> = Vec::with_capacity(toks.len());
|
||||
for (i, t) in toks.iter().enumerate() {
|
||||
if t.tok == Tok::Space {
|
||||
let prev_end = out.last().is_some_and(|p| matches!(p.tok, Tok::Word(_) | Tok::RParen | Tok::Struct(_) | Tok::Error(_)));
|
||||
let next_start =
|
||||
toks.get(i + 1).is_some_and(|n| matches!(n.tok, Tok::Word(_) | Tok::Sheet(..) | Tok::LParen | Tok::Func(_) | Tok::Error(_)));
|
||||
// `Tok::Ref` only comes from another syntax's tokenizer (see `parse_tokens`).
|
||||
let prev_end = out.last().is_some_and(|p| matches!(p.tok, Tok::Word(_) | Tok::RParen | Tok::Struct(_) | Tok::Error(_) | Tok::Ref(_)));
|
||||
let next_start = toks
|
||||
.get(i + 1)
|
||||
.is_some_and(|n| matches!(n.tok, Tok::Word(_) | Tok::Sheet(..) | Tok::LParen | Tok::Func(_) | Tok::Error(_) | Tok::Ref(_)));
|
||||
if prev_end && next_start {
|
||||
out.push(t.clone());
|
||||
}
|
||||
@@ -307,6 +439,7 @@ impl Parser {
|
||||
Tok::Text(s) => Ok(Expr::Text(Arc::from(s))),
|
||||
Tok::Bool(b) => Ok(Expr::Bool(b)),
|
||||
Tok::Error(e) => Ok(Expr::Error(e)),
|
||||
Tok::Ref(r) => Ok(Expr::Ref(r)),
|
||||
Tok::Op("-") => Ok(Expr::Unary(UnOp::Neg, Box::new(self.expr(60, allow_union)?))),
|
||||
Tok::Op("+") => Ok(Expr::Unary(UnOp::Plus, Box::new(self.expr(60, allow_union)?))),
|
||||
Tok::Op("@") => Ok(Expr::Unary(UnOp::At, Box::new(self.expr(95, allow_union)?))),
|
||||
|
||||
+144
-87
@@ -1,5 +1,6 @@
|
||||
//! [`Expr`] → formula text (without `=`), A1 or R1C1.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write;
|
||||
|
||||
use gridcraft_core::{CellRef, number_to_text};
|
||||
@@ -47,6 +48,7 @@ fn push_col(s: &mut String, col: u32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference in A1 notation.
|
||||
pub fn reference_a1(r: &Reference) -> String {
|
||||
range_a1(r, ":")
|
||||
}
|
||||
@@ -202,7 +204,7 @@ fn write_struct_ref(s: &StructRef, at_shorthand: bool) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn number(n: f64) -> String {
|
||||
pub(crate) fn number(n: f64) -> String {
|
||||
let text = number_to_text(n);
|
||||
// 15 significant digits can round past f64::MAX, which no longer parses.
|
||||
if text.parse::<f64>().is_ok_and(f64::is_finite) {
|
||||
@@ -215,21 +217,92 @@ fn number(n: f64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a syntax spells what the printer writes. Every method defaults to Excel's A1 notation,
|
||||
/// so a syntax states only where it differs ([`print_with`]).
|
||||
pub trait Dialect {
|
||||
/// A reference, with `sep` between its two ends (`:`, or a trim operator).
|
||||
fn reference(&self, s: &mut String, r: &Reference, sep: &str) {
|
||||
push_range_a1(s, r, sep);
|
||||
}
|
||||
/// A defined name, possibly sheet-qualified (`Sheet2!Total`).
|
||||
fn name(&self, s: &mut String, n: &str) {
|
||||
match sheet_split(n) {
|
||||
// A sheet-qualified name is stored with the bare sheet name (`My Sheet!Total`): quote
|
||||
// it so it parses back.
|
||||
Some((sheet, name)) => {
|
||||
s.push_str("e_sheet(sheet));
|
||||
s.push('!');
|
||||
s.push_str(name);
|
||||
}
|
||||
_ => s.push_str(n),
|
||||
}
|
||||
}
|
||||
/// A structured reference (`Table1[Col]`).
|
||||
fn struct_ref(&self, s: &mut String, st: &StructRef) {
|
||||
s.push_str(&struct_ref(st));
|
||||
}
|
||||
/// A function's name as this syntax calls it.
|
||||
fn function<'a>(&self, name: &'a str) -> Cow<'a, str> {
|
||||
Cow::Borrowed(name)
|
||||
}
|
||||
/// A logical constant (`TRUE`, `FALSE`).
|
||||
fn boolean(&self, b: bool) -> &'static str {
|
||||
if b { "TRUE" } else { "FALSE" }
|
||||
}
|
||||
/// The separators between a call's arguments, between an inline array's columns, and between
|
||||
/// its rows (`,` `,` `;` in A1).
|
||||
fn separators(&self) -> (char, char, char) {
|
||||
(',', ',', ';')
|
||||
}
|
||||
/// A binary operator's symbol (`+`, `&`, `:`, a space for the intersection, ...).
|
||||
fn operator(&self, op: BinOp) -> &'static str {
|
||||
op.symbol()
|
||||
}
|
||||
/// The function written for a unary operator the syntax has no symbol for (`@`, `#`, a trim
|
||||
/// reference), taking the operand (and, for a trim, its mode twice).
|
||||
fn unary_call(&self, _op: UnOp) -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
struct A1;
|
||||
impl Dialect for A1 {}
|
||||
|
||||
struct R1C1(CellRef);
|
||||
impl Dialect for R1C1 {
|
||||
fn reference(&self, s: &mut String, r: &Reference, sep: &str) {
|
||||
s.push_str(&range_r1c1(r, self.0, sep));
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints an expression in A1 notation.
|
||||
pub fn print(e: &Expr) -> String {
|
||||
let mut s = String::new();
|
||||
write_expr(&mut s, e, None);
|
||||
s
|
||||
print_with(e, &A1)
|
||||
}
|
||||
|
||||
/// Prints an expression in R1C1 notation relative to `at`.
|
||||
pub fn print_r1c1(e: &Expr, at: CellRef) -> String {
|
||||
print_with(e, &R1C1(at))
|
||||
}
|
||||
|
||||
/// Prints an expression in another syntax.
|
||||
pub fn print_with(e: &Expr, d: &dyn Dialect) -> String {
|
||||
let mut s = String::new();
|
||||
write_expr(&mut s, e, Some(at));
|
||||
write_expr(&mut s, e, d);
|
||||
s
|
||||
}
|
||||
|
||||
fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
|
||||
fn write_list<'e>(s: &mut String, items: impl IntoIterator<Item = &'e Expr>, sep: char, d: &dyn Dialect) {
|
||||
for (i, a) in items.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.push(sep);
|
||||
}
|
||||
write_expr(s, a, d);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_expr(s: &mut String, e: &Expr, d: &dyn Dialect) {
|
||||
let (arg_sep, col_sep, row_sep) = d.separators();
|
||||
match e {
|
||||
Expr::Number(n) => s.push_str(&number(*n)),
|
||||
Expr::Text(t) => {
|
||||
@@ -237,81 +310,75 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
|
||||
s.push_str(&t.replace('"', "\"\""));
|
||||
s.push('"');
|
||||
}
|
||||
Expr::Bool(b) => s.push_str(if *b { "TRUE" } else { "FALSE" }),
|
||||
Expr::Bool(b) => s.push_str(d.boolean(*b)),
|
||||
Expr::Error(err) => s.push_str(err.as_str()),
|
||||
Expr::Array(rows) => {
|
||||
s.push('{');
|
||||
for (ri, row) in rows.iter().enumerate() {
|
||||
if ri > 0 {
|
||||
s.push(';');
|
||||
}
|
||||
for (ci, el) in row.iter().enumerate() {
|
||||
if ci > 0 {
|
||||
s.push(',');
|
||||
}
|
||||
write_expr(s, el, r1c1);
|
||||
s.push(row_sep);
|
||||
}
|
||||
write_list(s, row, col_sep, d);
|
||||
}
|
||||
s.push('}');
|
||||
}
|
||||
Expr::Ref(r) => match r1c1 {
|
||||
Some(at) => s.push_str(&reference_r1c1(r, at)),
|
||||
None => push_range_a1(s, r, ":"),
|
||||
},
|
||||
Expr::Name(n) => match sheet_split(n) {
|
||||
// A sheet-qualified name is stored with the bare sheet name (`My Sheet!Total`): quote it so it parses back.
|
||||
Some((sheet, name)) => {
|
||||
s.push_str("e_sheet(sheet));
|
||||
s.push('!');
|
||||
s.push_str(name);
|
||||
}
|
||||
_ => s.push_str(n),
|
||||
},
|
||||
Expr::Struct(st) => s.push_str(&struct_ref(st)),
|
||||
Expr::Unary(op, x) => match op {
|
||||
UnOp::Neg => {
|
||||
s.push('-');
|
||||
write_expr(s, x, r1c1);
|
||||
}
|
||||
UnOp::Plus => {
|
||||
s.push('+');
|
||||
write_expr(s, x, r1c1);
|
||||
}
|
||||
UnOp::At => {
|
||||
s.push('@');
|
||||
write_expr(s, x, r1c1);
|
||||
}
|
||||
UnOp::Percent => {
|
||||
write_expr(s, x, r1c1);
|
||||
s.push('%');
|
||||
}
|
||||
UnOp::Spill => {
|
||||
write_expr(s, x, r1c1);
|
||||
// A reference that became #REF! (its sheet or cell was deleted) stays `#REF!`.
|
||||
if !matches!(**x, Expr::Error(_)) {
|
||||
s.push('#');
|
||||
Expr::Ref(r) => d.reference(s, r, ":"),
|
||||
Expr::Name(n) => d.name(s, n),
|
||||
Expr::Struct(st) => d.struct_ref(s, st),
|
||||
Expr::Unary(op, x) => {
|
||||
if let Some(f) = d.unary_call(*op) {
|
||||
s.push_str(f);
|
||||
s.push('(');
|
||||
write_expr(s, x, d);
|
||||
if let UnOp::Trim(mode) = op {
|
||||
let _ = write!(s, "{arg_sep}{0}{arg_sep}{0}", mode.code());
|
||||
}
|
||||
s.push(')');
|
||||
return;
|
||||
}
|
||||
UnOp::Trim(mode) => match &**x {
|
||||
Expr::Ref(r) if !matches!(r.kind, RefKind::Cell(_)) => match r1c1 {
|
||||
Some(at) => s.push_str(&range_r1c1(r, at, mode.symbol())),
|
||||
None => push_range_a1(s, r, mode.symbol()),
|
||||
match op {
|
||||
UnOp::Neg => {
|
||||
s.push('-');
|
||||
write_expr(s, x, d);
|
||||
}
|
||||
UnOp::Plus => {
|
||||
s.push('+');
|
||||
write_expr(s, x, d);
|
||||
}
|
||||
UnOp::At => {
|
||||
s.push('@');
|
||||
write_expr(s, x, d);
|
||||
}
|
||||
UnOp::Percent => {
|
||||
write_expr(s, x, d);
|
||||
s.push('%');
|
||||
}
|
||||
UnOp::Spill => {
|
||||
write_expr(s, x, d);
|
||||
// A reference that became #REF! (its sheet or cell was deleted) stays `#REF!`.
|
||||
if !matches!(**x, Expr::Error(_)) {
|
||||
s.push('#');
|
||||
}
|
||||
}
|
||||
UnOp::Trim(mode) => match &**x {
|
||||
Expr::Ref(r) if !matches!(r.kind, RefKind::Cell(_)) => d.reference(s, r, mode.symbol()),
|
||||
Expr::Binary(BinOp::Range, a, b) => {
|
||||
write_expr(s, a, d);
|
||||
s.push_str(mode.symbol());
|
||||
write_expr(s, b, d);
|
||||
}
|
||||
// A reference that became #REF! stays `#REF!`.
|
||||
Expr::Error(_) => write_expr(s, x, d),
|
||||
// No operator form (e.g. a range shrunk to one cell): the equivalent call.
|
||||
other => {
|
||||
s.push_str(&d.function("TRIMRANGE"));
|
||||
s.push('(');
|
||||
write_expr(s, other, d);
|
||||
let _ = write!(s, "{arg_sep}{0}{arg_sep}{0})", mode.code());
|
||||
}
|
||||
},
|
||||
Expr::Binary(BinOp::Range, a, b) => {
|
||||
write_expr(s, a, r1c1);
|
||||
s.push_str(mode.symbol());
|
||||
write_expr(s, b, r1c1);
|
||||
}
|
||||
// A reference that became #REF! stays `#REF!`.
|
||||
Expr::Error(_) => write_expr(s, x, r1c1),
|
||||
// No operator form (e.g. a range shrunk to one cell): the equivalent call.
|
||||
other => {
|
||||
s.push_str("TRIMRANGE(");
|
||||
write_expr(s, other, r1c1);
|
||||
let _ = write!(s, ",{0},{0})", mode.code());
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
Expr::Binary(..) => {
|
||||
// Walk the left spine iteratively: a flat chain such as `1+1+1+...` parses into a
|
||||
// tree one level deeper per operator, and recursing on it could exhaust the stack.
|
||||
@@ -321,38 +388,28 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
|
||||
rest.push((op, b));
|
||||
first = a;
|
||||
}
|
||||
write_expr(s, first, r1c1);
|
||||
write_expr(s, first, d);
|
||||
for (op, right) in rest.into_iter().rev() {
|
||||
s.push_str(op.symbol());
|
||||
write_expr(s, right, r1c1);
|
||||
s.push_str(d.operator(*op));
|
||||
write_expr(s, right, d);
|
||||
}
|
||||
}
|
||||
Expr::Call(name, args) => {
|
||||
s.push_str(name);
|
||||
s.push_str(&d.function(name));
|
||||
s.push('(');
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.push(',');
|
||||
}
|
||||
write_expr(s, a, r1c1);
|
||||
}
|
||||
write_list(s, args, arg_sep, d);
|
||||
s.push(')');
|
||||
}
|
||||
Expr::Invoke(c, args) => {
|
||||
write_expr(s, c, r1c1);
|
||||
write_expr(s, c, d);
|
||||
s.push('(');
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
if i > 0 {
|
||||
s.push(',');
|
||||
}
|
||||
write_expr(s, a, r1c1);
|
||||
}
|
||||
write_list(s, args, arg_sep, d);
|
||||
s.push(')');
|
||||
}
|
||||
Expr::Missing => {}
|
||||
Expr::Paren(x) => {
|
||||
s.push('(');
|
||||
write_expr(s, x, r1c1);
|
||||
write_expr(s, x, d);
|
||||
s.push(')');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -603,6 +603,226 @@ fn column_starting_with_at_round_trips() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Another syntax's tokens parse with this grammar: a reference its tokenizer already read, a
|
||||
/// space as the intersection, and the same errors as text.
|
||||
#[test]
|
||||
fn parse_tokens_reads_another_syntaxs_tokens() -> Result<(), ParseError> {
|
||||
use crate::lexer::{Tok, Token};
|
||||
let cell = |col| Reference { sheet: SheetSel::Current, kind: RefKind::Cell(Anchor { row: 0, col, row_abs: false, col_abs: false }) };
|
||||
let toks = |ts: Vec<Tok>| ts.into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect::<Vec<_>>();
|
||||
let e = crate::parse_tokens(toks(vec![Tok::Func("SUM".into()), Tok::Ref(cell(0)), Tok::Comma, Tok::Ref(cell(1)), Tok::RParen]))?;
|
||||
assert_eq!(e, parse("SUM(A1,B1)")?);
|
||||
assert_eq!(print(&e), "SUM(A1,B1)");
|
||||
let e = crate::parse_tokens(toks(vec![Tok::Ref(cell(0)), Tok::Space, Tok::Ref(cell(1))]))?;
|
||||
assert!(matches!(e, Expr::Binary(BinOp::Intersect, ..)));
|
||||
// A trailing Eof is accepted; leftovers and an empty list are errors.
|
||||
assert!(crate::parse_tokens(toks(vec![Tok::Number(1.0), Tok::Eof])).is_ok());
|
||||
assert!(crate::parse_tokens(toks(vec![Tok::Number(1.0), Tok::Number(2.0)])).is_err());
|
||||
assert!(crate::parse_tokens(Vec::new()).is_err());
|
||||
// Hostile input: more tokens than a formula may have characters is refused up front.
|
||||
let long = toks(std::iter::repeat_n(Tok::Number(1.0), crate::MAX_FORMULA_LEN + 1).collect());
|
||||
assert!(crate::parse_tokens(long).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tokens from another tokenizer are as hostile as text: a reference off the grid and text
|
||||
/// longer than a formula may be are refused; ends of a range keep their order, as in text.
|
||||
#[test]
|
||||
fn parse_tokens_refuses_hostile_tokens() -> Result<(), ParseError> {
|
||||
use crate::lexer::{Tok, Token};
|
||||
use gridcraft_core::{MAX_COLS, MAX_ROWS};
|
||||
let one = |tok| crate::parse_tokens(vec![Token { tok, start: 0, end: 0 }]);
|
||||
let anchor = |row, col| Anchor { row, col, row_abs: false, col_abs: false };
|
||||
let reference = |kind| Tok::Ref(Reference { sheet: SheetSel::Current, kind });
|
||||
for kind in [
|
||||
RefKind::Cell(anchor(MAX_ROWS, 0)),
|
||||
RefKind::Cell(anchor(0, MAX_COLS)),
|
||||
RefKind::Cell(anchor(u32::MAX, u32::MAX)),
|
||||
RefKind::Range(anchor(0, 0), anchor(MAX_ROWS, 0)),
|
||||
RefKind::Rows(0, false, MAX_ROWS, false),
|
||||
RefKind::Cols(MAX_COLS, false, 0, false),
|
||||
] {
|
||||
assert!(one(reference(kind.clone())).is_err(), "{kind:?}");
|
||||
}
|
||||
// The last row and column are on the grid; reversed ends stay as given, as `B2:A1` parses.
|
||||
let last = one(reference(RefKind::Cell(anchor(MAX_ROWS - 1, MAX_COLS - 1))))?;
|
||||
assert_eq!(print(&last), "XFD1048576");
|
||||
assert_eq!(one(reference(RefKind::Range(anchor(1, 1), anchor(0, 0))))?, parse("B2:A1")?);
|
||||
// Text, names and sheet names count against the formula length.
|
||||
let long = "x".repeat(crate::MAX_FORMULA_LEN + 1);
|
||||
assert!(one(Tok::Text(long.clone())).is_err());
|
||||
assert!(one(Tok::Word(long.clone())).is_err());
|
||||
let sheet = Tok::Ref(Reference { sheet: SheetSel::Named(long), kind: RefKind::Cell(anchor(0, 0)) });
|
||||
assert!(one(sheet).is_err());
|
||||
// A string whose formula text, quotes included, fits the limit is read; one more is not, as
|
||||
// that text would not parse.
|
||||
let fits = "x".repeat(crate::MAX_FORMULA_LEN - 2);
|
||||
assert_eq!(one(Tok::Text(fits.clone()))?, Expr::Text(fits.into()));
|
||||
assert!(one(Tok::Text("x".repeat(crate::MAX_FORMULA_LEN - 1))).is_err());
|
||||
// Many tokens that each fit still add up past the limit.
|
||||
let half = "x".repeat(crate::MAX_FORMULA_LEN / 2 + 1);
|
||||
let toks = [Tok::Text(half.clone()), Tok::Op("&"), Tok::Text(half)].into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect();
|
||||
assert!(crate::parse_tokens(toks).is_err());
|
||||
// A number the text lexer would refuse (not finite) is refused, not printed as `0`.
|
||||
for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert!(one(Tok::Number(n)).is_err(), "{n}");
|
||||
}
|
||||
// An end token before the last is an error, not the end of what is read.
|
||||
let toks = [Tok::Number(1.0), Tok::Eof, Tok::Op("+"), Tok::Number(2.0)].into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect();
|
||||
assert!(crate::parse_tokens(toks).is_err());
|
||||
// A sheet name is never empty.
|
||||
let cell = RefKind::Cell(anchor(0, 0));
|
||||
for sheet in [SheetSel::Named(String::new()), SheetSel::Span(String::new(), "S".into()), SheetSel::Span("S".into(), String::new())] {
|
||||
assert!(one(Tok::Ref(Reference { sheet: sheet.clone(), kind: cell.clone() })).is_err(), "{sheet:?}");
|
||||
}
|
||||
let toks = [Tok::Sheet(String::new(), None), Tok::Word("A1".into())].into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect();
|
||||
assert!(crate::parse_tokens(toks).is_err());
|
||||
let toks = [Tok::Sheet("S".into(), Some(String::new())), Tok::Word("A1".into())].into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect();
|
||||
assert!(crate::parse_tokens(toks).is_err());
|
||||
// A word or function name must be one the A1 tokenizer would read as that token: empty, or
|
||||
// text that reads as something else (`A!1` is a sheet then a number, `TRUE` a boolean, `a b`
|
||||
// two words), would print as text that does not parse back to it.
|
||||
let words = |w: &str| vec![Token { tok: Tok::Word(w.into()), start: 0, end: 0 }];
|
||||
for w in ["", "A!1", "TRUE", "a b", "A#", "1abc", "x(", "A1:B2", "\"x\""] {
|
||||
assert!(crate::parse_tokens(words(w)).is_err(), "Word({w:?})");
|
||||
}
|
||||
for w in ["Total", "A1", "$A$1", "My.Name", "_xleta.SUM", "\\x"] {
|
||||
assert_eq!(crate::parse_tokens(words(w))?, parse(w)?, "Word({w:?})");
|
||||
}
|
||||
let call = |f: &str| vec![Token { tok: Tok::Func(f.into()), start: 0, end: 0 }, Token { tok: Tok::RParen, start: 0, end: 0 }];
|
||||
for f in ["", "A B", "1", "(", "S!F"] {
|
||||
assert!(crate::parse_tokens(call(f)).is_err(), "Func({f:?})");
|
||||
}
|
||||
assert_eq!(crate::parse_tokens(call("SUM"))?, parse("SUM()")?);
|
||||
// An empty structured reference body is what text reads for `[]` (the whole table).
|
||||
assert_eq!(one(Tok::Struct(String::new()))?, parse("[]")?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every tree `parse_tokens` accepts prints as text that parses back to it: token shapes with no
|
||||
/// text form are refused, and the whole-tree nesting bound applies as it does to text.
|
||||
#[test]
|
||||
fn parse_tokens_accepts_only_what_prints_back() -> Result<(), ParseError> {
|
||||
use crate::lexer::{Tok, Token};
|
||||
let read = |toks: Vec<Tok>| crate::parse_tokens(toks.into_iter().map(|tok| Token { tok, start: 0, end: 0 }).collect());
|
||||
let a1 = Tok::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Cell(Anchor { row: 0, col: 0, row_abs: false, col_abs: false }) });
|
||||
// Wrappers stacked across levels: the text form is refused as a whole, and so are its tokens.
|
||||
let mut toks = vec![Tok::LParen; 7];
|
||||
toks.push(Tok::Number(1.0));
|
||||
for _ in 0..7 {
|
||||
toks.push(Tok::RParen);
|
||||
toks.extend(std::iter::repeat_n(Tok::Op("%"), 40));
|
||||
}
|
||||
assert!(read(toks).is_err(), "7 x 41 wrappers on one path");
|
||||
// A space is the intersection only between two operands; elsewhere it is dropped, as in text.
|
||||
assert!(read(vec![Tok::Bool(true), Tok::Space, Tok::Number(1.0)]).is_err());
|
||||
assert_eq!(read(vec![Tok::Number(1.0), Tok::Space, Tok::Op("+"), Tok::Space, Tok::Number(2.0)])?, parse("1+2")?);
|
||||
assert_eq!(read(vec![a1.clone(), Tok::Space, Tok::Word("B1".into())])?, parse("A1 B1")?);
|
||||
assert_eq!(read(vec![Tok::Word("B1".into()), Tok::Space, a1.clone()])?, parse("B1 A1")?);
|
||||
// A negative number reads back from text as a negation, so a minus must be an operator.
|
||||
for n in [-1.0, -0.0] {
|
||||
assert!(read(vec![Tok::Number(n)]).is_err(), "{n}");
|
||||
}
|
||||
assert_eq!(read(vec![Tok::Op("-"), Tok::Number(1.0)])?, parse("-1")?);
|
||||
// A `:` in a sheet name reads back as a span of sheets.
|
||||
let at = |sheet| Tok::Ref(Reference { sheet, kind: RefKind::Cell(Anchor { row: 0, col: 0, row_abs: false, col_abs: false }) });
|
||||
for sheet in [SheetSel::Named("a:b".into()), SheetSel::Span("a:b".into(), "c".into()), SheetSel::Span("a".into(), "b:c".into())] {
|
||||
assert!(read(vec![at(sheet.clone())]).is_err(), "{sheet:?}");
|
||||
}
|
||||
assert!(read(vec![Tok::Sheet("a:b".into(), None), Tok::Word("C".into())]).is_err());
|
||||
assert!(read(vec![Tok::Sheet("a".into(), Some("b:c".into())), Tok::Word("C".into())]).is_err());
|
||||
assert_eq!(read(vec![at(SheetSel::Named("a b".into()))])?, parse("'a b'!A1")?);
|
||||
// The trim operators are Excel's own: around anything but a plain range they have no text form.
|
||||
assert!(read(vec![Tok::Bool(true), Tok::Trim(TrimMode::All), Tok::Bool(true)]).is_err());
|
||||
assert!(read(vec![a1.clone(), Tok::Trim(TrimMode::All), Tok::Word("B2".into())]).is_err());
|
||||
// A name directly before `(` is a function name to the A1 tokenizer.
|
||||
assert!(read(vec![Tok::Word("_x".into()), Tok::LParen, Tok::RParen]).is_err());
|
||||
assert_eq!(read(vec![Tok::Word("_x".into()), Tok::Space, Tok::LParen, a1.clone(), Tok::RParen])?, parse("_x (A1)")?);
|
||||
// Operands of `:` that print as text which regroups, or reads as rows or a sheet span.
|
||||
let cell = |row, col| Anchor { row, col, row_abs: false, col_abs: false };
|
||||
let range = Tok::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Range(cell(1, 1), cell(2, 2)) });
|
||||
let rows = Tok::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Rows(0, false, 2, false) });
|
||||
for toks in [
|
||||
vec![Tok::Number(1.0), Tok::Colon, Tok::Number(3.0)],
|
||||
vec![a1.clone(), Tok::Colon, range.clone()],
|
||||
vec![a1.clone(), Tok::Colon, at(SheetSel::Named("S".into()))],
|
||||
vec![rows, Tok::Space, Tok::Word("A1".into())],
|
||||
] {
|
||||
assert!(read(toks.clone()).is_err(), "{toks:?}");
|
||||
}
|
||||
// In parentheses they keep their shape.
|
||||
let e = read(vec![a1.clone(), Tok::Colon, Tok::LParen, range, Tok::RParen])?;
|
||||
assert_eq!(e, parse("A1:(B2:C3)")?);
|
||||
// A number with more digits than text keeps is read as given, not refused.
|
||||
assert_eq!(read(vec![Tok::Number(std::f64::consts::PI)])?, Expr::Number(std::f64::consts::PI));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A dialect changes only what it states; the rest prints as A1.
|
||||
#[test]
|
||||
fn print_with_a_dialect() -> Result<(), ParseError> {
|
||||
use std::borrow::Cow;
|
||||
struct Test;
|
||||
impl crate::Dialect for Test {
|
||||
fn separators(&self) -> (char, char, char) {
|
||||
(';', ';', '|')
|
||||
}
|
||||
fn boolean(&self, b: bool) -> &'static str {
|
||||
if b { "TRUE()" } else { "FALSE()" }
|
||||
}
|
||||
fn function<'a>(&self, name: &'a str) -> Cow<'a, str> {
|
||||
Cow::Owned(format!("X.{name}"))
|
||||
}
|
||||
fn operator(&self, op: BinOp) -> &'static str {
|
||||
if op == BinOp::Concat { " CONCAT " } else { op.symbol() }
|
||||
}
|
||||
fn unary_call(&self, op: UnOp) -> Option<&'static str> {
|
||||
(op == UnOp::Spill).then_some("ANCHOR")
|
||||
}
|
||||
fn reference(&self, s: &mut String, r: &Reference, sep: &str) {
|
||||
s.push('[');
|
||||
s.push_str(&printer::reference_a1(r).replace(':', sep));
|
||||
s.push(']');
|
||||
}
|
||||
}
|
||||
let e = parse("IF(A1,{1,2;3,4},TRUE)&SUM(B1:C2,D1#)")?;
|
||||
assert_eq!(crate::print_with(&e, &Test), "X.IF([A1];{1;2|3;4};TRUE()) CONCAT X.SUM([B1:C2];ANCHOR([D1]))");
|
||||
assert_eq!(print(&e), "IF(A1,{1,2;3,4},TRUE)&SUM(B1:C2,D1#)");
|
||||
// A trim with no operator form prints as the TRIMRANGE call, named through the dialect.
|
||||
let e = Expr::Unary(UnOp::Trim(TrimMode::All), Box::new(parse("A1")?));
|
||||
assert_eq!(crate::print_with(&e, &Test), "X.TRIMRANGE([A1];3;3)");
|
||||
assert_eq!(print(&e), "TRIMRANGE(A1,3,3)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `print` and `print_r1c1` go through the default dialect: Excel's text is unchanged.
|
||||
#[test]
|
||||
fn default_dialect_prints_excel_text_unchanged() -> Result<(), ParseError> {
|
||||
let at = gridcraft_core::CellRef::new(4, 2);
|
||||
for (a1, r1c1) in [
|
||||
("SUM(A1:B2,$C$3)", "SUM(R[-4]C[-2]:R[-3]C[-1],R3C3)"),
|
||||
("IF(TRUE,\"a\"\"b\",FALSE)", "IF(TRUE,\"a\"\"b\",FALSE)"),
|
||||
("{1,2;3,4}", "{1,2;3,4}"),
|
||||
("-A1%+@B:B", "-R[-4]C[-2]%+@C[-1]"),
|
||||
("A1#", "R[-4]C[-2]#"),
|
||||
("'My Sheet'!A1&Total", "'My Sheet'!R[-4]C[-2]&Total"),
|
||||
("'My Sheet'!Total", "'My Sheet'!Total"),
|
||||
("Table1[[#Headers],[Col]]", "Table1[[#Headers],[Col]]"),
|
||||
("SUM(A1:.B3)+SUM(A.:.B)", "SUM(R[-4]C[-2]:.R[-2]C[-1])+SUM(C[-2].:.C[-1])"),
|
||||
("TRIMRANGE(A1,1,1)", "TRIMRANGE(R[-4]C[-2],1,1)"),
|
||||
("(A1 B1)*2^3>=1<>0", "(R[-4]C[-2] R[-4]C[-1])*2^3>=1<>0"),
|
||||
("LAMBDA(x,x+1)(2)", "LAMBDA(x,x+1)(2)"),
|
||||
("Sheet1:Sheet3!B2", "Sheet1:Sheet3!R[-3]C[-1]"),
|
||||
("#REF!+1", "#REF!+1"),
|
||||
("SUM(,1)", "SUM(,1)"),
|
||||
] {
|
||||
let e = parse(a1)?;
|
||||
assert_eq!(print(&e), a1);
|
||||
assert_eq!(printer::print_r1c1(&e, at), r1c1, "{a1}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_stacked_across_levels_are_bounded_as_a_whole() {
|
||||
// Each level adds 40 percents inside the parser's per-level bound, so no level is too deep alone.
|
||||
|
||||
@@ -291,8 +291,7 @@ fn cash_flows() {
|
||||
let m = col(&[-120000.0, 39000.0, 30000.0, 21000.0, 37000.0, 46000.0]);
|
||||
close_tol(ev("MIRR", vec![rf(m), n(0.1), n(0.12)]), 0.1260943, 1e-6);
|
||||
close_tol(ev("MIRR", vec![rf(col(&[-120000.0, 39000.0, 30000.0, 21000.0])), n(0.1), n(0.12)]), -0.048044655, 1e-7);
|
||||
is_err(ev("MIRR", vec![rf(col(&[1.0, 2.0])), n(0.1), n(0.1)]), CellError::Div0);
|
||||
// Excel 365 gives -1 when every flow is negative: the positive flows are worth nothing.
|
||||
is_err(ev("MIRR", vec![rf(col(&[1.0, 2.0])), n(0.1), n(0.1)]), CellError::Div0); // Excel 365 gives -1 when every flow is negative: the positive flows are worth nothing.
|
||||
close_tol(ev("MIRR", vec![rf(col(&[-10000.0, -3400.0, -6500.0, -1000.0])), n(0.07), n(0.01)]), -1.0, 1e-12);
|
||||
close(ev("FVSCHEDULE", vec![n(1.0), av(row(&[0.09, 0.11, 0.1]))]), 1.33089);
|
||||
close(ev("EFFECT", vec![n(0.0525), n(4.0)]), 0.0535426673707584);
|
||||
@@ -311,6 +310,19 @@ fn cash_flows() {
|
||||
is_err(ev("DOLLARDE", vec![n(1.02), n(-1.0)]), CellError::Num);
|
||||
}
|
||||
|
||||
/// Excel does not read a Boolean guess as 1/0: `XIRR(..., TRUE)` and `XIRR(..., FALSE)` are
|
||||
/// #VALUE!, from a literal and from a reference alike, while a numeric guess still solves (#4045).
|
||||
#[test]
|
||||
fn xirr_rejects_a_boolean_guess() {
|
||||
let flows = || rf(col(&[-100.0, 110.0]));
|
||||
let dates = || rf(col(&[1.0, 366.0]));
|
||||
is_err(ev("XIRR", vec![flows(), dates(), b(true)]), CellError::Value);
|
||||
is_err(ev("XIRR", vec![flows(), dates(), b(false)]), CellError::Value);
|
||||
is_err(ev("XIRR", vec![flows(), dates(), Arg::reference(Value::Bool(true))]), CellError::Value);
|
||||
is_err(ev("XIRR", vec![flows(), dates(), Arg::reference(Value::Bool(false))]), CellError::Value);
|
||||
close_tol(ev("XIRR", vec![flows(), dates(), n(0.1)]), 0.0999999, 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depreciation() {
|
||||
close(ev("SLN", vec![n(30000.0), n(7500.0), n(10.0)]), 2250.0);
|
||||
|
||||
@@ -451,7 +451,13 @@ impl XirrSolver<'_> {
|
||||
|
||||
pub(super) fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?;
|
||||
let guess = opt_num(a, 2, 0.1)?;
|
||||
// A Boolean guess is #VALUE!: Excel does not read TRUE/FALSE as 1/0 here, while `opt_num`
|
||||
// would. Every other coercion (a numeric guess, numeric text, an empty literal) stays.
|
||||
let guess = match a.get(2).map(|g| g.value.scalar()) {
|
||||
None => 0.1,
|
||||
Some(Value::Bool(_)) => return Err(CellError::Value),
|
||||
Some(_) => opt_num(a, 2, 0.1)?,
|
||||
};
|
||||
if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
|
||||
@@ -366,7 +366,7 @@ fn base_tool_definitions() -> Vec<Value> {
|
||||
"save_workbook",
|
||||
"Save workbook",
|
||||
"Save the active workbook. The format follows the extension (.xlsx default; .csv/.tsv save the active sheet; .json; .html). \
|
||||
Without `path` saves to the workbook's current file.",
|
||||
Without `path` saves to the workbook's current file. Check `warnings` in the result: it lists what the format could not keep.",
|
||||
obj(json!({"path": string("Destination path")}), &[]),
|
||||
false,
|
||||
),
|
||||
|
||||
@@ -56,6 +56,10 @@ pub struct PrintSettings {
|
||||
/// sheet is more than one page wide and tall.
|
||||
#[serde(default)]
|
||||
pub page_order: PageOrder,
|
||||
/// Left out when the whole workbook prints or exports to PDF, unless every visible sheet is
|
||||
/// (an OpenDocument sheet's `table:print="false"`; Excel has no such flag).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub excluded: bool,
|
||||
/// Page Setup › Page › First page number: the number the sheet's first printed page takes,
|
||||
/// or `None` for Automatic (XLSX `pageSetup firstPageNumber` with `useFirstPageNumber`). Left
|
||||
/// out of a JSON workbook when Automatic, so files without it are written as before.
|
||||
@@ -195,6 +199,7 @@ impl Default for PrintSettings {
|
||||
hf_scale_with_doc: true,
|
||||
hf_align_with_margins: true,
|
||||
page_order: PageOrder::DownThenOver,
|
||||
excluded: false,
|
||||
first_page_number: None,
|
||||
}
|
||||
}
|
||||
@@ -292,6 +297,16 @@ mod tests {
|
||||
assert_eq!(p, PrintSettings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_is_saved_only_when_set_and_old_settings_load_included() {
|
||||
let saved = serde_json::to_value(PrintSettings::default()).unwrap();
|
||||
assert!(saved.get("excluded").is_none());
|
||||
let p = PrintSettings { excluded: true, ..Default::default() };
|
||||
let saved = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(saved["excluded"], true);
|
||||
assert_eq!(serde_json::from_value::<PrintSettings>(saved).unwrap(), p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_page_number_is_saved_only_when_set() {
|
||||
// Automatic writes nothing, so a JSON workbook without a first page number is unchanged and
|
||||
|
||||
@@ -32,7 +32,7 @@ pub use style::{
|
||||
};
|
||||
pub use workbook::{
|
||||
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
|
||||
RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation,
|
||||
RefHost, ScriptDefault, ShowObjects, TextDefaults, Workbook, WorkbookView, WriteReservation,
|
||||
};
|
||||
|
||||
/// Font used for new workbooks. Only a name: renderers substitute an available open font
|
||||
|
||||
@@ -144,6 +144,56 @@ pub struct DefinedName {
|
||||
pub hidden: bool,
|
||||
}
|
||||
|
||||
/// The language, script, country and font a document gives one script's text by default, each
|
||||
/// `None` when unstated. Codes are as files spell them (`de`/`DE`; ODF states "no language" as
|
||||
/// language `zxx` with country `none`). ODF 1.2 and later can also state a script code (`Latn` in `sr-Latn-RS`) and a full
|
||||
/// BCP 47 tag for locales the separate codes cannot express (`ca-ES-valencia`); both are kept so
|
||||
/// such a locale survives open and save.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct ScriptDefault {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
/// ISO 15924 script code (ODF `fo:script`, `style:script-asian`, `style:script-complex`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub script: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub country: Option<String>,
|
||||
/// BCP 47 language tag (ODF `style:rfc-language-tag`, `-asian`, `-complex`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rfc_language_tag: Option<String>,
|
||||
/// The font family name (not an ODF `style:font-face` declaration name: a reader resolves
|
||||
/// `style:font-name-asian`/`-complex` to its family, a writer declares a face for it). Read
|
||||
/// for Asian and complex text only; Western text takes the default style's font, so
|
||||
/// `western.font` is unused.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub font: Option<String>,
|
||||
}
|
||||
|
||||
impl ScriptDefault {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.language.is_none() && self.script.is_none() && self.country.is_none() && self.rfc_language_tag.is_none() && self.font.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Default language and fonts of Western, Asian (CJK) and complex (right-to-left, Indic) text.
|
||||
/// Empty unless a reader for a format that states them fills them (OpenDocument puts them on
|
||||
/// its default cell style); Excel has no equivalent, so XLSX neither reads nor writes them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct TextDefaults {
|
||||
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
|
||||
pub western: ScriptDefault,
|
||||
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
|
||||
pub asian: ScriptDefault,
|
||||
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
|
||||
pub complex: ScriptDefault,
|
||||
}
|
||||
|
||||
impl TextDefaults {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.western.is_empty() && self.asian.is_empty() && self.complex.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DocProps {
|
||||
pub title: String,
|
||||
@@ -266,6 +316,11 @@ pub struct Workbook {
|
||||
/// Shared between snapshots, as nothing changes them.
|
||||
#[serde(skip)]
|
||||
pub macros_unread: Arc<Vec<serde_json::Value>>,
|
||||
/// The language and fonts the document gives text of each script by default (an
|
||||
/// OpenDocument file's default cell style). Empty until a reader for a format that states
|
||||
/// them fills them.
|
||||
#[serde(default, skip_serializing_if = "TextDefaults::is_empty")]
|
||||
pub text_defaults: TextDefaults,
|
||||
/// Unmodelled file content kept for saving (package root and workbook level). Not in JSON.
|
||||
#[serde(skip)]
|
||||
pub preserved: Option<Arc<crate::preserved::Preserved>>,
|
||||
@@ -585,6 +640,7 @@ impl Workbook {
|
||||
macros: crate::macros::Macros::default(),
|
||||
macros_read: vec![],
|
||||
macros_unread: Arc::default(),
|
||||
text_defaults: TextDefaults::default(),
|
||||
preserved: None,
|
||||
source_dir: None,
|
||||
region: gridcraft_core::region::default_region(),
|
||||
@@ -847,6 +903,59 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_defaults_round_trip_in_json_and_are_skipped_when_empty() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut wb = Workbook::new();
|
||||
assert!(wb.text_defaults.is_empty(), "new workbooks state no text defaults");
|
||||
// A workbook without them serialises exactly as before the field existed.
|
||||
let json = serde_json::to_string(&wb)?;
|
||||
let value: serde_json::Value = serde_json::from_str(&json)?;
|
||||
assert!(value.get("text_defaults").is_none(), "empty text defaults are not written");
|
||||
// JSON written before the field existed still loads, with empty defaults.
|
||||
assert!(serde_json::from_str::<Workbook>(&json)?.text_defaults.is_empty());
|
||||
|
||||
wb.text_defaults = TextDefaults {
|
||||
western: ScriptDefault {
|
||||
language: Some("sr".into()),
|
||||
script: Some("Latn".into()),
|
||||
country: Some("RS".into()),
|
||||
rfc_language_tag: Some("sr-Latn-RS".into()),
|
||||
font: None,
|
||||
},
|
||||
asian: ScriptDefault {
|
||||
language: Some("ja".into()),
|
||||
country: Some("JP".into()),
|
||||
font: Some("Noto Sans CJK JP".into()),
|
||||
..Default::default()
|
||||
},
|
||||
complex: ScriptDefault { font: Some("Noto Naskh Arabic".into()), ..Default::default() },
|
||||
};
|
||||
assert!(!wb.text_defaults.is_empty());
|
||||
let json = serde_json::to_string(&wb)?;
|
||||
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
|
||||
// Unstated parts stay out of the JSON.
|
||||
let value: serde_json::Value = serde_json::from_str(&json)?;
|
||||
let td = value.get("text_defaults").ok_or("text_defaults written")?;
|
||||
assert!(td["western"].get("font").is_none());
|
||||
assert!(td["complex"].get("language").is_none());
|
||||
assert!(td["asian"].get("script").is_none() && td["asian"].get("rfc_language_tag").is_none());
|
||||
assert_eq!(td["western"]["script"], "Latn");
|
||||
assert_eq!(td["western"]["rfc_language_tag"], "sr-Latn-RS");
|
||||
// A script that states only a script code or only a language tag is not empty.
|
||||
assert!(!ScriptDefault { script: Some("Latn".into()), ..Default::default() }.is_empty());
|
||||
assert!(!ScriptDefault { rfc_language_tag: Some("ca-ES-valencia".into()), ..Default::default() }.is_empty());
|
||||
|
||||
// Only one script stated: the others are skipped and load back empty.
|
||||
wb.text_defaults =
|
||||
TextDefaults { asian: ScriptDefault { font: Some("Noto Serif CJK SC".into()), ..Default::default() }, ..Default::default() };
|
||||
let json = serde_json::to_string(&wb)?;
|
||||
let value: serde_json::Value = serde_json::from_str(&json)?;
|
||||
let td = value.get("text_defaults").ok_or("text_defaults written")?;
|
||||
assert!(td.get("western").is_none() && td.get("complex").is_none());
|
||||
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_names() {
|
||||
let wb = Workbook::new();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use super::clock::monotonic_ms;
|
||||
use super::clock::now_ms;
|
||||
use super::services::{Chrome, Services};
|
||||
use super::state::{NoticeKind, OpenWindow, SaveAnswer, SheetView};
|
||||
use super::state::{AfterSave, NoticeKind, OpenWindow, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetView};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::updates_ui;
|
||||
use super::{
|
||||
@@ -75,6 +75,9 @@ impl SheetApp {
|
||||
chart_cache: Default::default(),
|
||||
clipboard_text_at_copy: None,
|
||||
cut_text: None,
|
||||
accepted_losses: Default::default(),
|
||||
held_losses: Default::default(),
|
||||
after_save: None,
|
||||
tab_run: None,
|
||||
macros: macro_ui::MacroUi::default(),
|
||||
started: now_ms(),
|
||||
|
||||
@@ -62,6 +62,22 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// `data.fromClipboard {delimiter?, at?}`: the text on the system clipboard, imported as
|
||||
/// `data.fromTextCsv` imports text: into a new sheet as a table, or at the cell `at`. Without
|
||||
/// a `delimiter` the engine picks comma, semicolon or tab by the text.
|
||||
pub(super) fn import_clipboard_text(&mut self, p: &Json) -> Result<Json, String> {
|
||||
let text = self.clipboard_text_to_import()?;
|
||||
self.run_command("data.fromTextCsv", json!({"text": text, "delimiter": p.get("delimiter"), "at": p.get("at")}))
|
||||
}
|
||||
|
||||
/// The text From Clipboard imports, or why there is none.
|
||||
pub(crate) fn clipboard_text_to_import(&mut self) -> Result<String, String> {
|
||||
if self.services.paste_text.is_none() {
|
||||
return Err("GridCraft can't read the clipboard here. Paste the text into a cell, then use Text to Columns.".into());
|
||||
}
|
||||
self.system_clipboard_text().filter(|t| !t.trim().is_empty()).ok_or_else(|| "There's no text on the clipboard to import.".into())
|
||||
}
|
||||
|
||||
/// Paste a picture from the system clipboard (a screenshot, an image copied in a browser) as
|
||||
/// a floating picture whose top-left corner is the active cell, as Excel does.
|
||||
pub fn paste_picture(&mut self, image: image::RgbaImage) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
INTERFACE_SCALE_MAX, INTERFACE_SCALE_MIN, Json, Notice, NoticeKind, SheetApp, UiRequest, backstage, clamp_interface_scale, clean_error, dialogs,
|
||||
formula_locale, i18n, json, now_ms, printing,
|
||||
INTERFACE_SCALE_MAX, INTERFACE_SCALE_MIN, Json, Notice, NoticeKind, SaveRequest, SheetApp, UiRequest, backstage, clamp_interface_scale,
|
||||
clean_error, dialogs, formula_locale, i18n, json, now_ms, printing,
|
||||
};
|
||||
|
||||
impl SheetApp {
|
||||
@@ -153,6 +153,11 @@ impl SheetApp {
|
||||
self.open_switch_windows = true;
|
||||
return;
|
||||
}
|
||||
// A menu-style save that would lose something asks first; programmatic callers of `run`
|
||||
// get `warnings` in the result instead.
|
||||
if matches!(id, "file.save" | "file.saveAs") && self.hold_save(SaveRequest::Command { id: id.into(), params: params.clone() }) {
|
||||
return;
|
||||
}
|
||||
match self.run(id, params) {
|
||||
// A refused cell draft already shows its own message (with the rule's title).
|
||||
Err(e) if self.message.as_ref().is_some_and(|(_, m)| *m == e) => {}
|
||||
@@ -217,6 +222,7 @@ impl SheetApp {
|
||||
self.check_for_updates();
|
||||
Ok(Json::Null)
|
||||
}
|
||||
"data.fromClipboard" => self.import_clipboard_text(p),
|
||||
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
|
||||
"ui.printSubmit" => self.submit_print(p.clone()),
|
||||
"ui.ribbonTab" => {
|
||||
@@ -465,42 +471,43 @@ impl SheetApp {
|
||||
let path = if std::path::Path::new(&path).extension().is_none() { format!("{path}.xlsx") } else { path };
|
||||
self.run_or_alert("file.save", json!({"path": path}));
|
||||
}
|
||||
} else if self.services.download.is_some()
|
||||
&& let Ok(r) = self.run("file.saveBytes", json!({"format": "xlsx"}))
|
||||
&& let Some(dl) = &self.services.download
|
||||
&& let Some(b) = r.get("base64").and_then(Json::as_str).and_then(gridcraft_engine::io::base64_decode)
|
||||
{
|
||||
let name = r.get("name").and_then(Json::as_str).unwrap_or("Book.xlsx").to_string();
|
||||
dl(&name, &b);
|
||||
} else if self.services.download.is_some() && !self.hold_save(SaveRequest::Download) {
|
||||
self.download_workbook("xlsx");
|
||||
}
|
||||
}
|
||||
// The notice AutoSave holds back with: Save asks what the notice says.
|
||||
"saveLoss" => self.run_or_alert("file.save", json!({})),
|
||||
// File › Options (`file.options`) and the File tab itself open the Backstage view.
|
||||
"options" => self.open_backstage(backstage::Page::Options),
|
||||
"backstage" => {
|
||||
let page = params.get("page").and_then(Json::as_str).and_then(backstage::Page::parse).unwrap_or(backstage::Page::Home);
|
||||
self.open_backstage(page);
|
||||
}
|
||||
// The macro step editor stays until it closes itself (its draft, overlays and debug
|
||||
// run go with it), so another dialog can't replace it.
|
||||
_ if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") => {
|
||||
self.message = Some((
|
||||
"Macro".into(),
|
||||
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
|
||||
));
|
||||
}
|
||||
other => {
|
||||
// A dialog replaced while one of its reference boxes picks (a ribbon command
|
||||
// opening another dialog) first puts the sheet and selection from before picking
|
||||
// back, as closing it does.
|
||||
if let Some(mut old) = self.dialog.take() {
|
||||
// The draft was committed above, so the sheet can be shown again.
|
||||
let _ = old.end_pick(self);
|
||||
}
|
||||
self.dialog = dialogs::Dialog::open(self, other, params);
|
||||
}
|
||||
other => self.replace_dialog(|app| dialogs::Dialog::open(app, other, params)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the dialog `make` builds in place of the one that is open.
|
||||
pub(super) fn replace_dialog(&mut self, make: impl FnOnce(&mut SheetApp) -> Option<dialogs::Dialog>) {
|
||||
// The macro step editor stays until it closes itself (its draft, overlays and debug
|
||||
// run go with it), so another dialog can't replace it.
|
||||
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
|
||||
self.message = Some((
|
||||
"Macro".into(),
|
||||
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
// A dialog replaced while one of its reference boxes picks (a ribbon command opening
|
||||
// another dialog) first puts the sheet and selection from before picking back, as closing
|
||||
// it does.
|
||||
if let Some(mut old) = self.dialog.take() {
|
||||
// The draft was committed by the caller, so the sheet can be shown again.
|
||||
let _ = old.end_pick(self);
|
||||
}
|
||||
self.dialog = make(self);
|
||||
}
|
||||
|
||||
/// Opens the File tab's Backstage view on `page`, committing a cell still being edited first
|
||||
/// (File actions work on the whole workbook). A draft that can't be committed keeps the sheet.
|
||||
pub fn open_backstage(&mut self, page: backstage::Page) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Json, Notice, NoticeKind, OpenWindow, SheetApp, clean_error, json};
|
||||
use super::{Json, Notice, NoticeKind, OpenWindow, SaveRequest, SheetApp, clean_error, json};
|
||||
|
||||
impl SheetApp {
|
||||
pub fn open_path(&mut self, path: &str) {
|
||||
@@ -113,11 +113,26 @@ 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")));
|
||||
if !(self.ui.autosave && dirty_xlsx) {
|
||||
self.end_autosave_hold();
|
||||
}
|
||||
let now = crate::monotonic_ms();
|
||||
let autosave_due =
|
||||
self.ui.autosave && self.editor.is_none() && self.text_box_editor.is_none() && now - self.grid.last_autosave > 2000.0 && dirty_xlsx;
|
||||
if autosave_due {
|
||||
self.grid.last_autosave = now;
|
||||
// AutoSave never drops something on its own: it waits for a Save, which asks.
|
||||
let losses = self.save_losses_to_ask(&SaveRequest::Command { id: "file.save".into(), params: json!({}) });
|
||||
if !losses.is_empty() {
|
||||
let uid = self.session.active().map(|d| d.uid).unwrap_or_default();
|
||||
if self.held_losses.get(&uid) != Some(&losses) {
|
||||
let text = format!("AutoSave is on hold for this workbook. {}", losses.messages().join(" "));
|
||||
self.notice = Some(Notice { text, kind: NoticeKind::Warning, action: Some(("Save…".into(), "saveLoss".into())) });
|
||||
self.held_losses.insert(uid, losses);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.end_autosave_hold();
|
||||
self.store_view_state();
|
||||
let _ = self.session.run("file.save", json!({}));
|
||||
} else if self.ui.autosave && dirty_xlsx {
|
||||
@@ -126,6 +141,18 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// AutoSave's hold on the active workbook lasts while AutoSave is on and the workbook has
|
||||
/// changes whose loss wasn't agreed to. When it ends, so does its notice (another notice stays),
|
||||
/// and a later hold is said again.
|
||||
fn end_autosave_hold(&mut self) {
|
||||
let Some(uid) = self.session.active().map(|d| d.uid) else { return };
|
||||
if self.held_losses.remove(&uid).is_some()
|
||||
&& self.notice.as_ref().is_some_and(|n| n.action.as_ref().is_some_and(|(_, dialog)| dialog == "saveLoss"))
|
||||
{
|
||||
self.notice = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Flip AutoSave (title-bar switch / Options ▸ Save). Persisted with the other UI
|
||||
/// preferences, so it stays as the user left it across restarts (#1901).
|
||||
pub fn toggle_autosave(&mut self) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use craft_ui::shell::embed::CloseDecision;
|
||||
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
|
||||
|
||||
use super::{SaveAnswer, SheetApp, json};
|
||||
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
|
||||
|
||||
impl SheetApp {
|
||||
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
|
||||
@@ -77,18 +78,137 @@ impl SheetApp {
|
||||
if !self.commit_edit(0, 0, false, false) {
|
||||
return false;
|
||||
}
|
||||
self.run_or_alert("file.save", json!({}));
|
||||
if self.session.active().is_some_and(|x| !x.is_dirty()) {
|
||||
self.run_or_alert("file.close", json!({"force": true, "document": true}));
|
||||
if quitting {
|
||||
self.continue_quit(ctx);
|
||||
let request = SaveRequest::Command { id: "file.save".into(), params: json!({}) };
|
||||
self.save_then(request, AfterSave { close: true, quit: quitting }, ctx);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn close_if_saved(&mut self, quitting: bool, ctx: &egui::Context) {
|
||||
if self.session.active().is_some_and(|x| !x.is_dirty()) {
|
||||
self.run_or_alert("file.close", json!({"force": true, "document": true}));
|
||||
if quitting {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a save and then `after`. When the save (or the Save As it leads to) has to ask what it
|
||||
/// may lose, the question takes `after` along and the answer goes on with it.
|
||||
fn save_then(&mut self, request: SaveRequest, after: AfterSave, ctx: &egui::Context) {
|
||||
self.after_save = Some(after);
|
||||
match request {
|
||||
SaveRequest::Command { id, params } => self.run_or_alert(&id, params),
|
||||
SaveRequest::Download => {
|
||||
if !self.hold_save(SaveRequest::Download) {
|
||||
self.download_workbook("xlsx");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(after) = self.after_save.take()
|
||||
&& after.close
|
||||
{
|
||||
self.close_if_saved(after.quit, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds back a save that would lose something the user hasn't agreed to losing, and asks.
|
||||
/// Returns whether it was held: the answer runs it ([`Self::answer_save_loss`]).
|
||||
pub(super) fn hold_save(&mut self, request: SaveRequest) -> bool {
|
||||
let losses = self.save_losses_to_ask(&request);
|
||||
let Some(doc) = self.session.active().map(|d| d.uid).filter(|_| !losses.is_empty()) else { return false };
|
||||
let destination = self.save_destination(&request);
|
||||
let pending = PendingSave { doc, request, destination, losses, after: self.after_save.take().unwrap_or_default() };
|
||||
if let Err(e) = self.commit_text_box_edit() {
|
||||
self.message = Some(("Text Box".into(), super::clean_error(&e)));
|
||||
} else {
|
||||
self.replace_dialog(|_| Some(crate::dialogs::Dialog::save_loss(pending)));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The file a held save writes when it names none: the active workbook's own file.
|
||||
fn save_destination(&self, request: &SaveRequest) -> Option<String> {
|
||||
match request {
|
||||
SaveRequest::Command { id, params } if id == "file.save" && params.get("path").is_none() => {
|
||||
self.session.active().and_then(|d| d.path.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the save would lose, unless the user already agreed to exactly that for this document.
|
||||
pub(super) fn save_losses_to_ask(&self, request: &SaveRequest) -> SaveLosses {
|
||||
let losses = match request {
|
||||
SaveRequest::Command { id, params } => save_losses(&self.session, id, params),
|
||||
SaveRequest::Download => xlsx_save_losses(&self.session),
|
||||
};
|
||||
let agreed = self.session.active().and_then(|d| self.accepted_losses.get(&d.uid));
|
||||
if agreed == Some(&losses) { SaveLosses::default() } else { losses }
|
||||
}
|
||||
|
||||
/// Answers the question [`Self::hold_save`] asked. Returns whether it is settled: a cancelled
|
||||
/// file picker keeps it open.
|
||||
pub(crate) fn answer_save_loss(&mut self, answer: SaveLossAnswer, pending: PendingSave, ctx: &egui::Context) -> bool {
|
||||
if answer == SaveLossAnswer::Cancel {
|
||||
return true;
|
||||
}
|
||||
// The question stays in its window, so its workbook is the active one; should another be,
|
||||
// nothing is saved that the user wasn't asked about.
|
||||
if self.session.active().map(|d| d.uid) != Some(pending.doc) {
|
||||
self.message = Some(("GridCraft".into(), "The workbook this question was about is no longer in front, so nothing was saved.".into()));
|
||||
return true;
|
||||
}
|
||||
match answer {
|
||||
SaveLossAnswer::Cancel => {}
|
||||
// The workbook's file changed while the question was open (a Save As through
|
||||
// automation): the save is asked about again for the file it would write now.
|
||||
SaveLossAnswer::Anyway if self.save_destination(&pending.request) != pending.destination => {
|
||||
self.save_then(pending.request, pending.after, ctx);
|
||||
}
|
||||
SaveLossAnswer::Anyway => {
|
||||
self.accepted_losses.insert(pending.doc, pending.losses);
|
||||
self.save_then(pending.request, pending.after, ctx);
|
||||
}
|
||||
SaveLossAnswer::Json => {
|
||||
let title = self.session.active().map(|d| d.display_title()).unwrap_or_else(|| "Book1".into());
|
||||
let name = std::path::Path::new(&title).with_extension("json").to_string_lossy().into_owned();
|
||||
if let Some(pick) = &self.services.pick_save {
|
||||
let Some(path) = pick(&name) else { return false };
|
||||
// The picked name is kept (the picker asked about replacing that file): another
|
||||
// type goes by its extension, and asks again if it loses something.
|
||||
let path = if std::path::Path::new(&path).extension().is_none() { format!("{path}.json") } else { path };
|
||||
self.save_then(SaveRequest::Command { id: "file.save".into(), params: json!({"path": path}) }, pending.after, ctx);
|
||||
} else if self.services.download.is_some() {
|
||||
self.download_workbook("json");
|
||||
if pending.after.close {
|
||||
self.close_if_saved(pending.after.quit, ctx);
|
||||
}
|
||||
} else {
|
||||
self.message =
|
||||
Some(("GridCraft".into(), "Saving under another name needs a file picker, which this window doesn't have.".into()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Hands the workbook, encoded as `format`, to the browser.
|
||||
pub(super) fn download_workbook(&mut self, format: &str) {
|
||||
match self.run("file.saveBytes", json!({"format": format})) {
|
||||
Ok(r) => {
|
||||
if let Some(dl) = &self.services.download
|
||||
&& let Some(b) = r.get("base64").and_then(Json::as_str).and_then(gridcraft_engine::io::base64_decode)
|
||||
{
|
||||
dl(r.get("name").and_then(Json::as_str).unwrap_or("Book.xlsx"), &b);
|
||||
}
|
||||
}
|
||||
Err(e) => self.alert(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Quit (the macOS app menu, ⌘Q): commits every window's cell draft as Enter would, lets the
|
||||
/// macro step editor ask about its unsaved steps, then asks about each unsaved workbook in its
|
||||
/// window; Cancel on any of them stops the quit. A draft its
|
||||
@@ -121,3 +241,64 @@ impl SheetApp {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
/// Save Anyway answers for the workbook that asked: with another one active, nothing is
|
||||
/// written and nothing is agreed to for it.
|
||||
#[test]
|
||||
fn a_save_loss_answer_never_acts_on_another_workbook() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-owner-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, crate::Services::default());
|
||||
app.run("file.save", json!({"path": at("First.xlsx")})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"excluded": true})).unwrap();
|
||||
let first = app.session.active().unwrap().uid;
|
||||
app.run_or_alert("file.save", json!({}));
|
||||
let pending = app.dialog.as_ref().and_then(|d| d.pending_save()).unwrap();
|
||||
assert_eq!(pending.doc, first);
|
||||
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.run("file.save", json!({"path": at("Second.xlsx")})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"excluded": true})).unwrap();
|
||||
let (second, before) = (app.session.active().unwrap().uid, std::fs::read(at("Second.xlsx")).unwrap());
|
||||
assert!(app.answer_save_loss(SaveLossAnswer::Anyway, pending, &egui::Context::default()));
|
||||
assert_eq!(std::fs::read(at("Second.xlsx")).unwrap(), before);
|
||||
assert!(app.session.active().is_some_and(|d| d.uid == second && d.is_dirty()));
|
||||
assert!(!app.accepted_losses.contains_key(&second) && app.message.is_some());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
/// A held Save is about the workbook's file when it asked: should that file change before the
|
||||
/// answer, Save Anyway writes neither file and asks again about the new one.
|
||||
#[test]
|
||||
fn save_anyway_asks_again_when_the_workbooks_file_changed() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-moved-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let mut session = gridcraft_engine::Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, crate::Services::default());
|
||||
app.run("file.save", json!({"path": at("First.xlsx")})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"excluded": true})).unwrap();
|
||||
app.run_or_alert("file.save", json!({}));
|
||||
let pending = app.dialog.as_ref().and_then(|d| d.pending_save()).unwrap();
|
||||
|
||||
// While the question is open, automation gives the same workbook another file and changes it.
|
||||
app.run("file.saveAs", json!({"path": at("Moved.xlsx")})).unwrap();
|
||||
app.run("cell.set", json!({"cell": "A1", "input": "changed"})).unwrap();
|
||||
let (first, moved) = (std::fs::read(at("First.xlsx")).unwrap(), std::fs::read(at("Moved.xlsx")).unwrap());
|
||||
assert!(app.answer_save_loss(SaveLossAnswer::Anyway, pending, &egui::Context::default()));
|
||||
assert_eq!(std::fs::read(at("First.xlsx")).unwrap(), first);
|
||||
assert_eq!(std::fs::read(at("Moved.xlsx")).unwrap(), moved);
|
||||
assert!(app.session.active().is_some_and(|d| d.is_dirty()));
|
||||
let again = app.dialog.as_ref().and_then(|d| d.pending_save()).unwrap();
|
||||
assert_eq!(again.destination.as_deref(), Some(at("Moved.xlsx").as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -723,7 +723,9 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
|
||||
let before = app.session.active().map(|d| (d.path.clone(), d.is_dirty()));
|
||||
app.open_dialog("saveAs", json!({}));
|
||||
let after = app.session.active().map(|d| (d.path.clone(), d.is_dirty()));
|
||||
if after != before || app.services.pick_save.is_none() {
|
||||
// A question about what the save would lose shows over the sheet.
|
||||
let asking = app.dialog.as_ref().is_some_and(|d| d.name() == "saveLoss");
|
||||
if after != before || asking || app.services.pick_save.is_none() {
|
||||
out.close = true;
|
||||
}
|
||||
} else if export_as(app, fmt) {
|
||||
|
||||
@@ -262,6 +262,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
for (id, label, params) in [
|
||||
("ui.ribbonTab", "Ribbon Tab", ""),
|
||||
("app.checkForUpdates", "Check for Updates…", ""),
|
||||
(
|
||||
"data.fromClipboard",
|
||||
"From Clipboard",
|
||||
"{delimiter?, at?} → as data.fromTextCsv {text, delimiter?, at?} with the text on the system clipboard: into a new sheet, or at the cell `at`",
|
||||
),
|
||||
("view.collapseRibbon", "Collapse Ribbon", ""),
|
||||
(
|
||||
"view.expandFormulaBar",
|
||||
|
||||
@@ -32,7 +32,7 @@ mod zoom;
|
||||
|
||||
use analysis::toolpak_defaults;
|
||||
use charts::select_chart;
|
||||
use data::{abs, data_validation_fields, remove_duplicates_range, validation_defaults};
|
||||
use data::{abs, data_validation_fields, from_clipboard_form, remove_duplicates_range, validation_defaults};
|
||||
use find::go_to_entries;
|
||||
pub(crate) use names::insert_name;
|
||||
use names::pasteable_names;
|
||||
@@ -81,6 +81,8 @@ pub struct Dialog {
|
||||
/// Open Hyperlink: the address the prompt shows, which OK opens. Private, unlike `values`, so
|
||||
/// `ui.dialog.set` can't swap it behind the text the user reads (#2181).
|
||||
link: Option<String>,
|
||||
/// Save Workbook: the save the question holds back. Not in `values`, as for `link`.
|
||||
save: Option<crate::state::PendingSave>,
|
||||
pub(crate) focus_initialized: bool,
|
||||
/// The formula box that takes references clicked or dragged on the grid (New Formatting Rule).
|
||||
pick: Option<RefPick>,
|
||||
@@ -138,6 +140,10 @@ impl Dialog {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Typing a separator in From Clipboard's Other box chooses Other.
|
||||
if self.name == "fromClipboard" && key == "other" && value.as_str().is_some_and(|s| !s.is_empty()) {
|
||||
self.values.insert("separator".into(), json!("other"));
|
||||
}
|
||||
self.values.insert(key.into(), value);
|
||||
}
|
||||
|
||||
@@ -245,6 +251,7 @@ impl Dialog {
|
||||
picture_target: None,
|
||||
back: None,
|
||||
link: None,
|
||||
save: None,
|
||||
focus_initialized: false,
|
||||
pick: None,
|
||||
original_link_text: None,
|
||||
@@ -271,6 +278,7 @@ impl Dialog {
|
||||
picture_target: None,
|
||||
back: None,
|
||||
link: None,
|
||||
save: None,
|
||||
focus_initialized: false,
|
||||
pick: None,
|
||||
original_link_text: None,
|
||||
@@ -279,6 +287,16 @@ impl Dialog {
|
||||
}
|
||||
|
||||
/// Opens the named dialog with defaults from the active workbook, including a cell's stored hyperlink.
|
||||
/// The save the Save Workbook question holds back.
|
||||
pub(crate) fn pending_save(&self) -> Option<crate::state::PendingSave> {
|
||||
self.save.clone()
|
||||
}
|
||||
|
||||
/// The question a save asks first about what it would lose.
|
||||
pub(crate) fn save_loss(pending: crate::state::PendingSave) -> Dialog {
|
||||
Dialog { save: Some(pending), ..Dialog::custom("saveLoss", "Save Workbook", json!({})) }
|
||||
}
|
||||
|
||||
pub fn open(app: &mut SheetApp, name: &str, params: Json) -> Option<Dialog> {
|
||||
let sel = app.session.active().map(|d| d.selection.current().a1()).unwrap_or_default();
|
||||
let active = app.session.active().map(|d| d.selection.active.a1()).unwrap_or_default();
|
||||
@@ -687,6 +705,7 @@ impl Dialog {
|
||||
],
|
||||
json!({"tab": true, "comma": true, "destination": active}),
|
||||
),
|
||||
"fromClipboard" => from_clipboard_form(app, p("at").as_str())?,
|
||||
"removeDuplicates" => Dialog::form(
|
||||
"removeDuplicates",
|
||||
"Remove Duplicates",
|
||||
|
||||
@@ -3,6 +3,44 @@ use super::show::build_params;
|
||||
use super::show::{form_fields, ok_cancel};
|
||||
use super::{Dialog, Field, Json, SheetApp, json, vec2};
|
||||
|
||||
/// Data › Get Data › From Clipboard…, and the cell menu's Paste Data… with the cell `at`: the
|
||||
/// separator to split the clipboard text at, starting on the one the text seems to use. The text
|
||||
/// read now is the text OK imports, whatever the clipboard holds by then. With no text to import
|
||||
/// that is said now, not after OK.
|
||||
pub(super) fn from_clipboard_form(app: &mut SheetApp, at: Option<&str>) -> Option<Dialog> {
|
||||
use Field::{Choice, Note, Ref, Text};
|
||||
let text = match app.clipboard_text_to_import() {
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
app.alert(e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let separator = match gridcraft_engine::io::guess_separator(&text) {
|
||||
'\t' => "tab",
|
||||
';' => "semicolon",
|
||||
_ => "comma",
|
||||
};
|
||||
// From Paste Data… the columns go in at the cell; from Get Data, into a new sheet. As a
|
||||
// reference box the cell means the sheet the dialog opened on, whichever is shown by OK.
|
||||
let mut fields = Vec::new();
|
||||
if at.is_some() {
|
||||
fields.push(Note("The columns replace what is there.".into()));
|
||||
fields.push(Ref { key: "at", label: "Paste at:" });
|
||||
}
|
||||
fields.extend([
|
||||
Choice {
|
||||
key: "separator",
|
||||
label: "Separator",
|
||||
// Keyed as Text to Columns keys it: the separator, not the Comma cell style.
|
||||
options: vec![("comma", "Text to Columns|Comma"), ("semicolon", "Semicolon"), ("tab", "Tab"), ("space", "Space"), ("other", "Other")],
|
||||
},
|
||||
Text { key: "other", label: "Other separator:" },
|
||||
]);
|
||||
let title = if at.is_some() { "Paste Data" } else { "Import from Clipboard" };
|
||||
Some(Dialog::form("fromClipboard", title, "data.fromTextCsv", fields, json!({"separator": separator, "other": "", "at": at, "text": text})))
|
||||
}
|
||||
|
||||
/// Initial values of the Data Validation form: the rule stored on the active cell, so OK without
|
||||
/// edits keeps it; a plain list rule when the cell has none.
|
||||
pub(super) fn validation_defaults(app: &SheetApp) -> Json {
|
||||
|
||||
@@ -57,6 +57,16 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
|
||||
}
|
||||
}
|
||||
}
|
||||
"fromClipboard" => {
|
||||
let delimiter = match d.values.get("separator").and_then(Json::as_str) {
|
||||
Some("semicolon") => ";",
|
||||
Some("tab") => "\t",
|
||||
Some("space") => " ",
|
||||
Some("other") => d.values.get("other").and_then(Json::as_str).unwrap_or_default(),
|
||||
_ => ",",
|
||||
};
|
||||
v = json!({ "text": d.values.get("text"), "delimiter": delimiter, "at": d.values.get("at") });
|
||||
}
|
||||
"textToColumns" => {
|
||||
let mut delims = Vec::new();
|
||||
for (k, c) in [("tab", "\t"), ("semicolon", ";"), ("comma", ","), ("space", " ")] {
|
||||
@@ -374,6 +384,24 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
}
|
||||
"saveLoss" => {
|
||||
let lang = app.ui.language;
|
||||
let pending = d.pending_save();
|
||||
for loss in pending.iter().flat_map(|p| p.losses.messages()) {
|
||||
ui.add(egui::Label::new(loss).wrap());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
for (label, answer) in [
|
||||
("Cancel", crate::SaveLossAnswer::Cancel),
|
||||
("Save Anyway", crate::SaveLossAnswer::Anyway),
|
||||
("Save as GridCraft Workbook…", crate::SaveLossAnswer::Json),
|
||||
] {
|
||||
if ui.button(lang.tr(label)).clicked() && pending.clone().is_none_or(|p| app.answer_save_loss(answer, p, ui.ctx())) {
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
"start" => {
|
||||
ui.heading("Start a new workbook");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
@@ -634,7 +662,7 @@ pub(super) fn form_fields(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
};
|
||||
take_first_focus(d, &r);
|
||||
if r.changed() {
|
||||
d.values.insert(key.into(), json!(s));
|
||||
d.set_value(key, json!(s));
|
||||
}
|
||||
if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == key) {
|
||||
track_pick(pick, &r, r.changed());
|
||||
|
||||
@@ -134,6 +134,7 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
("Copy", "edit.copy"),
|
||||
("Paste", "edit.paste"),
|
||||
("Paste Special…", "ui:pasteSpecial"),
|
||||
("Paste Data…", "ui:pasteData"),
|
||||
("-", ""),
|
||||
("Insert…", "ui:insertCells"),
|
||||
("Delete…", "ui:deleteCells"),
|
||||
@@ -151,8 +152,10 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
("Define Name…", "ui:defineName"),
|
||||
("Link…", "ui:insertLink"),
|
||||
];
|
||||
if let Some(item) = insert_copied {
|
||||
items.insert(6, item);
|
||||
if let Some(item) = insert_copied
|
||||
&& let Some(i) = items.iter().position(|(_, id)| *id == "ui:insertCells")
|
||||
{
|
||||
items.insert(i + 1, item);
|
||||
}
|
||||
if link.is_some()
|
||||
&& let Some(i) = items.iter().position(|(_, id)| *id == "ui:insertLink")
|
||||
@@ -178,6 +181,11 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
close = true;
|
||||
match id {
|
||||
"ui:pasteSpecial" => app.open_dialog("pasteSpecial", json!({})),
|
||||
"ui:pasteData" => {
|
||||
// Where Paste pastes: the selection's top-left cell.
|
||||
let at = app.session.active().map(|d| d.selection.current().start.a1());
|
||||
app.open_dialog("fromClipboard", json!({"at": at}));
|
||||
}
|
||||
"ui:insertPaste" => app.open_dialog("insertPaste", json!({})),
|
||||
"ui:insertCells" => app.open_dialog("insertCells", json!({})),
|
||||
"ui:deleteCells" => app.open_dialog("deleteCells", json!({})),
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct KeyTips {
|
||||
alt_held: bool,
|
||||
// Keep consuming a held mnemonic after its action closes keytips.
|
||||
held: Vec<Key>,
|
||||
// Up or Down pressed this frame while a sequence was under way, for a menu that key tips
|
||||
// opened to take (`take_menu_arrow`).
|
||||
menu_arrow: Option<Key>,
|
||||
}
|
||||
|
||||
impl KeyTips {
|
||||
@@ -45,6 +48,13 @@ impl KeyTips {
|
||||
self.alt_armed = false;
|
||||
self.alt_held = false;
|
||||
self.held.clear();
|
||||
self.menu_arrow = None;
|
||||
}
|
||||
|
||||
/// Up or Down pressed this frame during a sequence: a menu that key tips opened (Alt, H, V)
|
||||
/// takes it to move keyboard focus onto its items. Unclaimed, it is dropped next frame.
|
||||
pub fn take_menu_arrow(&mut self) -> Option<Key> {
|
||||
self.menu_arrow.take()
|
||||
}
|
||||
|
||||
fn toggle(&mut self) {
|
||||
@@ -54,6 +64,7 @@ impl KeyTips {
|
||||
|
||||
/// Remove only handled events before any text editors or the grid see them.
|
||||
pub fn process(&mut self, ctx: &Context, enabled: bool) -> Vec<Action> {
|
||||
self.menu_arrow = None;
|
||||
if !enabled || !ctx.input(|i| i.focused) {
|
||||
self.clear();
|
||||
return Vec::new();
|
||||
@@ -121,6 +132,8 @@ impl KeyTips {
|
||||
handled = true;
|
||||
if *key == Key::Escape {
|
||||
self.back();
|
||||
} else if matches!(key, Key::ArrowDown | Key::ArrowUp) {
|
||||
self.menu_arrow = Some(*key);
|
||||
} else if key.name().len() == 1 {
|
||||
let next = format!("{}{key_name}", self.prefix.as_deref().unwrap_or_default(), key_name = key.name());
|
||||
match keytip_table::lookup(&next) {
|
||||
|
||||
@@ -287,6 +287,7 @@ pub const SEQUENCES: &[(&str, Entry)] = &[
|
||||
("AO", Entry::Finish(Action::Command("data.queriesConnections"))), // Excel: Queries & Connections
|
||||
("AP1", Entry::Finish(Action::Command("file.properties"))), // Excel: Properties
|
||||
("APN", Entry::Continue), // Excel: Get Data (Power Query) Menu; group level: Power Query variants = GAP
|
||||
("APNC", Entry::Finish(Action::Dialog("fromClipboard"))), // Excel: (none); From Clipboard… item GridCraft adds to the Get Data menu (Excel's has none); C is free under APN
|
||||
("APND", Entry::Finish(Action::Pending("data.fromDatabase"))), // pending; Excel: From Database (Microsoft Query); gap #12; reserved until the command lands
|
||||
("APNE", Entry::Finish(Action::Pending("data.powerQueryEditor"))), // pending; Excel: Launch Power Query Editor; gap #12; reserved until the command lands
|
||||
("APNG", Entry::Finish(Action::Command("data.getData"))), // Excel: Get Data (Power Query); containment(Get Data)
|
||||
|
||||
@@ -1972,6 +1972,13 @@
|
||||
"excel": "Get Data (Power Query) Menu",
|
||||
"note": "group level: Power Query variants = GAP"
|
||||
},
|
||||
{
|
||||
"seq": "APNC",
|
||||
"kind": "dialog",
|
||||
"target": "fromClipboard",
|
||||
"excel": "(none)",
|
||||
"note": "From Clipboard… item GridCraft adds to the Get Data menu (Excel's has none); C is free under APN"
|
||||
},
|
||||
{
|
||||
"seq": "APND",
|
||||
"kind": "command",
|
||||
|
||||
@@ -88,7 +88,7 @@ mod state;
|
||||
|
||||
pub use clock::{monotonic_ms, now_ms};
|
||||
pub use services::{Chrome, Inbox, Services};
|
||||
pub use state::{NoticeKind, OpenWindow, SaveAnswer, SheetView};
|
||||
pub use state::{NoticeKind, OpenWindow, SaveAnswer, SaveLossAnswer, SheetView};
|
||||
pub mod desktop_theme;
|
||||
|
||||
fn parse_resize_direction(value: &str) -> Option<egui::ResizeDirection> {
|
||||
@@ -323,6 +323,12 @@ pub struct SheetApp {
|
||||
/// text noted for an unpublished cut); `None` after a copy, or once the clipboard is seen
|
||||
/// holding other text. Once the cut has been pasted, Paste leaves this text alone.
|
||||
cut_text: Option<String>,
|
||||
/// Save losses the user said yes to, per document uid: saving asks again only about others.
|
||||
accepted_losses: std::collections::HashMap<u64, gridcraft_engine::cmd::file::SaveLosses>,
|
||||
/// The losses AutoSave last held back for, per document uid, so it says so once.
|
||||
held_losses: std::collections::HashMap<u64, gridcraft_engine::cmd::file::SaveLosses>,
|
||||
/// What follows the save being run, until a question holds that save back and takes it along.
|
||||
after_save: Option<state::AfterSave>,
|
||||
/// A run of Tabs: (doc uid, sheet, column it started in, cell the last Tab landed on).
|
||||
/// Enter on that cell goes to the next row in the starting column, as in Excel (#911).
|
||||
tab_run: Option<(u64, usize, u32, CellRef)>,
|
||||
|
||||
@@ -274,6 +274,7 @@ fn combo_popup(
|
||||
}
|
||||
|
||||
pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str, serde_json::Value)]) {
|
||||
let mut buttons = Vec::new();
|
||||
for (label, id, p) in items {
|
||||
if *label == "-" {
|
||||
ui.separator();
|
||||
@@ -285,6 +286,13 @@ pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str,
|
||||
keytip(app, ui, sequence, pos2(response.rect.right() - 10.0, response.rect.center().y));
|
||||
}
|
||||
if response.clicked() {
|
||||
// Enter on a focused item clicks it without a pointer click to close the menu, and the
|
||||
// same press must not also confirm the dialog or message the item opens.
|
||||
ui.close();
|
||||
ui.input_mut(|i| {
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Enter);
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Space);
|
||||
});
|
||||
if let Some(d) = id.strip_prefix("dialog:") {
|
||||
app.open_dialog(d, p.clone());
|
||||
} else if *id == "edit.paste" {
|
||||
@@ -293,6 +301,36 @@ pub(super) fn menu_items(app: &mut SheetApp, ui: &mut Ui, items: &[(&str, &str,
|
||||
act(app, id, p.clone());
|
||||
}
|
||||
}
|
||||
buttons.push(response);
|
||||
}
|
||||
menu_focus(app, ui, &buttons);
|
||||
}
|
||||
|
||||
/// Up and Down in a menu, as in Excel's: in one that key tips opened (Alt, H, V), the first press
|
||||
/// ends key tips and moves keyboard focus onto the first or last item; egui then moves it between
|
||||
/// items, Enter runs the focused one and Esc closes the menu. Focus wraps at the ends rather than
|
||||
/// leaving the open menu.
|
||||
fn menu_focus(app: &mut SheetApp, ui: &Ui, buttons: &[egui::Response]) {
|
||||
let (Some(first), Some(last)) = (buttons.first(), buttons.last()) else { return };
|
||||
if let Some(key) = app.keytips.take_menu_arrow() {
|
||||
app.keytips.clear();
|
||||
let target = if key == egui::Key::ArrowUp { last } else { first };
|
||||
target.request_focus();
|
||||
// egui read the arrow before key tips took it: with a widget focused, it would move on
|
||||
// from the item just focused.
|
||||
ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
|
||||
return;
|
||||
}
|
||||
let focused = buttons.iter().position(egui::Response::has_focus);
|
||||
let wrap = ui.input(|i| match focused {
|
||||
Some(0) if i.key_pressed(egui::Key::ArrowUp) => Some(last),
|
||||
Some(n) if n + 1 == buttons.len() && i.key_pressed(egui::Key::ArrowDown) => Some(first),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(target) = wrap {
|
||||
target.request_focus();
|
||||
// Instead of the move egui would make, out of the menu.
|
||||
ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
use super::controls::{act, control_keytip, keytip, menu_items, sep};
|
||||
use super::{Icon, SheetApp, Ui, big_button, json, keytip_table, small_button};
|
||||
use super::controls::{act, control_keytip, keytip, menu_items, popup_command, sep};
|
||||
use super::{Icon, SheetApp, Ui, big_button, big_split_button, json, keytip_table, small_button};
|
||||
|
||||
pub(super) fn data(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let gd = big_button(ui, Icon::Folder, "Get Data\n(Text/CSV)", "Import a text or CSV file", false);
|
||||
control_keytip(app, ui, &gd, "data.getData");
|
||||
// The button opens a text or CSV file; its menu can also import the text on the clipboard.
|
||||
let (gd, gd_menu) = big_split_button(ui, Icon::Folder, "Get Data\n(Text/CSV)", "Import a text or CSV file");
|
||||
// Alt, A, P, N opens the menu with its item letters, G for a file and C for the clipboard,
|
||||
// which the button's own badge would repeat.
|
||||
let keyed = keytip_table::opens_menu(app.keytips.prefix().unwrap_or_default(), "data.getData");
|
||||
if !keyed {
|
||||
control_keytip(app, ui, &gd_menu, "data.getData");
|
||||
}
|
||||
if gd.clicked() {
|
||||
app.open_dialog("open", json!({}));
|
||||
}
|
||||
egui::Popup::menu(&gd_menu).open_memory(popup_command(keyed, gd_menu.clicked())).show(|ui| {
|
||||
menu_items(app, ui, &[("From Text/CSV…", "data.getData", json!({})), ("From Clipboard…", "dialog:fromClipboard", json!({}))]);
|
||||
});
|
||||
sep(ui);
|
||||
ui.vertical(|ui| {
|
||||
let __k = small_button(ui, Icon::SortAsc, "", "Sort A to Z", false);
|
||||
|
||||
@@ -19,6 +19,49 @@ pub enum SaveAnswer {
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// How a save held back for an answer goes on.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum SaveRequest {
|
||||
/// The save command as it was run (`file.save` or `file.saveAs`, with its params).
|
||||
Command { id: String, params: serde_json::Value },
|
||||
/// The web's Save, which hands the .xlsx file to the browser.
|
||||
Download,
|
||||
}
|
||||
|
||||
/// What follows a save once it has written the workbook.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct AfterSave {
|
||||
/// Close the workbook (Save Changes asked while closing it).
|
||||
pub close: bool,
|
||||
/// Then go on quitting.
|
||||
pub quit: bool,
|
||||
}
|
||||
|
||||
/// A save that waits for the answer to what it would lose: all the question is about, so
|
||||
/// answering it never acts on whatever happens to be active, or on what the question became.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct PendingSave {
|
||||
/// The workbook that asked (its document uid).
|
||||
pub doc: u64,
|
||||
pub request: SaveRequest,
|
||||
/// The file a Save without a path of its own writes: the workbook's file when it asked. Should
|
||||
/// the workbook's file change before the answer, the question is asked again for the new one.
|
||||
pub destination: Option<String>,
|
||||
/// Exactly what the user is asked about.
|
||||
pub losses: gridcraft_engine::cmd::file::SaveLosses,
|
||||
pub after: AfterSave,
|
||||
}
|
||||
|
||||
/// An answer to the question a save that would lose something asks first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SaveLossAnswer {
|
||||
/// Save in the format asked for, without what it can't keep.
|
||||
Anyway,
|
||||
/// Save as a GridCraft workbook (.json), which keeps it.
|
||||
Json,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// One open window, as View › Switch Windows and the macOS Window menu list it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OpenWindow {
|
||||
|
||||
@@ -26,8 +26,8 @@ mod font_setup;
|
||||
pub use font_fallback::symbol_face_installed;
|
||||
#[cfg(test)]
|
||||
use font_fallback::{
|
||||
PREFERRED_ARABIC, arabic, cjk_han_japanese, cjk_han_simplified, cjk_hangul, fallback_faces, hebrew, lao, load_faces, preferred_file,
|
||||
symbols_more, thai,
|
||||
Indic, PREFERRED_ARABIC, arabic, cjk_han_japanese, cjk_han_simplified, cjk_hangul, fallback_faces, hebrew, indic, lao, load_faces,
|
||||
preferred_file, symbols_more, thai,
|
||||
};
|
||||
#[cfg(all(test, unix, not(target_os = "macos")))]
|
||||
use font_fallback::{covers_arabic, fontconfig_arabic, parse_fc_match};
|
||||
|
||||
@@ -127,6 +127,15 @@ pub(super) fn fallback_faces(han: HanOrder) -> Vec<(&'static str, Vec<(String, u
|
||||
("sys-lao", lao()),
|
||||
("sys-hebrew", hebrew()),
|
||||
("sys-arabic", arabic()),
|
||||
("sys-devanagari", indic(Indic::Devanagari)),
|
||||
("sys-bengali", indic(Indic::Bengali)),
|
||||
("sys-gurmukhi", indic(Indic::Gurmukhi)),
|
||||
("sys-gujarati", indic(Indic::Gujarati)),
|
||||
("sys-odia", indic(Indic::Odia)),
|
||||
("sys-tamil", indic(Indic::Tamil)),
|
||||
("sys-telugu", indic(Indic::Telugu)),
|
||||
("sys-kannada", indic(Indic::Kannada)),
|
||||
("sys-malayalam", indic(Indic::Malayalam)),
|
||||
("sys-symbols", symbols()),
|
||||
("sys-symbols-2", symbols_more()),
|
||||
]
|
||||
@@ -330,6 +339,93 @@ pub(super) fn arabic() -> Vec<(String, u32)> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The Indian scripts with a fallback face. epaint shapes every run with harfrust, so a face with
|
||||
/// the script's OpenType tables is all conjuncts and reordered vowel signs need.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Indic {
|
||||
Devanagari,
|
||||
Bengali,
|
||||
Gurmukhi,
|
||||
Gujarati,
|
||||
Odia,
|
||||
Tamil,
|
||||
Telugu,
|
||||
Kannada,
|
||||
Malayalam,
|
||||
}
|
||||
|
||||
/// Indian-script faces. Windows' Nirmala UI covers all nine scripts (loaded once, see
|
||||
/// [`load_fallback`]), with the older per-script faces behind it; macOS ships Kohinoor, Noto and
|
||||
/// Sangam MN faces; Linux and the BSDs usually have Noto Sans or Lohit.
|
||||
/// A script's faces: Windows file, macOS files with the Regular face's index, Noto name, Lohit
|
||||
/// directory and file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
type IndicFaces = (&'static str, &'static [(&'static str, u32)], &'static str, (&'static str, &'static str));
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn indic(script: Indic) -> Vec<(String, u32)> {
|
||||
let mac_sys = "/System/Library/Fonts";
|
||||
let mac_sup = "/System/Library/Fonts/Supplemental";
|
||||
let win = windows_fonts();
|
||||
// (Windows face, macOS faces with the Regular face's index, Noto name, Lohit directory and file)
|
||||
let (win_face, mac, noto, lohit): IndicFaces = match script {
|
||||
Indic::Devanagari => (
|
||||
"mangal.ttf",
|
||||
&[("{sys}/Kohinoor.ttc", 0), ("{sup}/Devanagari Sangam MN.ttc", 0), ("{sup}/ITFDevanagari.ttc", 0)],
|
||||
"Devanagari",
|
||||
("lohit-devanagari", "Lohit-Devanagari"),
|
||||
),
|
||||
Indic::Bengali => {
|
||||
("vrinda.ttf", &[("{sys}/KohinoorBangla.ttc", 0), ("{sup}/Bangla Sangam MN.ttc", 0)], "Bengali", ("lohit-bengali", "Lohit-Bengali"))
|
||||
}
|
||||
Indic::Gurmukhi => {
|
||||
("raavi.ttf", &[("{sup}/Gurmukhi Sangam MN.ttc", 0), ("{sup}/Gurmukhi MN.ttc", 0)], "Gurmukhi", ("lohit-punjabi", "Lohit-Gurmukhi"))
|
||||
}
|
||||
Indic::Gujarati => (
|
||||
"shruti.ttf",
|
||||
&[("{sys}/KohinoorGujarati.ttc", 3), ("{sup}/Gujarati Sangam MN.ttc", 0)],
|
||||
"Gujarati",
|
||||
("lohit-gujarati", "Lohit-Gujarati"),
|
||||
),
|
||||
Indic::Odia => ("kalinga.ttf", &[("{sys}/NotoSansOriya.ttc", 0), ("{sup}/Oriya Sangam MN.ttc", 0)], "Oriya", ("lohit-oriya", "Lohit-Odia")),
|
||||
Indic::Tamil => ("latha.ttf", &[("{sup}/Tamil Sangam MN.ttc", 0), ("{sup}/Tamil MN.ttc", 0)], "Tamil", ("lohit-tamil", "Lohit-Tamil")),
|
||||
Indic::Telugu => {
|
||||
("gautami.ttf", &[("{sys}/KohinoorTelugu.ttc", 0), ("{sup}/Telugu Sangam MN.ttc", 0)], "Telugu", ("lohit-telugu", "Lohit-Telugu"))
|
||||
}
|
||||
Indic::Kannada => {
|
||||
("tunga.ttf", &[("{sys}/NotoSansKannada.ttc", 3), ("{sup}/Kannada Sangam MN.ttc", 0)], "Kannada", ("lohit-kannada", "Lohit-Kannada"))
|
||||
}
|
||||
Indic::Malayalam => (
|
||||
"kartika.ttf",
|
||||
&[("{sup}/Malayalam Sangam MN.ttc", 0), ("{sup}/Malayalam MN.ttc", 0)],
|
||||
"Malayalam",
|
||||
("lohit-malayalam", "Lohit-Malayalam"),
|
||||
),
|
||||
};
|
||||
let mut v: Vec<(String, u32)> = vec![(format!("{win}\\Nirmala.ttc"), 0), (format!("{win}\\Nirmala.ttf"), 0), (format!("{win}\\{win_face}"), 0)];
|
||||
v.extend(mac.iter().map(|(m, index)| (m.replace("{sys}", mac_sys).replace("{sup}", mac_sup), *index)));
|
||||
let mut linux: Vec<String> = Vec::new();
|
||||
for d in ["truetype/noto", "opentype/noto", "google-noto", "noto", "TTF"] {
|
||||
linux.push(format!("{d}/NotoSans{noto}-Regular.ttf"));
|
||||
}
|
||||
// Fedora ships the variable Noto Sans faces; their default instance is Regular.
|
||||
linux.push(format!("google-noto-vf/NotoSans{noto}[wght].ttf"));
|
||||
let (dir, file) = lohit;
|
||||
for d in ["truetype/", ""] {
|
||||
linux.push(format!("{d}{dir}/{file}.ttf"));
|
||||
}
|
||||
// The system fonts, then the same layouts under a Flatpak sandbox's read-only host mounts.
|
||||
for root in ["/usr/share/fonts", "/run/host/fonts"] {
|
||||
v.extend(linux.iter().map(|f| (format!("{root}/{f}"), 0)));
|
||||
}
|
||||
for root in ["/usr/local/share/fonts", "/run/host/local-fonts"] {
|
||||
v.push((format!("{root}/noto/NotoSans{noto}-Regular.ttf"), 0));
|
||||
v.push((format!("{root}/{dir}/{file}.ttf"), 0));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Symbol faces behind the UI font. Interface fonts such as Noto Sans and Cantarell (and egui's
|
||||
/// built-in Ubuntu) lack arrows, check marks, geometric shapes and keyboard symbols (▾ ✓ ✕ ▲ ↳ ⇧),
|
||||
/// which then render as empty boxes (#197, #54). DejaVu Sans covers most of them; the paths cover
|
||||
|
||||
@@ -122,11 +122,49 @@ fn language_reorders_only_the_han_faces() {
|
||||
let keys = |han| fallback_faces(han).into_iter().map(|(k, _)| k).collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
keys(HanOrder::Japanese),
|
||||
["sys-cjk-han-ja", "sys-cjk-han-zh", "sys-cjk-hangul", "sys-thai", "sys-lao", "sys-hebrew", "sys-arabic", "sys-symbols", "sys-symbols-2"]
|
||||
[
|
||||
"sys-cjk-han-ja",
|
||||
"sys-cjk-han-zh",
|
||||
"sys-cjk-hangul",
|
||||
"sys-thai",
|
||||
"sys-lao",
|
||||
"sys-hebrew",
|
||||
"sys-arabic",
|
||||
"sys-devanagari",
|
||||
"sys-bengali",
|
||||
"sys-gurmukhi",
|
||||
"sys-gujarati",
|
||||
"sys-odia",
|
||||
"sys-tamil",
|
||||
"sys-telugu",
|
||||
"sys-kannada",
|
||||
"sys-malayalam",
|
||||
"sys-symbols",
|
||||
"sys-symbols-2"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
keys(HanOrder::Chinese),
|
||||
["sys-cjk-han-zh", "sys-cjk-han-ja", "sys-cjk-hangul", "sys-thai", "sys-lao", "sys-hebrew", "sys-arabic", "sys-symbols", "sys-symbols-2"]
|
||||
[
|
||||
"sys-cjk-han-zh",
|
||||
"sys-cjk-han-ja",
|
||||
"sys-cjk-hangul",
|
||||
"sys-thai",
|
||||
"sys-lao",
|
||||
"sys-hebrew",
|
||||
"sys-arabic",
|
||||
"sys-devanagari",
|
||||
"sys-bengali",
|
||||
"sys-gurmukhi",
|
||||
"sys-gujarati",
|
||||
"sys-odia",
|
||||
"sys-tamil",
|
||||
"sys-telugu",
|
||||
"sys-kannada",
|
||||
"sys-malayalam",
|
||||
"sys-symbols",
|
||||
"sys-symbols-2"
|
||||
]
|
||||
);
|
||||
assert_eq!(HanOrder::of(Language::Ja), HanOrder::Japanese);
|
||||
for l in [Language::En, Language::Zh, Language::Ko, Language::Ru, Language::PtBr, Language::De, Language::Cs, Language::Fr, Language::Tr] {
|
||||
@@ -185,7 +223,7 @@ fn fallback_covers_its_script() {
|
||||
// face or the optional craft-fonts input provides one; the printed skip is a recorded
|
||||
// gate, and a present face that is not wired in fails.
|
||||
type Case = (&'static str, Vec<(String, u32)>, &'static str);
|
||||
let cases: [Case; 11] = [
|
||||
let cases: [Case; 20] = [
|
||||
("sys-cjk-han-ja", cjk_han_japanese(), "カテゴリ"),
|
||||
// Chinese uses a system Han face or the native-only permitted LXGW craft face; the
|
||||
// barred Noto CJK collection never supplies it.
|
||||
@@ -195,6 +233,16 @@ fn fallback_covers_its_script() {
|
||||
("sys-lao", lao(), "ພາສາລາວ"),
|
||||
("sys-hebrew", hebrew(), "עברית"),
|
||||
("sys-arabic", arabic(), "العربية١٢٣"),
|
||||
// Indian scripts, each with a conjunct or a vowel sign the shaper has to place.
|
||||
("sys-devanagari", indic(Indic::Devanagari), "हिन्दी क्षेत्र"),
|
||||
("sys-bengali", indic(Indic::Bengali), "বাংলা ক্ষেত্র"),
|
||||
("sys-gurmukhi", indic(Indic::Gurmukhi), "ਪੰਜਾਬੀ"),
|
||||
("sys-gujarati", indic(Indic::Gujarati), "ગુજરાતી"),
|
||||
("sys-odia", indic(Indic::Odia), "ଓଡ଼ିଆ"),
|
||||
("sys-tamil", indic(Indic::Tamil), "தமிழ் கொண்டு"),
|
||||
("sys-telugu", indic(Indic::Telugu), "తెలుగు"),
|
||||
("sys-kannada", indic(Indic::Kannada), "ಕನ್ನಡ"),
|
||||
("sys-malayalam", indic(Indic::Malayalam), "മലയാളം"),
|
||||
("craft-noto-sans-arabic", Vec::new(), "مرحبا"),
|
||||
("craft-noto-sans-georgian", Vec::new(), "ქართული"),
|
||||
("ui", candidates(UI), "Русский"),
|
||||
@@ -489,3 +537,81 @@ fn fedora_package_folders_are_searched_after_the_other_linux_layouts() {
|
||||
let noto = mono.iter().position(|p| p == "/usr/share/fonts/google-noto-vf/NotoSansMono[wght].ttf");
|
||||
assert!(noto.is_some() && noto.unwrap_or(0) + 1 == mono.len(), "Fedora's default Noto Sans Mono must be the last resort: {mono:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indic_text_is_shaped_not_drawn_letter_by_letter() {
|
||||
// epaint shapes each run with harfrust, so with a face in the chain a conjunct is one glyph
|
||||
// and a split vowel sign is drawn on both sides of its consonant. Drawn per character, क्ष
|
||||
// would show three glyphs (क, a visible virama, ष) and கொ two.
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(font_definitions());
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {});
|
||||
out.textures_delta.clear(); // nothing consumes the atlas in a headless test
|
||||
let drawn = |text: &str| {
|
||||
let galley = ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), FontId::proportional(14.0), Color32::BLACK));
|
||||
galley.rows.iter().flat_map(|r| r.glyphs.iter()).filter(|g| g.uv_rect.size.x > 0.0).count()
|
||||
};
|
||||
let has = |script| indic(script).iter().any(|(p, _)| std::path::Path::new(p).exists());
|
||||
if has(Indic::Devanagari) {
|
||||
assert_eq!(drawn("क्ष"), 1, "क + virama + ष forms the conjunct क्ष");
|
||||
}
|
||||
if has(Indic::Tamil) {
|
||||
// Shaped, the split vowel sign is either drawn on both sides of க (3 glyphs) or ligated with
|
||||
// it (1, Nirmala UI); one glyph per code point (2) means no shaping.
|
||||
assert_ne!(drawn("கொ"), 2, "the vowel sign ொ is shaped around க");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indic_faces_are_regular_weight() {
|
||||
// A family collection's face order is not alphabetical by weight (macOS's Kohinoor Gujarati
|
||||
// starts with Bold, Noto Sans Kannada with Thin), so each candidate names its Regular face.
|
||||
use skrifa::MetadataProvider;
|
||||
let scripts = [
|
||||
Indic::Devanagari,
|
||||
Indic::Bengali,
|
||||
Indic::Gurmukhi,
|
||||
Indic::Gujarati,
|
||||
Indic::Odia,
|
||||
Indic::Tamil,
|
||||
Indic::Telugu,
|
||||
Indic::Kannada,
|
||||
Indic::Malayalam,
|
||||
];
|
||||
for script in scripts {
|
||||
for (path, index) in indic(script) {
|
||||
let Ok(bytes) = std::fs::read(&path) else { continue };
|
||||
let Ok(font) = skrifa::FontRef::from_index(&bytes, index) else { continue };
|
||||
let weight = font.attributes().weight.value();
|
||||
assert!((350.0..=500.0).contains(&weight), "{script:?}: {path} face {index} has weight {weight}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indic_faces_reach_fedora_and_flatpak_layouts() {
|
||||
// Fedora installs only the variable Noto Sans faces; a Flatpak sees the host's fonts under
|
||||
// /run/host. Missing either leaves the interface in tofu boxes there.
|
||||
let cases = [
|
||||
(Indic::Devanagari, "Devanagari"),
|
||||
(Indic::Bengali, "Bengali"),
|
||||
(Indic::Gurmukhi, "Gurmukhi"),
|
||||
(Indic::Gujarati, "Gujarati"),
|
||||
(Indic::Odia, "Oriya"),
|
||||
(Indic::Tamil, "Tamil"),
|
||||
(Indic::Telugu, "Telugu"),
|
||||
(Indic::Kannada, "Kannada"),
|
||||
(Indic::Malayalam, "Malayalam"),
|
||||
];
|
||||
for (script, noto) in cases {
|
||||
let paths: Vec<String> = indic(script).into_iter().map(|(path, _)| path).collect();
|
||||
for expected in [
|
||||
format!("/usr/share/fonts/google-noto-vf/NotoSans{noto}[wght].ttf"),
|
||||
format!("/run/host/fonts/google-noto-vf/NotoSans{noto}[wght].ttf"),
|
||||
format!("/run/host/fonts/truetype/noto/NotoSans{noto}-Regular.ttf"),
|
||||
format!("/run/host/local-fonts/noto/NotoSans{noto}-Regular.ttf"),
|
||||
] {
|
||||
assert!(paths.contains(&expected), "{script:?} doesn't probe {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,3 +559,119 @@ fn ribbon_paste_prefers_clipboard_text_over_a_picture() {
|
||||
assert_eq!(value_at(&h, "D2"), Some(Value::from("words")));
|
||||
assert!(pictures(&h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_data_from_clipboard_splits_the_clipboard_text_at_the_chosen_separator() {
|
||||
// Semicolon-separated, as Excel writes CSV where a comma is the decimal separator.
|
||||
let (clipboard, services) = system_clipboard("Name;City\r\n\"Smith; John\";Oslo\r\nAda;42\r\n");
|
||||
let mut h = harness(services);
|
||||
let sheets = |h: &Harness| h.state().session.active().unwrap().wb.sheets.len();
|
||||
let separator = |h: &Harness| h.state().dialog.as_ref().and_then(|d| d.values.get("separator")?.as_str().map(str::to_string));
|
||||
let before = sheets(&h);
|
||||
h.state_mut().ui.ribbon_tab = "Data".into();
|
||||
h.run_steps(2);
|
||||
let open_from_clipboard = |h: &mut Harness| {
|
||||
h.get_by_role_and_label(Role::Button, "Get Data (Text/CSV) options").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "From Clipboard…").click();
|
||||
h.run_steps(3);
|
||||
};
|
||||
|
||||
// The dialog starts on the separator the text uses, and OK imports that text into a new
|
||||
// sheet, even when the clipboard has moved on.
|
||||
open_from_clipboard(&mut h);
|
||||
assert_eq!(separator(&h).as_deref(), Some("semicolon"));
|
||||
clipboard.borrow_mut().0 = "copied later".into();
|
||||
h.get_by_label_contains("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().message.is_none(), "{:?}", h.state().message);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(sheets(&h), before + 1, "the text goes into a new sheet");
|
||||
assert_eq!(value_at(&h, "A2"), Some(Value::from("Smith; John")), "a quoted separator stays in its field");
|
||||
assert_eq!(value_at(&h, "B2"), Some(Value::from("Oslo")));
|
||||
assert_eq!(value_at(&h, "B3"), Some(Value::number(42.0)));
|
||||
|
||||
// Typing a separator in Other chooses it.
|
||||
clipboard.borrow_mut().0 = "a|b,c\n".into();
|
||||
open_from_clipboard(&mut h);
|
||||
assert_eq!(separator(&h).as_deref(), Some("comma"));
|
||||
h.get_by_role_and_label(Role::TextInput, "Other separator:").click();
|
||||
h.run_steps(2);
|
||||
h.input_mut().events.push(Event::Text("|".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(separator(&h).as_deref(), Some("other"));
|
||||
h.get_by_label_contains("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(sheets(&h), before + 2);
|
||||
assert_eq!(value_at(&h, "A1"), Some(Value::from("a")));
|
||||
assert_eq!(value_at(&h, "B1"), Some(Value::from("b,c")));
|
||||
|
||||
// With no text on the clipboard it says so and opens no dialog.
|
||||
clipboard.borrow_mut().0 = " \n".into();
|
||||
open_from_clipboard(&mut h);
|
||||
let message = format!("{:?}", h.state().message);
|
||||
assert!(message.contains("no text on the clipboard"), "{message}");
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert_eq!(sheets(&h), before + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_clipboard_without_a_separator_reads_text_starting_with_a_bracket_as_columns() {
|
||||
// Delimited text whose first field is in brackets is not JSON, and the separator is picked
|
||||
// by the text; a JSON array of objects is still read as records.
|
||||
let (clipboard, services) = system_clipboard("[Draft];Oslo\nDone;Bergen\n");
|
||||
let mut h = harness(services);
|
||||
let sheets = |h: &Harness| h.state().session.active().unwrap().wb.sheets.len();
|
||||
let before = sheets(&h);
|
||||
h.state_mut().run("data.fromClipboard", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(sheets(&h), before + 1);
|
||||
assert_eq!(value_at(&h, "A1"), Some(Value::from("[Draft]")));
|
||||
assert_eq!(value_at(&h, "B1"), Some(Value::from("Oslo")), "the next field is the next column");
|
||||
assert_eq!(value_at(&h, "B2"), Some(Value::from("Bergen")));
|
||||
|
||||
clipboard.borrow_mut().0 = r#"[{"city": "Oslo"}]"#.into();
|
||||
h.state_mut().run("data.fromClipboard", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(sheets(&h), before + 2);
|
||||
assert_eq!(value_at(&h, "A1"), Some(Value::from("city")), "the key is the header");
|
||||
assert_eq!(value_at(&h, "A2"), Some(Value::from("Oslo")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_data_in_the_cell_menu_splits_the_clipboard_text_into_columns_at_the_cell() {
|
||||
let (_, services) = system_clipboard("x;y\r\n1;\"a; b\"\r\n");
|
||||
let mut h = harness(services);
|
||||
let sheets = h.state().session.active().unwrap().wb.sheets.len();
|
||||
h.state_mut().run("selection.set", json!({"cell": "C3"})).unwrap();
|
||||
h.run_steps(2);
|
||||
let app = h.state();
|
||||
let sh = app.session.active().unwrap().wb.active().unwrap();
|
||||
let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll);
|
||||
let pos = geo.cell_rect(sh, CellRef::parse("C3").unwrap()).center();
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
assert!(h.state().grid.context_menu.is_some());
|
||||
h.get_by_role_and_label(Role::Button, "Paste Data…").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.title.as_str()), Some("Paste Data"));
|
||||
// By OK its sheet is renamed and another sheet, now active, has its old name (the sheet tabs
|
||||
// and the control channel work while the dialog is open).
|
||||
h.state_mut().session.execute("sheet.rename", json!({"sheet": 0, "name": "Renamed"})).unwrap();
|
||||
h.state_mut().session.execute("home.insertSheet", json!({"name": "Sheet1"})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.get_by_label_contains("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().message.is_none(), "{:?}", h.state().message);
|
||||
let wb = &h.state().session.active().unwrap().wb;
|
||||
assert_eq!(wb.sheets.len(), sheets + 1, "no sheet of its own");
|
||||
assert_eq!(wb.active().unwrap().name, "Renamed", "the paste goes to the sheet it was asked on");
|
||||
assert!(wb.active().unwrap().tables.is_empty(), "no table either");
|
||||
assert_eq!(value_at(&h, "C3"), Some(Value::from("x")));
|
||||
assert_eq!(value_at(&h, "D3"), Some(Value::from("y")));
|
||||
assert_eq!(value_at(&h, "C4"), Some(Value::number(1.0)));
|
||||
assert_eq!(value_at(&h, "D4"), Some(Value::from("a; b")));
|
||||
}
|
||||
|
||||
@@ -767,3 +767,290 @@ fn control_requests_route_to_a_window_and_list_windows() {
|
||||
let r = call(&mut h, "engine.execute", serde_json::json!({"command": "cell.get", "params": {"cell": "A1"}, "window": 999}));
|
||||
assert_eq!(r["ok"], false, "{r}");
|
||||
}
|
||||
|
||||
/// A workbook with a sheet left out of whole-workbook printing, saved as `path` before it was marked.
|
||||
fn marked_after_saving(services: Services, path: &str) -> egui_kittest::Harness<'static, SheetApp> {
|
||||
let mut h = harness(services);
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": path})).unwrap();
|
||||
h.state_mut().run("pageLayout.pageSetup", serde_json::json!({"excluded": true})).unwrap();
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
fn dialog(h: &egui_kittest::Harness<'static, SheetApp>) -> Option<String> {
|
||||
h.state().dialog.as_ref().map(|d| d.name().to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_asks_before_it_drops_a_print_exclusion() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-save-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (path, kept) = (dir.join("Book.xlsx").to_string_lossy().into_owned(), dir.join("Kept.json").to_string_lossy().into_owned());
|
||||
let target = kept.clone();
|
||||
let mut h = marked_after_saving(Services { pick_save: Some(Box::new(move |_| Some(target.clone()))), ..Default::default() }, &path);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
|
||||
// Cancel: nothing is written and the workbook stays unsaved.
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
click(&mut h, "Cancel");
|
||||
assert_eq!(dialog(&h), None);
|
||||
assert!(h.state().session.active().unwrap().is_dirty());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
|
||||
// The other format keeps the mark and becomes the workbook's file.
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save as GridCraft Workbook…");
|
||||
assert_eq!(dialog(&h), None);
|
||||
let d = h.state().session.active().unwrap();
|
||||
assert!(!d.is_dirty() && d.path.as_deref() == Some(kept.as_str()));
|
||||
let (wb, _) = gridcraft_engine::io::open_bytes("Kept.json", &std::fs::read(&kept).unwrap()).unwrap();
|
||||
assert!(wb.active().unwrap().print.excluded);
|
||||
|
||||
// Going ahead saves the .xlsx, and the same loss isn't asked about again.
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({"path": &path}));
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save Anyway");
|
||||
assert!(!h.state().session.active().unwrap().is_dirty());
|
||||
assert_ne!(std::fs::read(&path).unwrap().len(), 0);
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h), None);
|
||||
assert!(!h.state().session.active().unwrap().is_dirty());
|
||||
|
||||
// A script is never asked: the result carries the loss.
|
||||
let r = h.state_mut().run("file.save", serde_json::json!({})).unwrap();
|
||||
assert!(r["warnings"][0].is_string() && dialog(&h).is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_goes_on_once_the_save_loss_is_answered() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-close-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = marked_after_saving(Services::default(), &path);
|
||||
request_window_close(&mut h);
|
||||
let sent = click_commands(&mut h, "Save");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "the question comes first: {sent:?}");
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
click_commands(&mut h, "Cancel");
|
||||
assert_eq!(h.state().session.documents().len(), 1, "Cancel keeps the workbook open");
|
||||
request_window_close(&mut h);
|
||||
click_commands(&mut h, "Save");
|
||||
let sent = click_commands(&mut h, "Save Anyway");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_waits_instead_of_dropping_a_print_exclusion() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-autosave-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = marked_after_saving(Services::default(), &path);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
h.state_mut().ui.autosave = true;
|
||||
for _ in 0..40 {
|
||||
h.run_steps(1);
|
||||
if h.state().notice.is_some() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
assert!(h.state().notice.is_some(), "it says AutoSave is on hold");
|
||||
assert!(h.state().session.active().unwrap().is_dirty());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// AutoSave's hold ends, with its notice, when there is nothing left to hold back for, and a later
|
||||
/// hold on the same sheets is said again. A notice about something else stays.
|
||||
#[test]
|
||||
fn an_autosave_hold_ends_with_its_notice() {
|
||||
fn until(h: &mut egui_kittest::Harness<'_, SheetApp>, done: impl Fn(&SheetApp) -> bool) -> bool {
|
||||
for _ in 0..60 {
|
||||
h.run_steps(1);
|
||||
if done(h.state()) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
false
|
||||
}
|
||||
let held = |a: &SheetApp| a.notice.as_ref().is_some_and(|n| n.text.contains("on hold"));
|
||||
let exclude = |h: &mut egui_kittest::Harness<'_, SheetApp>, on: bool| {
|
||||
h.state_mut().run("pageLayout.pageSetup", serde_json::json!({"excluded": on})).unwrap();
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-autosave-resume-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = marked_after_saving(Services::default(), &path);
|
||||
h.state_mut().ui.autosave = true;
|
||||
assert!(until(&mut h, held));
|
||||
// Nothing is lost any more: AutoSave saves.
|
||||
exclude(&mut h, false);
|
||||
assert!(until(&mut h, |a| a.session.active().is_some_and(|d| !d.is_dirty())), "AutoSave resumed");
|
||||
assert!(until(&mut h, |a| a.notice.is_none()), "the hold's notice goes with it");
|
||||
// The same sheets again: held, and said again.
|
||||
exclude(&mut h, true);
|
||||
assert!(until(&mut h, held), "a later hold is said again");
|
||||
// Turning AutoSave off ends the hold, but not a notice about something else.
|
||||
let other = gridcraft_ui_egui::Notice { text: "Macros were kept.".into(), kind: gridcraft_ui_egui::NoticeKind::Info, action: None };
|
||||
h.state_mut().notice = Some(other.clone());
|
||||
h.state_mut().ui.autosave = false;
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().notice.as_ref(), Some(&other));
|
||||
// A Save the user agreed to ends it too.
|
||||
h.state_mut().notice = None;
|
||||
h.state_mut().ui.autosave = true;
|
||||
assert!(until(&mut h, held));
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save Anyway");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().notice, None);
|
||||
assert!(!h.state().session.active().unwrap().is_dirty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Save As asks about the file that was picked, and leaves the workbook's own file alone.
|
||||
#[test]
|
||||
fn save_as_asks_about_the_picked_file_and_keeps_the_first_one() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-save-as-loss-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let (path, other) = (at("Book.xlsx"), at("Other.xlsx"));
|
||||
let target = other.clone();
|
||||
let mut h = marked_after_saving(Services { pick_save: Some(Box::new(move |_| Some(target.clone()))), ..Default::default() }, &path);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
h.state_mut().run_or_alert("file.saveAs", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
click(&mut h, "Save Anyway");
|
||||
assert_eq!(dialog(&h), None);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before, "the workbook's own file isn't overwritten");
|
||||
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some(other.as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The question keeps what it asked about: neither a file that opens meanwhile nor the control
|
||||
/// channel changes what Save Anyway writes.
|
||||
#[test]
|
||||
fn save_anyway_writes_what_was_asked_about() {
|
||||
use gridcraft_ui_egui::control::handle;
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-bound-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let inbox: gridcraft_ui_egui::Inbox = Default::default();
|
||||
let mut h = marked_after_saving(Services { inbox: Some(inbox.clone()), ..Default::default() }, &at("Book.xlsx"));
|
||||
let window = h.state().session.active_window().unwrap();
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(2);
|
||||
let ctx = h.ctx.clone();
|
||||
let set = serde_json::json!({"field": "params", "value": {"path": at("Elsewhere.xlsx")}});
|
||||
handle(h.state_mut(), &ctx, "ui.dialog.set", &set);
|
||||
|
||||
inbox.lock().unwrap().push(("Dropped.csv".into(), b"1,2".to_vec()));
|
||||
h.run_steps(3);
|
||||
assert_eq!((h.state().session.documents().len(), dialog(&h)), (2, None), "the question stays in its window");
|
||||
h.state_mut().enter_window(window);
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save Anyway");
|
||||
assert!(!std::path::Path::new(&at("Elsewhere.xlsx")).exists());
|
||||
let d = h.state().session.active().unwrap();
|
||||
assert!(!d.is_dirty() && d.path.as_deref() == Some(at("Book.xlsx").as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Agreeing is to exactly the sheets that lose the mark, also those the question only counts.
|
||||
#[test]
|
||||
fn another_excluded_sheet_is_asked_about_also_past_the_names_shown() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-many-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = harness(Services::default());
|
||||
let exclude = |h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str, on: bool| {
|
||||
h.state_mut().run("pageLayout.pageSetup", serde_json::json!({"sheet": name, "excluded": on})).unwrap();
|
||||
};
|
||||
for i in 0..13 {
|
||||
h.state_mut().run("home.insertSheet", serde_json::json!({"name": format!("S{i:02}")})).unwrap();
|
||||
}
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
|
||||
// In tab order: the last two in the workbook are past the ten names shown.
|
||||
let names: Vec<String> = h.state().session.active().unwrap().wb.sheets.iter().map(|s| s.name.clone()).collect();
|
||||
for n in &names[..12] {
|
||||
exclude(&mut h, n, true);
|
||||
}
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save Anyway");
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h), None, "the same sheets aren't asked about again");
|
||||
exclude(&mut h, &names[11], false);
|
||||
exclude(&mut h, &names[12], true);
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A question that another one replaces hands its close and quit on.
|
||||
#[test]
|
||||
fn closing_goes_on_after_a_second_save_loss_question() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-again-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let at = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let target = at("Other.xlsx");
|
||||
let mut h = marked_after_saving(Services { pick_save: Some(Box::new(move |_| Some(target.clone()))), ..Default::default() }, &at("Book.xlsx"));
|
||||
request_window_close(&mut h);
|
||||
click_commands(&mut h, "Save");
|
||||
let sent = click_commands(&mut h, "Save as GridCraft Workbook…");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "an .xlsx was picked: asked again");
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
let sent = click_commands(&mut h, "Save Anyway");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
|
||||
assert!(std::path::Path::new(&at("Other.xlsx")).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A workbook with no file goes through Save As first, and the close still follows the answer.
|
||||
#[test]
|
||||
fn closing_a_new_workbook_goes_on_after_save_as_asks() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-loss-new-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("New.xlsx").to_string_lossy().into_owned();
|
||||
let target = path.clone();
|
||||
let mut h = harness(Services { pick_save: Some(Box::new(move |_| Some(target.clone()))), ..Default::default() });
|
||||
h.state_mut().run("pageLayout.pageSetup", serde_json::json!({"excluded": true})).unwrap();
|
||||
h.run_steps(2);
|
||||
request_window_close(&mut h);
|
||||
click_commands(&mut h, "Save");
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
let sent = click_commands(&mut h, "Save Anyway");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close) && std::path::Path::new(&path).exists(), "{sent:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The web's Save asks before the .xlsx is handed to the browser.
|
||||
#[test]
|
||||
fn a_download_asks_before_it_drops_a_print_exclusion() {
|
||||
let got = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = got.clone();
|
||||
let mut h = harness(Services { download: Some(Box::new(move |name, _| sink.lock().unwrap().push(name.to_string()))), ..Default::default() });
|
||||
h.state_mut().run("pageLayout.pageSetup", serde_json::json!({"excluded": true})).unwrap();
|
||||
for (answer, kind) in [("Cancel", None), ("Save as GridCraft Workbook…", Some(".json")), ("Save Anyway", Some(".xlsx"))] {
|
||||
h.state_mut().run_or_alert("file.save", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog(&h).as_deref(), Some("saveLoss"));
|
||||
assert!(got.lock().unwrap().is_empty());
|
||||
click(&mut h, answer);
|
||||
let names = std::mem::take(&mut *got.lock().unwrap());
|
||||
assert_eq!((names.len(), names.first().map(|n| n.ends_with(kind.unwrap_or_default()))), (usize::from(kind.is_some()), kind.map(|_| true)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2093,6 +2093,16 @@ fn keytip_apn_() {
|
||||
assert_eq!(h.state().keytips.prefix(), Some("APN"), "APN must stay armed waiting for more input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keytip_apnc_() {
|
||||
let mut h = harness(blank());
|
||||
sequence(&mut h, "APNC", false);
|
||||
assert!(
|
||||
h.state().message.as_ref().is_some_and(|(_, m)| m.contains("clipboard")),
|
||||
"APNC must open From Clipboard, which says there is no clipboard here"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keytip_apnd_() {
|
||||
let mut h = harness(blank());
|
||||
@@ -3086,7 +3096,7 @@ fn keytip_q_() {
|
||||
|
||||
#[test]
|
||||
fn generated_test_count_matches_the_table() {
|
||||
const EXPECTED: usize = 413;
|
||||
const EXPECTED: usize = 414;
|
||||
assert_eq!(gridcraft_ui_egui::keytips::keytip_table::SEQUENCES.len(), EXPECTED);
|
||||
}
|
||||
|
||||
|
||||
@@ -827,3 +827,39 @@ fn borders_keytip_opens_the_borders_menu() {
|
||||
assert_eq!(h.state().keytips.prefix(), Some("H"), "Esc backs out to the Home letters");
|
||||
assert!(!egui::Popup::is_any_open(&h.ctx), "and closes the menu");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_data_key_tips_open_its_menu_and_arrows_move_through_it() {
|
||||
let mut h = harness(blank());
|
||||
let focused = |h: &Harness, label: &str| h.get_by_label(label).is_focused();
|
||||
// A ribbon button has keyboard focus first, so egui would act on the arrow too.
|
||||
h.state_mut().ui.ribbon_tab = "Data".into();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Filter").focus();
|
||||
h.run_steps(2);
|
||||
// Alt, A, P, N opens the menu; Down then moves keyboard focus onto its items, wrapping.
|
||||
sequence(&mut h, &[Key::A, Key::P, Key::N], false);
|
||||
assert_eq!(h.state().keytips.prefix(), Some("APN"));
|
||||
key(&mut h, Key::ArrowDown);
|
||||
assert_eq!(h.state().keytips.prefix(), None, "an arrow ends key tips");
|
||||
assert!(focused(&h, "From Text/CSV…"));
|
||||
key(&mut h, Key::ArrowDown);
|
||||
assert!(focused(&h, "From Clipboard…"));
|
||||
key(&mut h, Key::ArrowDown);
|
||||
assert!(focused(&h, "From Text/CSV…"), "Down on the last item wraps to the first");
|
||||
key(&mut h, Key::ArrowUp);
|
||||
assert!(focused(&h, "From Clipboard…"), "Up on the first item wraps to the last");
|
||||
// Enter runs the focused item and closes the menu, and doesn't also dismiss what the item
|
||||
// shows: this harness has no system clipboard, which From Clipboard says.
|
||||
key(&mut h, Key::Enter);
|
||||
let message = format!("{:?}", h.state().message);
|
||||
assert!(message.contains("can't read the clipboard"), "{message}");
|
||||
assert!(h.query_by_label("From Clipboard…").is_none(), "the menu closed");
|
||||
|
||||
// C runs From Clipboard straight from the key tips.
|
||||
h.state_mut().message = None;
|
||||
h.run_steps(2);
|
||||
sequence(&mut h, &[Key::A, Key::P, Key::N, Key::C], false);
|
||||
let message = format!("{:?}", h.state().message);
|
||||
assert!(message.contains("can't read the clipboard"), "{message}");
|
||||
}
|
||||
|
||||
+11
-2
@@ -40,9 +40,10 @@ pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option<char>, usize)>
|
||||
}
|
||||
}
|
||||
|
||||
/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields.
|
||||
/// [`craft_csv::parse_records`] with a record kept to one field past the grid's [`MAX_COLS`], so a
|
||||
/// wider record can be told from one that fits; readers use the first `MAX_COLS`.
|
||||
fn parse_records(text: &str, delim: char, quote: char, on_record: impl FnMut(Vec<String>) -> bool) {
|
||||
craft_csv::parse_records(text, delim, quote, MAX_COLS as usize, on_record);
|
||||
craft_csv::parse_records(text, delim, quote, MAX_COLS as usize + 1, on_record);
|
||||
}
|
||||
|
||||
/// The delimiter and quote character to read `text` with. craft-csv always splits and unquotes, so
|
||||
@@ -351,10 +352,16 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook
|
||||
// The bounding box of the non-empty cells, which is the sheet's used range.
|
||||
let mut used: Option<(u32, u32, u32, u32)> = None;
|
||||
let mut too_many = false;
|
||||
let mut widest = 0;
|
||||
parse_records(body, delim, quote, |rec| {
|
||||
if row >= MAX_ROWS {
|
||||
report.truncated = true;
|
||||
return false;
|
||||
}
|
||||
if rec.len() > MAX_COLS as usize {
|
||||
report.truncated = true;
|
||||
}
|
||||
widest = widest.max(rec.len().min(MAX_COLS as usize));
|
||||
// A blank line is an empty row.
|
||||
for (col, f) in rec.into_iter().enumerate() {
|
||||
if col as u32 >= MAX_COLS {
|
||||
@@ -401,6 +408,8 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook
|
||||
}
|
||||
wb.styles = styles;
|
||||
wb.sheets = vec![Arc::new(sheet)];
|
||||
report.records = row;
|
||||
report.fields = u32::try_from(widest).unwrap_or(MAX_COLS);
|
||||
Ok((wb, report))
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,13 @@ pub enum IoError {
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ReadReport {
|
||||
pub warnings: Vec<String>,
|
||||
/// A CSV read: how many records the text has and the most fields one of them has, blank ones
|
||||
/// included, which a paste covers. The sheet's used range holds only the non-empty cells.
|
||||
pub records: u32,
|
||||
pub fields: u32,
|
||||
/// A CSV read: the text has records past a sheet's last row, or fields past its last column,
|
||||
/// which were left out.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl ReadReport {
|
||||
|
||||
@@ -317,6 +317,7 @@ fn sample() -> Workbook {
|
||||
hf_scale_with_doc: false,
|
||||
hf_align_with_margins: true,
|
||||
page_order: PageOrder::OverThenDown,
|
||||
excluded: false,
|
||||
first_page_number: Some(7),
|
||||
};
|
||||
s.sparklines.push(Sparkline { cell: at("J2"), source: "B2:B3".into(), kind: SparklineKind::WinLoss, color: Color::Rgb(0x112233), markers: true });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Architecture
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: one workbook-wide reference rewrite; formula printer dialects and parsing from tokens; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md).
|
||||
|
||||
@@ -14,7 +14,7 @@ including tests, 2026-10-10.
|
||||
|---|---|---|---|
|
||||
| L0 | `core` | ~1.3k | Cell and range addresses (A1, R1C1, sheet-qualified; 1,048,576 × 16,384), `Value`, `CellError`, Excel coercion, 1900/1904 date serials, typed-input parsing |
|
||||
| L0 | `numfmt` | ~2.1k | Excel number-format codes (sections, conditions, colours, dates, elapsed time, fractions, scientific, fill), General, `TEXT()`; en-US only |
|
||||
| L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits |
|
||||
| L1 | `formula` | ~1.7k | Tokenizer, parser (also from another syntax's tokens: `parse_tokens`), AST, printer (A1 and R1C1, or any syntax through a `Dialect` and `print_with`), reference adjustment for copy, fill and structural edits |
|
||||
| L1 | `functions` | ~13.4k | The function library: `FnSpec` registry (name, arity, category, scalar args, signature, description) and pure implementations; automatic array lifting |
|
||||
| L1 | `math` | ~1.1k | Equations: LaTeX laid out by RaTeX (MIT, pinned) into plain glyph, rule and path data, and LaTeX to Office Math; every entry point capped and panic-guarded |
|
||||
| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings (paper names and sizes in `paper`, the one table file formats and print layout read), protection |
|
||||
@@ -274,6 +274,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in
|
||||
|---|---|---|
|
||||
| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means no paper is stated (no reader sets it yet); `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size |
|
||||
| 2026-11-13 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut |
|
||||
| 2026-11-13 | minor | Formula printer dialects: a `Dialect` trait states how another syntax spells references, names, functions, booleans, separators and operators, and `print_with` prints through it (`print`/`print_r1c1` are the A1 and R1C1 dialects, output unchanged); `parse_tokens` builds an `Expr` from another tokenizer's tokens, with `Tok::Ref` for a reference it has already read (every accepted tree prints as text that parses back to it: refused off the grid, for a negative or non-finite number, a sheet name empty or holding `:`, a word or function name the A1 tokenizer would not read as one, a word before `(`, a trim operator, tokens after `Eof`, or any other tree whose printed text reads back differently (numbers compared as printed); spaces only intersect between operands; text and nesting bounded as formula text is; `Tok` is `#[non_exhaustive]`) |
|
||||
| 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` |
|
||||
| 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused |
|
||||
| 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it |
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -75,12 +75,12 @@ Cell text now uses shared Unicode bidi layout while retaining logical source ind
|
||||
embedded faces tagged with CJK scripts share the Latin baseline in cells, editors and titles
|
||||
(#1265, #2621); other script, emoji and symbol fallbacks retain their alignment.
|
||||
Lao falls back to Lao Sangam MN / Lao MN (macOS),
|
||||
Leelawadee UI / DokChampa (Windows) or Noto Sans Lao / Phetsarath OT (Linux). egui uses harfrust shaping and Unicode bidi layout; script-specific coverage
|
||||
beyond Arabic still needs verification. **Sheet Right-to-Left**
|
||||
Leelawadee UI / DokChampa (Windows) or Noto Sans Lao / Phetsarath OT (Linux). Arabic falls back to a system Arabic face, fontconfig's
|
||||
Arabic choice or craft-fonts' Noto Sans Arabic; fontconfig's choice leads these fallbacks, but a UI font with Arabic of its
|
||||
own (DejaVu Sans in the Flatpak) still draws interface Arabic (#229). There is no complex-text shaping: Arabic and
|
||||
Devanagari don't join or reorder, and there is no bidirectional layout. **Sheet Right-to-Left**
|
||||
own (DejaVu Sans in the Flatpak) still draws interface Arabic (#229). Indian scripts fall back to Nirmala UI and the
|
||||
per-script faces (Windows), Kohinoor, Noto and Sangam MN (macOS) or Noto Sans and Lohit (Linux, BSD, Flatpak). egui uses
|
||||
harfrust shaping and Unicode bidi layout, so conjuncts and reordered vowel signs render wherever a face is present
|
||||
(`theme::tests::indic_text_is_shaped_not_drawn_letter_by_letter`). **Sheet Right-to-Left**
|
||||
(`view.rightToLeft`, Page Layout › Sheet Options, XLSX `rightToLeft`, `.xls` WINDOW2 fRightToLeft) mirrors the grid (#146):
|
||||
column A and the row headers on the right, the vertical scrollbar on the left; hit-testing,
|
||||
arrow keys, editor, popups and floating objects follow; text follows its cell reading direction inside its box,
|
||||
@@ -107,7 +107,7 @@ separators, number/date formats, machine translation with agent review, and scri
|
||||
| English | en | ~2,200 / ~2,200 (100%, source) | yes | Latin: yes | yes | full | — |
|
||||
| Simplified Chinese (Mandarin) | zh-Hans | 266 (~12%) | no | CJK system-font fallback (#38); IME unverified; PDF can't export | no | menus only | 8–13 h |
|
||||
| Spanish | es | 0 (0%) | no | Latin: yes | no | none | 6–10 h |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari: **no shaping** | no | none | 12–18 h |
|
||||
| Hindi | hi | 0 (0%) | no | Devanagari: shaped, system faces | no | none | 12–18 h |
|
||||
| Arabic | ar | 0 (0%) | no | shared shaping/bidi; no Arabic UI catalog or mirrored shell; PDF export: shaped and joined, follows cell direction, mirrors RTL sheets; Sheet RTL mirrors the grid (#146) | no | none | 25–35 h |
|
||||
| French | fr | 0 (0%) | no | Latin: yes | no | none | 6–10 h |
|
||||
| Portuguese | pt-BR | 943 (~43%) | dialogs and tooltips (dialogs take effect with #669) | Latin: yes | no | menus, File view, dialogs | 2–4 h |
|
||||
|
||||
+16
-14
@@ -6,6 +6,8 @@ Each entry is an Excel ribbon or menu command (feature names only). It counts as
|
||||
|
||||
**Overall: 282 / 296 commands implemented (95.3%).**
|
||||
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 282 yes, 14 no (window 0, os 10, engine-gap 4), 0 partial, 0 unknown.** An implemented command is `headless: yes`: it is in the engine registry that `gridcraft-cli` and the MCP server load. A missing one carries its hand mark from `HEADLESS` in `xtask/src/parity.rs`, or `unknown`.
|
||||
|
||||
| Tab | Implemented | Total | Parity |
|
||||
|---|---|---|---|
|
||||
| File | 11 | 11 | 100% |
|
||||
@@ -166,12 +168,12 @@ Implemented:
|
||||
|
||||
Missing:
|
||||
|
||||
- `insert.smartArt` Diagram (Illustrations)
|
||||
- `insert.screenshot` Screenshot (Illustrations)
|
||||
- `insert.map` Maps (Charts)
|
||||
- `insert.timeline` Timeline (Filters)
|
||||
- `insert.signatureLine` Signature Line (Text)
|
||||
- `insert.object` Object (Text)
|
||||
- `insert.smartArt` Diagram (Illustrations): headless: no, reach: engine-gap (diagrams could be built by a command)
|
||||
- `insert.screenshot` Screenshot (Illustrations): headless: no, reach: os (screen capture of other windows)
|
||||
- `insert.map` Maps (Charts): headless: no, reach: os (online map service)
|
||||
- `insert.timeline` Timeline (Filters): headless: no, reach: engine-gap (a date filter for pivot tables could be a command)
|
||||
- `insert.signatureLine` Signature Line (Text): headless: no, reach: engine-gap (a signature line object could be inserted by a command)
|
||||
- `insert.object` Object (Text): headless: no, reach: os (embedding another program's object)
|
||||
|
||||
## Draw (4 / 4, 100%)
|
||||
|
||||
@@ -268,11 +270,11 @@ Implemented:
|
||||
|
||||
Missing:
|
||||
|
||||
- `data.fromWeb` From Web (Get & Transform Data)
|
||||
- `data.stocks` Stocks (Data Types)
|
||||
- `data.geography` Geography (Data Types)
|
||||
- `data.relationships` Relationships (Data Tools)
|
||||
- `data.analyzeData` Analyze Data (Analysis)
|
||||
- `data.fromWeb` From Web (Get & Transform Data): headless: no, reach: os (fetching a web page)
|
||||
- `data.stocks` Stocks (Data Types): headless: no, reach: os (online stock data service)
|
||||
- `data.geography` Geography (Data Types): headless: no, reach: os (online geography data service)
|
||||
- `data.relationships` Relationships (Data Tools): headless: no, reach: engine-gap (data-model relationships could be commands)
|
||||
- `data.analyzeData` Analyze Data (Analysis): headless: no, reach: os (online analysis service)
|
||||
|
||||
## Review (15 / 18, 83%)
|
||||
|
||||
@@ -296,9 +298,9 @@ Implemented:
|
||||
|
||||
Missing:
|
||||
|
||||
- `review.smartLookup` Smart Lookup (Insights)
|
||||
- `review.translate` Translate (Language)
|
||||
- `review.showChanges` Show Changes (Changes)
|
||||
- `review.smartLookup` Smart Lookup (Insights): headless: no, reach: os (online search service)
|
||||
- `review.translate` Translate (Language): headless: no, reach: os (online translation service)
|
||||
- `review.showChanges` Show Changes (Changes): headless: no, reach: os (co-authoring change history service)
|
||||
|
||||
## View (21 / 21, 100%)
|
||||
|
||||
|
||||
+5
-3
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Data › Get Data's menu imports the text on the clipboard, Alt, A, P, N, C; the cell menu's Paste Data… pastes it as columns; arrows move through key-tip menus; earlier: File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
|
||||
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
|
||||
@@ -16,7 +16,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes
|
||||
|---|---|---|---|
|
||||
| 2026-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) |
|
||||
| Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) |
|
||||
| Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow |
|
||||
| Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum, Data › Get Data); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow |
|
||||
| Ribbon collapse, simplified ribbon, customize ribbon/QAT | yes | partial | customization missing (File ▸ Options is the one missing File command) |
|
||||
| Formulas › Function Library | Insert Function, AutoSum, Recently Used and a menu per function category | yes (10-24): a big Insert Function button and three columns of labelled small buttons, the layout Excel uses when the window is not wide enough for a big button per category; each category's book icon has its own colour; a category menu shows each function's description on hover and ends with Insert Function…, which opens the dialog on that category; More Functions cascades into Statistical, Engineering, Cube, Information, Compatibility and Web; AutoSum is a split button whose menu (Sum, Average, Count Numbers, Max, Min, More Functions…) Home › Editing shares; Recently Used has the MR key tip | the wide layout with a big button per category is not offered; a function counts as recently used once its formula is entered, not when Insert Function's OK is pressed |
|
||||
| Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable tabs) | done; missing contextual tabs for pictures, shapes, sparklines, header/footer, slicers |
|
||||
@@ -67,12 +67,13 @@ this logic, with one undo step.
|
||||
| Header resize and double-click AutoFit | done (#42, #88 for header dividers) |
|
||||
| AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Without a search, Apply preserves selected and excluded values and blanks absent from the narrowed list. With a search, Apply excludes nonmatches throughout the column, including values hidden by another filter. Clear Filter clears the whole column. Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. |
|
||||
| Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). |
|
||||
| Data › Get Data (Text/CSV) | a split button: the button opens a text or CSV file, as before; its menu has From Text/CSV… and From Clipboard…, which asks for the separator (Comma, Semicolon, Tab, Space, or one character typed in Other; it starts on the one the text's first line uses) and imports the text on the clipboard into a new sheet as a table. `data.fromClipboard {delimiter?}` does the same without the dialog, guessing the separator when none is given. Excel's Get Data menu has no clipboard entry; this one is GridCraft's own. Where the host can't read the clipboard (the web build), it says so instead of importing nothing. Alt or F10, A, P, N opens the menu with its key tips (G a file, C the clipboard); Up or Down then moves keyboard focus onto its items, wrapping at the ends, and Enter runs one, as in every key-tip menu drawn from a list (Paste's too). The cell menu's Paste Data… opens the same dialog with a Paste at reference box (the selection's top-left cell, where Paste pastes; the sheet is the dialog's own, as in other dialogs with reference boxes) and puts the columns there instead (`data.fromClipboard {at}`), replacing what is there, with no table; every field of the text is written, so blank ones at either end clear what is under them. Both, like From Text/CSV, keep the number formats the CSV reader gives dates, percents and currency (dates in the workbook's 1900 or 1904 date system), and without a separator the reader picks comma, semicolon or tab by the text (`data.fromTextCsv`; a JSON array of records is read only then) |
|
||||
| Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog |
|
||||
| Reorder selected whole columns by dragging their headers | done (10-11) |
|
||||
| Freeze panes, split panes | freeze done; split to verify |
|
||||
| A Table's header names and filter buttons in the column headings once its header row scrolls away | done (#1423): with the active cell in the Table, as in Excel; the button opens the column's filter menu, the rest of the heading still selects the column. Plain AutoFilter ranges keep their letters (Excel does the same) |
|
||||
| Copy as HTML table for other apps | done (#36, 10-10) |
|
||||
| Context menu on cells | 16 items (Cut, Copy, Paste, Paste Special, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Show Details on a PivotTable's value, subtotal or grand total cell (`pivot.showDetails`). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup |
|
||||
| Context menu on cells | 17 items (Cut, Copy, Paste, Paste Special, Paste Data, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Show Details on a PivotTable's value, subtotal or grand total cell (`pivot.showDetails`). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup |
|
||||
| Move and resize charts, pictures and shapes | done (#190, #213): charts, pictures, shapes, equations and slicers select with a frame of eight handles; each handle resizes only its own edges (they never cross), the body moves the object, and the pointer shows a resize or move cursor; Delete or Backspace deletes the selected object and Escape drops the selection; double-click edits a text box, opens Format Chart for a chart. Rotation handle, Shift for proportional resizing, Alt to snap to cells and multi-object selection missing |
|
||||
| Form controls: buttons, scroll bars (sliders), spin buttons | done (10-31): Insert › Controls (Button, Slider, Spin Button; Excel has them under Developer › Insert) places one by a drag, or at its default size by a click; a click works a control: drag the thumb, page on the track, click or hold an arrow (a drag or a hold is one undo step), press a button, which runs a macro or a command and asks first in a workbook opened from a file (an answer runs only the action it asked about: if an agent changes the button, its macro or the selection while the prompt is open, nothing runs); the control last worked takes the arrows, Page Up and Page Down, Home, End, and Space or Enter (a button gives the keyboard back as soon as the grid takes a key or a right-click; Space on a slider or spin button does what it does with no control focused: it toggles a checkbox cell or starts a cell edit like any other character); Ctrl or Cmd+click or a right-click selects it to move or resize; its menu has Edit Text, Assign Action, Format Control and Delete. Check boxes, option buttons, list boxes and drop-downs (form controls) are kept from files but not shown |
|
||||
| Context menus on row/column headers, sheet tabs, charts, shapes | headers and tabs done; objects partial |
|
||||
@@ -296,6 +297,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | minor | Data › Get Data (Text/CSV) is a split button: the button still opens a text or CSV file, and its menu adds From Clipboard…, which asks for the separator (comma, semicolon, tab, space or another character; the one the text uses is chosen first) and imports the text on the clipboard into a new sheet as a table, as From Text/CSV imports a file (`data.fromClipboard {delimiter?}`); Alt, A, P, N, C reaches it, and Up or Down in a menu key tips opened (Get Data, Paste) moves focus onto its items. The cell menu's Paste Data… uses the same dialog to put the columns at the cell (`at`) |
|
||||
| 2026-11-19 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, and a lone `+` or `-` and an entry that doesn't read as a formula (`--`, `+49 170 1234567`) stay text, as observed in Excel for the web; only `=` entries are refused (#2023) |
|
||||
| 2026-11-19 | minor | AutoSum from the ribbon or keyboard on one cell proposes `=SUM(range)` in the editor instead of entering it, with the range pointed and selected: a click, drag, arrow key or typing replaces it and Enter enters it, as in Excel. With nothing to sum the caret waits inside `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` is unchanged (#1834) |
|
||||
| 2026-11-15 | minor | The rows of both validation list popups are drawn in slots of exactly the row height the popup scrolls by, so a font whose text is laid out a pixel taller than its nominal line height no longer pushes the last visible row under the "More entries not shown" note (seen with the pinned test fonts, not with the fonts of a desktop install). That note is translated in all 18 interface catalogs, and the validation-list UI tests run on the pinned font set |
|
||||
|
||||
@@ -297,7 +297,9 @@ class StagedFormats(unittest.TestCase):
|
||||
desktop = (stage / "usr/share/applications/ai.storyteller.gridcraft.desktop").read_text()
|
||||
self.assertIn("Exec=gridcraft %F\n", desktop)
|
||||
self.assertIn("MimeType=", desktop)
|
||||
with tarfile.open(self.dist / "gridcraft-0.19.1-linux-x86_64.tar.gz") as tar:
|
||||
import tomllib
|
||||
cargo_version = tomllib.loads((ROOT / "Cargo.toml").read_text())["workspace"]["package"]["version"]
|
||||
with tarfile.open(self.dist / f"gridcraft-{cargo_version}-linux-x86_64.tar.gz") as tar:
|
||||
names = {member.name.split("/", 1)[-1] for member in tar.getmembers()}
|
||||
self.assertIn("bin/gridcraft", names)
|
||||
self.assertNotIn("bin/gridcraft-nightly", names)
|
||||
|
||||
@@ -33,11 +33,12 @@ OUTPUT="$DIST/gridcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/GridCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/GridCraft"
|
||||
cp "$ROOT/assets/app-icon/gridcraft-nightly.icns" "$APP/Contents/Resources/gridcraft-nightly.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
|
||||
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"gridcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "GridCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
@@ -183,6 +185,50 @@ class Fixture:
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/gridcraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
|
||||
(self.bin / "cargo").write_text(
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/gridcraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'GridCraft %s (nightly-v1)'\\n\" \"$GRIDCRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_VERSION=version,
|
||||
GRIDCRAFT_BUILD_SHA=commit, GRIDCRAFT_BUILD_DATE="2026-11-23")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
@@ -430,6 +476,40 @@ class Verify(unittest.TestCase):
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = Fixture(self)
|
||||
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "gridcraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/GridCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
|
||||
@@ -171,7 +171,7 @@ def reviewed_manual_actors(caller_source, policy):
|
||||
|
||||
|
||||
def caller_pin(name):
|
||||
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
|
||||
return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0]
|
||||
|
||||
|
||||
class TrustedSourcePreparation(unittest.TestCase):
|
||||
@@ -214,15 +214,22 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
(indicator, expression), = job_conditions(jobs)
|
||||
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
|
||||
|
||||
def test_no_nightly_schedule_is_registered(self):
|
||||
for name, event in (("nightly.yml", "workflow_dispatch"),
|
||||
("nightly-sign.yml", "workflow_dispatch")):
|
||||
def test_nightly_triggers_match_reviewed_schedule(self):
|
||||
expected_triggers = {
|
||||
"nightly.yml": [" schedule:", " workflow_dispatch:"],
|
||||
"nightly-sign.yml": [" workflow_dispatch:"],
|
||||
"nightly-dispatch.yml": [" workflow_run:"],
|
||||
}
|
||||
for name, expected in expected_triggers.items():
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
|
||||
triggers = [line for line in events.splitlines() if line.startswith(" ")
|
||||
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
|
||||
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
|
||||
nightly = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
self.assertEqual(re.findall(r"(?m)^ - cron: '([^']+)'$", nightly), ["30 3 * * *"],
|
||||
"scheduled nightly cadence must match the reviewed cron expression")
|
||||
|
||||
def test_signer_serialization_contract_is_enforced(self):
|
||||
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
|
||||
@@ -258,17 +265,17 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
self.assertEqual(len(entries), len(expected), "duplicate fixture classification")
|
||||
|
||||
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
for name in ("nightly.yml", "nightly-dispatch.yml", "nightly-sign.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
executable = "\n".join(line for line in source.splitlines()
|
||||
if not line.lstrip().startswith("#"))
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
# The producer caller forwards nothing. The signer caller declares the release
|
||||
# environment and forwards exactly the fifteen secrets the sign steps read; those
|
||||
# The producer and dispatcher forward nothing. The signer caller declares no
|
||||
# environment and forwards exactly the named secrets the sign steps read; those
|
||||
# are the only allowed forms, and `inherit` is never one of them.
|
||||
if name == "nightly.yml":
|
||||
if name in ("nightly.yml", "nightly-dispatch.yml"):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
else:
|
||||
@@ -309,7 +316,7 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
|
||||
pins.update(uses)
|
||||
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
|
||||
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
|
||||
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
|
||||
|
||||
|
||||
class NightlyEnabledCallers(unittest.TestCase):
|
||||
@@ -319,6 +326,7 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
"nightly.yml": "github.repository == 'storytold/gridcraft' && github.ref == 'refs/heads/main' && "
|
||||
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-dispatch.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_run'",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
|
||||
}
|
||||
@@ -337,7 +345,8 @@ class NightlyEnabledCallers(unittest.TestCase):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
|
||||
"automatic signer is limited to github-actions[bot]")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
@@ -420,7 +429,8 @@ class NightlyInstalledPolicy(unittest.TestCase):
|
||||
for platform, (field, value) in NIGHTLY_TRUST.items():
|
||||
row = self.policy["platforms"][platform]
|
||||
with self.subTest(platform=platform):
|
||||
self.assertEqual(set(row), {"unsigned_artifact_name", "trust"})
|
||||
expected_keys = {"unsigned_artifact_name", "trust", "package_formats"} if platform == "linux-x86_64" and "package_formats" in row else {"unsigned_artifact_name", "trust"}
|
||||
self.assertEqual(set(row), expected_keys)
|
||||
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}")
|
||||
self.assertEqual(row["trust"], {field: value})
|
||||
|
||||
@@ -739,7 +749,7 @@ def trust_closure_problems(workflows):
|
||||
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
|
||||
if name == "nightly-sign.yml":
|
||||
signer_calls += 1
|
||||
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
|
||||
if name != "nightly-sign.yml" or ref != "main":
|
||||
problems.append(name + " calls nightly-release.yml@" + ref)
|
||||
if workflow.lower() in ("release.yml", "release.yaml"):
|
||||
stable_callers.add(name)
|
||||
@@ -789,7 +799,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
|
||||
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
|
||||
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
|
||||
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
|
||||
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
|
||||
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
|
||||
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
|
||||
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
|
||||
}
|
||||
@@ -811,9 +821,14 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
|
||||
self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard)
|
||||
self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch")
|
||||
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["gridcraft"], "the shared signer needs the reviewed registry app")
|
||||
# This app ships no completion dispatcher yet: that workflow forwards scheduled producers
|
||||
# only, and no schedule is approved. Adding it is part of a reviewed cadence change.
|
||||
self.assertFalse(DISPATCHER.exists(), "a completion dispatcher needs its own reviewed activation")
|
||||
self.assertTrue(DISPATCHER.exists(), "scheduled nightly requires the completion dispatcher")
|
||||
dispatcher = DISPATCHER.read_text()
|
||||
producer_name = re.findall(r"(?m)^name: (.+)$", (ROOT / ".github/workflows/nightly.yml").read_text())[0]
|
||||
self.assertIn(f"workflows: [{producer_name}]", dispatcher, "dispatcher must match the producer workflow name")
|
||||
self.assertIn("refs/heads/" + SIGNER_BRANCH, dispatcher, "dispatcher must target the signer branch")
|
||||
self.assertIn("https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches",
|
||||
dispatcher, "dispatcher must target gridcraft nightly-sign.yml")
|
||||
self.assertNotIn("false &&", dispatcher, "dispatcher must be enabled for scheduled runs")
|
||||
self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH)
|
||||
self.assertFalse((ROOT / "docs/nightly-signing-policy.example.json").exists(),
|
||||
"a policy example must then name the signer branch")
|
||||
|
||||
@@ -331,6 +331,12 @@ fn render_tests(entries: &[Entry], probe: &Probe) -> String {
|
||||
"sequence(&mut h, {seq:?}, false);\n assert!(h.state().backstage.is_some(), \"{seq} must open the Options page\");",
|
||||
seq = e.seq,
|
||||
),
|
||||
// From Clipboard first reads the clipboard, which the test harness doesn't have: it
|
||||
// says so rather than opening a dialog with nothing to import.
|
||||
"dialog" if e.target == "fromClipboard" => format!(
|
||||
"sequence(&mut h, {seq:?}, false);\n assert!(h.state().message.as_ref().is_some_and(|(_, m)| m.contains(\"clipboard\")), \"{seq} must open From Clipboard, which says there is no clipboard here\");",
|
||||
seq = e.seq,
|
||||
),
|
||||
"dialog" => format!(
|
||||
"sequence(&mut h, {seq:?}, false);\n assert!(h.state().dialog.is_some(), \"{seq} must open the {dialog} dialog\");",
|
||||
seq = e.seq,
|
||||
|
||||
+158
-2
@@ -19,6 +19,89 @@ pub struct Entry {
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
/// RFC-0052 hand marks for catalog ids with no engine command: `id|headless|reach|why`.
|
||||
///
|
||||
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
|
||||
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
|
||||
/// command, isn't one yet). `yes` is never written here: an id is `yes` only when the engine registry
|
||||
/// that `gridcraft-cli` and the MCP server load has it, and a mark on such an id is stale
|
||||
/// (`mark_errors`). A missing id with no mark is `unknown`.
|
||||
pub const HEADLESS: &str = "\
|
||||
insert.smartArt|no|engine-gap|diagrams could be built by a command
|
||||
insert.screenshot|no|os|screen capture of other windows
|
||||
insert.map|no|os|online map service
|
||||
insert.timeline|no|engine-gap|a date filter for pivot tables could be a command
|
||||
insert.signatureLine|no|engine-gap|a signature line object could be inserted by a command
|
||||
insert.object|no|os|embedding another program's object
|
||||
data.fromWeb|no|os|fetching a web page
|
||||
data.stocks|no|os|online stock data service
|
||||
data.geography|no|os|online geography data service
|
||||
data.relationships|no|engine-gap|data-model relationships could be commands
|
||||
data.analyzeData|no|os|online analysis service
|
||||
review.smartLookup|no|os|online search service
|
||||
review.translate|no|os|online translation service
|
||||
review.showChanges|no|os|co-authoring change history service
|
||||
";
|
||||
|
||||
/// A row's RFC-0052 `headless:` value, and for `no`/`partial` its `reach:` and reason.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Headless<'a> {
|
||||
pub value: &'a str,
|
||||
pub reach: Option<&'a str>,
|
||||
pub why: &'a str,
|
||||
}
|
||||
|
||||
const YES: Headless<'static> = Headless { value: "yes", reach: None, why: "" };
|
||||
const UNKNOWN: Headless<'static> = Headless { value: "unknown", reach: None, why: "" };
|
||||
|
||||
/// Parse `HEADLESS`-format marks. A malformed line, a hand-written `yes`, an unknown reach or a
|
||||
/// repeated id is an error.
|
||||
pub fn parse_marks(src: &str) -> Result<Vec<(&str, Headless<'_>)>, String> {
|
||||
let mut out: Vec<(&str, Headless<'_>)> = Vec::new();
|
||||
for line in src.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let f: Vec<&str> = line.splitn(4, '|').collect();
|
||||
let [id, value, reach, why] = f[..] else {
|
||||
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
|
||||
};
|
||||
if !matches!(value, "no" | "partial") {
|
||||
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !matches!(reach, "window" | "os" | "engine-gap") {
|
||||
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if out.iter().any(|(m, _)| *m == id) {
|
||||
return Err(format!("headless mark `{id}` is written twice"));
|
||||
}
|
||||
out.push((id, Headless { value, reach: Some(reach), why }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `yes` for an id the engine registry has, else its mark, else `unknown`.
|
||||
pub fn headless_of<'a>(e: &Entry, marks: &[(&str, Headless<'a>)]) -> Headless<'a> {
|
||||
if e.done {
|
||||
return YES;
|
||||
}
|
||||
marks.iter().find(|(m, _)| *m == e.id).map_or(UNKNOWN, |(_, h)| *h)
|
||||
}
|
||||
|
||||
/// Marks that name no catalog id, or an id the engine registry has (it would hide a `yes`).
|
||||
pub fn mark_errors(src: &str, entries: &[Entry]) -> Vec<String> {
|
||||
let marks = match parse_marks(src) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return vec![e],
|
||||
};
|
||||
let mut errs = Vec::new();
|
||||
for (id, _) in &marks {
|
||||
match entries.iter().find(|e| e.id == *id) {
|
||||
None => errs.push(format!("headless mark `{id}` is not a catalog id")),
|
||||
Some(e) if e.done => errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`")),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
fn pct(done: usize, total: usize) -> f64 {
|
||||
if total == 0 { 0.0 } else { 100.0 * done as f64 / total as f64 }
|
||||
}
|
||||
@@ -26,6 +109,12 @@ fn pct(done: usize, total: usize) -> f64 {
|
||||
/// The markdown for docs/parity-checklist.md. Ids are counted once (the first catalog row wins), tabs keep
|
||||
/// catalog order.
|
||||
pub fn render(entries: &[Entry]) -> String {
|
||||
render_with(entries, HEADLESS)
|
||||
}
|
||||
|
||||
/// `render` with the given `HEADLESS`-format marks (bad marks are left out; `mark_errors` reports them).
|
||||
pub fn render_with(entries: &[Entry], marks: &str) -> String {
|
||||
let marks = parse_marks(marks).unwrap_or_default();
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
let mut unique: Vec<&Entry> = Vec::new();
|
||||
for e in entries {
|
||||
@@ -50,6 +139,22 @@ pub fn render(entries: &[Entry]) -> String {
|
||||
registers a command with the same id. This measures breadth only; the overall assessment (depth, \
|
||||
fidelity, effort) is in [target-app-parity.md](target-app-parity.md).\n\n";
|
||||
s += &format!("**Overall: {done} / {total} commands implemented ({:.1}%).**\n\n", pct(done, total));
|
||||
let hs: Vec<Headless<'_>> = unique.iter().map(|e| headless_of(e, &marks)).collect();
|
||||
let count = |v: &str| hs.iter().filter(|h| h.value == v).count();
|
||||
let no = |r: &str| hs.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
|
||||
s += &format!(
|
||||
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no \
|
||||
(window {}, os {}, engine-gap {}), {} partial, {} unknown.** An implemented command is `headless: yes`: it is in the \
|
||||
engine registry that `gridcraft-cli` and the MCP server load. A missing one carries its hand mark from `HEADLESS` in \
|
||||
`xtask/src/parity.rs`, or `unknown`.\n\n",
|
||||
count("yes"),
|
||||
count("no"),
|
||||
no("window"),
|
||||
no("os"),
|
||||
no("engine-gap"),
|
||||
count("partial"),
|
||||
count("unknown")
|
||||
);
|
||||
s += "| Tab | Implemented | Total | Parity |\n|---|---|---|---|\n";
|
||||
for t in &tabs {
|
||||
let rows: Vec<&&Entry> = unique.iter().filter(|e| e.tab == *t).collect();
|
||||
@@ -61,7 +166,21 @@ pub fn render(entries: &[Entry]) -> String {
|
||||
let d = rows.iter().filter(|e| e.done).count();
|
||||
s += &format!("\n## {t} ({d} / {}, {:.0}%)\n", rows.len(), pct(d, rows.len()));
|
||||
for (title, want) in [("Implemented", true), ("Missing", false)] {
|
||||
let list: Vec<String> = rows.iter().filter(|e| e.done == want).map(|e| format!("- `{}` {} ({})", e.id, e.label, e.group)).collect();
|
||||
let list: Vec<String> = rows
|
||||
.iter()
|
||||
.filter(|e| e.done == want)
|
||||
.map(|e| {
|
||||
let line = format!("- `{}` {} ({})", e.id, e.label, e.group);
|
||||
if want {
|
||||
return line;
|
||||
}
|
||||
let h = headless_of(e, &marks);
|
||||
match h.reach {
|
||||
Some(r) => format!("{line}: headless: {}, reach: {r} ({})", h.value, h.why),
|
||||
None => format!("{line}: headless: {}", h.value),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !list.is_empty() {
|
||||
s += &format!("\n{title}:\n\n{}\n", list.join("\n"));
|
||||
}
|
||||
@@ -109,7 +228,12 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
|
||||
other => return Err(format!("parity: unknown argument `{other}` (usage: cargo xtask parity [--check] [--out PATH])")),
|
||||
}
|
||||
}
|
||||
let text = render(&entries());
|
||||
let entries = entries();
|
||||
let errs = mark_errors(HEADLESS, &entries);
|
||||
if !errs.is_empty() {
|
||||
return Err(format!("parity: RFC-0052 headless marks in xtask/src/parity.rs:\n {}", errs.join("\n ")));
|
||||
}
|
||||
let text = render(&entries);
|
||||
if check {
|
||||
let current = std::fs::read_to_string(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
if !up_to_date(¤t, &text) {
|
||||
@@ -151,6 +275,38 @@ mod tests {
|
||||
assert!(s.find("## File").unwrap_or(usize::MAX) < s.find("## Home").unwrap_or(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_comes_only_from_the_registry() {
|
||||
let marks = "file.open|no|window|a dialog\n";
|
||||
let s = render_with(&[e("file.new", "File", true), e("file.open", "File", false), e("home.bold", "Home", false)], marks);
|
||||
assert!(s.contains("1 yes, 1 no (window 1, os 0, engine-gap 0), 0 partial, 1 unknown"), "{s}");
|
||||
assert!(s.contains("- `file.open` FILE.OPEN (G): headless: no, reach: window (a dialog)"), "{s}");
|
||||
assert!(s.contains("- `home.bold` HOME.BOLD (G): headless: unknown"), "{s}");
|
||||
// A live id is `yes` whatever a mark says.
|
||||
let parsed = parse_marks("file.new|no|os|x\n").unwrap_or_default();
|
||||
assert_eq!(headless_of(&e("file.new", "File", true), &parsed).value, "yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_marks_are_refused() {
|
||||
for bad in ["a.b|yes|window|x", "a.b|no|desk|x", "a.b|no", "a.b|no|os|x\na.b|partial|os|y"] {
|
||||
assert!(parse_marks(bad).is_err(), "{bad}");
|
||||
}
|
||||
let entries = [e("a.b", "T", true), e("c.d", "T", false)];
|
||||
let errs = mark_errors("a.b|no|os|x\nz.z|no|os|y\nc.d|partial|engine-gap|z\n", &entries);
|
||||
assert_eq!(errs.len(), 2, "{errs:?}");
|
||||
assert!(errs.iter().any(|m| m.contains("`a.b` is stale")), "{errs:?}");
|
||||
assert!(errs.iter().any(|m| m.contains("`z.z` is not a catalog id")), "{errs:?}");
|
||||
assert_eq!(mark_errors("junk", &entries).len(), 1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "engine")]
|
||||
#[test]
|
||||
fn checked_in_marks_are_current() {
|
||||
let errs = mark_errors(HEADLESS, &entries());
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_catalog_renders() {
|
||||
assert!(render(&[]).contains("0 / 0 commands implemented (0.0%)"));
|
||||
|
||||
Reference in New Issue
Block a user