Compare commits

..
Author SHA1 Message Date
FredApps 8e85bbfcc6 Advertise two self-describing named forms on the private CUPS fixture [linux only] 2026-12-03 02:18:47 +01:00
FredApps 0cebd8c846 Verify separately named equal-size media in the combined private CUPS test [linux only] 2026-12-03 02:14:14 +01:00
FredApps 5e947b598f Point both hosted GridCraft jobs at the checked-out fonts 2026-12-03 01:57:22 +01:00
FredApps 329ab9f034 Verify queue paper and workbook ranges together on hosted runners 2026-12-03 01:50:24 +01:00
FredApps a942b176e3 Use paper sizes offered by the selected print queue 2026-12-03 01:48:52 +01:00
FredApps e6bba235af Lock the shared workbook page range dependencies 2026-12-03 00:28:31 +01:00
FredApps 91a7e1b533 Return the workbook preview to the first sheet when its page range changes
(cherry picked from commit 7f6a69b126)
2026-12-03 00:26:53 +01:00
FredApps 897158c43c Restore the print scope import for ranged workbook previews 2026-12-03 00:26:53 +01:00
FredApps 860be81832 Use current queue fixtures and inspect the selected worksheet PDF page
(cherry picked from commit a52182d431)
2026-12-03 00:26:52 +01:00
FredApps 79c0836f34 Use shared page bounds for workbook print, preview and PDF output 2026-12-02 23:25:58 +01:00
FredApps 894bb14be2 Integrate the contributor page-range controls with current GridCraft printing 2026-12-02 23:21:15 +01:00
Ingmar Lübbe c50fa8d3e1 Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-13 14:08:55 +01:00
Ingmar Lübbe 30bfcac0d1 Merge remote-tracking branch 'origin/main' into feat/print-page-range
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-05 09:47:47 +01:00
Ingmar Lübbe 078ef5f7cc Merge remote-tracking branch 'origin/main' into feat/print-page-range 2026-11-04 07:44:45 +01:00
Ingmar LübbeandClaude Opus 5.5 1bfd0f0cf0 Print: a call to another window uses that window's page range (#3016)
`engine.execute` with `window` or `doc` made the target window active in the engine, but a UI
command such as `ui.printSettings` or `ui.printSubmit` still read and changed the interface state
of the window that was active: it set that window's page range, and printed the target workbook
with it. `run_in` now brings in the target window's interface state before the command and the
active window's after it.

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SAgnkqJiy3v24Hp25dQLRj
2026-10-31 10:15:30 +01:00
66 changed files with 2160 additions and 1935 deletions
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
old=8fa4db64a9bb943520259ea95331a303ba788f21
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$GRID_FRAMEWORK/g"
cargo metadata --locked --format-version 1 > "$RUNNER_TEMP/gridcraft-queue-paper-graph.json"
python - "$RUNNER_TEMP/gridcraft-queue-paper-graph.json" "$GRID_FRAMEWORK" <<'PY'
import json
import sys
graph = json.load(open(sys.argv[1], encoding="utf-8-sig"))
for crate in ("craft-print", "craft-pages"):
package, = [p for p in graph["packages"] if p["name"] == crate]
assert package["source"].endswith("#" + sys.argv[2]), (crate, package["source"])
PY
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -euo pipefail
shared=shared-print/crates/print/examples/print_acceptance/cups_capture.sh
anchor='timeout 20s "$harness" list | tee "$results/discovery.log"'
grep -Fxq "$anchor" "$shared"
awk -v anchor="$anchor" '$0 == anchor { exit } { print }' "$shared" >"$RUNNER_TEMP/gridcraft-cups-setup.sh"
source "$RUNNER_TEMP/gridcraft-cups-setup.sh" "$1" "$PWD/gridcraft-print-output"
timeout 20s lpadmin -h "$CUPS_SERVER" -d "$queue"
test -z "$(timeout 10s lpstat -W all -o "$queue")"
# Give the private printer distinct names with the same Legal geometry. The
# size suffix lets the shared catalog interpret lpoptions on a private socket,
# where it deliberately does not read the host system's PPD directory.
awk '
{ print }
/^\*(PageSize|PageRegion|ImageableArea|PaperDimension) Legal([/:])/ {
left = right = $0
sub(/ Legal[^:]*:/, " qa_left_8.5x14in/Legal left feed:", left)
sub(/ Legal[^:]*:/, " qa_right_8.5x14in/Legal right feed:", right)
print left
print right
}
' "$work/capture.ppd" >"$work/equal-forms.ppd"
for key in qa_left_8.5x14in qa_right_8.5x14in; do
grep -Eq "^\*PaperDimension $key[/:]" "$work/equal-forms.ppd"
done
timeout 20s lpadmin -h "$CUPS_SERVER" -p "$queue" -P "$work/equal-forms.ppd"
for key in qa_left_8.5x14in qa_right_8.5x14in; do
case_dir="$results/$key"
mkdir "$case_dir"
sudo -n test ! -e "$capture"
sudo -n install -m 0600 /dev/null "$capture"
offset=$(wc -l <"$results/scheduler.log")
GRIDCRAFT_PRIVATE_CUPS=1 GRIDCRAFT_TEST_PAPER="$key" timeout 90s "$harness" \
--test-threads=1 --nocapture selected_queue_legal_paper_and_page_range_reach_the_private_cups_file | tee "$case_dir/app.log"
mapfile -t receipts < <(sed -nE 's/^.*GRIDCRAFT_RECEIPT=.*(craft-print-capture-[0-9]+).*$/\1/p' "$case_dir/app.log")
[[ ${#receipts[@]} == 1 ]]
job_id=${receipts[0]}
echo "$job_id" >>"$results/receipts.txt"
for elapsed in {1..60}; do
timeout 10s lpstat -W completed -o "$queue" >"$case_dir/completed-jobs.log"
if awk -v id="$job_id" '$1 == id { seen=1 } END { exit !seen }' "$case_dir/completed-jobs.log" && sudo -n test -s "$capture"; then
sudo -n cat -- "$capture" >"$case_dir/captured.pdf"
sudo -n rm -- "$capture"
break
fi
sleep 1
done
tail -n "+$((offset + 1))" "$results/scheduler.log" >"$case_dir/ipp.log"
grep -F 'cupsdProcessIPPRequest: media ' "$case_dir/ipp.log" | grep -Fq "'$key'"
pdfinfo "$case_dir/captured.pdf" >"$case_dir/captured.pdfinfo"
pdftotext -layout "$case_dir/captured.pdf" "$case_dir/captured.txt"
grep -Eq '^Pages: +1$' "$case_dir/captured.pdfinfo"
grep -Eq '^Page size: +612 x 1008 pts' "$case_dir/captured.pdfinfo"
grep -Fq 'Paper form selected page' "$case_dir/captured.txt"
if grep -Fq 'Paper form first page' "$case_dir/captured.txt"; then
echo "The unselected worksheet page was printed" >&2
exit 1
fi
echo "Verified $key in the scheduler request, one Legal sheet and only the selected worksheet page from $job_id"
done
timeout 10s lpstat -W all -o "$queue" >"$results/all-jobs.log"
diff -u <(sort "$results/receipts.txt") <(awk '{print $1}' "$results/all-jobs.log" | sort)
+82
View File
@@ -0,0 +1,82 @@
name: GridCraft queue paper and range
on:
push:
branches: [verify/gridcraft-queue-paper-4859]
permissions:
contents: read
env:
GRID_FRAMEWORK: 6992dba3069ff7342bb81efb40d657e81ee37ca8
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_INCREMENTAL: '0'
CRAFT_FONTS_REQUIRED: '1'
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
jobs:
linux:
runs-on: ubuntu-24.04
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: fa63a22393bb03f40e33accbffa67c51465ee327
path: shared-print
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev
libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev
xvfb xauth cups-daemon cups-client cups-filters poppler-utils
- name: Apply the exact app framework baseline plus the staged catalog and range code
run: bash .github/qa/queue-paper-overlay.sh
- name: Check that the selected paper reflows workbook layout
if: "!contains(github.event.head_commit.message, '[linux only]')"
run: cargo test --locked -p gridcraft-engine --lib job_paper_override
- name: Exercise the paper, preview, range and retry regressions
run: xvfb-run -a cargo test --locked -p gridcraft-ui-egui --test it --test print_selection -- queue_papers the_print_views_page_fields_set_the_range_and_the_preview_follows print_selection_previews refused_browser_handoff --test-threads=1
- name: Build the real native submit path and capture its output
run: |
set -euo pipefail
cargo test --locked -p gridcraft --bin gridcraft --no-run --message-format json > "$RUNNER_TEMP/gridcraft-build.jsonl"
binary=$(jq -er 'select(.reason == "compiler-artifact" and .profile.test and .target.name == "gridcraft" and .executable) | .executable' "$RUNNER_TEMP/gridcraft-build.jsonl")
echo "GRIDCRAFT_QA_BINARY=$binary" >> "$GITHUB_ENV"
bash .github/qa/verify-queue-paper.sh "$binary"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: failure() && env.GRIDCRAFT_QA_BINARY != ''
with:
name: gridcraft-compiled-cups-test
path: ${{ env.GRIDCRAFT_QA_BINARY }}
retention-days: 3
if-no-files-found: error
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: gridcraft-queue-paper-output
path: gridcraft-print-output/
if-no-files-found: warn
windows:
if: "!contains(github.event.head_commit.message, '[linux only]')"
runs-on: windows-2025
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- name: Apply the exact app framework baseline plus the staged catalog and range code
shell: bash
run: bash .github/qa/queue-paper-overlay.sh
- name: Check the real Windows adapter against the shared forms API
shell: bash
run: |
set -euo pipefail
cargo check --locked -p gridcraft --bin gridcraft
Generated
+19 -143
View File
@@ -199,56 +199,12 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -840,65 +796,6 @@ dependencies = [
"libloading",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_complete"
version = "4.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "clap_mangen"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
dependencies = [
"clap",
"roff",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -976,12 +873,6 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "colored"
version = "2.2.0"
@@ -1390,6 +1281,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-text",
"kurbo",
"serde",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -1515,6 +1416,14 @@ dependencies = [
"vectorcraft-pathops",
]
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"serde",
]
[[package]]
name = "craft-theme"
version = "0.1.0"
@@ -3013,16 +2922,12 @@ dependencies = [
name = "gridcraft-cli"
version = "0.20.0"
dependencies = [
"clap",
"clap_complete",
"clap_mangen",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
"log",
"quick-xml 0.42.0",
"serde_json",
"thiserror 2.0.21",
"zip",
]
@@ -3054,6 +2959,7 @@ version = "0.20.0"
dependencies = [
"craft-csv",
"craft-gridcraft-format",
"craft-pages",
"gridcraft-calc",
"gridcraft-chart",
"gridcraft-core",
@@ -3849,12 +3755,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.13.0"
@@ -4916,12 +4816,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "open"
version = "5.4.4"
@@ -5857,12 +5751,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "roff"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "roxmltree"
version = "0.21.2"
@@ -6633,12 +6521,6 @@ dependencies = [
"float-cmp",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.28.0"
@@ -7345,12 +7227,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.27.0"
+1 -4
View File
@@ -44,6 +44,7 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pages = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
@@ -58,10 +59,6 @@ craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a
# foundation
thiserror = "2"
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
clap = { version = "4", features = ["derive"] }
clap_complete = "4"
clap_mangen = "0.2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
-11
View File
@@ -9,10 +9,6 @@ publish = false
[lints]
workspace = true
[lib]
name = "gridcraft_cli"
path = "src/lib.rs"
[[bin]]
name = "gridcraft-cli"
path = "src/main.rs"
@@ -26,10 +22,3 @@ log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
zip = { workspace = true }
quick-xml = { workspace = true }
thiserror = { workspace = true }
clap = { workspace = true }
[dev-dependencies]
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
@@ -1,42 +0,0 @@
//! Writes gridcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `gridcraft-cli.1` and one per subcommand, such as
//! `gridcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
//! (see `packaging/`):
//!
//! ```sh
//! cargo run -p gridcraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = gridcraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "gridcraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`gridcraft-cli-help-convert.1`).
clap_mangen::generate_to(gridcraft_cli::command(), dir)
}
-321
View File
@@ -1,321 +0,0 @@
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string;
//! what clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
//!
//! `run` is ordered: its `--cmd` and `--script` steps run in the order they were given, so the repeatable options are
//! kept with their positions and read back in order ([`RunArgs::steps`]).
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::Value;
use crate::script::{ScriptError, Step, parse_command};
/// The end of every subcommand's `--help`.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// The top-level `--help` ends with the environment and the exit status.
const TOP_NOTES: &str = "Environment:\n none: the CLI reads no environment variables of its own\n\nExit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// What a script line looks like (the `run` help ends with it).
const SCRIPT_LINES: &str = "A script line is `id={json}`, `id {json}`, `id`, or {\"command\": \"id\", \"params\": {…}}; blank lines and lines starting with # or // are skipped.";
/// Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window
#[derive(Parser, Debug)]
#[command(name = "gridcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Sheets, used ranges, tables, charts and names of a workbook
#[command(after_help = EXIT_STATUS)]
Info(InfoArgs),
/// Convert a workbook: xlsx, csv, tsv, json, html or pdf, by the extension of OUT
#[command(after_help = EXIT_STATUS)]
Convert(ConvertArgs),
/// Evaluate one formula, optionally against a workbook
#[command(after_help = EXIT_STATUS)]
Eval(EvalArgs),
/// Print a range as an aligned table or CSV
#[command(after_help = EXIT_STATUS)]
Cat(CatArgs),
/// Cached-value calc oracle and XLSX round-trip fidelity of files or folders (exit 1 on any difference)
#[command(after_help = EXIT_STATUS)]
Check(CheckArgs),
/// Run commands and scripts on a workbook, then save or print it
#[command(after_help = format!("{SCRIPT_LINES}\n\n{EXIT_STATUS}"))]
Run(RunArgs),
/// List the commands
#[command(after_help = EXIT_STATUS)]
Commands(ListArgs),
/// List the formula functions
#[command(after_help = EXIT_STATUS)]
Functions(FunctionsArgs),
/// Serve MCP on stdio, headless or driving the running app
#[command(after_help = EXIT_STATUS)]
Mcp(McpArgs),
/// Send one control-channel request to the running app
#[command(after_help = EXIT_STATUS)]
Send(SendArgs),
/// Whether this system confines programs (no program: a confined self-test)
///
/// With a program it runs that program confined, with the given read and executable paths and the system's shared
/// libraries, passing its output and exit status through; its own lines then go to standard error. Every path is
/// absolute. Exit status: 0 when every attempt is as required (or the program succeeded), 1 otherwise (a refused
/// launch included), 2 when GridCraft has no sandbox for this kind of system.
#[command(name = "sandbox-check", after_help = EXIT_STATUS)]
SandboxCheck(SandboxCheckArgs),
}
#[derive(Args, Debug)]
pub(crate) struct InfoArgs {
/// The workbook
pub(crate) file: PathBuf,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ConvertArgs {
/// The workbook to read
pub(crate) input: PathBuf,
/// The file to write (.xlsx, .csv, .tsv, .json, .html or .pdf)
pub(crate) output: PathBuf,
/// The sheet to write, by name or index
#[arg(long, value_name = "NAME")]
pub(crate) sheet: Option<String>,
/// Allow OUTPUT to replace the input workbook
#[arg(long)]
pub(crate) overwrite: bool,
}
#[derive(Args, Debug)]
pub(crate) struct EvalArgs {
/// The formula; a leading `=` is optional
#[arg(allow_hyphen_values = true)]
pub(crate) formula: String,
/// Evaluate against this workbook
#[arg(long = "in", value_name = "FILE")]
pub(crate) input: Option<PathBuf>,
/// The sheet to evaluate on, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// The cell the formula sits in
#[arg(long, value_name = "A1")]
pub(crate) cell: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CatArgs {
/// The workbook
pub(crate) file: PathBuf,
/// The range to print (default: the used range)
#[arg(long, value_name = "A1:D20")]
pub(crate) range: Option<String>,
/// The sheet to print, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// Show formulas instead of values
#[arg(long)]
pub(crate) formulas: bool,
/// Print CSV instead of an aligned table
#[arg(long)]
pub(crate) csv: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CheckArgs {
/// Files to check, or folders to scan for .xlsx and .xlsm files
#[arg(required = true, value_name = "FILE_OR_DIR")]
pub(crate) inputs: Vec<PathBuf>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
/// How far a cached number may differ from the recalculated one
#[arg(long, value_name = "T", allow_negative_numbers = true, value_parser = tolerance)]
pub(crate) tolerance: Option<f64>,
/// How many mismatches to list per file
#[arg(long = "max-report", value_name = "N")]
pub(crate) max_report: Option<usize>,
}
fn tolerance(text: &str) -> Result<f64, UsageError> {
text.parse().ok().filter(|t: &f64| t.is_finite() && *t >= 0.0).ok_or_else(|| UsageError::Tolerance(text.to_owned()))
}
/// The command or the script file of a `run` step.
#[derive(Clone, Debug)]
pub(crate) enum RunStep {
/// `--cmd`; a blank or comment line is `None`.
Cmd(Option<Step>),
/// `--script`
Script(PathBuf),
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// Start from this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Start from a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
/// Run one command, `ID={json}`; repeatable, in order with `--script`
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = command_step)]
cmds: Vec<Option<Step>>,
/// Run a script file of command lines (.jsonl); repeatable, in order with `--cmd`
#[arg(long = "script", value_name = "FILE")]
scripts: Vec<PathBuf>,
/// Save the workbook here when the steps are done (by extension)
#[arg(long, value_name = "FILE")]
pub(crate) out: Option<PathBuf>,
/// Allow `--out` to replace `--in`
#[arg(long, requires = "out")]
pub(crate) overwrite: bool,
/// Print a range when the steps are done (`used` or empty: the used range); repeatable
#[arg(long, value_name = "RANGE")]
pub(crate) print: Vec<String>,
/// The sheet `--print` shows, by name or index
#[arg(long, value_name = "S", requires = "print")]
pub(crate) sheet: Option<String>,
/// `--print` shows formulas instead of values
#[arg(long, requires = "print")]
pub(crate) formulas: bool,
/// `--print` writes CSV instead of an aligned table
#[arg(long, requires = "print")]
pub(crate) csv: bool,
/// Don't print each command's result
#[arg(long)]
pub(crate) quiet: bool,
/// The steps in the order they were given.
#[arg(skip)]
pub(crate) steps: Vec<RunStep>,
}
/// The values of a repeatable option with the position each was given at.
fn at<T: Clone>(sub: &ArgMatches, id: &str, values: &[T]) -> Vec<(usize, T)> {
sub.indices_of(id).into_iter().flatten().zip(values.iter().cloned()).collect()
}
impl RunArgs {
fn check(&mut self, sub: &ArgMatches) {
let mut steps: Vec<(usize, RunStep)> = at(sub, "cmds", &self.cmds).into_iter().map(|(i, c)| (i, RunStep::Cmd(c))).collect();
steps.extend(at(sub, "scripts", &self.scripts).into_iter().map(|(i, p)| (i, RunStep::Script(p))));
steps.sort_by_key(|(i, _)| *i);
self.steps = steps.into_iter().map(|(_, s)| s).collect();
}
}
fn command_step(text: &str) -> Result<Option<Step>, UsageError> {
parse_command(text).map_err(UsageError::Cmd)
}
#[derive(Args, Debug)]
pub(crate) struct ListArgs {
/// Only those whose id, label or menu contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct FunctionsArgs {
/// Only those whose name or description contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// Only this category
#[arg(long, value_name = "C")]
pub(crate) category: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
/// Drive the running app (started with `gridcraft --control PORT`) instead of a headless workbook
#[arg(long, value_name = "PORT", conflicts_with_all = ["input", "sample"])]
pub(crate) connect: Option<String>,
/// Serve this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Serve a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct SendArgs {
/// The control port of the running app
pub(crate) port: String,
/// The control-channel method
pub(crate) method: String,
/// Its parameters, as JSON
#[arg(value_name = "JSON", allow_negative_numbers = true, value_parser = json_value)]
pub(crate) params: Option<Value>,
}
fn json_value(text: &str) -> Result<Value, UsageError> {
serde_json::from_str(text).map_err(|e| UsageError::Json(e.to_string()))
}
#[derive(Args, Debug)]
pub(crate) struct SandboxCheckArgs {
/// Let the program read this path; repeatable
#[arg(long, value_name = "PATH")]
pub(crate) read: Vec<PathBuf>,
/// Let the program execute this path; repeatable
#[arg(long = "exec", value_name = "PATH")]
pub(crate) exec: Vec<PathBuf>,
/// After `--`: the program to run confined, and its arguments
#[arg(last = true, value_name = "PROGRAM")]
pub(crate) program: Vec<OsString>,
}
/// A mistake in the command line that clap can't see by itself.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum UsageError {
#[error("--tolerance: expected a number ≥ 0, not `{0}`")]
Tolerance(String),
#[error("--cmd: {0}")]
Cmd(ScriptError),
#[error("bad JSON params: {0}")]
Json(String),
}
/// The clap definition of the whole command line (completions and man pages are generated from it).
pub fn command() -> clap::Command {
Cli::command()
}
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("gridcraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
if let (Command::Run(run), Some(("run", sub))) = (&mut cli.command, matches.subcommand()) {
run.check(sub);
}
if let Command::SandboxCheck(check) = &cli.command
&& check.program.is_empty()
&& args.iter().any(|arg| arg == "--")
{
return Err(Cli::command().error(clap::error::ErrorKind::InvalidValue, "sandbox-check: a program is required after `--`"));
}
Ok(cli)
}
+29 -15
View File
@@ -15,6 +15,7 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::{Cursor, Read as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use gridcraft_engine::calc::{Calc, Key};
use gridcraft_engine::cmd::inspect::value_json;
@@ -23,10 +24,7 @@ use gridcraft_engine::formula::{Expr, quote_sheet};
use gridcraft_engine::model::{Cell, Sheet, Workbook};
use serde_json::{Value as Json, json};
use crate::args::CheckArgs;
use crate::commands::{number_text, pretty};
use crate::error::{CliError, unicode};
use crate::{Io, outln};
use super::{Args, USAGE, number_text, pretty};
mod calc;
mod fidelity;
@@ -191,16 +189,32 @@ impl Diffs {
/// `check <file-or-dir>... [--json] [--tolerance X] [--max-report N]`. Exit 0 when every file opens,
/// every checked formula matches and every round trip is clean; 1 otherwise; 2 on a usage error.
pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
let usage = |e: String| {
eprintln!("gridcraft-cli: {e}\n{USAGE}");
ExitCode::from(2)
};
let a = match Args::parse(args, &["tolerance", "max-report"], &["json"]) {
Ok(a) => a,
Err(e) => return usage(e),
};
if a.positional.is_empty() {
return usage("missing <file-or-dir>".into());
}
let mut opts = Options::default();
if let Some(t) = a.tolerance {
opts.tolerance = t;
if let Some(t) = a.opt("tolerance") {
match t.parse::<f64>() {
Ok(t) if t.is_finite() && t >= 0.0 => opts.tolerance = t,
_ => return usage(format!("--tolerance needs a number ≥ 0, not `{t}`")),
}
}
if let Some(n) = a.max_report {
opts.max_report = n;
if let Some(n) = a.opt("max-report") {
match n.parse::<usize>() {
Ok(n) => opts.max_report = n,
Err(_) => return usage(format!("--max-report needs a whole number, not `{n}`")),
}
}
let inputs: Vec<String> = a.inputs.iter().map(|p| unicode(p).map(str::to_owned)).collect::<Result<_, _>>()?;
let Discovery { files, failures: mut reports, .. } = collect_inputs(&inputs);
let Discovery { files, failures: mut reports, .. } = collect_inputs(&a.positional);
reports.extend(files.iter().map(|p| {
let path = p.to_string_lossy().into_owned();
match gridcraft_engine::io::read_file(&path) {
@@ -208,12 +222,12 @@ pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
Err(e) => FileReport { path, error: Some(e.to_string()), ..Default::default() },
}
}));
if a.json {
outln!(io, "{}", pretty(&report_json(&reports, &opts)));
if a.has("json") {
outln!("{}", pretty(&report_json(&reports, &opts)));
} else {
print_human(io, &reports, &opts)?;
print_human(&reports, &opts);
}
Ok(if !files.is_empty() && reports.iter().all(FileReport::is_clean) { 0 } else { 1 })
if !files.is_empty() && reports.iter().all(FileReport::is_clean) { ExitCode::SUCCESS } else { ExitCode::FAILURE }
}
#[derive(Default)]
+31 -41
View File
@@ -131,16 +131,15 @@ fn fit(s: &str, w: usize) -> String {
if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::<String>()) }
}
fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_reports(reports: &[FileReport]) {
for r in reports {
outln!(io, "== {}", r.path);
outln!("== {}", r.path);
if let Some(e) = &r.error {
outln!(io, " can't open: {e}");
outln!(" can't open: {e}");
continue;
}
let c = &r.calc;
outln!(
io,
" formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile",
c.formula_cells,
c.checked,
@@ -150,15 +149,14 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
c.volatile
);
if c.stale_cache {
outln!(io, " (the producer asked for a full recalculation on load: its cached values aren't results)");
outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)");
}
if c.bool_as_number > 0 {
outln!(io, " ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
}
for m in &c.mismatches {
let tag = if m.primary { "mismatch" } else { " (downstream)" };
outln!(
io,
" {tag} {} {} expected {} got {} [{}]",
m.cell,
one_line(&m.formula),
@@ -168,33 +166,31 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
);
}
if c.mismatched > c.mismatches.len() {
outln!(io, " … {} more mismatches", c.mismatched - c.mismatches.len());
outln!(" … {} more mismatches", c.mismatched - c.mismatches.len());
}
let rt = &r.round_trip;
if let Some(e) = &rt.error {
outln!(io, " round trip: {e}");
outln!(" round trip: {e}");
}
let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect();
if differing.is_empty() && rt.error.is_none() {
outln!(io, " round trip: all equal");
outln!(" round trip: all equal");
}
for cat in differing {
outln!(io, " round trip {}: {} difference(s)", cat.name, cat.diffs);
outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs);
for e in &cat.examples {
outln!(io, " {}", one_line(e));
outln!(" {}", one_line(e));
}
if cat.diffs > cat.examples.len() {
outln!(io, " … {} more", cat.diffs - cat.examples.len());
outln!(" … {} more", cat.diffs - cat.examples.len());
}
}
}
Ok(())
}
fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_table(reports: &[FileReport]) {
let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50);
outln!(
io,
"{:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip",
"file",
"formulas",
@@ -207,7 +203,7 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
for r in reports {
let label = fit(&r.path, w);
if let Some(e) = &r.error {
outln!(io, "{label:<w$} can't open: {}", one_line(&fit(e, 100)));
outln!("{label:<w$} can't open: {}", one_line(&fit(e, 100)));
continue;
}
let c = &r.calc;
@@ -217,7 +213,6 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
(None, d) => d.join(","),
};
outln!(
io,
"{label:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}",
c.formula_cells,
c.checked,
@@ -227,36 +222,33 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
c.volatile
);
}
Ok(())
}
fn print_rankings(io: &mut Io, t: &Totals, opts: &Options) -> Result<(), CliError> {
fn print_rankings(t: &Totals, opts: &Options) {
let top = ranked(&t.functions);
if !top.is_empty() {
outln!(io, "");
outln!(io, "top mismatching functions (primary = no mismatching precedent):");
outln!(io, " {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
outln!("");
outln!("top mismatching functions (primary = no mismatching precedent):");
outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
for (n, s) in top.iter().take(opts.max_report.max(1)) {
outln!(io, " {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
}
}
let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect();
sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
if !sigs.is_empty() {
outln!(io, "");
outln!(io, "mismatch signatures (expected → GridCraft):");
outln!("");
outln!("mismatch signatures (expected → GridCraft):");
for (sig, n) in sigs.iter().take(opts.max_report.max(1)) {
outln!(io, " {n:>8} {sig}");
outln!(" {n:>8} {sig}");
}
}
Ok(())
}
fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
outln!(io, "");
outln!(io, "files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
fn print_totals(t: &Totals) {
outln!("");
outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
outln!(
io,
"formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)",
t.formula_cells,
t.checked,
@@ -266,25 +258,23 @@ fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
t.volatile
);
if t.bool_as_number > 0 {
outln!(io, "booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
}
let cats: Vec<String> = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect();
outln!(
io,
"round trip: {} of {} files differ{}{}",
t.round_trip_differing,
t.opened,
if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() },
if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) }
);
Ok(())
}
pub(super) fn print_human(io: &mut Io, reports: &[FileReport], opts: &Options) -> Result<(), CliError> {
print_file_reports(io, reports)?;
outln!(io, "");
print_file_table(io, reports)?;
pub(super) fn print_human(reports: &[FileReport], opts: &Options) {
print_file_reports(reports);
outln!("");
print_file_table(reports);
let t = totals(reports);
print_rankings(io, &t, opts)?;
print_totals(io, &t)
print_rankings(&t, opts);
print_totals(&t);
}
-468
View File
@@ -1,468 +0,0 @@
//! The subcommands: each takes its typed arguments and the streams, and returns what to exit with.
use std::path::Path;
use gridcraft_engine::Session;
use serde_json::{Value, json};
use crate::args::{CatArgs, Command, ConvertArgs, EvalArgs, FunctionsArgs, InfoArgs, ListArgs, McpArgs, RunArgs, RunStep, SendArgs};
use crate::error::{CliError, unicode};
use crate::script::parse_command;
use crate::{Io, check, errln, outln, sandbox_check};
/// Run a parsed command line; gives the exit code (0, or 1 when `check` found a difference and said so itself).
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<i32, CliError> {
match command {
Command::Info(a) => info(&a, io),
Command::Convert(a) => convert(&a, io),
Command::Eval(a) => eval(&a, io),
Command::Cat(a) => cat(&a, io),
Command::Run(a) => run(&a, io),
Command::Commands(a) => commands(&a, io),
Command::Functions(a) => functions(&a, io),
Command::Mcp(a) => mcp(&a, io),
Command::Send(a) => send(&a, io),
Command::Check(a) => return check::run(&a, io),
Command::SandboxCheck(a) => return sandbox_check::run(&a, io),
}
.map(|()| 0)
}
// ---------------------------------------------------------------- helpers
fn exec(io: &mut Io, s: &mut Session, id: &str, params: Value) -> Result<Value, CliError> {
let r = s.execute_headless(id, params).map_err(CliError::engine);
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)
{
for warning in warnings.iter().filter_map(Value::as_str) {
errln!(io, "Warning: {warning}");
}
}
r
}
fn open(io: &mut Io, path: &std::path::Path) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.open", json!({"path": unicode(path)?}))?;
Ok(s)
}
fn sample(io: &mut Io, name: &str) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.new", json!({"sample": name}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(io: &mut Io, s: &mut Session, sheet: Option<&str>) -> Result<(), CliError> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(io, s, "sheet.activate", p)?;
}
Ok(())
}
pub(crate) fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
pub(crate) fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(a: &InfoArgs, io: &mut Io) -> Result<(), CliError> {
let path = unicode(&a.file)?;
let mut s = open(io, &a.file)?;
let v = exec(io, &mut s, "document.inspect", json!({}))?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
outln!(io, "{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
io,
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(
io,
" table {} {} ({})",
t["name"].as_str().unwrap_or("?"),
t["range"].as_str().unwrap_or("?"),
t["style"].as_str().unwrap_or("")
);
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(io, " chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(io, " filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!(io, "names:");
for n in names {
outln!(io, " {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
/// Whether `out` is the file `input` names: the same path, a symlink to it or, on Unix, a hard
/// link (the same device and inode). An `out` that doesn't exist yet can't be the input.
fn names_the_same_file(input: &Path, out: &Path) -> bool {
let (Ok(a), Ok(b)) = (std::fs::canonicalize(input), std::fs::canonicalize(out)) else { return false };
if a == b {
return true;
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let (Ok(a), Ok(b)) = (std::fs::metadata(&a), std::fs::metadata(&b)) {
return (a.dev(), a.ino()) == (b.dev(), b.ino());
}
}
false
}
fn refuse_replace(input: &Path, out: &Path, overwrite: bool) -> Result<(), CliError> {
if !overwrite && names_the_same_file(input, out) {
return Err(CliError::WouldReplace { out: out.to_owned(), input: input.to_owned() });
}
Ok(())
}
fn convert(a: &ConvertArgs, io: &mut Io) -> Result<(), CliError> {
refuse_replace(&a.input, &a.output, a.overwrite)?;
let out = unicode(&a.output)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(CliError::OutputFormat { out: out.to_owned() });
}
let mut s = open(io, &a.input)?;
activate_sheet(io, &mut s, a.sheet.as_deref())?;
if pdf {
let result = exec(io, &mut s, "file.exportPdf", json!({"path": out}))?;
errln!(io, "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() {
errln!(io, "Warning: {warning}");
}
let d = s.doc().map_err(CliError::engine)?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(CliError::engine)?;
gridcraft_engine::io::write_file(out, &bytes).map_err(CliError::engine)?;
errln!(io, "wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(a: &EvalArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match &a.input {
Some(p) => open(io, p)?,
None => blank(),
};
activate_sheet(io, &mut s, a.sheet.as_deref())?;
let formula = if a.formula.starts_with('=') { a.formula.clone() } else { format!("={}", a.formula) };
let mut p = json!({"formula": formula});
if let Some(c) = &a.cell {
p["cell"] = json!(c);
}
let v = exec(io, &mut s, "formulas.evaluate", p)?;
if a.json {
outln!(io, "{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!(io, "{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(io: &mut Io, s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), CliError> {
activate_sheet(io, s, sheet)?;
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
// Activation already selected a numeric `--sheet` index; `sheet.read` takes names only.
let raw = exec(io, s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(io, s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!(io, "{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!(io, "{}", line.trim_end());
}
Ok(())
}
fn cat(a: &CatArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = open(io, &a.file)?;
print_range(io, &mut s, a.range.as_deref(), a.sheet.as_deref(), a.formulas, a.csv)
}
fn run(a: &RunArgs, io: &mut Io) -> Result<(), CliError> {
if let (Some(input), Some(out)) = (&a.input, &a.out) {
refuse_replace(input, out, a.overwrite)?;
}
let mut s = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
let mut step = 0usize;
for item in &a.steps {
let cmds: Vec<(String, Value, String)> = match item {
RunStep::Cmd(c) => c.iter().map(|(id, p)| (id.clone(), p.clone(), "--cmd".to_string())).collect(),
RunStep::Script(path) => {
let value = path.display().to_string();
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
let origin = format!("{value}:{}", i + 1);
if let Some((id, p)) = parse_command(line).map_err(|source| CliError::Script { origin: origin.clone(), source })? {
v.push((id, p, origin));
}
}
v
}
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(io, &mut s, &id, p).map_err(|e| CliError::Step { step, origin, id: id.clone(), message: e.to_string() })?;
if !a.quiet && !r.is_null() {
outln!(io, "{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = &a.out {
let out = unicode(out)?;
let r = exec(io, &mut s, "file.save", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes)", r["bytes"]);
}
for range in &a.print {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(io, &mut s, range, a.sheet.as_deref(), a.formulas, a.csv)?;
}
Ok(())
}
fn commands(a: &ListArgs, io: &mut Io) -> Result<(), CliError> {
let q = a.search.as_ref().or(a.word.as_ref()).map(|q| q.to_ascii_lowercase());
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.json {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!(io, "{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!(io, "{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!(io, "{:<w$} {}", "", c.params);
}
errln!(io, "{} commands", list.len());
Ok(())
}
fn functions(a: &FunctionsArgs, io: &mut Io) -> Result<(), CliError> {
let mut p = json!({});
if let Some(q) = a.search.as_ref().or(a.word.as_ref()) {
p["search"] = json!(q);
}
if let Some(c) = &a.category {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(io, &mut s, "formulas.functions", p)?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!(io, "{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(io, " {cat}: {desc}");
}
errln!(io, "{} functions", list.len());
Ok(())
}
fn connect(port: &str) -> Result<gridcraft_mcp::Remote, CliError> {
use gridcraft_mcp::control_addr;
let addr = control_addr(port);
gridcraft_mcp::Remote::connect(&addr).map_err(|e| CliError::Connect { addr, port: port.to_owned(), message: e.to_string() })
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app started with
/// `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(a: &McpArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::{Backend, Headless, Server};
let backend: Box<dyn Backend> = match &a.connect {
Some(c) => Box::new(connect(c)?),
None => {
let session = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
errln!(io, "gridcraft-cli: MCP server on stdio ({})", backend.describe());
// Replies go to the writer supplied to `run` (the CLI binary passes process stdout).
let stdin = std::io::stdin();
Server::new(backend).serve(stdin.lock(), &mut *io.out).map_err(CliError::engine)
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(a: &SendArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::Backend;
let params = a.params.clone().unwrap_or_else(|| json!({}));
let mut r = connect(&a.port)?;
let v = r.call(&a.method, params).map_err(CliError::engine)?;
outln!(io, "{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = crate::run(["convert", input.to_str().unwrap(), output.to_str().unwrap()], &mut out, &mut err);
assert_eq!(code, 0, "{}", String::from_utf8_lossy(&err));
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
-41
View File
@@ -1,41 +0,0 @@
use std::path::{Path, PathBuf};
/// Why a command failed: printed as `error: {e}`, exit 1. The engine, the MCP backends and the sandbox report their
/// failures as text; [`CliError::Engine`] carries it.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError {
/// What the engine, a backend or a library reported.
#[error("{0}")]
Engine(String),
/// The engine's commands take paths as JSON, which holds only text.
#[error("{}: the path is not valid Unicode", .0.display())]
NotUnicode(PathBuf),
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: std::io::Error },
#[error("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)")]
OutputFormat { out: String },
#[error("{} is the workbook {}: writing it would replace the input (pass --overwrite to replace it)", out.display(), input.display())]
WouldReplace { out: PathBuf, input: PathBuf },
#[error("cannot connect to the GridCraft app at {addr}: {message} (start it with `gridcraft --control {port}`)")]
Connect { addr: String, port: String, message: String },
#[error("step {step} ({origin}, {id}): {message}")]
Step { step: usize, origin: String, id: String, message: String },
#[error("{origin}: {source}")]
Script { origin: String, source: crate::script::ScriptError },
#[error("sandbox-check: {0}")]
Sandbox(String),
/// Standard output went away.
#[error("can't write to stdout: {0}")]
Stdout(std::io::Error),
}
impl CliError {
pub(crate) fn engine(e: impl ToString) -> Self {
Self::Engine(e.to_string())
}
}
/// A path as the text the engine's commands take.
pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> {
path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned()))
}
-131
View File
@@ -1,131 +0,0 @@
//! Headless GridCraft (`gridcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
//! through the binary; `gridcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod args;
mod check;
mod commands;
mod error;
mod sandbox_check;
mod script;
use std::ffi::OsString;
use std::io::Write;
use error::CliError;
pub use args::command;
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
pub(crate) struct Io<'a> {
pub(crate) out: &'a mut dyn Write,
pub(crate) err: &'a mut dyn Write,
}
/// Writes a line of results; fails with [`CliError::Stdout`], which `run` turns into a quiet end for a closed pipe
/// (`gridcraft-cli commands | head`) and a message for any other error.
macro_rules! outln {
($io:expr, $($arg:tt)*) => {
writeln!($io.out, $($arg)*).map_err($crate::error::CliError::Stdout)?
};
}
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
macro_rules! errln {
($io:expr, $($arg:tt)*) => {
drop(writeln!($io.err, $($arg)*))
};
}
pub(crate) use {errln, outln};
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the tokens a shell would see
/// before `--` count: after it they are file names.
fn launch_profile_argument(args: &[OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
/// to `out`, exit 0.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// A confined launcher run (and its probes) comes first, before anything else starts.
if let Some(code) = gridcraft_sandbox::handle_args(&args) {
return code;
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a CLI option, and a CLI
// that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&args) {
let _ = writeln!(err, "error: {flag} belongs to the GridCraft desktop app, not this CLI");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match args::parse(&args) {
Ok(cli) => cli,
Err(e) if e.use_stderr() => {
// A usage diagnostic that cannot be written still returns 2.
let _ = write!(err, "{}", e.render()).and_then(|()| err.flush());
return e.exit_code();
}
Err(e) => {
// Help or the version, on stdout: a closed pipe ends quietly; any other failure is reported and returns 1.
return match write!(out, "{}", e.render()).and_then(|()| out.flush()) {
Ok(()) => e.exit_code(),
Err(w) if w.kind() == std::io::ErrorKind::BrokenPipe => e.exit_code(),
Err(w) => {
let _ = writeln!(err, "error: {}", CliError::Stdout(w));
1
}
};
}
};
let mut io = Io { out, err };
match commands::dispatch(cli.command, &mut io) {
Ok(code) => code,
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
Err(CliError::Stdout(e)) if e.kind() == std::io::ErrorKind::BrokenPipe => 0,
Err(e) => {
errln!(io, "error: {e}");
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 rather than acting on
/// whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
}
+705 -4
View File
@@ -1,9 +1,710 @@
//! `gridcraft-cli`: headless GridCraft. Thin wiring over [`gridcraft_cli::run`].
//! Headless GridCraft.
//!
//! ```text
//! gridcraft-cli info <file> [--json]
//! gridcraft-cli convert <in> <out> [--sheet NAME]
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
//! gridcraft-cli version | --version
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use std::process::ExitCode;
/// `println!` that ends the program quietly when stdout is closed (`gridcraft-cli commands |
/// head`) instead of panicking on a broken pipe.
macro_rules! outln {
($($arg:tt)*) => {{
use std::io::Write as _;
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
$crate::stdout_failed(e);
}
}};
}
mod check;
mod sandbox_check;
use gridcraft_engine::Session;
use serde_json::{Value, json};
const USAGE: &str = "usage:
gridcraft-cli info <file> [--json] sheets, used ranges, tables, charts, names
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html/pdf by extension
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
[--out FILE] [--print RANGE] [--quiet]
a script line is id={json} or {\"command\": \"id\", \"params\": {…}};
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli send <port> <method> [json]
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
whether this system confines programs (no program: a confined self-test)
gridcraft-cli version";
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly; any
/// other write error is reported.
fn stdout_failed(e: std::io::Error) -> ! {
if e.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("gridcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
}
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the
/// tokens a shell would see before `--` count: after it they are file names.
fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
fn main() -> ExitCode {
let (mut out, mut err) = (std::io::stdout().lock(), std::io::stderr().lock());
// An exit code is 0 to 2 here; 128 + signal is the shell's, for a process a signal ended.
ExitCode::from(u8::try_from(gridcraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err)).unwrap_or(1))
// A confined launcher run (and its probes) comes first, before anything else starts.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
return ExitCode::from(u8::try_from(code).unwrap_or(1));
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a
// CLI option, and a CLI that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&raw) {
eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI");
return ExitCode::from(2);
}
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let r = match args.first().map(String::as_str) {
Some("--version" | "-V" | "version") => {
outln!("gridcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--help" | "-h" | "help") => {
outln!("{USAGE}");
Ok(())
}
Some("info") => info(rest),
Some("convert") => convert(rest),
Some("eval") => eval(rest),
Some("cat") => cat(rest),
Some("run") => run(rest),
Some("check") => return check::main(rest),
Some("sandbox-check") => return sandbox_check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("mcp") => mcp(rest),
Some("send") => send(rest),
Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")),
None => Err(USAGE.to_string()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("gridcraft-cli: {e}");
ExitCode::FAILURE
}
}
}
// ---------------------------------------------------------------- argument parsing
/// Parsed arguments: positionals, `--flag value` options and boolean `--switch`es.
struct Args {
positional: Vec<String>,
opts: Vec<(String, String)>,
switches: Vec<String>,
}
impl Args {
/// `with_value` lists the options that take a value; `switches` the boolean ones. Anything
/// else starting with `--` is an error.
fn parse(args: &[String], with_value: &[&str], switches: &[&str]) -> Result<Args, String> {
let mut out = Args { positional: vec![], opts: vec![], switches: vec![] };
let mut it = args.iter();
while let Some(a) = it.next() {
if let Some(name) = a.strip_prefix("--").filter(|n| !n.is_empty()) {
let (name, inline) = match name.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (name, None),
};
if with_value.contains(&name) {
let v = match inline {
Some(v) => v,
None => it.next().cloned().ok_or_else(|| format!("--{name} needs a value"))?,
};
out.opts.push((name.to_string(), v));
} else if switches.contains(&name) && inline.is_none() {
out.switches.push(name.to_string());
} else {
return Err(format!("unknown option --{name}"));
}
} else {
out.positional.push(a.clone());
}
}
Ok(out)
}
fn opt(&self, name: &str) -> Option<&str> {
self.opts.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
}
fn has(&self, name: &str) -> bool {
self.switches.iter().any(|s| s == name)
}
fn pos(&self, i: usize, what: &str) -> Result<&str, String> {
self.positional.get(i).map(String::as_str).ok_or_else(|| format!("missing {what}\n{USAGE}"))
}
fn no_extra(&self, n: usize) -> Result<(), String> {
match self.positional.get(n) {
Some(x) => Err(format!("unexpected argument `{x}`")),
None => Ok(()),
}
}
}
// ---------------------------------------------------------------- helpers
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 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)
{
for warning in warnings.iter().filter_map(Value::as_str) {
eprintln!("Warning: {warning}");
}
}
r
}
fn open(path: &str) -> Result<Session, String> {
let mut s = Session::new();
exec(&mut s, "file.open", json!({"path": path}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(s: &mut Session, sheet: Option<&str>) -> Result<(), String> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(s, "sheet.activate", p)?;
}
Ok(())
}
fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &[], &["json"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
let v = exec(&mut s, "document.inspect", json!({}))?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
outln!("{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(" table {} {} ({})", t["name"].as_str().unwrap_or("?"), t["range"].as_str().unwrap_or("?"), t["style"].as_str().unwrap_or(""));
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(" chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(" filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!("names:");
for n in names {
outln!(" {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["sheet"], &[])?;
let input = a.pos(0, "<in>")?;
let out = a.pos(1, "<out>")?;
a.no_extra(2)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(format!("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)"));
}
let mut s = open(input)?;
activate_sheet(&mut s, a.opt("sheet"))?;
if pdf {
let result = exec(&mut s, "file.exportPdf", json!({"path": out}))?;
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())?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sheet", "cell"], &["json"])?;
let formula = a.pos(0, "<formula>")?;
a.no_extra(1)?;
let mut s = match a.opt("in") {
Some(p) => open(p)?,
None => blank(),
};
activate_sheet(&mut s, a.opt("sheet"))?;
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
let mut p = json!({"formula": formula});
if let Some(c) = a.opt("cell") {
p["cell"] = json!(c);
}
let v = exec(&mut s, "formulas.evaluate", p)?;
if a.has("json") {
outln!("{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!("{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), String> {
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!("{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!("{}", line.trim_end());
}
Ok(())
}
fn cat(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["range", "sheet"], &["formulas", "csv"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
print_range(&mut s, a.opt("range"), a.opt("sheet"), a.has("formulas"), a.has("csv"))
}
/// One command from `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
fn parse_command(text: &str) -> Result<Option<(String, Value)>, String> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| format!("bad JSON: {e}"))?;
// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the
// script still exited 0, so a typo made a valid, wrong workbook (#2256).
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let (plural, list) = (if unknown.len() == 1 { "key" } else { "keys" }, unknown.join("`, `"));
return Err(format!("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}"));
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or("JSON command needs a `command` field")?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| format!("{id}: bad JSON params: {e}"))? };
Ok(Some((id.to_string(), params)))
}
fn run(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sample", "cmd", "script", "out", "print", "sheet"], &["quiet", "csv", "formulas"])?;
a.no_extra(0)?;
let mut s = match (a.opt("in"), a.opt("sample")) {
(Some(_), Some(_)) => return Err("give --in or --sample, not both".into()),
(Some(p), None) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
let quiet = a.has("quiet");
let mut step = 0usize;
for (name, value) in &a.opts {
let cmds: Vec<(String, Value, String)> = match name.as_str() {
"cmd" => parse_command(value)?.map(|(id, p)| vec![(id, p, "--cmd".to_string())]).unwrap_or_default(),
"script" => {
let text = std::fs::read_to_string(value).map_err(|e| format!("{value}: {e}"))?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
if let Some((id, p)) = parse_command(line).map_err(|e| format!("{value}:{}: {e}", i + 1))? {
v.push((id, p, format!("{value}:{}", i + 1)));
}
}
v
}
_ => continue,
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(&mut s, &id, p).map_err(|e| format!("step {step} ({origin}, {id}): {e}"))?;
if !quiet && !r.is_null() {
outln!("{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = a.opt("out") {
let r = exec(&mut s, "file.save", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes)", r["bytes"]);
}
for (name, range) in &a.opts {
if name == "print" {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(&mut s, range, a.opt("sheet"), a.has("formulas"), a.has("csv"))?;
}
}
Ok(())
}
fn commands(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search"], &["json"])?;
let q = a.opt("search").or(a.positional.first().map(String::as_str)).map(str::to_ascii_lowercase);
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.has("json") {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!("{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!("{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!("{:<w$} {}", "", c.params);
}
eprintln!("{} commands", list.len());
Ok(())
}
fn functions(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search", "category"], &["json"])?;
let mut p = json!({});
if let Some(q) = a.opt("search").or(a.positional.first().map(String::as_str)) {
p["search"] = json!(q);
}
if let Some(c) = a.opt("category") {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(&mut s, "formulas.functions", p)?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!("{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(" {cat}: {desc}");
}
eprintln!("{} functions", list.len());
Ok(())
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
a.no_extra(0)?;
let backend: Box<dyn Backend> = match a.opt("connect") {
Some(c) => {
let addr = control_addr(c);
Box::new(
Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
)
}
None => {
let session = match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Remote, control_addr};
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
let params: Value = match args.get(2) {
Some(t) => serde_json::from_str(t).map_err(|e| format!("bad JSON params: {e}"))?,
None => json!({}),
};
if let Some(x) = args.get(3) {
return Err(format!("unexpected argument `{x}`"));
}
let addr = control_addr(port);
let mut r = Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
let v = r.call(method, params)?;
outln!("{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2
/// rather than acting on whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused");
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused");
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn args_parsing() {
let v: Vec<String> = ["a", "--range", "A1", "--csv", "--sheet=S"].iter().map(|s| s.to_string()).collect();
let a = Args::parse(&v, &["range", "sheet"], &["csv"]).unwrap();
assert_eq!(a.positional, ["a"]);
assert_eq!(a.opt("range"), Some("A1"));
assert_eq!(a.opt("sheet"), Some("S"));
assert!(a.has("csv"));
assert!(Args::parse(&["--nope".to_string()], &[], &[]).is_err());
assert!(Args::parse(&["--range".to_string()], &["range"], &[]).is_err());
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
convert(&[input.to_string_lossy().into_owned(), output.to_string_lossy().into_owned()]).unwrap();
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
+46 -58
View File
@@ -12,99 +12,87 @@
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
use crate::args::SandboxCheckArgs;
use crate::error::CliError;
use crate::{Io, errln, outln};
use gridcraft_sandbox::{Canary, Policy, REFUSED_EXIT_CODE, REPORT_FLAG, Support};
pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("gridcraft-cli: sandbox-check: {e}");
ExitCode::FAILURE
}
}
}
fn run(args: &[String]) -> Result<ExitCode, String> {
let mut policy = Policy::new().with_system_libraries();
for path in &a.read {
policy = policy.read(path);
let mut it = args.iter();
let mut program: Option<(PathBuf, Vec<OsString>)> = None;
while let Some(a) = it.next() {
match a.as_str() {
"--read" => policy = policy.read(it.next().ok_or("--read needs a path")?),
"--exec" => policy = policy.exec(it.next().ok_or("--exec needs a path")?),
"--" => {
let p = it.next().ok_or("a program follows `--`")?;
program = Some((PathBuf::from(p), it.by_ref().map(OsString::from).collect()));
}
other => return Err(format!("unknown option `{other}`")),
}
}
for path in &a.exec {
policy = policy.exec(path);
}
let program: Option<(PathBuf, Vec<OsString>)> = a.program.split_first().map(|(p, rest)| (PathBuf::from(p), rest.to_vec()));
// With a program, its standard output is passed through untouched, so this command's own
// lines go to standard error; the self-test's report is the output, on standard output.
let report = program.is_none();
let say = |io: &mut Io, line: String| -> Result<(), CliError> {
let say = |line: String| {
if report {
outln!(io, "{line}");
outln!("{line}");
} else {
errln!(io, "{line}");
eprintln!("{line}");
}
Ok(())
};
match gridcraft_sandbox::support() {
Support::Available(how) => say(io, format!("sandbox: available ({how})"))?,
Support::Available(how) => say(format!("sandbox: available ({how})")),
Support::Unsupported(why) => {
say(io, format!("sandbox: unsupported ({why})"))?;
return Ok(2);
say(format!("sandbox: unsupported ({why})"));
return Ok(ExitCode::from(2));
}
}
let canary = Canary::create().map_err(|e| CliError::Sandbox(e.to_string()))?;
let exe = std::env::current_exe().map_err(|e| CliError::Sandbox(e.to_string()))?;
let canary = Canary::create().map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let (program, program_args) = match program {
Some((p, a)) => (p, a),
// A confined copy of this program, reporting each attempt; it reads its own executable as
// the allowed file.
None => {
// The self-test re-runs this executable with REPORT_FLAG. That only works when this
// process is the gridcraft-cli binary (its `main` calls `handle_args` first). A host
// that only called `run` — a test binary, for example — would not run the probes.
if !is_gridcraft_cli_binary(&exe) {
return Err(CliError::Sandbox(
"the self-test must be run through the gridcraft-cli binary (pass a program after `--` to confine one from any host)".into(),
));
}
let home = std::env::var_os("HOME").unwrap_or_default();
(exe.clone(), vec![REPORT_FLAG.into(), canary.file().into(), exe.clone().into(), home])
}
};
let policy = policy.exec(program.clone());
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| CliError::Sandbox(e.to_string()))?;
let status = cmd.status().map_err(|e| CliError::Sandbox(format!("couldn't start the launcher: {e}")))?;
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| e.to_string())?;
let status = cmd.status().map_err(|e| format!("couldn't start the launcher: {e}"))?;
drop(canary);
match status.code() {
Some(0) => {
say(
io,
if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into(),
)?;
Ok(0)
say(if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into());
Ok(ExitCode::SUCCESS)
}
Some(REFUSED_EXIT_CODE) => {
// The launcher's refusal and a program's own exit share the code; the launcher's reason,
// when it refused, is the `gridcraft-sandbox: refused:` line above.
say(
io,
format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
),
)?;
Ok(1)
say(format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
));
Ok(ExitCode::FAILURE)
}
other => {
say(
io,
format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
),
)?;
Ok(1)
say(format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
));
Ok(ExitCode::FAILURE)
}
}
}
/// The installed CLI, including the nightly package's renamed command.
fn is_gridcraft_cli_binary(exe: &std::path::Path) -> bool {
exe.file_name()
.and_then(|n| n.to_str())
.map(|n| n.strip_suffix(".exe").unwrap_or(n))
.is_some_and(|n| n == "gridcraft-cli" || n == "gridcraft-nightly-cli")
}
-92
View File
@@ -1,92 +0,0 @@
//! One command of a script: `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
use serde_json::{Value, json};
/// A command line that cannot be read.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum ScriptError {
#[error("bad JSON: {0}")]
BadJson(String),
/// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
/// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the script still exited 0, so a
/// typo made a valid, wrong workbook (#2256).
#[error("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}")]
UnknownKeys { plural: &'static str, list: String },
#[error("JSON command needs a `command` field")]
NoCommand,
#[error("{id}: bad JSON params: {why}")]
BadParams { id: String, why: String },
}
/// A command and its parameters.
pub(crate) type Step = (String, Value);
/// The command in `text`, or `None` for a blank line, a `#` comment or a `//` comment.
pub(crate) fn parse_command(text: &str) -> Result<Option<Step>, ScriptError> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| ScriptError::BadJson(e.to_string()))?;
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let plural = if unknown.len() == 1 { "key" } else { "keys" };
return Err(ScriptError::UnknownKeys { plural, list: unknown.join("`, `") });
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or(ScriptError::NoCommand)?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() {
json!({})
} else {
serde_json::from_str(rest).map_err(|e| ScriptError::BadParams { id: id.to_string(), why: e.to_string() })?
};
Ok(Some((id.to_string(), params)))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused").to_string();
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused").to_string();
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
}
-147
View File
@@ -1,147 +0,0 @@
//! What the command line does with its arguments: RFC-0018's contract, through the binary. A usage error exits 2 on
//! stderr; help and the version go to stdout with exit 0; an unknown or repeated flag after a subcommand is refused.
use std::process::Command;
struct Ran {
code: Option<i32>,
out: String,
err: String,
}
fn run(args: &[&str]) -> Ran {
let o = Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).output().unwrap();
Ran { code: o.status.code(), out: String::from_utf8_lossy(&o.stdout).into_owned(), err: String::from_utf8_lossy(&o.stderr).into_owned() }
}
const SUBCOMMANDS: [&str; 11] = ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"];
/// A usage error: exit 2, nothing on stdout, `error:` and the offending argument on stderr.
fn usage_error(args: &[&str], names: &str) {
let r = run(args);
assert_eq!(r.code, Some(2), "{args:?}: {:?} / {:?}", r.out, r.err);
assert_eq!(r.out, "", "{args:?}");
assert!(r.err.starts_with("error:") && r.err.contains(names), "{args:?}: {:?}", r.err);
}
#[test]
fn every_subcommand_answers_help_and_version_on_stdout() {
for sub in SUBCOMMANDS {
for flag in ["--help", "-h"] {
let r = run(&[sub, flag]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} {flag}");
assert!(r.out.contains(&format!("Usage: gridcraft-cli {sub}")), "{sub} {flag}: {:?}", r.out);
assert!(r.out.contains("Exit status:"), "{sub} {flag}: {:?}", r.out);
}
let r = run(&[sub, "--version"]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} --version");
assert!(r.out.starts_with(&format!("gridcraft-cli-{sub} ")), "{sub}: {:?}", r.out);
}
let r = run(&["help", "run"]);
assert_eq!(r.code, Some(0));
}
#[test]
fn an_unknown_option_is_refused_by_name_in_every_subcommand() {
for sub in ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"] {
usage_error(&[sub, "--no-such-option"], "--no-such-option");
}
// An option of another subcommand is not this one's.
usage_error(&["commands", "--sample", "x"], "--sample");
usage_error(&["info", "a.xlsx", "--csv"], "--csv");
usage_error(&["cat", "a.xlsx", "--json"], "--json");
}
#[test]
fn a_missing_or_extra_argument_is_a_usage_error() {
usage_error(&["info"], "FILE");
usage_error(&["info", "a", "b"], "b");
usage_error(&["convert", "a.xlsx"], "OUTPUT");
usage_error(&["eval"], "FORMULA");
usage_error(&["check"], "FILE_OR_DIR");
usage_error(&["send", "7979"], "METHOD");
usage_error(&["run", "--in"], "--in");
usage_error(&["run", "--cmd"], "--cmd");
usage_error(&["commands", "a", "b"], "b");
}
#[test]
fn a_repeated_single_value_flag_is_refused() {
usage_error(&["convert", "a.xlsx", "b.csv", "--sheet", "1", "--sheet", "2"], "--sheet");
usage_error(&["run", "--in", "a.xlsx", "--in", "b.xlsx"], "--in");
usage_error(&["run", "--out", "a.xlsx", "--out", "b.xlsx"], "--out");
usage_error(&["check", "x.xlsx", "--tolerance", "1", "--tolerance", "2"], "--tolerance");
}
#[test]
fn conflicting_flags_are_refused_before_anything_starts() {
usage_error(&["run", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["mcp", "--connect", "7979", "--in", "a.xlsx"], "--connect");
usage_error(&["mcp", "--connect", "7979", "--sample", "sales"], "--connect");
usage_error(&["mcp", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["commands", "x", "--search", "y"], "--search");
// `--print` carries the options that shape it.
usage_error(&["run", "--csv"], "--print");
usage_error(&["run", "--sheet", "1"], "--print");
}
#[test]
fn a_value_that_cannot_mean_anything_is_a_usage_error() {
usage_error(&["check", "x.xlsx", "--tolerance", "-1"], "--tolerance");
usage_error(&["check", "x.xlsx", "--tolerance", "nan"], "--tolerance");
usage_error(&["check", "x.xlsx", "--max-report", "many"], "--max-report");
usage_error(&["run", "--cmd", "x={bad"], "--cmd");
usage_error(&["send", "7979", "m", "{bad"], "JSON");
}
/// `eval` takes its formula as the first thing, even one that starts with a dash; `--` ends the options.
#[test]
fn a_formula_may_start_with_a_dash() {
let r = run(&["eval", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2"), "{:?}", r.err);
let r = run(&["eval", "--json", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2.0"), "{:?}", r.err);
// A mistyped option is not a formula; `=` makes it one.
usage_error(&["eval", "--no-such-option"], "--no-such-option");
assert_eq!(run(&["eval", "=--1"]).code, Some(0));
// After `--`, a formula that starts with `--` is a positional value, not an option.
let r = run(&["eval", "--", "--1"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "1"), "{:?}", r.err);
usage_error(&["sandbox-check", "--"], "--");
}
/// A word after the options (or after `--`) is a filter; `--search` is the same filter as an option.
#[test]
fn commands_and_functions_filter_by_a_word_or_search() {
let a = run(&["commands", "--json", "home.bold"]);
let b = run(&["commands", "--json", "--search", "home.bold"]);
assert_eq!((a.code, b.code), (Some(0), Some(0)));
assert_eq!(a.out, b.out);
assert!(a.out.contains("home.bold"));
let r = run(&["functions", "--json", "--category", "Math and trigonometry", "SUM"]);
assert_eq!(r.code, Some(0), "{}", r.err);
}
/// A failed command is exit 1 with `error:`; connection failures are command failures, not usage errors.
#[test]
fn a_failed_command_exits_1_with_an_error_line() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port().to_string();
drop(listener);
for args in [&["send", &port, "x"][..], &["mcp", "--connect", &port], &["info", "/no/such/file.xlsx"], &["convert", "/no/such.xlsx", "o.csv"]] {
let r = run(args);
assert_eq!(r.code, Some(1), "{args:?}: {:?}", r.err);
assert_eq!(r.out, "");
assert!(r.err.starts_with("error:"), "{args:?}: {:?}", r.err);
}
}
/// The nightly profile protocol belongs to the desktop app: exit 2 before any subcommand parses it.
#[test]
fn the_launcher_profile_arguments_are_refused() {
for args in [&["--launch-profile", "nightly-v1", "info", "a.xlsx"][..], &["info", "--profile-root=/tmp/x", "a.xlsx"]] {
let r = run(args);
assert_eq!((r.code, r.out.as_str()), (Some(2), ""), "{args:?}");
assert!(r.err.contains("desktop app"), "{:?}", r.err);
}
}
+6 -12
View File
@@ -25,18 +25,12 @@ fn tmpdir(name: &str) -> PathBuf {
#[test]
fn version_and_usage() {
assert_eq!(ok(&["--version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
assert_eq!(ok(&["-V"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
// `--version` reaches the subcommands, and there is no `version` subcommand.
assert!(ok(&["run", "--version"]).starts_with("gridcraft-cli-run "));
for unknown in ["frobnicate", "version"] {
let o = run(&[unknown]);
assert_eq!(o.status.code(), Some(2), "{unknown}");
assert!(String::from_utf8_lossy(&o.stderr).contains("unrecognized subcommand"));
}
// No arguments: the usage on stderr, a usage error.
assert_eq!(ok(&["version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
let o = run(&["frobnicate"]);
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown subcommand"));
let o = run(&[]);
assert_eq!(o.status.code(), Some(2));
assert!(o.stdout.is_empty() && String::from_utf8_lossy(&o.stderr).contains("Usage: gridcraft-cli"));
assert!(!o.status.success());
}
#[test]
@@ -281,7 +275,7 @@ fn a_script_line_with_an_unknown_key_stops_the_run() {
assert!(!info.contains("Sheet2"), "and no sheet was added with a default name: {info}");
// The usage text says what a line looks like, which is how this was found.
let usage = ok(&["run", "--help"]);
let usage = String::from_utf8_lossy(&run(&[]).stderr).into_owned() + &String::from_utf8_lossy(&run(&["--help"]).stdout);
assert!(usage.contains(r#"{"command": "id", "params": {…}}"#), "{usage}");
let _ = std::fs::remove_dir_all(&dir);
-188
View File
@@ -1,188 +0,0 @@
//! `gridcraft_cli::run` called in-process: the same program the binary is, with its streams captured, so the whole of
//! RFC-0018's surface is covered without a subprocess per case.
fn run(args: &[&str]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = gridcraft_cli::run(args.iter().copied(), &mut out, &mut err);
(code, String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap())
}
struct Dir(std::path::PathBuf);
impl Dir {
fn new(name: &str) -> Dir {
let dir = std::env::temp_dir().join(format!("gc-inproc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Dir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_owned()
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn help_and_version_exit_0_on_stdout_and_usage_errors_exit_2_on_stderr() {
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"], &["run", "-V"], &["check", "--help"]] {
let (code, out, err) = run(args);
assert_eq!((code, err.as_str()), (0, ""), "{args:?}");
assert!(!out.is_empty(), "{args:?}");
}
for args in [&[][..], &["bogus"], &["info"], &["run", "--nope"], &["info", "--bogus"]] {
let (code, out, err) = run(args);
assert_eq!((code, out.as_str()), (2, ""), "{args:?}");
assert!(err.contains("Usage: gridcraft-cli"), "{args:?}: {err}");
}
}
#[test]
fn eval_info_cat_and_commands_write_results_to_stdout_and_progress_to_stderr() {
let dir = Dir::new("flow");
let book = dir.file("b.xlsx");
let (code, out, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("cell.set") && err.contains("wrote"), "{out} / {err}");
let (code, out, _) = run(&["eval", "=SUM(1,2,3)"]);
assert_eq!((code, out.trim()), (0, "6"));
let (code, out, err) = run(&["info", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("Sheet1"), "{out}");
let (code, out, _) = run(&["info", "--json", &book]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, out, _) = run(&["cat", &book, "--csv"]);
assert_eq!((code, out.trim()), (0, "2"));
let (code, out, _) = run(&["cat", &book, "--formulas"]);
assert_eq!((code, out.trim()), (0, "=1+1"));
let csv = dir.file("b.csv");
let (code, _, err) = run(&["convert", &book, &csv]);
assert_eq!(code, 0, "{err}");
assert_eq!(std::fs::read_to_string(&csv).unwrap().trim(), "2");
let (code, _, err) = run(&["convert", &book, &dir.file("b.nope")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:") && err.contains("unknown output format"), "{err}");
}
#[test]
fn run_keeps_cmd_and_script_in_the_order_given() {
let dir = Dir::new("order");
let script = dir.file("s.jsonl");
std::fs::write(&script, "cell.set={\"cell\":\"A1\",\"input\":\"2\"}\n").unwrap();
// The script writes A1 = 2 after the first --cmd wrote 1 and before the last wrote 3: the last one wins.
let (code, out, err) = run(&[
"run",
"--quiet",
"--cmd",
r#"cell.set={"cell":"A1","input":"1"}"#,
"--script",
&script,
"--cmd",
r#"cell.set={"cell":"B1","input":"=A1*10"}"#,
"--print",
"A1:B1",
"--csv",
]);
assert_eq!(code, 0, "{err}");
assert_eq!(out.trim(), "2,20", "{out}");
let (code, _, err) = run(&["run", "--script", &dir.file("missing.jsonl")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:"), "{err}");
let (code, _, err) = run(&["run", "--cmd", "no.such.command"]);
assert_eq!(code, 1);
assert!(err.contains("step 1 (--cmd, no.such.command)"), "{err}");
}
#[test]
fn check_reports_and_exits_with_the_verdict() {
let dir = Dir::new("check");
let book = dir.file("b.xlsx");
assert_eq!(run(&["run", "--quiet", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]).0, 0);
let (code, out, _) = run(&["check", &book]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("files: 1"), "{out}");
let (code, out, _) = run(&["check", "--json", &book, "--tolerance", "1e-6", "--max-report", "3"]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, _, _) = run(&["check", &dir.file("missing.xlsx")]);
assert_eq!(code, 1);
}
#[test]
fn sandbox_check_without_a_program_reports_on_stdout() {
// In-process `run` is not the CLI binary, so the no-program self-test is refused. The real
// verdict is asserted in `tests/it/sandbox.rs` through `CARGO_BIN_EXE_gridcraft-cli`.
let (code, out, err) = run(&["sandbox-check"]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("error:") && err.contains("gridcraft-cli binary"), "{err}");
}
/// A closed stdout (`gridcraft-cli commands | head`) ends the program quietly; any other write error is reported.
#[test]
fn a_closed_pipe_ends_quietly_and_another_write_error_is_an_error() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err).unwrap().starts_with("error:"));
}
/// `convert` and `run --out` refuse to replace the input without `--overwrite`.
#[test]
fn convert_and_run_refuse_to_replace_the_input() {
let dir = Dir::new("replace");
let book = dir.file("book.xlsx");
let (code, _, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
let before = std::fs::read(&book).unwrap();
let (code, out, err) = run(&["convert", &book, &book]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("would replace") || err.contains("--overwrite"), "{err}");
assert_eq!(std::fs::read(&book).unwrap(), before);
let (code, out, err) = run(&["run", "--in", &book, "--cmd", r#"cell.set={"cell":"A1","input":"9"}"#, "--out", &book]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("would replace") || err.contains("--overwrite"), "{err}");
assert_eq!(std::fs::read(&book).unwrap(), before);
let (code, _, err) = run(&["run", "--in", &book, "--cmd", r#"cell.set={"cell":"A1","input":"9"}"#, "--out", &book, "--overwrite"]);
assert_eq!(code, 0, "{err}");
}
/// A StorageFull write of `--help` is reported and returns 1; a usage write failure still returns 2.
#[test]
fn help_write_failures_other_than_a_closed_pipe_return_1() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["--help"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
err.clear();
assert_eq!(gridcraft_cli::run(["--help"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err.clone()).unwrap().starts_with("error:"));
err.clear();
let mut out = Vec::new();
assert_eq!(gridcraft_cli::run(["eval"], &mut out, &mut Failing(std::io::ErrorKind::StorageFull)), 2);
}
-3
View File
@@ -1,7 +1,4 @@
//! The crate's integration tests, one module per file, built as one test binary.
mod args;
mod cli;
mod in_process;
mod man_and_completions;
mod sandbox;
mod text_to_columns_quotes;
@@ -1,55 +0,0 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
gridcraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut gridcraft_cli::command(), "gridcraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
#[test]
fn man_pages_render_for_the_command_and_every_subcommand() {
let cmd = gridcraft_cli::command();
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
let mut out = Vec::new();
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
assert!(!out.is_empty(), "{}", page.get_name());
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
/// `packaging/freebsd/package.sh` install, `gridcraft-cli.1` and a page per subcommand, and no
/// pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("gc-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["gridcraft-cli.bash", "_gridcraft-cli", "gridcraft-cli.fish", "gridcraft-cli.elv", "_gridcraft-cli.ps1"];
let subcommands = ["cat", "check", "commands", "convert", "eval", "functions", "info", "mcp", "run", "sandbox-check", "send"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("gridcraft-cli.1".into());
expected.extend(subcommands.iter().map(|s| format!("gridcraft-cli-{s}.1")));
expected.sort();
assert_eq!(written, expected);
std::fs::remove_dir_all(&dir).unwrap();
}
+1
View File
@@ -231,6 +231,7 @@ fn services() -> Services {
})),
open_url: Some(Box::new(|url: &str| open_with_system(url))),
printers: Some(print::discover()),
printer_papers: Some(print::discover_papers()),
print_native: Some(print::submit()),
..Default::default()
}
+117 -3
View File
@@ -1,5 +1,5 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{Destination, Discover, DiscoverPapers, Duplex, Paper, Printer, Settings, Submit};
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
pub fn discover() -> Discover {
@@ -13,6 +13,45 @@ pub fn discover() -> Discover {
})
}
pub fn discover_papers() -> DiscoverPapers {
Box::new(|queue| {
let queue = queue.to_owned();
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-paper-discovery".into()).spawn(move || {
let _ = sender.send(papers(&queue));
});
receiver
})
}
#[cfg(windows)]
fn papers(queue: &str) -> Vec<Paper> {
craft_print::printer_papers(queue)
.into_iter()
.map(|form| Paper {
id: format!("{}x{}:{}", form.width, form.height, form.name),
name: form.name,
width: form.width,
height: form.height,
cups_media: None,
})
.collect()
}
#[cfg(unix)]
fn papers(queue: &str) -> Vec<Paper> {
craft_print::cups::media_catalog(queue)
.sizes
.into_iter()
.map(|size| Paper { id: size.key.clone(), name: size.label, width: size.width, height: size.height, cups_media: Some(size.key) })
.collect()
}
#[cfg(not(any(windows, unix)))]
fn papers(_queue: &str) -> Vec<Paper> {
Vec::new()
}
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
// let process exit kill PowerShell/CUPS before it hands the job to the spooler.
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
@@ -27,7 +66,7 @@ pub fn finish_pending_jobs() {
}
pub fn submit() -> Submit {
Box::new(|bytes, settings: Settings| {
Box::new(|bytes, settings: Settings, paper| {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
@@ -44,7 +83,8 @@ pub fn submit() -> Submit {
_ => None,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
scaling: if paper.is_some() { craft_print::Scaling::Exact } else { craft_print::Scaling::ShrinkToFit },
options: paper.and_then(|choice| choice.cups_media).into_iter().map(|key| ("media".into(), key)).collect(),
title: "GridCraft document".into(),
..Default::default()
};
@@ -79,3 +119,77 @@ mod tests {
assert!(JOBS.lock().unwrap().is_empty(), "workers were joined before shutdown returned");
}
}
#[cfg(all(test, target_os = "linux"))]
mod cups_paper_qa {
use super::*;
use std::{
os::unix::fs::FileTypeExt as _,
path::PathBuf,
thread::sleep,
time::{Duration, Instant},
};
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
#[test]
fn selected_queue_legal_paper_and_page_range_reach_the_private_cups_file() {
if std::env::var("GRIDCRAFT_PRIVATE_CUPS").as_deref() != Ok("1") {
return;
}
let socket = PathBuf::from(std::env::var_os("CUPS_SERVER").unwrap());
assert!(socket.starts_with("/run/cups") || socket.starts_with("/var/spool/cups"));
assert!(socket.ends_with("socket/cups.sock"));
assert!(socket.parent().unwrap().parent().unwrap().file_name().unwrap().to_string_lossy().starts_with("craft-print-acceptance."));
assert!(std::fs::metadata(socket).unwrap().file_type().is_socket());
let queue = "craft-print-capture";
let requested_paper = std::env::var("GRIDCRAFT_TEST_PAPER").unwrap();
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = SheetApp::new(
session,
Services { printers: Some(discover()), printer_papers: Some(discover_papers()), print_native: Some(submit()), ..Default::default() },
);
app.run("cell.set", json!({"cell":"A1","input":"Paper form first page"})).unwrap();
app.run("cell.set", json!({"cell":"A20","input":"Paper form selected page"})).unwrap();
app.run("pageLayout.pageSetup", json!({"paper":"Letter","rowBreaks":[10]})).unwrap();
app.run("ui.printSettings", json!({"refresh":true})).unwrap();
let ctx = egui::Context::default();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
app.poll_printing(&ctx);
let settings = app.run("ui.printSettings", json!({})).unwrap();
if settings["printer"] == queue && settings["papersLoading"] == false {
let papers = settings["papers"].as_array().unwrap();
let left = papers.iter().find(|paper| paper["id"] == "qa_left_8.5x14in").expect("left-feed form");
let right = papers.iter().find(|paper| paper["id"] == "qa_right_8.5x14in").expect("right-feed form");
assert_ne!(left["name"], right["name"]);
for paper in [left, right] {
assert!((paper["width"].as_f64().unwrap() - 612.0).abs() < 1.0);
assert!((paper["height"].as_f64().unwrap() - 1008.0).abs() < 1.0);
}
break;
}
assert!(Instant::now() < deadline, "Legal was not discovered on the private queue: {settings}");
sleep(Duration::from_millis(40));
}
let picked = app.run("ui.printSettings", json!({"printer":queue,"paper":requested_paper,"from":2,"to":2})).unwrap();
assert_eq!(picked["paper"], requested_paper);
app.run("ui.printSubmit", json!({})).unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
app.poll_printing(&ctx);
let settings = app.run("ui.printSettings", json!({})).unwrap();
if !app.printing.busy() {
assert_eq!(settings["status"], "submitted", "{settings}");
println!("GRIDCRAFT_RECEIPT={}", settings["detail"].as_str().unwrap());
break;
}
assert!(Instant::now() < deadline, "the print submission did not finish");
sleep(Duration::from_millis(40));
}
let preview = app.run("file.printPreview", json!({})).unwrap();
assert_eq!(preview["pageList"][0]["height"], 792.0);
}
}
+1
View File
@@ -22,6 +22,7 @@ thiserror = { workspace = true }
log = { workspace = true }
gridcraft-xlsx = { workspace = true }
craft-csv = { workspace = true }
craft-pages = { workspace = true }
craft-gridcraft-format = { workspace = true }
gridcraft-chart = { workspace = true }
gridcraft-pdf = { workspace = true }
+41 -13
View File
@@ -7,7 +7,9 @@
//! drawn into a PDF with `gridcraft-pdf`: fills, gridlines, borders, formatted text (fonts mapped
//! to the standard 14 PDF fonts), merged cells, wrapping, overflow into empty neighbours,
//! conditional formats, table styles, charts, images, shapes and sparklines. Headers and footers
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes.
//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes. A page range
//! (`from`/`to`, File › Print's Pages … to …) prints some of the job's pages, each still numbered
//! as in the whole job.
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
#[cfg(test)]
@@ -56,7 +58,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
#[cfg(test)]
use layout::bands;
pub(crate) use layout::split_bands;
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
pub use layout::{PaperOverride, PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
use layout::{seg_size, segments};
use objects::{PicCache, draw_objects};
#[cfg(test)]
@@ -69,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export as PDF",
["File", "Export"],
None,
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\" (active sheet), fitToPage?: bool, from?: page (1-based, counted over the whole job in sheet order), to?: page} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup. A page range prints only its pages, and their headers and footers keep the whole job's &P and &N; `from` after the last page is an error, `to` past it stops at the last page, and `from` greater than `to` prints the pages between them.",
has_doc,
export_pdf
),
@@ -78,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print…",
["File"],
Some("Cmd+P"),
"{path?, sheets?: active|all, range?, fitToPage?: bool} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog",
"{path?, sheets?: active|all, range?, fitToPage?: bool, paperOverride?: {name,width,height} (points), from?: page (1-based, over the whole job), to?: page} → {pages, bytes, base64} — the PDF the UI hands to the system print dialog; a page range works as in file.exportPdf",
has_doc,
print
),
@@ -87,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
["File"],
None,
"{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order",
"{page? (1-based), sheets?: active|all, range?, fitToPage?, paperOverride?: {name,width,height} (points), from?: page, to?: page} → {pages, total, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order; with a page range, pageList holds only the pages that print, under their numbers in the whole job of `total` pages",
has_doc,
print_preview
),
@@ -119,12 +121,19 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P
/// Renders laid-out sheets to a PDF.
pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result<RenderedPdf> {
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES)
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, 1..=usize::MAX)
}
/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it
/// to exercise the cap without building gigabytes of pictures).
fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result<RenderedPdf> {
fn render_pdf_with_image_budget(
wb: &Workbook,
layouts: &[SheetLayout],
file: &str,
path: &str,
image_bytes: u64,
pages: std::ops::RangeInclusive<usize>,
) -> Result<RenderedPdf> {
let mut doc = PdfDoc::new();
doc.set_image_budget(image_bytes);
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
@@ -145,6 +154,9 @@ fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &s
let (aw, ah) = lay.avail();
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
page_no += 1;
if !pages.contains(&page_no) {
continue;
}
let (Some(rband), Some(cband)) = (lay.row_bands.get(*ri).copied(), lay.col_bands.get(*ci).copied()) else { continue };
let rsegs = segments(lay.title_rows, rband);
let csegs = segments(lay.title_cols, cband);
@@ -223,8 +235,9 @@ fn build_pdf(s: &mut Session, p: &Json, cmd: &str) -> Result<(Vec<u8>, usize)> {
let opts = PrintOptions::from_params(p, cmd)?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let (first, last) = opts.page_span(lays.iter().map(|l| l.pages.len()).sum(), cmd)?;
let path = d.path.clone().unwrap_or_default();
let pdf = render_pdf(&d.wb, &lays, &d.display_title(), &path)?;
let pdf = render_pdf_with_image_budget(&d.wb, &lays, &d.display_title(), &path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES, first..=last)?;
if pdf.missing_arabic_font {
s.ui_requests.push(crate::UiRequest::Message(MISSING_ARABIC_FONT.into()));
}
@@ -252,16 +265,24 @@ fn print(s: &mut Session, p: &Json) -> Result<Json> {
Ok(out)
}
/// The pages a print would print, each with its number in the whole job: a page range lists only
/// the pages in it, under their own numbers.
fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
let opts = PrintOptions::from_params(p, "file.printPreview")?;
const CMD: &str = "file.printPreview";
let opts = PrintOptions::from_params(p, CMD)?;
let d = s.doc()?;
let lays = layouts(&d.wb, &opts);
let total: usize = lays.iter().map(|l| l.pages.len()).sum();
let (first, last) = opts.page_span(total, CMD)?;
let mut list = Vec::new();
let mut n = 0usize;
for lay in &lays {
let name = d.wb.sheet(lay.sheet).map(|s| s.name.clone()).unwrap_or_default();
for (ri, ci) in &lay.pages {
n += 1;
if !(first..=last).contains(&n) {
continue;
}
let (Some(rb), Some(cb)) = (lay.row_bands.get(*ri), lay.col_bands.get(*ci)) else { continue };
let r = RangeRef::new(CellRef::new(rb.0, cb.0), CellRef::new(rb.1, cb.1));
list.push(json!({
@@ -280,11 +301,18 @@ fn print_preview(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some(page) = u32_param(p, "page") {
let one =
list.get((page as usize).saturating_sub(1)).cloned().ok_or_else(|| bad("file.printPreview", format!("there are only {n} pages")))?;
return Ok(json!({"pages": n, "page": one}));
let page = (page as usize).max(1);
if page > total {
return Err(bad(CMD, format!("there are only {total} pages")));
}
let one = list
.iter()
.find(|pg| pg["page"].as_u64() == Some(page as u64))
.cloned()
.ok_or_else(|| bad(CMD, format!("page {page} is outside the pages to print ({first} to {last})")))?;
return Ok(json!({"pages": list.len(), "total": total, "page": one}));
}
Ok(json!({"pages": n, "pageList": list}))
Ok(json!({"pages": list.len(), "total": total, "pageList": list}))
}
fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
+62 -3
View File
@@ -75,6 +75,19 @@ pub struct PrintOptions {
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
pub ranges: Vec<RangeRef>,
pub fit_to_page: Option<bool>,
/// The page range (File › Print's Pages … to …): 1-based page numbers counted over the
/// whole job in sheet order. `None` = from the first page, to the last.
pub from: Option<usize>,
pub to: Option<usize>,
/// One physical paper size for this print job, without editing any worksheet's Page Setup.
pub paper_override: Option<PaperOverride>,
}
#[derive(Clone, Debug)]
pub struct PaperOverride {
pub name: String,
pub width: f32,
pub height: f32,
}
impl PrintOptions {
@@ -90,7 +103,48 @@ impl PrintOptions {
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
}
}
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
let paper_override = p
.get("paperOverride")
.map(|paper| {
let size = |key| paper.get(key).and_then(Json::as_f64).filter(|value| (36.0..=14_400.0).contains(value)).map(|v| v as f32);
let name = paper.get("name").and_then(Json::as_str).filter(|name| !name.trim().is_empty());
match (name, size("width"), size("height")) {
(Some(name), Some(width), Some(height)) => Ok(PaperOverride { name: name.into(), width, height }),
_ => Err(bad(cmd, "`paperOverride` needs a name and a width and height from 36 to 14400 points")),
}
})
.transpose()?;
let (from, to) = (page_param(p, "from", cmd)?, page_param(p, "to", cmd)?);
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage"), from, to, paper_override })
}
/// The first and last page that print out of a job of `total` pages (1-based, inclusive),
/// as Excel measures them: `from` after the last page is an error (nothing to print), `to`
/// past the last page stops at the last page, and `from` greater than `to` prints the pages
/// between them (3 to 2 prints pages 2 and 3).
pub(super) fn page_span(&self, total: usize, cmd: &str) -> Result<(usize, usize)> {
let span = craft_pages::range::print_page_span(total, self.from, self.to).map_err(|first| {
let pages = if total == 1 { "1 page".to_string() } else { format!("{total} pages") };
bad(cmd, format!("nothing to print: the job has {pages} and the page range starts at page {first}"))
})?;
Ok((span.start + 1, span.end))
}
}
/// A page-number param (`from`, `to`): a whole number from 1, as a number or as text. Absent,
/// `null` or empty text means no bound.
fn page_param(p: &Json, key: &str, cmd: &str) -> Result<Option<usize>> {
let n = match p.get(key) {
None | Some(Json::Null) => return Ok(None),
Some(Json::String(t)) if t.trim().is_empty() => return Ok(None),
Some(Json::String(t)) => t.trim().parse::<u64>().ok(),
// 2.0 is a whole number; 2.5, -1 and 0 are not page numbers.
Some(Json::Number(n)) => n.as_u64().or_else(|| n.as_f64().filter(|v| v.fract() == 0.0 && *v >= 1.0).map(|v| v as u64)),
Some(_) => None,
};
match n {
Some(n) if n >= 1 => Ok(Some(usize::try_from(n).unwrap_or(usize::MAX))),
_ => Err(bad(cmd, format!("`{key}` must be a page number from 1, not {}", p.get(key).map(Json::to_string).unwrap_or_default()))),
}
}
@@ -249,8 +303,13 @@ fn title_span(t: Option<(u32, u32)>, max: u32) -> Option<(u32, u32)> {
/// Paginates one sheet.
pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_override: Option<RangeRef>) -> Option<SheetLayout> {
let sh = wb.sheet(si)?;
let st = sh.print.clone();
let (mut pw, mut ph) = paper_size(&st.paper);
let mut st = sh.print.clone();
let (mut pw, mut ph) = if let Some(paper) = &opts.paper_override {
st.paper.clone_from(&paper.name);
(paper.width.min(paper.height), paper.width.max(paper.height))
} else {
paper_size(&st.paper)
};
if st.orientation == Orientation::Landscape {
std::mem::swap(&mut pw, &mut ph);
}
+212 -1
View File
@@ -1,4 +1,6 @@
use gridcraft_model::{Sparkline, SparklineKind};
use std::collections::BTreeSet;
use serde_json::json;
use super::*;
@@ -899,7 +901,7 @@ fn picture_copies_across_pages_stay_within_the_image_budget() {
// 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page.
let budget = 64 * 1024;
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap();
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget, 1..=usize::MAX).unwrap();
assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures");
let capped_draws = draws(&capped);
assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget");
@@ -1011,6 +1013,26 @@ fn page_setup_paper_sizes_reach_the_pdf_page() {
assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err());
}
#[test]
fn job_paper_override_reflows_the_preview_and_keeps_saved_orientation() {
let mut s = s();
let rows: Vec<_> = (0..60).map(|row| [row]).collect();
s.execute("range.setValues", json!({"range":"A1:A60","values":rows})).unwrap();
s.execute("pageLayout.pageSetup", json!({"paper":"A4","orientation":"landscape"})).unwrap();
let original = s.execute("file.printPreview", json!({})).unwrap();
let params = json!({"paperOverride":{"name":"Short Form","width":288.0,"height":432.0}});
let show = s.execute("file.printPreview", params.clone()).unwrap();
assert_eq!(show["pageList"][0]["paper"], "Short Form");
assert_eq!(show["pageList"][0]["width"], 432.0);
assert_eq!(show["pageList"][0]["height"], 288.0);
assert!(show["pages"].as_u64().unwrap() > original["pages"].as_u64().unwrap());
let (pdf, pages) = pdf_of(&mut s, params);
assert_eq!(pages as u64, show["pages"].as_u64().unwrap());
assert!(contains(&pdf, "/MediaBox [0 0 432 288]"));
assert_eq!(s.execute("file.printPreview", json!({})).unwrap(), original);
assert!(s.execute("file.print", json!({"paperOverride":{"name":"Bad","width":0,"height":432}})).is_err());
}
/// An empty paper name means no paper is stated; it prints on Letter.
#[test]
fn an_unstated_paper_prints_on_letter() {
@@ -1288,6 +1310,186 @@ fn checkbox_cells_print_as_boxes_not_true_false() {
assert!(contains(&pdf, "0.431 0.431 0.431 RG"), "the unchecked box is not outlined");
}
/// #3016's workbook: Sheet1 holds A1:A50 with a page break every 10 rows (5 pages), sheet Two
/// A1:A30 (3 pages), both with the footer "Page &P of &N". Each cell names its sheet, page and
/// row (`S1P2R11`).
fn paged_book() -> Session {
let mut s = s();
let labels =
|sheet: u32, rows: u32| -> Vec<Vec<Json>> { (1..=rows).map(|r| vec![json!(format!("S{sheet}P{}R{r}", (r - 1) / 10 + 1))]).collect() };
s.execute("range.setValues", json!({"range": "A1", "values": labels(1, 50)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21, 31, 41], "footer": "&CPage &P of &N"})).unwrap();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Two"})).unwrap();
s.execute("range.setValues", json!({"range": "A1", "values": labels(2, 30)})).unwrap();
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [11, 21], "footer": "&CPage &P of &N"})).unwrap();
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
s
}
/// Each page of a PDF as (the sheet and page its cells name, its footer): `("S1P2", "Page 2 of
/// 5")`. Pages are the content streams in order (one per page; the workbook has no pictures).
fn printed_pages(pdf: &[u8]) -> Vec<(String, String)> {
let text = String::from_utf8_lossy(pdf);
let chunks: Vec<&str> = text.split("endstream").collect();
let streams = chunks.get(..chunks.len().saturating_sub(1)).unwrap_or_default();
streams
.iter()
.map(|page| {
let shown: Vec<&str> = page.lines().filter_map(|l| l.strip_prefix('(')?.strip_suffix(") Tj")).collect();
let cells: BTreeSet<&str> = shown.iter().filter(|t| t.starts_with('S')).filter_map(|t| t.split_once('R').map(|(sp, _)| sp)).collect();
assert_eq!(cells.len(), 1, "a page shows the cells of one printed page: {shown:?}");
let footer = shown.iter().find(|t| t.starts_with("Page ")).copied().unwrap_or_default();
(cells.into_iter().next().unwrap_or_default().to_string(), footer.to_string())
})
.collect()
}
fn pages_of(s: &mut Session, cmd: &str, p: Json) -> Vec<(String, String)> {
let r = s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
let pdf = crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap();
let pages = printed_pages(&pdf);
assert_eq!(r["pages"].as_u64(), Some(pages.len() as u64), "{cmd} {p}: `pages` counts the printed pages");
pages
}
#[test]
fn a_page_range_prints_its_pages_under_the_whole_jobs_numbers() {
// #3016: the cases measured in Excel (ExportAsFixedFormat with From and To).
let mut s = paged_book();
let page = |sp: &str, n: u32, of: u32| (sp.to_string(), format!("Page {n} of {of}"));
let sheet1 = |pages: &[u32]| pages.iter().map(|n| page(&format!("S1P{n}"), *n, 5)).collect::<Vec<_>>();
for (params, want) in [
(json!({}), sheet1(&[1, 2, 3, 4, 5])),
(json!({"from": 2, "to": 3}), sheet1(&[2, 3])),
(json!({"from": 5, "to": 5}), sheet1(&[5])),
// `to` past the last page stops at the last page.
(json!({"from": 4, "to": 99}), sheet1(&[4, 5])),
// `from` greater than `to` prints the pages between them.
(json!({"from": 3, "to": 2}), sheet1(&[2, 3])),
// Only `from`: to the last page; only `to`: from the first.
(json!({"from": 4}), sheet1(&[4, 5])),
(json!({"to": 2}), sheet1(&[1, 2])),
// Whole numbers as text or as 3.0, and `null` or empty text for no bound.
(json!({"from": "2", "to": 3.0}), sheet1(&[2, 3])),
(json!({"from": null, "to": ""}), sheet1(&[1, 2, 3, 4, 5])),
// The whole workbook counts its pages in sheet order: Two's first page is page 6 of 8.
(json!({"sheets": "all", "from": 5, "to": 6}), vec![page("S1P5", 5, 8), page("S2P1", 6, 8)]),
(json!({"sheets": "all", "from": 6, "to": 8}), vec![page("S2P1", 6, 8), page("S2P2", 7, 8), page("S2P3", 8, 8)]),
] {
assert_eq!(pages_of(&mut s, "file.exportPdf", params.clone()), want, "file.exportPdf {params}");
// The printer gets the same pages.
assert_eq!(pages_of(&mut s, "file.print", params.clone()), want, "file.print {params}");
}
// A range that starts after the last page prints nothing: an error, not an empty PDF.
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for params in [json!({"from": 6, "to": 7}), json!({"from": 6}), json!({"from": 9, "to": 9, "sheets": "all"})] {
let e = s.execute(cmd, params.clone()).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{cmd} {params}: {e}");
}
}
// A written file holds the same pages.
let dir = std::env::temp_dir().join(format!("gridcraft-print-range-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("p.pdf");
let r = s.execute("file.exportPdf", json!({"path": path.to_str().unwrap(), "from": 2, "to": 3})).unwrap();
assert_eq!(r["pages"], 2);
assert_eq!(printed_pages(&std::fs::read(&path).unwrap()), sheet1(&[2, 3]));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn print_preview_lists_the_pages_of_a_range_under_their_numbers() {
let mut s = paged_book();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64()), (Some(2), Some(5)));
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["rows"].as_str().unwrap())).collect();
assert_eq!(listed, [(2, "11:20"), (3, "21:30")]);
let pv = s.execute("file.printPreview", json!({"sheets": "all", "from": 5, "to": 6})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["sheet"].as_str().unwrap())).collect();
assert_eq!(listed, [(5, "Sheet1"), (6, "Two")]);
assert_eq!(pv["total"], 8);
// `page` picks a page by its number in the job; one outside the range is an error.
assert_eq!(s.execute("file.printPreview", json!({"page": 3, "from": 2, "to": 3})).unwrap()["page"]["rows"], "21:30");
assert!(s.execute("file.printPreview", json!({"page": 1, "from": 2, "to": 3})).is_err());
assert!(s.execute("file.printPreview", json!({"page": 6})).is_err());
// Without a range nothing changes: every page, `pages` and `total` alike.
let pv = s.execute("file.printPreview", json!({})).unwrap();
assert_eq!((pv["pages"].as_u64(), pv["total"].as_u64(), pv["pageList"].as_array().map(Vec::len)), (Some(5), Some(5), Some(5)));
}
#[test]
fn a_page_range_counts_the_pages_in_the_sheets_page_order() {
let mut s = s();
let rows: Vec<Vec<Json>> = (0..60).map(|r| (0..15).map(|c| json!(r * 100 + c)).collect()).collect();
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap();
let pv = s.execute("file.printPreview", json!({"from": 2, "to": 3})).unwrap();
let listed: Vec<(u64, &str)> =
pv["pageList"].as_array().unwrap().iter().map(|p| (p["page"].as_u64().unwrap(), p["range"].as_str().unwrap())).collect();
// Over, then down: page 2 is the top right of the four, page 3 the bottom left.
assert_eq!(listed, [(2, "K1:O45"), (3, "A46:J60")]);
assert_eq!(pv["total"], 4);
}
#[test]
fn page_range_params_that_are_not_page_numbers_are_clear_errors() {
let mut s = paged_book();
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for bad_value in [json!(0), json!(-1), json!(2.5), json!("x"), json!("-2"), json!("1.5"), json!(true), json!([2]), json!({"page": 2})] {
for key in ["from", "to"] {
let params = json!({ key: bad_value.clone() });
let e = s.execute(cmd, params.clone()).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{cmd} {params}: {e:?}");
assert!(e.to_string().contains(&format!("`{key}` must be a page number from 1")), "{cmd} {params}: {e}");
}
}
}
}
#[test]
fn hostile_page_ranges_never_panic() {
// `every_command_survives_empty_params` for the page range: any value, alone or paired, on
// every print command gives a result or a clear error, never a caught panic.
let mut s = paged_book();
let values = [
json!(null),
json!(0),
json!(1),
json!(-1),
json!(2.5),
json!(1e300),
json!(-1e300),
json!(u64::MAX),
json!(i64::MIN),
json!(MAX_PAGES + 1),
json!(""),
json!(" 3 "),
json!("x"),
json!("99999999999999999999999999"),
json!(true),
json!([]),
json!({}),
];
for cmd in ["file.exportPdf", "file.print", "file.printPreview"] {
for from in &values {
for to in [json!(null), json!(2), json!(u64::MAX), json!("x")] {
for params in [json!({"from": from, "to": to}), json!({"to": from}), json!({"from": from, "to": to, "sheets": "all", "page": 7})] {
let r = s.execute(cmd, params.clone());
assert!(!matches!(r, Err(crate::EngineError::Internal(..))), "{cmd} {params}: {r:?}");
}
}
}
}
// Huge numbers are pages after the last one, not an overflow.
let e = s.execute("file.exportPdf", json!({"from": u64::MAX})).unwrap_err().to_string();
assert!(e.contains("nothing to print"), "{e}");
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": u64::MAX})).len(), 1);
assert_eq!(pages_of(&mut s, "file.exportPdf", json!({"from": 5, "to": 1e300})).len(), 1);
}
#[test]
fn an_equation_without_a_layout_prints_its_source_one_line_per_line() {
use super::objects::{MAX_FALLBACK_LINES, fallback_lines};
@@ -1567,6 +1769,15 @@ fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() {
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]);
// Several areas, like a multi-area selection: one run of pages each, in the order given.
assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]);
let second_area = json!({"range": "D4:E5,A1:B2", "from": 2, "to": 2});
let preview = s.execute("file.printPreview", second_area.clone()).unwrap();
assert_eq!(preview["pageList"].as_array().unwrap().len(), 1);
assert_eq!(preview["pageList"][0]["range"], "A1:B2");
assert_eq!(preview["pageList"][0]["page"], 2);
let (pdf, count) = pdf_of(&mut s, second_area);
assert_eq!(count, 1);
assert!(contains(&pdf, "/Count 1 >>"));
assert!(contains(&pdf, "(x) Tj"));
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]);
let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"}));
assert_eq!(pages, 2);
+3 -1
View File
@@ -42,6 +42,8 @@ impl SheetApp {
notice: None,
services,
printing: Default::default(),
print_pages: Default::default(),
print_paper: Default::default(),
print_feedback_seen: None,
synthetic: Default::default(),
ctrl_wheel: false,
@@ -579,7 +581,7 @@ mod lifecycle_tests {
let mut app = app();
app.printing.printers.push(crate::printing::Printer::new("Queue").is_default(true));
app.run("ui.printSettings", serde_json::json!({"printer": "Queue"})).unwrap();
app.services.print_native = Some(Box::new(|_, _| {
app.services.print_native = Some(Box::new(|_, _, _| {
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Err("printer is offline".into())).unwrap();
receiver
+14 -2
View File
@@ -223,8 +223,20 @@ impl SheetApp {
Ok(Json::Null)
}
"data.fromClipboard" => self.import_clipboard_text(p),
"ui.printSettings" => printing::settings(&mut self.printing, p, self.services.printers.as_ref()),
"ui.printSubmit" => self.submit_print(p.clone()),
"ui.printSettings" => printing::settings(
&mut self.printing,
&mut self.print_paper,
&mut self.print_pages,
p,
self.services.printers.as_ref(),
self.services.printer_papers.is_some(),
),
"ui.printSubmit" => {
// The Print view's page range applies unless the call names its own.
let mut params = p.clone();
self.print_pages.apply(&mut params);
self.submit_print(params)
}
"ui.ribbonTab" => {
self.ui.ribbon_tab = p.get("tab").and_then(Json::as_str).unwrap_or("Home").to_string();
Ok(Json::Null)
+17 -2
View File
@@ -46,16 +46,28 @@ impl SheetApp {
}
}
pub(super) fn submit_print(&mut self, params: Json) -> Result<Json, String> {
pub(super) fn submit_print(&mut self, mut params: Json) -> Result<Json, String> {
if self.services.print_native.is_some() && !self.printing.ready() {
return Err("Select an available printer in File > Print before submitting.".into());
}
let paper = self.print_paper.selected(printing::printer_name(&self.printing.settings)).cloned();
if self.services.print_native.is_some() {
// A native request may choose only a paper from the selected queue.
if let Some(fields) = params.as_object_mut() {
fields.remove("paperOverride");
}
if let Some(paper) = &paper {
paper.apply(&mut params);
}
}
let pdf = self.run("file.print", params)?;
let encoded = pdf.get("base64").and_then(Json::as_str).ok_or("The print command did not produce a PDF.")?;
let bytes = gridcraft_engine::io::base64_decode(encoded).ok_or("Couldn't decode the generated PDF.")?;
let len = bytes.len();
if let Some(submit) = &self.services.print_native {
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
self.printing
.begin(submit(bytes, self.printing.settings.clone(), paper))
.map_err(|_| "A print job is already being submitted.".to_owned())?;
self.print_feedback_seen = None;
} else if let Some(print) = &self.services.print {
print(&bytes);
@@ -70,6 +82,9 @@ impl SheetApp {
/// `tests/native_print.rs` deliberately bypass the lifecycle to test this helper alone.
pub fn poll_printing(&mut self, ctx: &egui::Context) {
self.printing.poll(ctx);
if let Some(discover) = &self.services.printer_papers {
self.print_paper.poll(printing::printer_name(&self.printing.settings), discover, ctx);
}
if self.printing.message == self.print_feedback_seen {
return;
}
+49 -17
View File
@@ -18,13 +18,14 @@ use serde_json::{Value as Json, json};
use crate::SheetApp;
use crate::i18n::{self, Language};
use crate::icons::{self, Icon};
use crate::printing::PageRange;
use crate::theme::{self, Tokens};
mod options;
mod print;
use options::{options, platform};
use print::print;
use print::{page_range_fields, print};
/// Width of the navigation column.
const NAV_W: f32 = 196.0;
@@ -99,8 +100,17 @@ impl Page {
}
/// What a print preview was built for: document, revision, scope, the selection when it is
/// the scope, and fit to page.
type PreviewKey = (u64, u64, PrintScope, String, bool);
/// the scope, fit to page, and the requested page range.
#[derive(Clone, Debug, PartialEq)]
struct PreviewKey {
document: u64,
revision: u64,
scope: PrintScope,
selection: String,
fit_to_page: bool,
pages: PageRange,
paper: Option<crate::printing::Paper>,
}
/// What File › Print › Settings prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -145,10 +155,15 @@ pub struct Backstage {
pub print_scope: PrintScope,
/// Print: fit each sheet on one page.
pub fit_to_page: bool,
/// Print: the previewed page (0-based).
/// Print: the previewed page (0-based, among the pages that print).
preview_page: usize,
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
/// Print: the preview and what it was made for.
preview: Option<(PreviewKey, Json)>,
/// Print: the Pages … to … fields as typed.
print_drafts: [String; 2],
/// Export: the page range of Create PDF, and its fields as typed.
pdf_pages: PageRange,
pdf_drafts: [String; 2],
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
pub save_format: &'static str,
/// Home and Open: when the recent workbooks were last changed.
@@ -170,6 +185,9 @@ impl Backstage {
fit_to_page: false,
preview_page: 0,
preview: None,
print_drafts: Default::default(),
pdf_pages: PageRange::default(),
pdf_drafts: Default::default(),
save_format: "xlsx",
recent: RecentFiles::default(),
}
@@ -250,7 +268,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
Page::Info => info(app, ui, &mut bs),
Page::SaveAs => save_as(app, ui, &mut bs, &mut out),
Page::Print => print(app, ui, &mut bs, &mut out),
Page::Export => export(app, ui, &mut out),
Page::Export => export(app, ui, &mut bs, &mut out),
Page::Options => options(app, ui),
Page::Account => account(app, ui),
}
@@ -728,7 +746,7 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
if after != before || asking || app.services.pick_save.is_none() {
out.close = true;
}
} else if export_as(app, fmt) {
} else if export_as(app, fmt, json!({})) {
out.close = true;
}
}
@@ -736,12 +754,23 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
dim(ui, lang.tr("A CSV file, web page or PDF is a copy: the workbook keeps its own file."));
}
fn export(app: &mut SheetApp, ui: &mut Ui, out: &mut Outcome) {
fn export(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let lang = app.ui.language;
if action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked()
&& export_as(app, "pdf")
{
out.close = true;
let create_pdf =
action_row(ui, Icon::Paper, lang.tr("Create PDF"), lang.tr("Save the sheet as a PDF document that keeps its page layout.")).clicked();
// Create PDF's page range, in line with its description; empty fields export every page.
ui.horizontal(|ui| {
ui.add_space(52.0);
if let Some(range) = page_range_fields(ui, lang, "backstage_pdf_pages", &mut bs.pdf_drafts, bs.pdf_pages) {
bs.pdf_pages = range;
}
});
if create_pdf {
let mut params = json!({});
bs.pdf_pages.apply(&mut params);
if export_as(app, "pdf", params) {
out.close = true;
}
}
ui.add_space(14.0);
section(ui, lang, "Change File Type");
@@ -749,15 +778,16 @@ fn export(app: &mut SheetApp, ui: &mut Ui, out: &mut Outcome) {
("csv", Icon::TextColumns, "CSV (Comma delimited)", "Save the active sheet as comma-separated text."),
("html", Icon::Link, "Web Page (.html)", "Save the workbook as a web page."),
] {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt) {
if action_row(ui, icon, lang.tr(title), lang.tr(detail)).clicked() && export_as(app, fmt, json!({})) {
out.close = true;
}
}
}
/// Exports the active workbook as `pdf`, `csv` or `html`: through the save picker on the desktop,
/// as a browser download on the web. Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
/// as a browser download on the web. `params` go to the export command with the path (a PDF's
/// page range). Returns whether a file was written or handed over.
pub fn export_as(app: &mut SheetApp, fmt: &str, params: Json) -> bool {
if !app.commit_edit(0, 0, false, false) {
return false;
}
@@ -767,13 +797,15 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
"html" => "file.exportHtml",
_ => return false,
};
let mut params = if params.is_object() { params } else { json!({}) };
let title = app.session.active().map(|d| d.display_title()).unwrap_or_else(|| "Book1".into());
let stem = std::path::Path::new(&title).file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
if let Some(pick) = &app.services.pick_save {
let Some(path) = pick(&format!("{stem}.{fmt}")) else { return false };
// The picker may suggest a workbook extension; the export writes the chosen format.
let path = std::path::Path::new(&path).with_extension(fmt).to_string_lossy().into_owned();
return match app.run(id, json!({"path": path})) {
params["path"] = json!(path);
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
@@ -787,7 +819,7 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
}
if fmt == "pdf" {
// Without a path the PDF comes back as bytes, which `SheetApp::run` hands to the browser.
return match app.run(id, json!({})) {
return match app.run(id, params) {
Ok(_) => true,
Err(e) => {
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
+59 -10
View File
@@ -1,9 +1,9 @@
use super::{
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
vec2,
Align2, Backstage, Icon, Json, Language, Outcome, PageRange, PreviewKey, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim,
json, pos2, square_button, theme, vec2,
};
/// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
/// Builds the print scope, page range and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) {
let t = Tokens::get(ui.ctx());
let lang = app.ui.language;
@@ -23,19 +23,37 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if bs.fit_to_page {
params["fitToPage"] = json!(true);
}
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
app.print_pages.apply(&mut params);
let queue = crate::printing::printer_name(&app.printing.settings);
let paper = app.print_paper.selected(queue).cloned();
if let Some(paper) = &paper {
paper.apply(&mut params);
}
let key = PreviewKey { document: uid, revision, scope: bs.print_scope, selection, fit_to_page: bs.fit_to_page, pages: app.print_pages, paper };
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
if bs.preview.as_ref().is_some_and(|(k, _)| k.pages != key.pages || k.paper != key.paper) {
bs.preview_page = 0;
}
// A range that starts after the last page is an error: nothing to print.
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
bs.preview = Some((key, preview));
}
let pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
let preview = bs.preview.as_ref().map(|(_, p)| p);
let pages: Vec<Json> = preview.and_then(|p| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
// The whole job's page count: a page range previews only its pages, under their numbers in the job.
let total = preview.and_then(|p| p.get("total")).and_then(Json::as_u64).unwrap_or(pages.len() as u64);
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
if let Some(discover) = &app.services.printers {
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
}
let can_print = app.services.print_native.is_none() || app.printing.ready();
if let Some(discover) = &app.services.printer_papers {
let queue = crate::printing::printer_name(&app.printing.settings);
app.print_paper.poll(queue, discover, ui.ctx());
app.print_paper.show(ui, queue, lang, !app.printing.busy());
}
let can_print = (app.services.print_native.is_none() || app.printing.ready()) && !pages.is_empty();
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
&& app.commit_edit(0, 0, false, false)
{
@@ -57,6 +75,16 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
.response
.accessible_name(lang.tr("Print What"));
ui.add_space(8.0);
// Pages … to …, counted over what the scope prints; empty fields print every page.
ui.horizontal(|ui| {
if let Some(range) = page_range_fields(ui, lang, "backstage_print_pages", &mut bs.print_drafts, app.print_pages) {
// Set through `ui.printSettings`, as a control client sets them. It refuses changes
// only while a job is being handed to the printer; a field left then shows the kept range.
let _ = app.run("ui.printSettings", json!({"from": range.from, "to": range.to}));
ui.ctx().request_repaint();
}
});
ui.add_space(8.0);
if ui.checkbox(&mut bs.fit_to_page, lang.tr("Fit Sheet on One Page")).changed() {
bs.preview_page = 0;
}
@@ -95,10 +123,9 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
if ui.add_enabled(bs.preview_page > 0, egui::Button::new("◀")).on_hover_text(lang.tr("Previous page")).clicked() {
bs.preview_page = bs.preview_page.saturating_sub(1);
}
let text = lang
.tr("Page {page} of {pages}")
.replace("{page}", &(bs.preview_page + 1).to_string())
.replace("{pages}", &pages.len().to_string());
// The page's own number in the job, as its header and footer print it.
let number = page.get("page").and_then(Json::as_u64).unwrap_or(bs.preview_page as u64 + 1);
let text = lang.tr("Page {page} of {pages}").replace("{page}", &number.to_string()).replace("{pages}", &total.to_string());
ui.label(text);
if ui.add_enabled(bs.preview_page < last, egui::Button::new("▶")).on_hover_text(lang.tr("Next page")).clicked() {
bs.preview_page = (bs.preview_page + 1).min(last);
@@ -108,6 +135,28 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
});
}
/// Pages [from] to [to]: a page range as two small number fields, in a horizontal layout. Empty
/// fields mean the first and the last page. `drafts` hold the text as typed (a field that isn't
/// being edited shows `range`); returns the new range when a field changed it.
pub(super) fn page_range_fields(ui: &mut Ui, lang: Language, id: &str, drafts: &mut [String; 2], range: PageRange) -> Option<PageRange> {
let mut next = range;
for (i, (label, bound)) in [("Pages", &mut next.from), ("Print pages|to", &mut next.to)].into_iter().enumerate() {
let Some(draft) = drafts.get_mut(i) else { continue };
let label = ui.label(lang.tr(label));
let field = ui.make_persistent_id((id, i));
if !ui.ctx().memory(|m| m.has_focus(field)) {
*draft = bound.map(|page| page.to_string()).unwrap_or_default();
}
let edit = egui::TextEdit::singleline(draft).id(field).desired_width(44.0).char_limit(5);
if ui.add(edit).labelled_by(label.id).changed() {
draft.retain(|c| c.is_ascii_digit());
// 0 is no page: like an empty field, it prints from the first or to the last page.
*bound = draft.parse::<u32>().ok().filter(|page| *page >= 1);
}
}
(next != range).then_some(next)
}
/// Most rows and columns one preview page draws (a page holds far fewer at any readable scale).
const PREVIEW_ROWS: u32 = 200;
+6 -2
View File
@@ -110,8 +110,12 @@ fn run(app: &mut SheetApp, id: &str, params: Json) -> Result<Json, String> {
/// window afterwards unless the command itself switched windows.
fn run_in(app: &mut SheetApp, target: gridcraft_engine::Target, id: &str, params: Json) -> Result<Json, String> {
let guard = app.session.enter_target(target).map_err(|e| e.to_string())?;
// A UI command reads and changes the target window's interface state (its page range…),
// and the active window's is back once the command is done.
app.follow_active_window();
let r = run(app, id, params);
app.session.leave_target(guard);
app.follow_active_window();
r
}
@@ -294,12 +298,12 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
(
"ui.printSettings",
"Print Settings",
"{printer?: discovered name, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, refresh?: bool} → {printer,copies,duplex,grayscale,printers,ready,busy,discovering,status,detail}; {} inspects without submitting",
"{printer?: discovered name, paper?: discovered paper id|null for workbook paper, copies?: 1..999, duplex?: printerDefault|off|longEdge|shortEdge|null, grayscale?: bool, from?: page (1-based)|null, to?: page|null, refresh?: bool} → {printer,paper,papers,papersLoading,copies,duplex,grayscale,from,to,printers,ready,busy,discovering,status,detail}; from/to are the Print view's page range (null clears a bound); {} inspects without submitting",
),
(
"ui.printSubmit",
"Submit Print Job",
"existing file.print sheet/pagination params → {printing,bytes,pending}; submits without opening a dialog",
"existing file.print sheet/pagination params; without from/to, the page range of ui.printSettings → {printing,bytes,pending}; submits without opening a dialog",
),
("app.language.set", "Interface Language", language_params.as_str()),
("app.language.english", "Interface Language: English", ""),
+2
View File
@@ -339,6 +339,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Vytisknout celý sešit",
"Print Selection" => "Vytisknout výběr",
"Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku",
"Pages" => "Stránky",
"Print pages|to" => "až",
"Page Setup…" => "Vzhled stránky…",
"Page {page} of {pages}" => "Stránka {page} z {pages}",
"Nothing to print." => "Není co tisknout.",
+2
View File
@@ -358,6 +358,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Gesamte Arbeitsmappe drucken",
"Print Selection" => "Auswahl drucken",
"Fit Sheet on One Page" => "Blatt auf einer Seite darstellen",
"Pages" => "Seiten",
"Print pages|to" => "bis",
"Page Setup…" => "Seite einrichten…",
"Page {page} of {pages}" => "Seite {page} von {pages}",
"Nothing to print." => "Nichts zu drucken.",
+2
View File
@@ -317,6 +317,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας",
"Print Selection" => "Εκτύπωση επιλογής",
"Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα",
"Pages" => "Σελίδες",
"Print pages|to" => "έως",
"Page Setup…" => "Διαμόρφωση σελίδας…",
"Page {page} of {pages}" => "Σελίδα {page} από {pages}",
"Nothing to print." => "Δεν υπάρχει περιεχόμενο για εκτύπωση.",
+2
View File
@@ -345,6 +345,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir todo el libro",
"Print Selection" => "Imprimir selección",
"Fit Sheet on One Page" => "Ajustar hoja en una página",
"Pages" => "Páginas",
"Print pages|to" => "a",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "No hay nada que imprimir.",
+2
View File
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimer tout le classeur",
"Print Selection" => "Imprimer la sélection",
"Fit Sheet on One Page" => "Ajuster la feuille sur une page",
"Pages" => "Pages",
"Print pages|to" => "à",
"Page Setup…" => "Mise en page…",
"Page {page} of {pages}" => "Page {page} sur {pages}",
"Nothing to print." => "Rien à imprimer.",
+2
View File
@@ -419,6 +419,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Stampa intera cartella di lavoro",
"Print Selection" => "Stampa selezione",
"Fit Sheet on One Page" => "Adatta foglio a una pagina",
"Pages" => "Pagine",
"Print pages|to" => "a",
"Page Setup…" => "Imposta pagina…",
"Page {page} of {pages}" => "Pagina {page} di {pages}",
"Nothing to print." => "Niente da stampare.",
+2
View File
@@ -422,6 +422,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Print Entire Workbook", "ブック全体を印刷"),
("Print Selection", "選択した部分を印刷"),
("Fit Sheet on One Page", "シートを 1 ページに印刷"),
("Pages", "ページ指定"),
("Print pages|to", "~"),
("Page Setup…", "ページ設定…"),
("Page {page} of {pages}", "{page} / {pages} ページ"),
("Nothing to print.", "印刷する内容がありません。"),
+2
View File
@@ -434,6 +434,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "전체 통합 문서 인쇄",
"Print Selection" => "선택 영역 인쇄",
"Fit Sheet on One Page" => "한 페이지에 시트 맞추기",
"Pages" => "페이지",
"Print pages|to" => "~",
"Page Setup…" => "페이지 설정…",
"Page {page} of {pages}" => "{page}/{pages} 페이지",
"Nothing to print." => "인쇄할 내용이 없습니다.",
+2
View File
@@ -421,6 +421,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Hele werkmap afdrukken",
"Print Selection" => "Selectie afdrukken",
"Fit Sheet on One Page" => "Blad op één pagina passen",
"Pages" => "Pagina's",
"Print pages|to" => "tot",
"Page Setup…" => "Pagina-instelling…",
"Page {page} of {pages}" => "Pagina {page} van {pages}",
"Nothing to print." => "Niets om af te drukken.",
+2
View File
@@ -411,6 +411,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Drukuj cały skoroszyt",
"Print Selection" => "Drukuj zaznaczenie",
"Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony",
"Pages" => "Strony",
"Print pages|to" => "do",
"Page Setup…" => "Ustawienia strony…",
"Page {page} of {pages}" => "Strona {page} z {pages}",
"Nothing to print." => "Nie ma nic do wydrukowania.",
+2
View File
@@ -428,6 +428,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimir toda a pasta de trabalho",
"Print Selection" => "Imprimir seleção",
"Fit Sheet on One Page" => "Ajustar planilha em uma página",
"Pages" => "Páginas",
"Print pages|to" => "até",
"Page Setup…" => "Configurar página…",
"Page {page} of {pages}" => "Página {page} de {pages}",
"Nothing to print." => "Nada para imprimir.",
+2
View File
@@ -418,6 +418,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Imprimare tot registrul",
"Print Selection" => "Imprimare selecție",
"Fit Sheet on One Page" => "Încadrare foaie pe o pagină",
"Pages" => "Pagini",
"Print pages|to" => "la",
"Page Setup…" => "Configurare pagină…",
"Page {page} of {pages}" => "Pagina {page} din {pages}",
"Nothing to print." => "Nimic de imprimat.",
+2
View File
@@ -433,6 +433,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Напечатать всю книгу",
"Print Selection" => "Напечатать выделенный диапазон",
"Fit Sheet on One Page" => "Вписать лист на одну страницу",
"Pages" => "Страницы",
"Print pages|to" => "по",
"Page Setup…" => "Параметры страницы…",
"Page {page} of {pages}" => "Страница {page} из {pages}",
"Nothing to print." => "Нечего печатать.",
+2
View File
@@ -427,6 +427,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Štampaj celu radnu svesku",
"Print Selection" => "Štampaj izbor",
"Fit Sheet on One Page" => "Uklopi list na jednu stranicu",
"Pages" => "Stranice",
"Print pages|to" => "do",
"Page Setup…" => "Podešavanje stranice…",
"Page {page} of {pages}" => "Stranica {page} od {pages}",
"Nothing to print." => "Nema ničega za štampu.",
+2
View File
@@ -332,6 +332,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır",
"Print Selection" => "Seçimi Yazdır",
"Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır",
"Pages" => "Sayfalar",
"Print pages|to" => "-",
"Page Setup…" => "Sayfa Yapısı…",
"Page {page} of {pages}" => "Sayfa {page} / {pages}",
"Nothing to print." => "Yazdırılacak bir şey yok.",
+2
View File
@@ -416,6 +416,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "Надрукувати всю книгу",
"Print Selection" => "Надрукувати виділений діапазон",
"Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку",
"Pages" => "Сторінки",
"Print pages|to" => "по",
"Page Setup…" => "Параметри сторінки…",
"Page {page} of {pages}" => "Сторінка {page} з {pages}",
"Nothing to print." => "Немає що друкувати.",
+2
View File
@@ -421,6 +421,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "In toàn bộ sổ làm việc",
"Print Selection" => "In vùng chọn",
"Fit Sheet on One Page" => "Vừa trang tính trên một trang in",
"Pages" => "Trang",
"Print pages|to" => "đến",
"Page Setup…" => "Thiết lập trang…",
"Page {page} of {pages}" => "Trang {page} trên {pages}",
"Nothing to print." => "Không có nội dung để in.",
+2
View File
@@ -426,6 +426,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Print Entire Workbook" => "打印整个工作簿",
"Print Selection" => "打印选定区域",
"Fit Sheet on One Page" => "将工作表调整为一页",
"Pages" => "页数",
"Print pages|to" => "至",
"Page Setup…" => "页面设置…",
"Page {page} of {pages}" => "第 {page} 页,共 {pages} 页",
"Nothing to print." => "没有可打印的内容。",
+4
View File
@@ -261,6 +261,10 @@ pub struct SheetApp {
pub notice: Option<Notice>,
pub services: Services,
pub printing: printing::State,
/// File › Print's page range (Pages … to …), set there or by `ui.printSettings`. Each window
/// has its own, parked with its other interface state while another window is active.
pub print_pages: printing::PageRange,
print_paper: printing::PaperSelection,
print_feedback_seen: Option<printing::Feedback>,
/// Synthetic input from agents, one batch per step (drags need several steps).
pub synthetic: std::collections::VecDeque<Vec<egui::Event>>,
+80 -6
View File
@@ -1,6 +1,12 @@
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
//! localized feedback. The panel's own words come from the framework host.
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State};
mod paper;
pub(crate) use paper::PaperSelection;
pub use paper::{DiscoverPapers, Paper};
pub type Submit = Box<dyn Fn(Vec<u8>, Settings, Option<Paper>) -> std::sync::mpsc::Receiver<Result<String, String>>>;
/// Draws the shared print controls and the feedback of the last discovery or job.
///
@@ -15,20 +21,52 @@ pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate
}
/// The printer queue the settings name; empty for none.
fn printer_name(settings: &Settings) -> &str {
pub(crate) fn printer_name(settings: &Settings) -> &str {
match &settings.destination {
Destination::Printer(name) => name,
_ => "",
}
}
/// File › Print's page range (Pages … to …): 1-based page numbers counted over the whole print
/// job. `None` prints from the first page or to the last.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageRange {
pub from: Option<u32>,
pub to: Option<u32>,
}
impl PageRange {
/// Adds the range to print-command params as `from` and `to`, unless they name a range of
/// their own (either bound, `null` included).
pub fn apply(&self, params: &mut serde_json::Value) {
let Some(map) = params.as_object_mut() else { return };
if map.contains_key("from") || map.contains_key("to") {
return;
}
for (key, page) in [("from", self.from), ("to", self.to)] {
if let Some(page) = page {
map.insert(key.into(), page.into());
}
}
}
}
/// Read print settings/status, or validate an explicit update before changing anything.
/// `refresh: true` starts discovery only; this command never submits a job or opens a dialog.
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
/// `from` and `to` set the Print view's page range (`null` clears a bound).
pub(crate) fn settings(
state: &mut State,
paper: &mut PaperSelection,
pages: &mut PageRange,
params: &serde_json::Value,
discover: Option<&Discover>,
has_catalog: bool,
) -> Result<serde_json::Value, String> {
use serde_json::{Value, json};
let object = params.as_object().ok_or("print settings must be an object")?;
if object.keys().any(|key| !["printer", "copies", "duplex", "grayscale", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, copies, duplex, grayscale or refresh".into());
if object.keys().any(|key| !["printer", "paper", "copies", "duplex", "grayscale", "from", "to", "refresh"].contains(&key.as_str())) {
return Err("unknown print setting; use printer, paper, copies, duplex, grayscale, from, to or refresh".into());
}
if state.busy() && !object.is_empty() {
return Err("wait for the active print submission before changing settings".into());
@@ -58,6 +96,33 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
if let Some(value) = object.get("grayscale") {
next.grayscale = value.as_bool().ok_or("grayscale must be a boolean")?;
}
let mut range = *pages;
for (key, bound) in [("from", &mut range.from), ("to", &mut range.to)] {
if let Some(value) = object.get(key) {
*bound = match value {
Value::Null => None,
_ => Some(
value
.as_u64()
.and_then(|page| u32::try_from(page).ok())
.filter(|page| *page >= 1)
.ok_or_else(|| format!("{key} must be a page number from 1, or null for no limit"))?,
),
};
}
}
let queue = printer_name(&next);
let requested_paper = match object.get("paper") {
None => None,
Some(Value::Null) => Some(None),
Some(value) => {
let id = value.as_str().ok_or("paper must be an id from the selected printer or null for workbook paper")?;
if !paper.offered(queue).iter().any(|size| size.id == id) {
return Err("paper must be an id from the selected printer's available papers".into());
}
Some(Some(id.to_owned()))
}
};
let refresh = object.get("refresh").map(|value| value.as_bool().ok_or("refresh must be a boolean")).transpose()?.unwrap_or(false);
if refresh {
let discover = discover.ok_or("native printer discovery is unavailable here")?;
@@ -65,7 +130,13 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
return Err("printer discovery or submission is already active".into());
}
}
paper.set_queue(queue);
if let Some(requested) = requested_paper {
paper.selected = requested;
}
state.settings = next;
*pages = range;
let queue = printer_name(&state.settings);
let (status, detail) = match state.message.as_ref() {
None => ("idle", ""),
Some(Feedback::FindingPrinters) => ("findingPrinters", ""),
@@ -80,7 +151,10 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
Ok(json!({
"printer": printer_name(&state.settings), "copies": state.settings.copies,
"duplex": match state.settings.duplex { Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", _ => "printerDefault" },
"grayscale": state.settings.grayscale,
"grayscale": state.settings.grayscale, "from": pages.from, "to": pages.to,
"paper": paper.selected(queue).map(|size| size.id.as_str()),
"papers": paper.offered(queue).iter().map(|size| json!({"id":size.id,"name":size.name,"width":size.width,"height":size.height})).collect::<Vec<_>>(),
"papersLoading": has_catalog && paper.loading(queue),
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
"busy": state.busy(), "discovering": state.discovering(), "ready": state.ready(), "status": status, "detail": detail,
}))
+115
View File
@@ -0,0 +1,115 @@
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::Duration;
use serde_json::{Value, json};
/// A paper offered by a system printer. Dimensions are in points.
#[derive(Clone, Debug, PartialEq)]
pub struct Paper {
pub id: String,
pub name: String,
pub width: f64,
pub height: f64,
/// The exact CUPS choice, where the spooler takes one independently of the PDF geometry.
pub cups_media: Option<String>,
}
impl Paper {
pub(crate) fn apply(&self, params: &mut Value) {
if !params.is_object() {
*params = json!({});
}
if let Some(fields) = params.as_object_mut() {
fields.insert("paperOverride".into(), json!({"name":self.name,"width":self.width,"height":self.height}));
}
}
fn usable(&self) -> bool {
!self.name.trim().is_empty() && [self.width, self.height].iter().all(|side| (36.0..=14_400.0).contains(side))
}
}
pub type DiscoverPapers = Box<dyn Fn(&str) -> Receiver<Vec<Paper>>>;
/// Paper choices belong to the selected queue and window, never the workbook.
#[derive(Default)]
pub(crate) struct PaperSelection {
queue: String,
offered: Option<Vec<Paper>>,
pub(super) selected: Option<String>,
pending: Vec<(String, Receiver<Vec<Paper>>)>,
}
impl PaperSelection {
pub(super) fn set_queue(&mut self, queue: &str) {
if self.queue != queue {
self.queue = queue.into();
self.offered = None;
self.selected = None;
}
}
pub(crate) fn poll(&mut self, queue: &str, discover: &DiscoverPapers, ctx: &egui::Context) {
self.set_queue(queue);
self.pending.retain(|(requested, answer)| {
match answer.try_recv() {
Err(TryRecvError::Empty) => return true,
Ok(mut papers) if *requested == self.queue => {
papers.retain(Paper::usable);
self.offered = Some(papers);
}
Err(TryRecvError::Disconnected) if *requested == self.queue => self.offered = Some(Vec::new()),
_ => {}
}
false
});
if !queue.is_empty() && self.offered.is_none() && self.pending.len() < 2 && !self.pending.iter().any(|(requested, _)| requested == queue) {
self.pending.push((queue.into(), discover(queue)));
}
if !self.pending.is_empty() {
ctx.request_repaint_after(Duration::from_millis(100));
}
}
pub(super) fn offered(&self, queue: &str) -> &[Paper] {
if self.queue == queue { self.offered.as_deref().unwrap_or_default() } else { &[] }
}
pub(super) fn loading(&self, queue: &str) -> bool {
!queue.is_empty() && (self.queue != queue || self.offered.is_none())
}
pub(crate) fn selected(&self, queue: &str) -> Option<&Paper> {
self.offered(queue).iter().find(|paper| self.selected.as_deref() == Some(paper.id.as_str()))
}
pub(crate) fn show(&mut self, ui: &mut egui::Ui, queue: &str, language: crate::i18n::Language, enabled: bool) {
use egui::accesskit::Role;
let papers = self.offered(queue);
let default = language.tr("Use workbook paper");
let label = language.tr("Paper");
let value = self.selected(queue).map_or(default, |paper| paper.name.as_str());
let mut selected = self.selected.clone();
ui.horizontal(|ui| {
ui.label(label);
ui.add_enabled_ui(enabled && !papers.is_empty(), |ui| {
let response = egui::ComboBox::from_id_salt("gridcraft_queue_paper")
.width(200.0)
.selected_text(value)
.show_ui(ui, |ui| {
ui.selectable_value(&mut selected, None, default);
for paper in papers {
ui.selectable_value(&mut selected, Some(paper.id.clone()), &paper.name);
}
})
.response;
ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label));
});
});
self.selected = selected;
if self.loading(queue) {
let response = ui.label(language.tr("Looking for printer paper sizes…"));
response.ctx.accesskit_node_builder(response.id, |node| node.set_role(Role::Status));
}
}
}
+2
View File
@@ -11,6 +11,8 @@ type PrintPdf = Box<dyn Fn(&[u8])>;
pub struct Services {
/// Desktop: discover configured printers on a worker.
pub printers: Option<printing::Discover>,
/// Desktop: discover the selected queue's physical paper dimensions on a worker.
pub printer_papers: Option<printing::DiscoverPapers>,
/// Desktop: submit the PDF with the chosen settings on a worker.
pub print_native: Option<printing::Submit>,
pub pick_open: Option<Box<dyn Fn() -> Option<String>>>,
+8 -1
View File
@@ -8,7 +8,7 @@
use gridcraft_engine::core::CellRef;
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, text_box};
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, printing, text_box};
/// One window's parked interface state (see the module docs).
#[derive(Default)]
@@ -17,6 +17,9 @@ pub struct WindowUi {
text_box_editor: Option<text_box::EditState>,
dialog: Option<dialogs::Dialog>,
backstage: Option<backstage::Backstage>,
/// File › Print's page range: each window prints its own workbook's pages.
print_pages: printing::PageRange,
print_paper: printing::PaperSelection,
message: Option<(String, String)>,
toast: Option<(String, f64)>,
notice: Option<Notice>,
@@ -61,6 +64,8 @@ impl SheetApp {
text_box_editor,
dialog,
backstage,
print_pages,
print_paper,
message,
toast,
notice,
@@ -78,6 +83,8 @@ impl SheetApp {
std::mem::swap(&mut self.text_box_editor, text_box_editor);
std::mem::swap(&mut self.dialog, dialog);
std::mem::swap(&mut self.backstage, backstage);
std::mem::swap(&mut self.print_pages, print_pages);
std::mem::swap(&mut self.print_paper, print_paper);
std::mem::swap(&mut self.message, message);
std::mem::swap(&mut self.toast, toast);
std::mem::swap(&mut self.notice, notice);
+305 -4
View File
@@ -1,6 +1,6 @@
//! Native print onboarding preserves engine PDF generation and submits the selected settings.
use gridcraft_engine::Session;
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Printer};
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Paper, Printer};
use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
use std::{cell::RefCell, rc::Rc};
@@ -14,7 +14,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
app.run("cell.set", json!({"cell":"A1", "input":"A sheet to print"})).unwrap();
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, settings| {
app.services.print_native = Some(Box::new(move |bytes, settings, _| {
observed.borrow_mut().push((bytes, settings));
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Err("printer is offline".into())).unwrap();
@@ -56,7 +56,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
sender.send(vec![Printer::new("Test queue").is_default(true)]).unwrap();
receiver
}));
app.services.print_native = Some(Box::new(|_, _| {
app.services.print_native = Some(Box::new(|_, _, _| {
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
@@ -97,6 +97,15 @@ fn invalid_print_settings_are_rejected_without_partial_changes() {
json!({"grayscale":"yes"}),
json!({"refresh":"yes"}),
json!({"copies":3,"duplex":"invalid"}),
json!({"from":0}),
json!({"from":-1}),
json!({"from":2.5}),
json!({"from":"2"}),
json!({"to":"x"}),
json!({"to":true}),
json!({"to":u64::MAX}),
json!({"from":2,"to":0}),
json!({"pages":2}),
json!([]),
] {
assert!(app.run("ui.printSettings", params.clone()).is_err(), "{params}");
@@ -112,7 +121,7 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
let mut app = SheetApp::new(session, Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
app.run("ui.printSettings", json!({"printer":"Queue"})).unwrap();
app.services.print_native = Some(Box::new(|_, _| {
app.services.print_native = Some(Box::new(|_, _, _| {
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("same receipt".into())).unwrap();
receiver
@@ -129,3 +138,295 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
assert!(app.toast.is_none());
}
}
/// A workbook of 5 pages (A1:A50, a page break every 10 rows) whose footer numbers its pages.
fn five_pages() -> Session {
let mut session = Session::new();
session.new_workbook();
let rows: Vec<Vec<serde_json::Value>> = (1..=50).map(|r| vec![json!(format!("R{r}"))]).collect();
session.run("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
session.run("pageLayout.pageSetup", json!({"rowBreaks": [11, 21, 31, 41], "footer": "&CPage &P of &N"})).unwrap();
session
}
/// Replaces the text of the field labelled `label` with `text` (empty clears it), as typed.
fn type_into(h: &mut egui_kittest::Harness<'_, SheetApp>, label: &str, text: &str) {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let rect = h.get_by_role_and_label(Role::TextInput, label).rect();
h.input_mut().events.push(egui::Event::PointerMoved(rect.center()));
h.run_steps(1);
h.get_by_role_and_label(Role::TextInput, label).click();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
if text.is_empty() {
h.key_press(egui::Key::Backspace);
} else {
h.input_mut().events.push(egui::Event::Text(text.into()));
}
h.run_steps(3);
}
/// The footers a PDF prints, in page order.
fn footers(pdf: &[u8]) -> Vec<String> {
String::from_utf8_lossy(pdf).lines().filter_map(|l| l.strip_prefix("(Page ")?.strip_suffix(") Tj")).map(|f| format!("Page {f}")).collect()
}
#[test]
/// `ui.printSettings` holds the Print view's page range: `from` and `to` are set, read back and
/// cleared with `null`, and `ui.printSubmit` prints that range unless the call names its own.
fn print_settings_hold_the_page_range_that_print_submit_prints() {
let mut app = SheetApp::new(five_pages(), Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, _, _| {
observed.borrow_mut().push(bytes);
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
}));
let unknown = app.run("ui.printSettings", json!({"pages": 2})).unwrap_err();
assert!(unknown.contains("from, to"), "the error lists the settings it takes: {unknown}");
let set = app.run("ui.printSettings", json!({"printer": "Queue", "from": 2, "to": 3})).unwrap();
assert_eq!((&set["from"], &set["to"]), (&json!(2), &json!(3)));
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["from"], 2, "the range stays until changed");
let submit = |app: &mut SheetApp, params: serde_json::Value| {
app.run("ui.printSubmit", params).unwrap();
app.printing.poll(&egui::Context::default());
app.poll_printing(&egui::Context::default());
footers(&jobs.borrow_mut().pop().unwrap())
};
assert_eq!(submit(&mut app, json!({})), ["Page 2 of 5", "Page 3 of 5"]);
// A call that names a range prints it instead: `from` alone runs to the last page.
assert_eq!(submit(&mut app, json!({"from": 4})), ["Page 4 of 5", "Page 5 of 5"]);
assert_eq!(submit(&mut app, json!({"from": null})).len(), 5, "an explicit null prints every page");
// `null` clears one bound, then the other.
let set = app.run("ui.printSettings", json!({"to": null})).unwrap();
assert_eq!((&set["from"], &set["to"]), (&json!(2), &json!(null)));
assert_eq!(submit(&mut app, json!({})), ["Page 2 of 5", "Page 3 of 5", "Page 4 of 5", "Page 5 of 5"]);
app.run("ui.printSettings", json!({"from": null})).unwrap();
assert_eq!(app.print_pages, gridcraft_ui_egui::printing::PageRange::default());
assert_eq!(submit(&mut app, json!({})).len(), 5);
// A range after the last page is refused when printing, with nothing sent to the printer.
app.run("ui.printSettings", json!({"from": 6})).unwrap();
let e = app.run("ui.printSubmit", json!({})).unwrap_err();
assert!(e.contains("nothing to print"), "{e}");
assert!(jobs.borrow().is_empty());
}
#[test]
/// Each window keeps its own page range: a range set in one window's Print view doesn't print
/// from another window, and comes back when its window is active again.
fn each_window_keeps_its_own_page_range() {
use gridcraft_ui_egui::printing::PageRange;
let mut app = SheetApp::new(five_pages(), Services::default());
// The first frame makes the window's interface state its own.
app.follow_active_window();
let first = app.session.active_window().unwrap();
app.run("ui.printSettings", json!({"from": 4})).unwrap();
app.run("view.newWindow", json!({})).unwrap();
let second = app.session.active_window().unwrap();
assert_ne!(first, second);
assert_eq!(app.print_pages, PageRange::default(), "a new window prints every page");
app.run("ui.printSettings", json!({"from": 2, "to": 3})).unwrap();
app.run("window.activate", json!({"window": first})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(4), to: None });
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["from"], 4);
app.run("window.activate", json!({"window": second})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(2), to: Some(3) });
}
#[test]
/// `ui.printSettings` and `ui.printSubmit` sent to another window through the control channel
/// read, change and print that window's page range, and leave the active window's alone.
fn print_calls_for_another_window_use_its_page_range() {
use gridcraft_ui_egui::control::{Outcome, handle};
use gridcraft_ui_egui::printing::PageRange;
let mut app = SheetApp::new(five_pages(), Services::default());
app.printing.printers.push(Printer::new("Queue").is_default(true));
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, _, _| {
observed.borrow_mut().push(bytes);
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
}));
app.follow_active_window();
let first = app.session.active_window().unwrap();
app.run("ui.printSettings", json!({"printer": "Queue", "from": 4})).unwrap();
app.run("view.newWindow", json!({})).unwrap();
let second = app.session.active_window().unwrap();
let ctx = egui::Context::default();
let call = |app: &mut SheetApp, command: &str, params: serde_json::Value| match handle(
app,
&ctx,
"engine.execute",
&json!({"command": command, "params": params, "window": first}),
) {
Outcome::Done(v) => v,
Outcome::Screenshot { .. } => panic!("{command} took a screenshot"),
};
let read = call(&mut app, "ui.printSettings", json!({}));
assert_eq!(read["result"]["from"], 4, "{read}");
let set = call(&mut app, "ui.printSettings", json!({"to": 4}));
assert_eq!((&set["result"]["from"], &set["result"]["to"]), (&json!(4), &json!(4)), "{set}");
assert_eq!(app.session.active_window(), Some(second), "the active window stays active");
assert_eq!(app.print_pages, PageRange::default(), "the active window's range is untouched");
let printed = call(&mut app, "ui.printSubmit", json!({}));
assert_eq!(printed["ok"], true, "{printed}");
app.printing.poll(&ctx);
app.poll_printing(&ctx);
assert_eq!(footers(&jobs.borrow_mut().pop().unwrap()), ["Page 4 of 5"]);
app.run("window.activate", json!({"window": first})).unwrap();
assert_eq!(app.print_pages, PageRange { from: Some(4), to: Some(4) });
}
#[test]
/// File › Print's Pages … to … fields set the page range, the preview shows the pages that will
/// print under their own numbers, and the fields follow `ui.printSettings`. In German too.
fn the_print_views_page_fields_set_the_range_and_the_preview_follows() {
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = crate::common::prepare(SheetApp::new(five_pages(), Services::default()));
app.run("ui.backstage", json!({"page": "print"})).unwrap();
let mut h = crate::common::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
assert!(h.query_by_label("Page 1 of 5").is_some());
type_into(&mut h, "Pages", "2");
type_into(&mut h, "to", "3x");
let range = h.state().print_pages;
assert_eq!((range.from, range.to), (Some(2), Some(3)), "digits only");
assert!(h.query_by_label("Page 2 of 5").is_some(), "the preview starts at the range's first page, under its own number");
h.get_by_label("▶").click();
h.run_steps(3);
assert!(h.query_by_label("Page 3 of 5").is_some());
assert!(h.get_by_label("▶").accesskit_node().is_disabled(), "page 3 is the last page that prints");
assert!(h.get_all_by_role_and_label(Role::Button, "Print").all(|b| !b.accesskit_node().is_disabled()));
// A range changed by automation also returns the preview to the start of the new range.
h.state_mut().run("ui.printSettings", json!({"from": 1, "to": 2})).unwrap();
h.run_steps(3);
assert!(h.query_by_label("Page 1 of 5").is_some());
// An emptied field has no bound; a range after the last page has nothing to print, and Print is off.
type_into(&mut h, "to", "");
assert_eq!(h.state().print_pages.to, None);
type_into(&mut h, "Pages", "9");
assert!(h.query_by_label("Nothing to print.").is_some());
// The square Print button, not the navigation entry of the same name.
assert!(h.get_all_by_role_and_label(Role::Button, "Print").any(|b| b.accesskit_node().is_disabled()));
// The fields show what `ui.printSettings` sets once they are left (Tab moves on to "to").
h.key_press(egui::Key::Tab);
h.run_steps(2);
h.state_mut().run("ui.printSettings", json!({"from": 4, "to": null})).unwrap();
h.run_steps(3);
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Pages").value().as_deref(), Some("4"));
assert_eq!(h.get_by_role_and_label(Role::TextInput, "to").value().as_deref(), Some(""));
assert!(h.query_by_label("Page 4 of 5").is_some());
// German labels.
h.state_mut().run("app.language.set", json!({"language": "de"})).unwrap();
h.run_steps(3);
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Seiten").value().as_deref(), Some("4"));
assert!(h.query_by_role_and_label(Role::TextInput, "bis").is_some());
assert!(h.query_by_label("Seite 4 von 5").is_some());
}
#[test]
/// Export › Create PDF exports the page range typed under it.
fn create_pdf_exports_the_page_range_under_it() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let dir = std::env::temp_dir().join(format!("gridcraft-export-range-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let target = dir.join("Range.pdf");
let path = target.to_string_lossy().into_owned();
let services = Services { pick_save: Some(Box::new(move |_| Some(path.clone()))), ..Default::default() };
let mut app = crate::common::prepare(SheetApp::new(five_pages(), services));
app.run("ui.backstage", json!({"page": "export"})).unwrap();
let mut h = crate::common::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(4);
type_into(&mut h, "Pages", "4");
h.get_by_role_and_label(Role::Button, "Create PDF").click();
h.run_steps(3);
assert!(h.state().message.is_none(), "{:?}", h.state().message);
assert_eq!(footers(&std::fs::read(&target).unwrap()), ["Page 4 of 5", "Page 5 of 5"]);
assert_eq!(h.state().print_pages, gridcraft_ui_egui::printing::PageRange::default(), "File › Print keeps its own range");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn queue_papers_ignore_late_answers_and_are_used_only_for_the_selected_queue() {
let mut session = Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Services::default());
app.run("cell.set", json!({"cell":"A1", "input":"Paper choice fixture"})).unwrap();
app.printing.printers = vec![Printer::new("Label queue"), Printer::new("Office queue")];
let (label_send, label_receive) = std::sync::mpsc::channel();
let (office_send, office_receive) = std::sync::mpsc::channel();
let replies = RefCell::new(std::collections::HashMap::from([("Label queue", label_receive), ("Office queue", office_receive)]));
app.services.printer_papers = Some(Box::new(move |queue| replies.borrow_mut().remove(queue).unwrap()));
let jobs = Rc::new(RefCell::new(Vec::new()));
let observed = jobs.clone();
app.services.print_native = Some(Box::new(move |bytes, settings, paper| {
observed.borrow_mut().push((bytes, settings, paper));
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok("queued".into())).unwrap();
receiver
}));
let ctx = egui::Context::default();
app.run("ui.printSettings", json!({"printer":"Label queue"})).unwrap();
app.poll_printing(&ctx);
app.run("ui.printSettings", json!({"printer":"Office queue"})).unwrap();
app.poll_printing(&ctx);
let office = Paper { id: "Legal".into(), name: "Office Legal".into(), width: 612.0, height: 1008.0, cups_media: Some("Legal".into()) };
let side_feed =
Paper { id: "LegalSideFeed".into(), name: "Office Legal Side Feed".into(), cups_media: Some("LegalSideFeed".into()), ..office.clone() };
office_send.send(vec![office.clone(), side_feed.clone()]).unwrap();
label_send.send(vec![Paper { id: "Label".into(), name: "Label".into(), width: 144.0, height: 216.0, cups_media: None }]).unwrap();
app.poll_printing(&ctx);
assert!(app.run("ui.printSettings", json!({"paper":"Label"})).is_err());
let configured = app.run("ui.printSettings", json!({"paper":"Legal"})).unwrap();
assert_eq!(configured["papers"].as_array().unwrap().len(), 2);
assert_eq!(configured["paper"], "Legal");
app.run("ui.printSubmit", json!({})).unwrap();
app.poll_printing(&ctx);
let configured = app.run("ui.printSettings", json!({"paper":"LegalSideFeed"})).unwrap();
assert_eq!(configured["paper"], "LegalSideFeed");
app.run("ui.printSubmit", json!({})).unwrap();
app.poll_printing(&ctx);
let preview = app.run("file.printPreview", json!({})).unwrap();
assert_eq!(preview["pageList"][0]["height"], 792.0, "workbook Page Setup stays Letter");
assert!(app.run("ui.printSettings", json!({"printer":"Label queue","paper":"Legal"})).is_err());
assert_eq!(app.run("ui.printSettings", json!({})).unwrap()["printer"], "Office queue");
let switched = app.run("ui.printSettings", json!({"printer":"Label queue"})).unwrap();
assert_eq!(switched["paper"], serde_json::Value::Null);
app.run("ui.printSubmit", json!({})).unwrap();
let jobs = jobs.borrow();
assert_eq!(jobs.len(), 3);
assert_eq!(jobs[0].1.destination, Destination::Printer("Office queue".into()));
assert_eq!(jobs[0].2.as_ref(), Some(&office));
assert!(String::from_utf8_lossy(&jobs[0].0).contains("/MediaBox [0 0 612 1008]"));
assert_eq!(jobs[1].1.destination, Destination::Printer("Office queue".into()));
assert_eq!(jobs[1].2.as_ref(), Some(&side_feed));
assert!(String::from_utf8_lossy(&jobs[1].0).contains("/MediaBox [0 0 612 1008]"));
assert_eq!(jobs[2].1.destination, Destination::Printer("Label queue".into()));
assert!(jobs[2].2.is_none());
assert!(String::from_utf8_lossy(&jobs[2].0).contains("/MediaBox [0 0 612 792]"));
}
+7 -15
View File
@@ -1,16 +1,7 @@
# gridcraft-cli
Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window.
`gridcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
(command-line conventions), and `gridcraft-cli --help` and `<subcommand> --help` are the reference for every flag; this page
shows what they are for. Exit status: 0 success, 1 a command failed (`check` found a difference), 2 a usage error (an
unknown or repeated flag, a bad value, flags that conflict or that a subcommand doesn't take, all checked before any file is
touched), and 128 plus the signal number when a signal ends the process. Errors are `error: <message>` on stderr; results
are on stdout. `--version`/`-V` work on every subcommand, and there is no `version` subcommand. `--json` is on the
subcommands whose output a program reads. The CLI reads no environment variables of its own. The Linux packages (deb, rpm and
tar.gz) and the FreeBSD package install its man pages and its bash, zsh and fish completions; the macOS and Windows downloads
do not carry them (RFC-0018 leaves those platforms out of scope).
Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window. Errors go to stderr with a
non-zero exit code.
`.xls` (Excel 97-2003, BIFF8) files are imported with values, formulas, number formats, merges,
column widths, row heights and defined names; fonts, fills, borders, charts and other objects are
@@ -32,7 +23,7 @@ cargo install --path apps/gridcraft-cli # or: cargo run -p gridcraft-cli --
| Subcommand | Example |
|---|---|
| `info <file> [--json]` | `gridcraft-cli info book.xlsx` — sheets, used ranges, cell counts, tables, charts, names. |
| `convert <in> <out> [--sheet NAME] [--overwrite]` | `gridcraft-cli convert book.xlsx data.csv --sheet Sales` — output format from the extension: `.xlsx`, `.csv`, `.tsv`, `.json`, `.html`. Replacing the input requires `--overwrite`. |
| `convert <in> <out> [--sheet NAME]` | `gridcraft-cli convert book.xlsx data.csv --sheet Sales` — output format from the extension: `.xlsx`, `.csv`, `.tsv`, `.json`, `.html`. |
| `eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]` | `gridcraft-cli eval '=PMT(5%/12,360,-300000)'`; `gridcraft-cli eval '=SUM(B2:B9)' --in book.xlsx` — formulas in English with `,` between arguments. A formula that couldn't be entered in a cell (it doesn't parse, or a function gets the wrong number of arguments) is an error saying why; an unknown function is `#NAME?`, as in Excel. |
| `cat <file> [--range R] [--sheet S] [--formulas] [--csv]` | `gridcraft-cli cat book.xlsx --range A1:F20` — aligned table of displayed values. |
| `check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]` | `gridcraft-cli check corpus/` — calc oracle and XLSX round-trip fidelity, see below. |
@@ -41,17 +32,18 @@ cargo install --path apps/gridcraft-cli # or: cargo run -p gridcraft-cli --
| `functions [--json] [--search X] [--category C]` | `gridcraft-cli functions --search lookup` |
| `mcp [--connect PORT] [--in FILE \| --sample NAME]` | MCP server on stdio ([mcp.md](mcp.md)). |
| `send <port> <method> [json]` | `gridcraft-cli send 7979 engine.execute '{"command":"home.bold","params":{"range":"A1:C1"}}'` — one control-channel request to a running app (`gridcraft --control 7979`). |
| `version` | Prints `gridcraft-cli <version>`. |
## `run`
```sh
gridcraft-cli run [--in FILE | --sample budget|sales|grades] \
[--cmd 'id={json}']... [--script steps.jsonl] \
[--out FILE] [--overwrite] [--print RANGE|used] [--sheet S] [--csv] [--formulas] [--quiet]
[--out FILE] [--print RANGE|used] [--sheet S] [--csv] [--formulas] [--quiet]
```
Opens a file (or a sample, or a blank workbook), runs `--cmd` and `--script` steps in the order given, then saves
`--out` and prints each `--print` range. `--out` that names the same file as `--in` requires `--overwrite`. Each non-null command result is printed as a JSON line unless `--quiet`.
`--out` and prints each `--print` range. Each non-null command result is printed as a JSON line unless `--quiet`.
The first failing step stops the run with a non-zero exit.
A `--cmd` is `id`, `id={json}` or `id {json}`. A script has one command per line in the same forms, or as JSON objects
@@ -62,7 +54,7 @@ gridcraft-cli run --in book.xlsx \
--cmd 'home.bold={"range":"A1:C1"}' \
--cmd 'cell.set={"cell":"D2","input":"=B2*C2"}' \
--cmd 'edit.fillDown={"range":"D2:D20"}' \
--out book-out.xlsx --print A1:D5
--out book.xlsx --print A1:D5
```
Command ids and parameters: `gridcraft-cli commands`.
+16 -5
View File
@@ -154,8 +154,19 @@ lists `ui.printSettings` and `ui.printSubmit` with their parameter and result fi
printer, copies, duplex, grayscale, discovery/submission status and backend receipt/error.
`{"refresh":true}` starts background discovery; poll the same command until `discovering` is
false. Set `printer` to a discovered name, integer `copies` from 1 to 999, `duplex` to
`printerDefault`, `off`, `longEdge` or `shortEdge`, and boolean `grayscale`. Invalid updates are
rejected without changing earlier settings. `ui.printSubmit` explicitly submits the current
print-ready PDF without opening a dialog; inspect `ui.printSettings` until `busy` becomes false
and check `status`/`detail`. The browser keeps its own print hook. PDF export remains separate.
GridCraft accepts the existing `file.print` sheet/pagination params on `ui.printSubmit`; the engine `file.print` command returns the PDF without spooling.
`printerDefault`, `off`, `longEdge` or `shortEdge`, and boolean `grayscale`. `from` and `to`
are the Print view's page range (Pages … to …) of the active window, or of the window named by
`window` or `doc`, as each window keeps its own: whole page numbers from 1, counted over the
whole print job in sheet order, or `null` to clear a bound; the result reports both. Invalid updates are rejected without changing earlier
settings. `ui.printSubmit` explicitly submits the current print-ready PDF without opening a
dialog; inspect `ui.printSettings` until `busy` becomes false and check `status`/`detail`. The
browser keeps its own print hook. PDF export remains
separate. GridCraft accepts the existing `file.print` sheet/pagination params on
`ui.printSubmit`, and the page range of `ui.printSettings` when the call names neither `from` nor
`to`; the engine `file.print` command returns the PDF without spooling.
`file.print`, `file.exportPdf` and `file.printPreview` take the same `from` and `to`. Only those
pages print, and their headers and footers keep the whole job's `&P` and `&N`. A range that
starts after the last page is an error, `to` past the last page stops there, and `from` greater
than `to` prints the pages between them. `file.printPreview` then lists only the pages that
print, each under its number in the job, with the job's page count as `total`.
+2 -1
View File
@@ -123,7 +123,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| Format | Excel | GridCraft | Notes |
|---|---|---|---|
| PDF | Save As / Export | yes (own PDF 1.7 writer; CLI `convert` output) | Printed cell hyperlinks export as clickable HTTP(S)/mailto links or destinations within printed pages (#954); unsafe schemes and destinations outside the print range are omitted. Latin text uses the standard Helvetica, Times and Courier faces (13 base-14 entries with Symbol), not embedded; Arabic exports as shaped, embedded Noto Arabic glyphs; cell reading direction and RTL sheet geometry are kept; other characters outside WinAnsiEncoding are set in a predefined, non-embedded CID font (STSong-Light, Adobe-GB1, `UniGB-UTF16-H`, #1912), so **Simplified Chinese displays where the reader supplies that font, and scripts outside Adobe-GB1 (Devanagari, Thai) export as code points but show as the reader's missing-glyph box**; equations use Symbol for the Greek letters and operators it has, the Times faces for letters and digits, and a `[?]` box for the rest; web build exports without a file prompt (#141) |
| PDF | Save As / Export | yes (own PDF 1.7 writer; CLI `convert` output) | Pages … to … in File › Print and Export › Create PDF select whole-job page numbers (#3016). Printed cell hyperlinks export as clickable HTTP(S)/mailto links or destinations within printed pages (#954); unsafe schemes and destinations outside the print range are omitted. Latin text uses the standard Helvetica, Times and Courier faces (13 base-14 entries with Symbol), not embedded; Arabic exports as shaped, embedded Noto Arabic glyphs; cell reading direction and RTL sheet geometry are kept; other characters outside WinAnsiEncoding are set in a predefined, non-embedded CID font (STSong-Light, Adobe-GB1, `UniGB-UTF16-H`, #1912), so **Simplified Chinese displays where the reader supplies that font, and scripts outside Adobe-GB1 (Devanagari, Thai) export as code points but show as the reader's missing-glyph box**; equations use Symbol for the Greek letters and operators it has, the Times faces for letters and digits, and a `[?]` box for the rest; web build exports without a file prompt (#141) |
| XPS | Windows | no | Low priority |
| Print | yes | yes (via PDF, system dialog on desktop; PR #143 for web) | Pages print in the sheet's page order: down, then over (the default) or over, then down. A sheet marked `excluded` (Page Setup) is left out when the whole workbook prints or exports to PDF, unless every visible sheet is, as LibreOffice treats an OpenDocument sheet set not to print; Excel has no such flag, so it is not kept in XLSX: Save asks first and offers GridCraft JSON, AutoSave waits, and `file.save`, `file.saveAs` and `file.saveBytes` return `warnings` |
| Images of ranges/charts (Copy as Picture) | yes | chart raster in `crates/chart` | No range-to-image command |
@@ -194,6 +194,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-11-01 | minor | Chart data tables preserve showKeys, showHorzBorder, showVertBorder and showOutline through native c:dTable XLSX import/export; synthetic tests cover all 16 flag combinations and boolean defaults. Excel-side verification remains outstanding. |
| 2026-11-01 | minor | XLSX reads and writes Page Setup's page order: `<pageSetup pageOrder="overThenDown">` for Over, then down, and no attribute for Down, then over (the default), as Excel writes them; PDF export and printing number and order the pages by it |
| 2026-11-01 | trivial | XLSX selects the first visible workbook view as one unit and bounds imported/exported tab ratios; isolated attributes and sheet-edit round trips covered, with firstSheet left to #2264 (#3057) |
| 2026-10-31 | minor | PDF export and printing take a page range (`from`/`to` on `file.exportPdf`, `file.print` and `file.printPreview`; Pages … to … in File › Print and Export › Create PDF, #3016). Only those pages print, counted over the whole job in sheet order, and their headers and footers keep the whole job's `&P` and `&N`. A range starting after the last page is an error, `to` past the last page stops there, and `from` greater than `to` prints the pages between them, as Excel's Export › PDF measured |
| 2026-10-31 | minor | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) |
| 2026-10-31 | minor | XLSX open reads Google Sheets' `IFERROR(__xludf.DUMMYFUNCTION("…"),cached)` export wrapper as the formula inside when GridCraft calculates every function in it (plain, shared and array formulas, whole or nested; Google-only functions and unparseable, over-long or over-deep inner text keep the wrapper and the cached value) and keeps the cached value; saving writes the real formula with Excel's `_xlfn.` prefixes (#2871) |
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
+2 -1
View File
@@ -149,7 +149,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
### 14. Page Layout view and print polish (U, F)
- Page Layout view landed (#329): paper view with rulers and in-place header/footer editing.
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h.
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Page ranges (Pages … to …) are in File › Print and Export › Create PDF (#3016). Driver tray/options UI remains. **Estimate:** 5–10 h.
### 15. Remaining functions and an oracle suite (F)
- 9 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 15–25 h.
@@ -205,6 +205,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 2026-11-02 | minor | §4: charts, like every floating object, move and resize from eight handles (#190), so resizing is no longer listed as missing; the evidence is one paragraph again, without the stale "PRs #158, #161 open" |
| 2026-11-01 | minor | §13: the Analysis ToolPak has all 19 of Excel's tools (two-factor Anova with and without replication, z-Test, Fourier Analysis, Random Number Generation, Sampling); its chart output remains. The stale "`data.solver`, `data.analysisToolPak` missing" and "no Forecast Start" sentences removed |
| 2026-11-01 | minor | §4: chart data tables implemented for column, bar, line, area and compatible combo charts, with legend keys and border settings, live source values, XLSX round-trip and print/PDF; other chart gaps remain. |
| 2026-10-31 | minor | §14: page ranges (Pages … to …) in File › Print and Export › Create PDF, and `from`/`to` on `file.print`, `file.exportPdf` and `file.printPreview` (#3016) |
| 2026-10-31 | minor | §13: Solver Options (Max Evaluations, Integer Optimality and the Evolutionary options), saved with the model |
| 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog |
| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly |
+2 -1
View File
@@ -43,7 +43,7 @@ desktops is not guaranteed. FreeBSD has not been tested locally.
| Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | template gallery missing |
| Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239); icons, reference colours, primary buttons and the comments pane follow the theme, and a unit test holds every token pair to WCAG 2 contrast in both themes |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Pages … to …, Page Setup), Export (PDF with a page range, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
| Dark mode, system appearance | yes | yes | done (10-09) |
| Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab, whose Different First Page and Different Odd & Even Pages give the first page and the even pages their own header and footer (#344), and whose Scale with Document and Align with Page Margins set whether header and footer text follows the print scale and the side margins, on paper and in the view | margins drag on the rulers (#792, with header and footer margins); header/footer pictures missing (1–3 h). Unverified: with Align with Page Margins off, header and footer text sits 0.7 in from the paper edge, a value not yet measured in the target app |
| Multiple windows per workbook | yes | yes (10-22, desktop): each workbook window is a native window of its own (New, Open and New Window open one; titles "Book1", or "Book1:1" / "Book1:2" for a workbook's second window, with " — Edited" while unsaved). Each window keeps its own cell draft, dialog, Backstage view, message and grid state, and its ribbon acts on it; on macOS the menu bar acts on the window focused last. Leaving a window enters its draft as Enter would. A window's close button closes that window: one of several on a workbook closes without asking, a workbook's last asks Save / Don't Save / Cancel when unsaved. Quit asks about each unsaved workbook in its window, and Cancel stops it. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar until New or Open. View › Arrange All (dialog: Tiled, Horizontal, Vertical, Cascade, Windows of active workbook; `view.arrangeAll` tiles by default) lays the visible windows out over the main window's monitor, the active one first. Web: one window | Arrange All uses one monitor; a hidden window (View › Hide) has no native window; every window repaints when one does; see [hardware-parity.md](hardware-parity.md) |
@@ -346,6 +346,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows |
| 2026-11-01 | minor | Trace arrows stay when the sheet is zoomed (View › Zoom, the status bar, Ctrl+wheel), as in Excel; every zoom used to remove them (#3097) |
| 2026-11-01 | minor | Assert shared baselines in the actual title layout and record manual visual-size validation of a compiled macOS build |
| 2026-10-31 | minor | File › Print has Pages … to … below Print Active Sheets / Print Entire Workbook, and Export › Create PDF has the same two fields (#3016). Empty fields print every page, and each window keeps its own range. Pages are counted over the whole job in sheet order, and the printed pages keep the job's numbers in their headers and footers (`&P` of `&N`: page 2 of a 5-page sheet prints "Page 2 of 5"), as in Excel. The preview shows only the pages that print, under their own numbers. `ui.printSettings` takes `from` and `to` (`null` clears one), and `ui.printSubmit` prints that range |
| 2026-10-31 | minor | Esc in a File-page text field leaves the field and cancels editing; the next Esc returns to the sheet (#3035) |
| 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown |
| 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used |
-25
View File
@@ -45,18 +45,8 @@ echo "==> GridCraft $VERSION for FreeBSD $ARCH"
if [[ "$SKIP_BUILD" = 0 ]]; then
(cd "$ROOT" && cargo build --release --locked -p gridcraft -p gridcraft-cli ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"})
# The man-and-completions example writes gridcraft-cli's man pages and shell completions below. It is built in its own
# cargo run: built with the binaries, its dev-dependencies' features would be unified into them. It runs on this
# machine, so it is built for the host: under a cross build CARGO_BUILD_TARGET would make a binary this machine cannot
# execute.
if [[ -n "${CARGO_BUILD_TARGET:-}" ]]; then
echo "note: cross build: the man-and-completions example runs on the build host, so it is built for the host" >&2
fi
(cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p gridcraft-cli --example man-and-completions)
fi
BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release"
# The example is built for the host (above), so it is not under the target triple.
HOST_BIN="$CARGO_TARGET_DIR/release"
WORK="$CARGO_TARGET_DIR/freebsd-package"
TREE="$WORK/$BASENAME"
rm -rf "$WORK"
@@ -65,21 +55,6 @@ install -d "$TREE/bin" "$TREE/share/applications" "$TREE/share/metainfo" "$TREE/
"$TREE/share/icons" "$TREE/share/doc/gridcraft"
install -m 755 "$BIN/gridcraft" "$BIN/gridcraft-cli" "$TREE/bin/"
strip "$TREE/bin/gridcraft" "$TREE/bin/gridcraft-cli" 2>/dev/null || true
# gridcraft-cli's man pages and shell completions, from its clap definition, written by the example built above (a
# --skip-build run needs it built too). Under /usr/local, man pages go in man/ and the completions in the directories
# bash, zsh and fish read there.
CLI_DOCS="$HOST_BIN/examples/man-and-completions"
if [[ ! -x "$CLI_DOCS" ]]; then
echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p gridcraft-cli --example man-and-completions)" >&2
exit 1
fi
"$CLI_DOCS" "$WORK/cli-docs"
install -d "$TREE/man/man1" "$TREE/share/bash-completion/completions" "$TREE/share/zsh/site-functions" \
"$TREE/share/fish/vendor_completions.d"
install -m 644 "$WORK"/cli-docs/*.1 "$TREE/man/man1/"
install -m 644 "$WORK/cli-docs/gridcraft-cli.bash" "$TREE/share/bash-completion/completions/gridcraft-cli"
install -m 644 "$WORK/cli-docs/_gridcraft-cli" "$TREE/share/zsh/site-functions/_gridcraft-cli"
install -m 644 "$WORK/cli-docs/gridcraft-cli.fish" "$TREE/share/fish/vendor_completions.d/gridcraft-cli.fish"
install -m 644 "$LINUX/$APP_ID.desktop" "$TREE/share/applications/$APP_ID.desktop"
install -m 644 "$LINUX/$APP_ID.mime.xml" "$TREE/share/mime/packages/$APP_ID.xml"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$GRIDCRAFT_BUILD_DATE/g" \
-7
View File
@@ -68,13 +68,6 @@ contents:
dst: /usr/share/
type: tree
# Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and
# openSUSE's do (its debian/rules sets --enable-additional-fpath).
- src: /usr/share/zsh/site-functions/_${NFPM_CLI}
dst: /usr/share/zsh/vendor-completions/_${NFPM_CLI}
type: symlink
packager: deb
scripts:
postinstall: packaging/linux/postinst.sh
postremove: packaging/linux/postinst.sh
+1 -11
View File
@@ -193,7 +193,7 @@ class FlatNightlyTar(unittest.TestCase):
class StagedFormats(unittest.TestCase):
"""package.sh with stub binaries, a stub man-and-completions example, a stub nfpm and a stub strip."""
"""package.sh with stub binaries, a stub nfpm and a stub strip."""
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
@@ -208,16 +208,6 @@ class StagedFormats(unittest.TestCase):
binary = self.target / "release" / name
binary.write_text(RECORDER)
binary.chmod(0o755)
# The man-and-completions example writes the files it does for a real build; this one writes placeholders.
example = self.target / "release" / "examples" / "man-and-completions"
example.parent.mkdir(parents=True, exist_ok=True)
example.write_text(
'#!/bin/sh\nmkdir -p "$1"\n'
'for f in gridcraft-cli.bash _gridcraft-cli gridcraft-cli.fish gridcraft-cli.1 gridcraft-cli-run.1; do\n'
' echo "stub" >"$1/$f"\n'
'done\n'
)
example.chmod(0o755)
# `strip` would refuse the recorder scripts; the real one is a no-op for a non-ELF file too.
(self.stubs / "strip").write_text("#!/bin/sh\nexit 0\n")
(self.stubs / "strip").chmod(0o755)
-28
View File
@@ -71,13 +71,8 @@ if [[ "$SKIP_BUILD" = 0 ]]; then
else
(cd "$ROOT" && cargo build --release --locked -p gridcraft -p gridcraft-cli)
fi
# The man-and-completions example writes gridcraft-cli's man pages and shell completions below. It is built in its own
# cargo run: built with the binaries, its dev-dependencies' features would be unified into them. It runs on the build
# host, so a cross build still builds it for the host.
(cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p gridcraft-cli --example man-and-completions)
fi
BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release"
HOST_BIN="$CARGO_TARGET_DIR/release"
WORK="$CARGO_TARGET_DIR/linux-package"
STAGE="$WORK/root"
rm -rf "$WORK"
@@ -86,19 +81,6 @@ rm -rf "$WORK"
install -Dm755 "$BIN/gridcraft" "$STAGE/usr/bin/gridcraft"
install -Dm755 "$BIN/gridcraft-cli" "$STAGE/usr/bin/gridcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/gridcraft" "$STAGE/usr/bin/gridcraft-cli" 2>/dev/null || true
# gridcraft-cli's man pages and shell completions, from its clap definition, written by the example built above (a
# --skip-build run needs it built too). zsh reads site-functions on Fedora and openSUSE; the deb also links the
# completion into Debian's vendor-completions (nfpm.yaml).
CLI_DOCS="$HOST_BIN/examples/man-and-completions"
if [[ ! -x "$CLI_DOCS" ]]; then
echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p gridcraft-cli --example man-and-completions)" >&2
exit 1
fi
"$CLI_DOCS" "$WORK/cli-docs"
install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1
install -Dm644 "$WORK/cli-docs/gridcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/gridcraft-cli"
install -Dm644 "$WORK/cli-docs/_gridcraft-cli" "$STAGE/usr/share/zsh/site-functions/_gridcraft-cli"
install -Dm644 "$WORK/cli-docs/gridcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/gridcraft-cli.fish"
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
if [[ "$IS_NIGHTLY" = 1 ]]; then
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.gridcraft.nightly-v1|' \
@@ -204,16 +186,6 @@ if has deb || has rpm; then
rm -f "$NFPM_STAGE/usr/bin/gridcraft"
nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN" /usr/lib/gridcraft-nightly/gridcraft
mv "$NFPM_STAGE/usr/bin/gridcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
# The man pages and completions name the command they document: rename them for the nightly's command.
for f in "$NFPM_STAGE"/usr/share/man/man1/gridcraft-cli*.1 "$NFPM_STAGE/usr/share/bash-completion/completions/gridcraft-cli" \
"$NFPM_STAGE/usr/share/zsh/site-functions/_gridcraft-cli" "$NFPM_STAGE/usr/share/fish/vendor_completions.d/gridcraft-cli.fish"; do
dir=$(dirname "$f")
base=$(basename "$f")
dest="$dir/${base//gridcraft-cli/$NFPM_CLI}"
sed -e "s/gridcraft-cli/$NFPM_CLI/g" -e "s/gridcraft\\\\-cli/${NFPM_CLI//-/\\\\-}/g" "$f" >"$dest.tmp"
rm -f "$f"
mv "$dest.tmp" "$dest"
done
mv "$NFPM_STAGE/usr/share/doc/gridcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=gridcraft$|TryExec=$NFPM_BIN|" \