Compare commits

..
Author SHA1 Message Date
FredApps 296a4bf9a6 Merge pull request #3341 from AnhNgoo/fix/filter-unicode-case-2912
AutoFilter: match Unicode case-insensitively (#2912)
2026-11-27 06:51:49 +01:00
FredApps 8cc5022abb fix(filter): match legacy checklist identities across merged case variants
Re-fold the stored base of every checklist identity with the Unicode case key
before comparing, so an identity saved with ASCII-only folding selects all rows
of the dropdown entry that now merges the case variants, and reapplying the
unchanged checklist keeps the same rows (#2912).
2026-11-27 12:39:41 +07:00
FredApps 4d5c8f2a4d fix(filter): keep ASCII-folded checklist identities matching their rows
Identities saved before the Unicode case key encode non-ASCII uppercase text
with ASCII-only folding. Accept that legacy base key when matching rows and
when deciding whether a selection splits formula and constant rows, so a saved
selection keeps its rows visible and its dropdown entry checked (#2912).
2026-11-27 12:26:59 +07:00
FredApps 1af87a37c5 Merge main into fix/filter-unicode-case-2912
Resolve the conflict with the checklist-identity matcher from #2943: apply the
char-wise Unicode lowercase key to the value-list lookup and to the typed and
formatted checklist identity tokens, so case variants share one dropdown entry
and match rows consistently. Update the two dropdown tests accordingly.
2026-11-27 12:12:32 +07:00
FredApps 401041f00c Merge pull request #3402 from AnhNgoo/fix/dialog-enter-error-2189
fix(ui): keep dialog errors visible after Enter (#2189)
2026-11-27 06:09:25 +01:00
FredApps 959497cad6 Merge pull request #2867 from AnhNgoo/fix/chart-explicit-style-rendering
fix(chart): render explicit Excel chart styles 1 and 9
2026-11-27 05:55:30 +01:00
FredApps c10f94fcd3 Merge pull request #2943 from AnhNgoo/fix/filter-whitespace-2911
fix(filter): ignore surrounding whitespace in AutoFilter values
2026-11-27 05:53:12 +01:00
AnhNgoo 5c4fcc65bd fix(filter): use char-wise lowercase keys matching compare_text 2026-11-27 10:39:51 +07:00
AnhNgoo 86a0c41e8f test(chart): use Series::default() for new upstream fields 2026-11-27 10:39:42 +07:00
AnhNgoo c159362b95 Merge remote-tracking branch 'upstream/main' into fix/filter-whitespace-2911
# Conflicts:
#	crates/engine/src/cmd/data.rs
#	crates/engine/src/cmd/data/filter.rs
#	crates/engine/src/cmd/data/tests.rs
#	crates/ui-egui/src/grid/menus.rs
2026-11-27 10:10:50 +07:00
AnhNgoo 93d8e97d16 Merge remote-tracking branch 'upstream/main' into fix/chart-explicit-style-rendering
# Conflicts:
#	crates/chart/src/resolve.rs
#	crates/xlsx/src/chart.rs
#	crates/xlsx/src/tests/chart_combo_kinds.rs
2026-11-27 10:10:44 +07:00
AnhNgoo 55d6879a94 Merge remote-tracking branch 'upstream/main' into fix/dialog-enter-error-2189
# Conflicts:
#	crates/ui-egui/src/dialogs/show.rs
#	crates/ui-egui/src/widgets.rs
2026-11-27 10:10:20 +07:00
AnhNgoo 791beee9f4 Merge remote-tracking branch 'upstream/main' into fix/filter-unicode-case-2912
# Conflicts:
#	crates/engine/src/cmd/data/filter.rs
2026-11-27 10:10:05 +07:00
AnhNgoo 9d9c9cdf83 style: format slicer.rs according to rustfmt 2026-11-21 15:47:43 +07:00
AnhNgoo c00fb9b67e fix(slicer,filter): use Unicode lowercase for slicer deduplication and align formatted-value matching 2026-11-21 15:22:06 +07:00
AnhNgoo e86b2ef0ef fix(xlsx): remove duplicate closing braces in chart reader 2026-11-21 14:56:43 +07:00
AnhNgoo 1e087adf28 Merge branch 'main' of https://github.com/storytold/gridcraft into fix/chart-explicit-style-rendering 2026-11-21 14:36:50 +07:00
AnhNgoo 50a6ea444a Merge branch 'main' of https://github.com/storytold/gridcraft into fix/filter-whitespace-2911 2026-11-21 14:25:08 +07:00
AnhNgoo 7bd4c2d17b fix(filter): distinguish formatted displays in cell tokens and deduplicate slicer tiles 2026-11-21 14:25:02 +07:00
AnhNgoo 0a642f86eb fix(filter): keep typed checklist identities across formats, Show Formulas, and XLSX 2026-11-19 15:14:46 +07:00
AnhNgoo 7e05f4e57e fix(chart): scan all AlternateContent style fallbacks and keep narrow-bar test below label cap 2026-11-19 14:10:57 +07:00
AnhNgoo 0329de4388 fix(filter): preserve checklist identities, formatted-blank values, and migrated visibility on open 2026-11-19 14:10:57 +07:00
AnhNgoo 5e75ffe429 fix(ui): ignore key-repeat Enter/Escape events in message_box (#2189) 2026-11-18 16:55:30 +07:00
AnhNgoo 67bea056d5 fix(filter): migrate legacy whitespace criteria and separate dropdown labels from values (#2911) 2026-11-18 16:02:13 +07:00
AnhNgoo e6f5de7e42 fix(ui): drain modified Escape/Enter in message_box so open dialogs stay open (#2189) 2026-11-18 15:54:39 +07:00
AnhNgoo 14bc675778 fix(chart): preserve narrow style 9 bar fill and validate fallback style (#2865) 2026-11-18 15:47:28 +07:00
AnhNgoo e59c6dfda2 Merge upstream main and document chart style helpers (#2865) 2026-11-18 14:29:06 +07:00
AnhNgoo ef124ce4a9 Merge upstream main and preserve blank rows when filtering by whitespace value (#2911) 2026-11-18 14:18:05 +07:00
AnhNgoo e4d0388944 test(ui): cover dialog error recovery, OK click, and message priority (#2189) 2026-11-18 14:10:07 +07:00
AnhNgoo 3131f30f5c fix(ui): prevent Enter from dismissing dialog errors (#2189) 2026-11-05 11:07:39 +07:00
AnhNgoo b1a1eee435 fix: use Unicode case-insensitive matching in AutoFilter (#2912) 2026-11-04 13:13:50 +07:00
Ngô Quốc Anh a1fc982132 test(chart): make XLSX roundtrip fixture compatible with newer Chart fields 2026-11-02 16:55:15 +07:00
AnhNgoo 8c0f60ec96 test(filter): align dropdown blank-group assertion 2026-11-02 16:41:59 +07:00
AnhNgoo 8e0d621a0f fix(chart): preserve Excel styles and line weights 2026-11-02 16:31:31 +07:00
AnhNgoo 5f55b755fa fix(filter): align blank filtering with Excel behavior 2026-11-02 15:21:34 +07:00
AnhNgoo 17abd46b97 fix(filter): address CodeRabbit review findings (#2911) 2026-10-30 16:57:51 +07:00
AnhNgoo 9187049f7f fix(filter): ignore surrounding whitespace in AutoFilter values (#2911) 2026-10-30 15:14:14 +07:00
AnhNgoo 47c5e3b816 docs(chart): document Cartesian chart rendering 2026-10-29 13:54:59 +07:00
AnhNgoo 9777459eb6 fix(chart): render explicit Excel chart styles 2026-10-29 13:23:50 +07:00
49 changed files with 3354 additions and 1952 deletions
Generated
-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"
@@ -3004,16 +2895,12 @@ dependencies = [
name = "gridcraft-cli"
version = "0.19.1"
dependencies = [
"clap",
"clap_complete",
"clap_mangen",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
"log",
"quick-xml 0.41.0",
"serde_json",
"thiserror 2.0.21",
"zip",
]
@@ -3829,12 +3716,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"
@@ -4896,12 +4777,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"
@@ -5837,12 +5712,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"
@@ -6613,12 +6482,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"
@@ -7325,12 +7188,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"
-4
View File
@@ -56,10 +56,6 @@ craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa
# 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)
}
-316
View File
@@ -1,316 +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>,
}
#[derive(Args, Debug)]
pub(crate) struct EvalArgs {
/// The formula; a leading `=` is optional
#[arg(allow_hyphen_values = true, value_parser = formula)]
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>,
}
/// A formula may start with one dash (`-1+3`), but `--word` is a mistyped option, not a formula (`=--1` is one).
fn formula(text: &str) -> Result<String, UsageError> {
if text.starts_with("--") { Err(UsageError::Formula(text.to_owned())) } else { Ok(text.to_owned()) }
}
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>,
/// 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", 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("unexpected argument '{0}' found (start a formula that begins with `--` with `=`, as in `=--1`)")]
Formula(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);
}
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;
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| p.to_string_lossy().into_owned()).collect();
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);
}
-438
View File
@@ -1,438 +0,0 @@
//! The subcommands: each takes its typed arguments and the streams, and returns what to exit with.
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 id == "file.open"
&& 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(())
}
fn convert(a: &ConvertArgs, io: &mut Io) -> Result<(), CliError> {
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(());
}
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);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
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> {
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());
// The server speaks on the process's own stdin and stdout: that is the protocol, not this program's output.
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).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();
}
}
-39
View File
@@ -1,39 +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("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()))
}
-120
View File
@@ -1,120 +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) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
let _ = write!(to, "{}", e.render());
return e.exit_code();
}
};
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);
}
}
+702 -4
View File
@@ -1,9 +1,707 @@
//! `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 id == "file.open"
&& 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(());
}
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 -42
View File
@@ -12,41 +12,54 @@
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
@@ -57,38 +70,29 @@ pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
}
};
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)
}
}
}
-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"})))
);
}
}
-142
View File
@@ -1,142 +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!(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));
}
/// 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);
-143
View File
@@ -1,143 +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() {
let (code, out, _) = run(&["sandbox-check"]);
assert!(out.starts_with("sandbox:"), "{out}");
assert!(code == 0 || code == 1 || code == 2, "{code}");
}
/// 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:"));
}
-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();
}
+29 -9
View File
@@ -58,6 +58,15 @@ fn has_markers(k: ChartKind) -> bool {
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
}
/// Stroke widths for explicitly selected Excel chart styles.
fn line_style_width(style: u32) -> f32 {
match style {
1 => 3.0,
9 => 5.0,
_ => 2.25,
}
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
/// bars' start positions) and along the value axis (`lo..hi`).
struct BarRun {
@@ -71,6 +80,7 @@ struct BarRun {
}
impl BarRun {
/// Starts a single-bar run at `pos` spanning `lo..hi`.
fn new(pos: f32, lo: f32, hi: f32) -> Self {
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
}
@@ -78,6 +88,7 @@ impl BarRun {
fn touches(&self, lo: f32, hi: f32) -> bool {
lo <= self.hi && hi >= self.lo
}
/// Extends the merged run to cover `pos` and `lo..hi`.
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
self.merged = true;
self.a0 = self.a0.min(pos);
@@ -112,13 +123,15 @@ struct BarSink {
bw: f32,
horizontal: bool,
color: Rgba,
stroke: Option<(Rgba, f32)>,
nslots: f32,
k: f32,
}
impl BarSink {
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, nslots, k }
/// Creates a bar emitter for series slot `k` of `nslots`.
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
}
/// Start of this series' slot along the category axis, for the category centered at `c`.
fn pos(&self, c: f32) -> f32 {
@@ -138,11 +151,10 @@ impl BarSink {
let pos = self.pos(c);
let band = self.band();
if !merge {
if self.horizontal {
ctx.rect(lo, pos, len, self.bw, self.color, None);
} else {
ctx.rect(pos, lo, self.bw, len, self.color, None);
}
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
ctx.rect(x, y, w, h, self.color, stroke);
return;
}
match &mut self.run {
@@ -154,6 +166,7 @@ impl BarSink {
}
}
}
/// Flushes any pending hairline bar run at the end of the series.
fn finish(self, ctx: &mut Ctx) {
let band = self.band();
if let Some(m) = self.run {
@@ -294,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
(slot_of, slot_keys.len().max(1) as f32)
}
/// Renders Cartesian column, bar, line, area, and combination charts.
///
/// Resolves series families and their axes, calculates stacking and
/// category positions, and draws the corresponding primitives.
/// Explicit chart style 9 adds white outlines to column and bar
/// rectangles, including stacked and 100%-stacked variants.
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
if ncat == 0 {
@@ -392,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
// Hairline bars are merged per pixel column (their envelope is what shows).
let cull = merge_hairlines(bw, labels_on);
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
for (j, sp) in row.iter().enumerate() {
let Some((b, t)) = sp else { continue };
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
@@ -429,7 +449,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
}
_ => {
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if has_markers(k) && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
+70 -3
View File
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
[r, g, b, 0xFF]
}
/// Excel reference colours for explicit styles 1 and 9.
///
/// These palettes cover measured default-theme examples.
/// Other counts still use the existing theme-based fallback.
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
if !matches!(style, 1 | 9) {
return series_color(theme, index);
}
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
let shades: &[u8] = match count {
1..=4 => &SMALL,
5..=8 => &MEDIUM,
9..=16 => &LARGE,
_ => return series_color(theme, index),
};
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
}
/// The first `n` series colours for `theme`.
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
@@ -470,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
let values = nums(wb, sheet, &s.values, limit);
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
let color =
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
let color = s
.color
.as_ref()
.and_then(|c| c.resolve(&wb.theme))
.map(|[r, g, b]| [r, g, b, 0xFF])
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
let kind = chart.series_kind(i);
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
// X values with text in them (labels) are ignored: the points are numbered 1..n.
@@ -519,10 +545,51 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
let palette = if matches!(chart.style, 1 | 9) {
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
} else {
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
};
ChartData { categories, category_levels, series, palette }
}
#[cfg(test)]
mod explicit_style_palette_tests {
use super::*;
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
#[test]
fn explicit_style_palette_boundaries() {
let theme = Workbook::default().theme;
for style in [1, 9] {
for count in [0, 17, 255] {
for index in [0, 1, 4, 8, 16] {
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
}
}
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
assert_eq!(
chart_style_series_color(&theme, style, 0, count),
[expected_first, expected_first, expected_first, 255],
"style {style}, count {count}",
);
assert_eq!(
chart_style_series_color(&theme, style, 16, count),
series_color(&theme, 16),
"out-of-range index for style {style}, count {count}",
);
}
}
for style in [0, 2, 10, 48] {
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
}
}
}
#[cfg(test)]
mod label_budget_tests {
use gridcraft_model::Workbook;
+205
View File
@@ -1743,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
}
/// Defined-name series titles on sheets with apostrophes resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
@@ -1780,6 +1781,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
@@ -1817,6 +1819,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Volatile functions in series values or names mark the chart as volatile.
#[test]
fn volatile_series_formulas_are_detected() {
let wb = Workbook::new();
@@ -1849,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
}
/// Defined names referenced by series formulas are followed for volatility checks.
#[test]
fn volatile_defined_names_are_followed() {
let with = |values: &str| {
@@ -1913,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
}
/// Explicit Excel chart styles should affect default series colours,
/// without changing the workbook theme.
#[test]
fn explicit_chart_styles_use_distinct_default_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
c.style = 2;
let style2 = resolve(&wb, 0, &c).series[0].color;
assert_eq!(style2, series_color(&wb.theme, 0));
c.style = 1;
let style1 = resolve(&wb, 0, &c).series[0].color;
c.style = 9;
let style9 = resolve(&wb, 0, &c).series[0].color;
assert_ne!(style1, style2, "style 1 should differ from style 2");
assert_ne!(style9, style2, "style 9 should differ from style 2");
}
/// Excel chart styles must not override explicitly assigned series colours.
#[test]
fn explicit_chart_styles_preserve_custom_series_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
}
}
/// Check the first four point colours measured in Excel for styles 1 and 9.
#[test]
fn excel_chart_styles_use_measured_point_palette() {
let wb = Workbook::default();
let mut c = chart(ChartKind::Pie);
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
for style in [1, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(&data.palette[..4], &expected);
assert_eq!(data.series[0].color, expected[0]);
}
}
/// Excel's default-theme chart colours depend on the total series count.
#[test]
fn excel_chart_styles_depend_on_series_count() {
let wb = Workbook::default();
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
let cases: &[(usize, [[u8; 4]; 3])] = &[
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
];
for (count, expected) in cases {
for style in [1, 9] {
let mut c = chart(ChartKind::ColumnClustered);
c.style = style;
c.series = vec![base_series.clone(); *count];
let data = resolve(&wb, 0, &c);
assert_eq!(data.series.len(), *count);
for (i, color) in expected.iter().enumerate() {
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
}
}
}
}
/// Style 9 uses white outlines on column and bar data rectangles.
#[test]
fn explicit_style_nine_draws_white_column_outlines() {
let wb = Workbook::default();
for kind in [
ChartKind::ColumnClustered,
ChartKind::BarClustered,
ChartKind::ColumnStacked,
ChartKind::BarStacked,
ChartKind::ColumnStacked100,
ChartKind::BarStacked100,
] {
let mut c = chart(kind);
c.legend = LegendPos::None;
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
let color = data.series[0].color;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let outlines: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
_ => None,
})
.collect();
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
}
}
}
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
/// Other styles retain GridCraft's existing stroke width.
#[test]
fn explicit_excel_styles_set_line_stroke_width() {
let color: Rgba = [17, 73, 131, 255];
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
let data = ChartData {
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
category_levels: vec![],
palette: vec![],
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
c.data_labels = false;
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
c.style = style;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let widths: Vec<f32> = prims
.iter()
.filter_map(|primitive| match primitive {
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
_ => None,
})
.collect();
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
}
}
}
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
#[test]
fn narrow_style_9_bars_retain_visible_fill() {
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
let count = 100usize;
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
let values = vec![50.0; count];
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
let data = ChartData {
categories: categories.clone(),
category_levels: vec![],
palette: vec![],
series: vec![series("S1", &values, fill_color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
c.data_labels = true;
c.gridlines = false;
c.style = 9;
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
let narrow_bars: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
_ => None,
})
.collect();
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
}
}
+4 -2
View File
@@ -23,9 +23,11 @@ mod sort;
mod tools;
mod validation;
pub(crate) use filter::{apply_filter, grow_autofilter};
pub use filter::{
FilterChoice, filter_by_cell_params, filter_choices, filter_choices_params, filter_choices_selection, filter_selection, filter_values,
};
pub(crate) use filter::{apply_filter, grow_autofilter, migrate_loaded_autofilters, slicer_identity_token, slicer_tile_text};
use filter::{clear_filter, filter_by, reapply, toggle_filter};
pub use filter::{filter_selection, filter_values};
use grouping::{detail, group, outline_settings, show_levels, subtotal};
pub use sort::sort_context;
use sort::{quick_sort, sort};
File diff suppressed because it is too large Load Diff
+59 -1
View File
@@ -7,7 +7,7 @@ fn filter_blanks_include_empty_text_and_formula_results() {
s.execute("range.setValues", json!({"range": "A1", "values": [["id", "f"], ["e", null], ["ef", "=\"\""], ["sp", " "], ["z", 0]]})).unwrap();
s.execute("data.filter", json!({"range": "A1:B5"})).unwrap();
let r = s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap();
assert_eq!(r["hiddenRows"], json!(2));
assert_eq!(r["hiddenRows"], json!(1));
let vals = filter_values(&s.doc().unwrap().wb, 0, 1);
// The `=""` result joins (Blanks) instead of showing as its own empty entry.
assert!(!vals.iter().any(|(t, _)| t.is_empty()), "{vals:?}");
@@ -557,6 +557,64 @@ fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() {
assert_eq!(sh.validations.len(), 3);
assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some());
}
/// Excel AutoFilter ignores surrounding spaces when matching text values.
#[test]
fn autofilter_value_lists_and_equality_ignore_surrounding_spaces() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
["Card"],
["Card "],
[" Card"],
[" Card "],
["card"],
["CARD"],
["Cardx"],
["Ca rd"],
[" "],
[""]
]
}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:A11"})).unwrap();
let assert_rows = |session: &Session| {
let sh = session.doc().unwrap().wb.active().unwrap();
for row in 1..=6 {
assert!(!sh.is_row_hidden(row), "row {row} should be visible");
}
for row in 7..=10 {
assert!(sh.is_row_hidden(row), "row {row} should be hidden");
}
};
for value in ["Card", " Card"] {
let result = s.execute("data.filterBy", json!({"column": "A", "values": [value]})).unwrap();
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
assert_rows(&s);
let choices = filter_values(&s.doc().unwrap().wb, 0, 0);
let card_entries: Vec<_> = choices.iter().filter(|(text, _)| text.trim().eq_ignore_ascii_case("Card")).collect();
assert_eq!(card_entries.len(), 1, "{choices:?}");
assert!(card_entries[0].1, "{choices:?}");
assert!(!choices.iter().any(|(text, _)| text.trim().is_empty()), "{choices:?}");
assert_eq!(choices.iter().filter(|(text, _)| text == "(Blanks)").count(), 1, "{choices:?}");
assert!(choices.iter().any(|(text, on)| text == "(Blanks)" && !on), "{choices:?}");
}
for value in ["Card", " Card"] {
let result = s.execute("data.filterBy", json!({"column": "A", "custom": {"op": "=", "value": value}})).unwrap();
assert_eq!(result["hiddenRows"], json!(4));
assert_rows(&s);
}
}
fn finds(item: &str, typed: &str) -> bool {
search_matches(&search_fold(item), &search_term(typed))
+34 -18
View File
@@ -51,12 +51,11 @@ pub fn column_values(wb: &Workbook, sheet: usize, table: &str, column: &str) ->
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for row in dr.start.row..=dr.end.row {
let text = crate::display::cell_text(wb, sh, CellRef::new(row, col));
if text.is_empty() {
let Some(tile) = super::data::slicer_tile_text(wb, sh, CellRef::new(row, col)) else {
continue;
}
if seen.insert(text.to_lowercase()) {
out.push(text);
};
if seen.insert(tile.to_lowercase()) {
out.push(tile);
}
}
out
@@ -70,7 +69,7 @@ pub fn slicer_items(wb: &Workbook, sheet: usize, sl: &Slicer) -> Vec<(String, bo
.map(|v| {
let on = match &sl.selected {
None => true,
Some(set) => set.iter().any(|x| x.eq_ignore_ascii_case(&v)),
Some(set) => set.iter().any(|x| x.trim().to_lowercase() == v.trim().to_lowercase()),
};
(v, on)
})
@@ -92,7 +91,8 @@ fn reapply_slicer(wb: &mut Workbook, sheet: usize, id: u32) {
let off = abs_col.saturating_sub(af.range.start.col);
af.criteria.retain(|(o, _)| *o != off);
if let Some(values) = selected {
af.criteria.push((off, FilterCriterion::Values { values, blanks: false }));
let identities = values.iter().map(|v| super::data::slicer_identity_token(v)).collect();
af.criteria.push((off, FilterCriterion::Values { values, blanks: false, identities }));
}
}
super::data::apply_filter(wb, sheet);
@@ -174,24 +174,40 @@ fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
(sl.table.clone(), sl.column.clone(), sl.selected.clone())
};
let all = column_values(&s.doc()?.wb, sheet, &table, &column);
if !all.iter().any(|v| v.eq_ignore_ascii_case(&value)) {
let trimmed_val = value.trim();
if !all.iter().any(|v| v.trim().to_lowercase() == trimmed_val.to_lowercase()) {
return Err(bad("slicer.toggle", "value is not in the column"));
}
let new_selected: Option<Vec<String>> = if multi {
let mut set: Vec<String> = current.unwrap_or_else(|| all.clone());
match set.iter().position(|x| x.eq_ignore_ascii_case(&value)) {
Some(pos) => {
set.remove(pos);
let dedup_tiles = |items: Vec<String>| -> Vec<String> {
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for item in items {
let t = item.trim();
if !t.is_empty() && seen.insert(t.to_lowercase()) {
out.push(t.to_string());
}
None => set.push(value.clone()),
}
out
};
let normalized_current = current.map(dedup_tiles);
let new_selected: Option<Vec<String>> = if multi {
let mut set: Vec<String> = normalized_current.unwrap_or_else(|| all.clone());
let before = set.len();
set.retain(|x| x.trim().to_lowercase() != trimmed_val.to_lowercase());
if set.len() == before {
set.push(trimmed_val.to_string());
}
// Everything selected is the same as no filter.
if set.len() == all.len() && all.iter().all(|a| set.iter().any(|x| x.eq_ignore_ascii_case(a))) { None } else { Some(set) }
if set.len() == all.len() && all.iter().all(|a| set.iter().any(|x| x.trim().to_lowercase() == a.trim().to_lowercase())) {
None
} else {
Some(set)
}
} else {
// Single click: show only this value; clicking the sole selected value clears the filter.
match &current {
Some(set) if set.len() == 1 && set.iter().any(|x| x.eq_ignore_ascii_case(&value)) => None,
_ => Some(vec![value.clone()]),
match &normalized_current {
Some(set) if set.len() == 1 && set.iter().any(|x| x.trim().to_lowercase() == trimmed_val.to_lowercase()) => None,
_ => Some(vec![trimmed_val.to_string()]),
}
};
edit(s, |cx| {
+1
View File
@@ -148,6 +148,7 @@ fn open_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
crate::cmd::controls::load_action_names(&mut wb);
warnings.extend(adopt_python(&mut wb));
warnings.extend(enforce_python_limits(&mut wb));
crate::cmd::data::migrate_loaded_autofilters(&mut wb);
Ok((wb, warnings))
}
@@ -198,7 +198,8 @@ fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() {
s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap();
s.execute("data.filter", json!({"range": "A1:B6"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true)]);
// Excel AutoFilter's (Blanks) group also matches whitespace-only text (#2911).
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true), ("spaces".into(), true)]);
for value in ["12", "12.00"] {
s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]);
@@ -249,7 +250,8 @@ fn duplicate_color_choices_keep_any_eligible_match() {
s.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) };
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.autofilter.as_mut().unwrap().criteria = vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }), (1, color)];
sh.autofilter.as_mut().unwrap().criteria =
vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] }), (1, color)];
s.execute("data.reapply", json!({})).unwrap();
assert_eq!(
filter_values(&s.doc().unwrap().wb, 0, 1),
@@ -290,7 +292,7 @@ fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria
let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap();
let sh = reopened.active().unwrap();
let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria };
assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })]);
assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })]);
assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5));
}
}
@@ -304,7 +306,7 @@ fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() {
s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap();
s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap();
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false })];
sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false, identities: vec![] })];
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
s.execute("data.filter", json!({"range": "B3:C6"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
@@ -395,7 +397,7 @@ fn merging_hidden_choices_preserves_the_active_criterion() {
}
#[test]
fn large_values_criteria_preserve_ascii_case_and_blank_matching() {
fn large_values_criteria_preserve_unicode_case_and_blank_matching() {
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::model::AutoFilter;
let mut s = Session::new();
@@ -409,8 +411,8 @@ fn large_values_criteria_preserve_ascii_case_and_blank_matching() {
}
selected.extend(["ITEM-1".into(), "Ä".into()]);
for (row, value, label) in [
(5_001, Value::Text("Ä".into()), "unicode selected"),
(5_002, Value::Text("ä".into()), "unicode excluded"),
(5_001, Value::Text("Ä".into()), "unicode exact"),
(5_002, Value::Text("ä".into()), "unicode case folded"),
(5_003, Value::Empty, "blank row"),
] {
sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() });
@@ -418,10 +420,10 @@ fn large_values_criteria_preserve_ascii_case_and_blank_matching() {
}
sh.autofilter = Some(AutoFilter {
range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)),
criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })],
criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true, identities: vec![] })],
});
let choices = filter_values(&s.doc().unwrap().wb, 0, 1);
let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect();
expected.extend([("blank row".into(), true), ("unicode selected".into(), true)]);
expected.extend([("blank row".into(), true), ("unicode case folded".into(), true), ("unicode exact".into(), true)]);
assert_eq!(choices, expected);
}
+715
View File
@@ -0,0 +1,715 @@
use gridcraft_engine::Session;
use serde_json::json;
/// Value-list and equality criteria ignore leading and trailing spaces (#2911).
#[test]
fn autofilter_ignores_surrounding_spaces_2911() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
["Card"],
["Card "],
[" Card"],
[" Card "],
["card"],
["CARD"],
["Cardx"],
["Ca rd"],
[" "],
[""]
]
}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:A11"})).unwrap();
for value in ["Card", " Card", "Card "] {
let result = s.execute("data.filterBy", json!({"column": "A", "values": [value]})).unwrap();
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=6 {
assert!(!sh.is_row_hidden(row), "row {row} should be visible for {value:?}");
}
for row in 7..=10 {
assert!(sh.is_row_hidden(row), "row {row} should be hidden for {value:?}");
}
}
for value in ["Card", " Card", "Card "] {
let result = s
.execute(
"data.filterBy",
json!({
"column": "A",
"custom": {"op": "=", "value": value}
}),
)
.unwrap();
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=6 {
assert!(!sh.is_row_hidden(row), "{value:?}: row {row}");
}
for row in 7..=10 {
assert!(sh.is_row_hidden(row), "{value:?}: row {row}");
}
}
}
/// Wildcard custom equality trims surrounding spaces before matching (#2911).
#[test]
fn filter_whitespace_wildcard_2911() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range":"A1", "parse":false,
"values":[["Name"], [" Card "], ["Cardx"], ["Other"]]}),
)
.unwrap();
s.execute("data.filter", json!({"range":"A1:A4"})).unwrap();
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"=", "value":"Card*"}})).unwrap();
assert_eq!(r["hiddenRows"], json!(1));
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1));
assert!(!sh.is_row_hidden(2));
assert!(sh.is_row_hidden(3));
}
/// Custom `=` with spaces matches empty and whitespace-only cells as in Excel (#2911).
#[test]
fn filter_whitespace_custom_blank_distinction_2911() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range":"A1", "parse":false,
"values":[["Name"], [null], [""], [" "], [" "], ["Card"]]}),
)
.unwrap();
s.execute("data.filter", json!({"range":"A1:A6"})).unwrap();
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"=", "value":" "}})).unwrap();
assert_eq!(r["hiddenRows"], json!(1));
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=4 {
assert!(!sh.is_row_hidden(row), "row {row} should be visible");
}
assert!(sh.is_row_hidden(5));
}
/// Custom `<>` trims surrounding spaces before excluding matching text (#2911).
#[test]
fn filter_whitespace_custom_not_equal_2911() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range":"A1", "parse":false,
"values":[["Name"], [" Card "], ["Card"], ["Other"]]}),
)
.unwrap();
s.execute("data.filter", json!({"range":"A1:A4"})).unwrap();
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"<>", "value":"Card"}})).unwrap();
assert_eq!(r["hiddenRows"], json!(2));
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(sh.is_row_hidden(1));
assert!(sh.is_row_hidden(2));
assert!(!sh.is_row_hidden(3));
}
/// Empty and whitespace-only custom `=` and `<>` criteria match Excel Desktop behavior (#2911).
#[test]
fn filter_whitespace_empty_criteria_regression_2911() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
[null],
[""],
[" "],
[" "],
["Card"]
]
}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:A6"})).unwrap();
for (op, criterion, expected_visible) in [("=", "", vec![1, 2, 3, 4]), ("=", " ", vec![1, 2, 3, 4]), ("<>", "", vec![5]), ("<>", " ", vec![5])] {
s.execute(
"data.filterBy",
json!({
"column": "A",
"custom": {
"op": op,
"value": criterion
}
}),
)
.unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
let visible: Vec<_> = (1..=5).filter(|&row| !sh.is_row_hidden(row)).collect();
assert_eq!(visible, expected_visible, "op={op:?}, criterion={criterion:?}");
}
}
/// Selecting `(Blanks)` in the AutoFilter dropdown includes whitespace-only text cells (#2943).
#[test]
fn filter_whitespace_dropdown_blanks_excel_2943() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
[null],
[""],
[" "],
[" "],
["Card"]
]
}),
)
.unwrap();
s.execute("data.filter", json!({"range":"A1:A6"})).unwrap();
let result = s
.execute(
"data.filterBy",
json!({
"column": "A",
"values": [],
"blanks": true
}),
)
.unwrap();
assert_eq!(result["hiddenRows"], json!(1));
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=4 {
assert!(!sh.is_row_hidden(row), "Excel (Blanks) should include row {row}");
}
assert!(sh.is_row_hidden(5));
}
/// Filtering by a selected whitespace-only cell (`values: [" "]` with `blanks` omitted) keeps blank rows visible (#2943).
#[test]
fn filter_by_selected_whitespace_cell_keeps_blanks_visible_2943() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
[null],
[""],
[" "],
[" "],
["Card"]
]
}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:A6"})).unwrap();
// Simulates "Filter by Selected Cell's Value" (`values: [text]`, no `blanks` key).
let result = s.execute("data.filterBy", json!({"column": "A", "values": [" "]})).unwrap();
assert_eq!(result["hiddenRows"], json!(1));
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=4 {
assert!(!sh.is_row_hidden(row), "whitespace/blank row {row} must stay visible");
}
assert!(sh.is_row_hidden(5));
// Explicit `blanks: false` from the dropdown overrides whitespace inference and hides blank/whitespace rows.
let result = s.execute("data.filterBy", json!({"column": "A", "values": ["Card", " "], "blanks": false})).unwrap();
assert_eq!(result["hiddenRows"], json!(4));
let sh = s.doc().unwrap().wb.active().unwrap();
for row in 1..=4 {
assert!(sh.is_row_hidden(row), "row {row} should be hidden when blanks: false");
}
assert!(!sh.is_row_hidden(5));
}
/// Legacy saved criteria with whitespace-only `<filter val=" "/>` and `blanks: false` migrate on load and update row visibility immediately (#2943).
#[test]
fn restored_whitespace_only_criterion_keeps_rows_visible_on_reapply_2943() {
use gridcraft_engine::cmd::data::{filter_choices, filter_choices_params};
use gridcraft_model::{AutoFilter, FilterCriterion};
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Name"],
[null],
[" "],
["Card"]
]
}),
)
.unwrap();
// Simulate a legacy saved workbook whose filter stored `values: [" "]` with `blanks: false`,
// and where the genuinely empty row (row 1 = A2) was hidden by the pre-fix blank branch.
{
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
sh.autofilter = Some(AutoFilter {
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
});
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(3).or_default().hidden = true;
}
// 1. XLSX save + reopen migrates `<filter val=" "/>` AND reapplies immediately on open so
// the genuinely empty row A2 is visible before any user `data.reapply` command.
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
let (reopened, _) = gridcraft_engine::io::open_bytes("legacy_filter.xlsx", &bytes).unwrap();
{
let sh = reopened.sheet(0).unwrap();
assert!(!sh.is_row_hidden(1), "genuinely empty row must be visible immediately on open");
assert!(!sh.is_row_hidden(2), "whitespace-only row must be visible immediately on open");
assert!(sh.is_row_hidden(3), "non-matching row must remain hidden on open");
}
s.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
// 2. Direct in-memory legacy criterion (`blanks: false`, `values: [" "]`) also keeps blank rows visible on reapply.
{
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
wb.sheet_mut(0).unwrap().autofilter = Some(AutoFilter {
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
});
}
s.execute("data.reapply", json!({})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "in-memory legacy empty row must stay visible after reapply");
assert!(!sh.is_row_hidden(2), "in-memory legacy whitespace-only row must stay visible after reapply");
assert!(sh.is_row_hidden(3), "non-matching row must be hidden after reapply");
// 3. Verify Show Formulas mode: distinct qualified labels, preserved checklist identity on Apply,
// single label for ordinary whitespace variants, and literal `(Blanks)` vs `'(Blanks)'` separation.
let mut s2 = Session::new();
s2.new_workbook();
s2.execute("cell.set", json!({"cell": "A1", "input": "Name"})).unwrap();
s2.execute("cell.set", json!({"cell": "A2", "input": "=\" Card \""})).unwrap();
s2.execute(
"range.setValues",
json!({
"range": "A3",
"parse": false,
"values": [[" =\" Card \" "], ["Card"], [" Card "], ["(Blanks)"], ["'(Blanks)'"], [" "]]
}),
)
.unwrap();
s2.execute("formulas.showFormulas", json!({"on": true})).unwrap();
// With no active criterion, ordinary whitespace variants `"Card"` and `" Card "` merge into one `"Card"` label,
// while formula `=" Card "` and literal `" =\" Card \" "` have distinct qualified labels.
s2.execute("data.filter", json!({"range": "A1:A8"})).unwrap();
let initial_choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
assert_eq!(initial_choices.iter().filter(|c| c.label == "Card").count(), 1, "{initial_choices:?}");
let formula_like_labels: Vec<_> = initial_choices.iter().filter(|c| c.label.starts_with("=\" Card \"")).map(|c| c.label.as_str()).collect();
assert_eq!(formula_like_labels.len(), 2, "{initial_choices:?}");
assert_ne!(formula_like_labels[0], formula_like_labels[1], "colliding identities must have distinct labels: {initial_choices:?}");
// Filtering by `"Card"` checks `"Card"` and formula `=" Card "`, leaving literal `" =\" Card \" "` unchecked.
s2.execute("data.filterBy", json!({"column": "A", "values": ["Card"], "blanks": false})).unwrap();
let choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
let formula_entry = choices.iter().find(|c| c.label == "=\" Card \" (result: Card)").expect("formula choice");
let literal_entry = choices.iter().find(|c| c.label == "=\" Card \" (text)").expect("literal choice");
assert!(formula_entry.checked, "{choices:?}");
assert!(!literal_entry.checked, "{choices:?}");
// Clicking Apply without changing the checks keeps the literal `" =\" Card \" "` row hidden.
let unchanged_checks: Vec<_> = choices.iter().map(|c| (c, c.checked)).collect();
s2.execute("data.filterBy", filter_choices_params("A", &unchanged_checks)).unwrap();
let sh2 = s2.doc().unwrap().wb.active().unwrap();
assert!(!sh2.is_row_hidden(1), "formula row A2 stays visible");
assert!(sh2.is_row_hidden(2), "literal row A3 stays hidden");
assert!(!sh2.is_row_hidden(3), "Card row A4 stays visible");
assert!(!sh2.is_row_hidden(4), "whitespace Card row A5 stays visible");
// Selecting ONLY the formula checkbox leaves the literal row hidden (and vice versa).
let only_formula: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (result: Card)")).collect();
s2.execute("data.filterBy", filter_choices_params("A", &only_formula)).unwrap();
let sh2 = s2.doc().unwrap().wb.active().unwrap();
assert!(!sh2.is_row_hidden(1), "formula row A2 visible");
assert!(sh2.is_row_hidden(2), "literal row A3 hidden");
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
let only_literal: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (text)")).collect();
s2.execute("data.filterBy", filter_choices_params("A", &only_literal)).unwrap();
let sh2 = s2.doc().unwrap().wb.active().unwrap();
assert!(sh2.is_row_hidden(1), "formula row A2 hidden");
assert!(!sh2.is_row_hidden(2), "literal row A3 visible");
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
// Literal `(Blanks)`, literal `'(Blanks)'`, and the actual `(Blanks)` toggle all have distinct labels and values.
assert!(choices.iter().any(|c| c.label == "(Blanks)" && c.value.is_none() && c.identity.is_none()), "{choices:?}");
assert!(choices.iter().any(|c| c.label == "'(Blanks)'" && c.value.as_deref() == Some("(Blanks)")), "{choices:?}");
assert!(choices.iter().any(|c| c.label == "''(Blanks)''" && c.value.as_deref() == Some("'(Blanks)'")), "{choices:?}");
}
/// Nonblank cells formatted to display only spaces stay selectable in both dropdown and selected-cell actions (#2943).
#[test]
fn nonblank_space_formatted_cells_stay_selectable_2943() {
use gridcraft_core::CellRef;
use gridcraft_engine::cmd::data::{filter_by_cell_params, filter_choices, filter_choices_params};
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
s.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [[null], [" "], ["Card"]]})).unwrap();
s.execute("data.filter", json!({"range": "A1:A5"})).unwrap();
// 1. Dropdown checklist: selecting only the space-formatted `42` entry keeps row A2 visible and hides blanks.
let choices = filter_choices(&s.doc().unwrap().wb, 0, 0);
let num_choice = choices.iter().find(|c| c.value.as_deref() == Some("42")).expect("numeric 42 choice");
assert_eq!(num_choice.label, "42");
let only_42: Vec<_> = choices.iter().map(|c| (c, c.value.as_deref() == Some("42"))).collect();
s.execute("data.filterBy", filter_choices_params("A", &only_42)).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "space-formatted 42 row A2 must stay visible");
assert!(sh.is_row_hidden(2), "empty row A3 must be hidden");
assert!(sh.is_row_hidden(3), "whitespace text row A4 must be hidden");
assert!(sh.is_row_hidden(4), "Card row A5 must be hidden");
// 2. Selected-cell action (`filter_by_cell_params`): on A2 (`42` formatted as `" "`) selects `42`, not blanks;
// on A4 (`" "` text) selects blanks, not `42`.
s.execute("data.clearFilter", json!({})).unwrap();
let params_a2 = {
let d = s.doc().unwrap();
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A2").unwrap(), "A")
};
s.execute("data.filterBy", params_a2).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "A2 selected-cell filter keeps 42 visible");
assert!(sh.is_row_hidden(2), "A2 selected-cell filter hides empty row");
assert!(sh.is_row_hidden(3), "A2 selected-cell filter hides whitespace text row");
let params_a4 = {
let d = s.doc().unwrap();
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A4").unwrap(), "A")
};
s.execute("data.filterBy", params_a4).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(sh.is_row_hidden(1), "A4 selected-cell filter hides 42");
assert!(!sh.is_row_hidden(2), "A4 selected-cell filter keeps empty row visible");
assert!(!sh.is_row_hidden(3), "A4 selected-cell filter keeps whitespace text row visible");
// 3. Formatted-blank number `42` vs formatted-blank text `"42"` (`;;;`) keep distinct qualified labels,
// and a >11-digit General number (`1234567890123`) keeps its checklist identity across Show Formulas toggles.
let mut s3 = Session::new();
s3.new_workbook();
s3.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
s3.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
s3.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
s3.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["42"]]})).unwrap();
s3.execute("home.numberFormat", json!({"range": "A3", "format": ";;;"})).unwrap();
s3.execute("cell.set", json!({"cell": "A4", "input": "1234567890123"})).unwrap();
s3.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
let c3 = filter_choices(&s3.doc().unwrap().wb, 0, 0);
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, number)"), "{c3:?}");
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, text)"), "{c3:?}");
let only_big: Vec<_> = c3.iter().map(|c| (c, c.value.as_deref() == Some("1.23457E+12"))).collect();
s3.execute("data.filterBy", filter_choices_params("A", &only_big)).unwrap();
s3.execute("formulas.showFormulas", json!({"on": true})).unwrap();
s3.execute("data.reapply", json!({})).unwrap();
assert!(!s3.doc().unwrap().wb.active().unwrap().is_row_hidden(3), "1234567890123 stays visible across Show Formulas toggle");
}
/// Checklist selections survive number-format changes, Show Formulas toggles, and XLSX save/reopen (#2943).
#[test]
fn checklist_identity_survives_format_change_show_formulas_and_xlsx_2943() {
use gridcraft_engine::cmd::data::{filter_choices, filter_choices_params};
// 1. Numeric `42` selected under General stays selected after formatting as `" "` and running `data.reapply`,
// without matching literal text `"42"`.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["42"], ["Other"]]})).unwrap();
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
let c1 = filter_choices(&s.doc().unwrap().wb, 0, 0);
let only_num: Vec<_> = c1.iter().map(|c| (c, c.label == "42 (number)")).collect();
s.execute("data.filterBy", filter_choices_params("A", &only_num)).unwrap();
s.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
s.execute("data.reapply", json!({})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "numeric 42 must stay visible after formatting as space");
assert!(sh.is_row_hidden(2), "literal text '42' must stay hidden");
assert!(sh.is_row_hidden(3), "Other row must stay hidden");
// 2. Show Formulas ON -> select only formula `="Card"` -> turn Show Formulas OFF ->
// checklist keeps `="Card"` checked and `"Card"`/`" Card "` merged & unchecked -> Apply keeps literal hidden.
let mut sf = Session::new();
sf.new_workbook();
sf.execute("cell.set", json!({"cell": "A1", "input": "Name"})).unwrap();
sf.execute("cell.set", json!({"cell": "A2", "input": "=\" Card \""})).unwrap();
sf.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["Card"], [" Card "], ["Other"]]})).unwrap();
sf.execute("formulas.showFormulas", json!({"on": true})).unwrap();
sf.execute("data.filter", json!({"range": "A1:A5"})).unwrap();
let on_choices = filter_choices(&sf.doc().unwrap().wb, 0, 0);
let only_formula: Vec<_> = on_choices.iter().map(|c| (c, c.label.starts_with("=\" Card \""))).collect();
sf.execute("data.filterBy", filter_choices_params("A", &only_formula)).unwrap();
// Save + reopen XLSX while formula identity is active, then `data.reapply` must still hide literal `"Card"`.
let bytes = gridcraft_xlsx::write_xlsx(&sf.doc().unwrap().wb).unwrap();
let (reopened, _) = gridcraft_engine::io::open_bytes("formula_identity.xlsx", &bytes).unwrap();
sf.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
sf.execute("data.reapply", json!({})).unwrap();
{
let sh = sf.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "formula row A2 stays visible after XLSX reopen + reapply");
assert!(sh.is_row_hidden(2), "literal Card row A3 stays hidden after XLSX reopen + reapply");
assert!(sh.is_row_hidden(3), "whitespace Card row A4 stays hidden after XLSX reopen + reapply");
}
// Turn Show Formulas OFF: dropdown keeps formula `=" Card "` checked and literal `"Card"` + `" Card "` merged & unchecked.
sf.execute("formulas.showFormulas", json!({"on": false})).unwrap();
let off_choices = filter_choices(&sf.doc().unwrap().wb, 0, 0);
assert_eq!(off_choices.len(), 3, "expected formula Card, merged literal Card, and Other: {off_choices:?}");
assert_eq!(off_choices.iter().filter(|c| c.checked).count(), 1, "{off_choices:?}");
let unchanged_off: Vec<_> = off_choices.iter().map(|c| (c, c.checked)).collect();
sf.execute("data.filterBy", filter_choices_params("A", &unchanged_off)).unwrap();
let sh = sf.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "formula row A2 stays visible after Apply with Show Formulas off");
assert!(sh.is_row_hidden(2), "literal Card row A3 stays hidden after Apply with Show Formulas off");
assert!(sh.is_row_hidden(3), "whitespace Card row A4 stays hidden after Apply with Show Formulas off");
assert!(sh.is_row_hidden(4), "Other row A5 stays hidden");
}
/// Migration preserves manually hidden rows and respects sibling side-by-side table filters (#2943).
#[test]
fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
use gridcraft_core::RangeRef;
use gridcraft_model::{AutoFilter, FilterCriterion, Table, TableColumn, TotalsFn};
// 1. Manually hidden `"Card"` row stays hidden when `[" ", "Card"]` migrates on open,
// while genuinely empty row excluded by old filter becomes visible.
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [["Name"], [null], ["Card"], ["Card"], ["Other"]]
}),
)
.unwrap();
{
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
sh.autofilter = Some(AutoFilter {
range: RangeRef::parse("A1:A5").unwrap(),
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into(), "Card".into()], blanks: false, identities: vec![] })],
});
// Row 1 (A2 = null) was hidden by old blank branch; Row 2 (A3 = "Card") was hidden manually;
// Row 3 (A4 = "Card") is visible; Row 4 (A5 = "Other") was hidden by filter.
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(2).or_default().hidden = true;
sh.rows.entry(4).or_default().hidden = true;
}
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
let (reopened, _) = gridcraft_engine::io::open_bytes("manual_hidden.xlsx", &bytes).unwrap();
let sh = reopened.sheet(0).unwrap();
assert!(!sh.is_row_hidden(1), "empty row A2 excluded by old filter becomes visible");
assert!(sh.is_row_hidden(2), "manually hidden matching Card row A3 must remain hidden");
assert!(!sh.is_row_hidden(3), "visible Card row A4 remains visible");
assert!(sh.is_row_hidden(4), "non-matching Other row A5 remains hidden");
// 2. Two side-by-side tables sharing worksheet rows: migrating Table1 must not unhide a row excluded by Table2.
let mut st = Session::new();
st.new_workbook();
st.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [
["Item", "Region"],
[null, "West"],
[null, "East"],
["Card", "East"]
]
}),
)
.unwrap();
{
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
let col =
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
sh.tables.push(Table {
id: 1,
name: "LeftTable".into(),
range: RangeRef::parse("A1:A4").unwrap(),
header_row: true,
totals_row: false,
columns: vec![col("Item")],
style: "TableStyleMedium2".into(),
banded_rows: true,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: true,
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
});
sh.tables.push(Table {
id: 2,
name: "RightTable".into(),
range: RangeRef::parse("B1:B4").unwrap(),
header_row: true,
totals_row: false,
columns: vec![col("Region")],
style: "TableStyleMedium2".into(),
banded_rows: true,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: true,
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
});
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(2).or_default().hidden = true;
sh.rows.entry(3).or_default().hidden = true;
}
let tbytes = gridcraft_xlsx::write_xlsx(&st.doc().unwrap().wb).unwrap();
let (treopened, _) = gridcraft_engine::io::open_bytes("two_tables.xlsx", &tbytes).unwrap();
let tsh = treopened.sheet(0).unwrap();
assert!(tsh.is_row_hidden(1), "row 1 (West) is still excluded by RightTable and must stay hidden");
assert!(!tsh.is_row_hidden(2), "row 2 (empty + East) passes both tables after migration and becomes visible");
assert!(tsh.is_row_hidden(3), "row 3 (Card + East) is excluded by LeftTable blanks filter and stays hidden");
}
/// Table slicers merge surrounding-whitespace variants into a single tile (#2943).
#[test]
fn slicer_groups_whitespace_variants_into_single_tile_2943() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [["Name"], [" Card "], ["Card"], ["Other"], [" "]]
}),
)
.unwrap();
s.execute("insert.table", json!({"range": "A1:A5", "name": "Items"})).unwrap();
let res = s.execute("insert.slicer", json!({"table": "Items", "column": "Name"})).unwrap();
let id = res["slicer"].as_u64().unwrap() as u32;
let wb = &s.doc().unwrap().wb;
let sl = wb.active().unwrap().slicers.iter().find(|x| x.id == id).unwrap();
let tiles = gridcraft_engine::cmd::slicer::slicer_items(wb, 0, sl);
assert_eq!(tiles, vec![("Card".to_string(), true), ("Other".to_string(), true)]);
s.execute("slicer.toggle", json!({"slicer": id, "value": "Card"})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "' Card ' row stays visible");
assert!(!sh.is_row_hidden(2), "'Card' row stays visible");
assert!(sh.is_row_hidden(3), "'Other' row hidden");
assert!(sh.is_row_hidden(4), "whitespace-only row hidden");
}
/// Table slicers merge non-ASCII Unicode case variants into a single tile and keep both visible (#2943).
#[test]
fn slicer_groups_unicode_case_variants_into_single_tile_2943() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({
"range": "A1",
"parse": false,
"values": [["School"], ["ÉCOLE"], ["école"], ["autre"]]
}),
)
.unwrap();
s.execute("insert.table", json!({"range": "A1:A4", "name": "Schools"})).unwrap();
let res = s.execute("insert.slicer", json!({"table": "Schools", "column": "School"})).unwrap();
let id = res["slicer"].as_u64().unwrap() as u32;
let wb = &s.doc().unwrap().wb;
let sl = wb.active().unwrap().slicers.iter().find(|x| x.id == id).unwrap();
let tiles = gridcraft_engine::cmd::slicer::slicer_items(wb, 0, sl);
// Unicode case variants 'ÉCOLE' and 'école' must share one tile.
assert_eq!(tiles.len(), 2, "must produce 2 tiles: ÉCOLE and autre, but was {tiles:?}");
assert!(tiles.iter().any(|(t, on)| (t == "ÉCOLE" || t == "école") && *on));
assert!(tiles.iter().any(|(t, on)| t == "autre" && *on));
// Selecting the shared tile keeps both 'ÉCOLE' and 'école' visible.
let tile_name = tiles.iter().find(|(t, _)| t == "ÉCOLE" || t == "école").unwrap().0.clone();
s.execute("slicer.toggle", json!({"slicer": id, "value": tile_name})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "ÉCOLE row stays visible");
assert!(!sh.is_row_hidden(2), "école row stays visible");
assert!(sh.is_row_hidden(3), "autre row hidden");
}
+1
View File
@@ -14,6 +14,7 @@ mod custom_filter_blanks;
mod custom_view_freeze;
mod dynamicmetadata;
mod extreme_selection_moves;
mod filter_whitespace;
mod font_scheme_minor;
mod format_as_table_restyle;
mod hidden_sheet_navigation;
+4
View File
@@ -1315,6 +1315,10 @@ pub enum FilterCriterion {
Values {
values: Vec<String>,
blanks: bool,
/// Exact checklist identities from dropdown or selected-cell UI actions so rows whose
/// formatted display text collides (for example under Show Formulas) stay distinct.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
identities: Vec<String>,
},
/// Custom: one or two comparisons (`op` like `>=`, `=*abc*`), joined by and/or.
Custom {
+9 -1
View File
@@ -249,10 +249,18 @@ impl SheetApp {
self.perf.grid_ms = now_ms() - g0;
});
}
// An existing message owns Enter/Escape before the underlying dialog.
// A newly created message is still shown in the same frame (#2189).
let had_message = self.message.is_some();
if had_message {
widgets::message_box(self, &ctx);
}
dialogs::show(self, &ctx);
macro_ui::forget_closed_editor(self);
macro_ui::question_box(self, &ctx);
widgets::message_box(self, &ctx);
if !had_message {
widgets::message_box(self, &ctx);
}
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
+4 -1
View File
@@ -537,6 +537,7 @@ pub(super) fn open_confirmed_link(app: &mut SheetApp, d: &Dialog) -> Result<(),
r
}
/// Draws the standard OK and Cancel button row, consuming unmodified Enter on confirmation (#2189).
pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool) {
ok_cancel_enabled(ui, confirm, open, true);
}
@@ -552,7 +553,9 @@ pub(super) fn ok_cancel_enabled(ui: &mut egui::Ui, confirm: &mut bool, open: &mu
let t = crate::theme::Tokens::get(ui.ctx());
let ok =
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
if enabled && (ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter))) {
// Consume Enter so a newly opened error message cannot dismiss itself (#2189).
let enter = enabled && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter));
if enabled && (ok.clicked() || enter) {
*confirm = true;
}
if ui.button(format!(" {} ", lang.tr("Cancel"))).clicked() {
+1 -1
View File
@@ -328,7 +328,7 @@ pub struct GridState {
/// Column and row of the clicked header cell, and where to open the menu.
pub filter_menu: Option<(u32, u32, Pos2)>,
/// Pending popup edits travel with this window and are dropped when its menu or window closes.
pub filter_checks: Option<Vec<(String, bool)>>,
pub filter_checks: Option<Vec<gridcraft_engine::cmd::data::FilterChoice>>,
pub filter_search: String,
pub filter_buttons: Vec<egui::Id>,
pub context_menu: Option<Pos2>,
+26 -20
View File
@@ -52,7 +52,7 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
}
ui.separator();
ui.label(egui::RichText::new("Filter").strong());
let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col));
let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_choices(&wb, si, col));
// A search narrows the list; Select All and Apply then only cover the matches.
let mut search = app.grid.filter_search.clone();
let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY));
@@ -61,24 +61,31 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
}
let needle = search.trim().to_lowercase();
let matches = |v: &str| needle.is_empty() || v.to_lowercase().contains(&needle);
let all = checks.iter().filter(|(v, _)| matches(v)).all(|(_, b)| *b);
let all = checks.iter().filter(|c| matches(&c.label)).all(|c| c.checked);
let mut all_new = all;
let label = if needle.is_empty() { "(Select All)" } else { "(Select All Search Results)" };
if ui.checkbox(&mut all_new, label).changed() {
for c in checks.iter_mut().filter(|(v, _)| matches(v)) {
c.1 = all_new;
for c in checks.iter_mut().filter(|c| matches(&c.label)) {
c.checked = all_new;
}
}
// Full width: shrunk to the longest value, the scroll bar sat mid-menu and the wheel only
// worked over the values themselves (#432).
egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, true]).show(ui, |ui| {
for (v, on) in checks.iter_mut().filter(|(v, _)| matches(v)) {
ui.checkbox(on, v.as_str());
for c in checks.iter_mut().filter(|c| matches(&c.label)) {
ui.checkbox(&mut c.checked, c.label.as_str());
}
});
app.grid.filter_checks = Some(checks.clone());
app.grid.filter_search.clone_from(&search);
let checks: Vec<(String, bool)> = checks.iter().map(|(v, on)| (v.clone(), *on && matches(v))).collect();
let visible_checks: Vec<gridcraft_engine::cmd::data::FilterChoice> = checks
.iter()
.cloned()
.map(|mut c| {
c.checked &= matches(&c.label);
c
})
.collect();
ui.separator();
ui.horizontal(|ui| {
let clear = ui.button("Clear Filter");
@@ -87,21 +94,16 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
close = true;
}
// Nothing checked would hide every row, so Enter (unlike a click on Apply) does nothing then.
let any = checks.iter().any(|(_, on)| *on);
let any = visible_checks.iter().any(|c| c.checked);
let apply = ui.button("Apply");
app.grid.filter_buttons = vec![ascending.id, descending.id, clear.id, apply.id];
if apply.clicked() || (enter && any) {
let mut checks = gridcraft_engine::cmd::data::filter_selection(&wb, si, col, &checks);
for (value, on) in &mut checks {
*on &= matches(value);
let mut merged = gridcraft_engine::cmd::data::filter_choices_selection(&wb, si, col, &visible_checks);
for c in &mut merged {
c.checked &= matches(&c.label);
}
let blanks = checks.iter().any(|(v, on)| v == "(Blanks)" && *on);
let vals: Vec<String> = checks.iter().filter(|(v, on)| *on && v != "(Blanks)").map(|(v, _)| v.clone()).collect();
let p = if checks.iter().all(|(_, b)| *b) {
json!({"column": col_to_letters(col), "clear": true})
} else {
json!({"column": col_to_letters(col), "values": vals, "blanks": blanks})
};
let active_checks: Vec<_> = merged.iter().map(|c| (c, c.checked)).collect();
let p = gridcraft_engine::cmd::data::filter_choices_params(&col_to_letters(col), &active_checks);
let _ = app.run("data.filterBy", p);
close = true;
}
@@ -193,12 +195,16 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
"ui:filterValue" => {
if let Some(d) = app.session.active() {
let a = d.selection.active;
let text = d.wb.active().map(|sh| gridcraft_engine::display::cell_text(&d.wb, sh, a)).unwrap_or_default();
let col = col_to_letters(a.col);
let params =
d.wb.active()
.map(|sh| gridcraft_engine::cmd::data::filter_by_cell_params(&d.wb, sh, a, &col))
.unwrap_or_else(|| json!({"column": col, "values": [], "blanks": true}));
let has = d.wb.active().is_some_and(|sh| sh.autofilter.is_some());
if !has {
let _ = app.run("data.filter", json!({}));
}
app.run_or_alert("data.filterBy", json!({"column": col_to_letters(a.col), "values": [text]}));
app.run_or_alert("data.filterBy", params);
}
}
"edit.copy" | "edit.cut" => {
+23 -2
View File
@@ -583,7 +583,28 @@ pub fn message_box(app: &mut SheetApp, ctx: &egui::Context) {
let Some((title, msg)) = app.message.clone() else { return };
let title = app.ui.language.tr(&title).to_owned();
let msg = app.ui.language.tr_error(&msg);
let mut close = false;
// Dismissal keys belong to this message, not `Modal` or the dialog underneath; key-repeat and modified
// Enter/Escape events are drained up front without dismissing the alert or closing the open dialog.
let (enter, escape) = ctx.input_mut(|i| {
let (mut enter, mut escape) = (false, false);
i.events.retain(|e| match e {
egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat, modifiers, .. } => {
if !*repeat && modifiers.is_none() {
enter = true;
}
false
}
egui::Event::Key { key: egui::Key::Escape, pressed: true, repeat, modifiers, .. } => {
if !*repeat && modifiers.is_none() {
escape = true;
}
false
}
_ => true,
});
(enter, escape)
});
let mut close = enter || escape || crate::framework::take_window_cancel(ctx);
egui::Modal::new(egui::Id::unique("message_box")).show(ctx, |ui| {
ui.set_width(380.0);
ui.horizontal(|ui| {
@@ -598,7 +619,7 @@ pub fn message_box(app: &mut SheetApp, ctx: &egui::Context) {
});
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) || crate::framework::escape_pressed(ui.ctx()) {
if ui.button(" OK ").clicked() {
close = true;
}
});
+209
View File
@@ -247,3 +247,212 @@ fn command_search_hides_disabled_and_handles_missing_shortcuts() {
h.get_by_label_contains("Align Right Home");
}
}
/// #2189: A failed rename must not dismiss its own error on Enter.
#[test]
fn failed_rename_enter_keeps_error_visible() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("a/b"));
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().dialog.is_some(), "failed dialog stays open");
assert!(
h.state().message.as_ref().is_some_and(|(_, text)| text.contains("A sheet name can't contain any of these characters: : \\ / ? * [ ]")),
"Enter must leave the invalid-sheet-name error visible: {:?}",
h.state().message
);
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Sheet1", "invalid rename must not change the sheet");
// The next Enter dismisses the error, not the dialog.
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().message.is_none(), "second Enter dismisses error");
assert!(h.state().dialog.is_some(), "rename dialog stays editable");
// After dismissing the error, the dialog remains usable for a valid rename.
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("Renamed"));
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().dialog.is_none(), "valid rename confirms and closes dialog");
assert!(h.state().message.is_none(), "valid rename leaves no error");
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Renamed");
}
/// Mouse OK still shows the error; Escape dismisses only the message.
#[test]
fn failed_rename_click_keeps_error_until_escape() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("a/b"));
h.get_by_label_contains("OK").click();
h.run_steps(3);
assert!(h.state().message.is_some(), "mouse OK shows error");
assert!(h.state().dialog.is_some());
h.key_press(Key::Escape);
h.run_steps(3);
assert!(h.state().message.is_none(), "Escape dismisses error");
assert!(h.state().dialog.is_some(), "Escape keeps dialog open");
}
/// #2189: Clicking the message box's OK button dismisses only the error and leaves the dialog usable.
#[test]
fn failed_rename_message_box_ok_dismisses_error_and_recovers() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("a/b"));
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().message.is_some(), "invalid rename shows message box");
assert!(h.state().dialog.is_some(), "rename dialog remains open behind message box");
// `message_box` renders `" OK "` while `dialogs::show::ok_cancel` renders `" OK "`.
assert_eq!(h.query_all_by_label(" OK ").count(), 1, "message box OK button is uniquely selectable");
h.get_by_label(" OK ").click();
h.run_steps(3);
assert!(h.state().message.is_none(), "clicking message box OK dismisses the error");
assert!(h.state().dialog.is_some(), "rename dialog stays open after dismissing message box");
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Sheet1");
// Verify recovery after dismissing via mouse OK.
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("Recovered"));
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().dialog.is_none(), "recovered rename closes dialog");
assert!(h.state().message.is_none());
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Recovered");
}
/// #2189: A pre-existing `state.message` consumes Enter and Escape before the underlying dialog.
#[test]
fn existing_message_takes_enter_and_escape_before_open_dialog() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("LaterName"));
h.state_mut().message = Some(("Alert".into(), "Existing alert".into()));
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().message.is_none(), "Enter dismisses pre-existing message");
assert!(h.state().dialog.is_some(), "dialog stays open because message owned Enter");
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Sheet1", "draft name was not submitted");
h.state_mut().message = Some(("Alert".into(), "Second alert".into()));
h.run_steps(2);
h.key_press(Key::Escape);
h.run_steps(3);
assert!(h.state().message.is_none(), "Escape dismisses pre-existing message");
assert!(h.state().dialog.is_some(), "dialog stays open because message owned Escape");
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Sheet1");
// Once the message is gone, Enter confirms the still-open dialog.
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().dialog.is_none(), "Enter confirms dialog after message dismissal");
assert!(h.state().message.is_none());
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "LaterName");
}
/// #2189: Ctrl+Escape while an error message is open must not close the dialog behind it or lose the draft.
#[test]
fn ctrl_escape_does_not_close_dialog_behind_error_message() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("a/b"));
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().message.is_some());
assert!(h.state().dialog.is_some());
h.key_press_modifiers(egui::Modifiers::CTRL, Key::Escape);
h.run_steps(3);
assert!(h.state().message.is_some(), "Ctrl+Escape does not dismiss the error alert");
assert!(h.state().dialog.is_some(), "Ctrl+Escape must not close the dialog behind the alert");
assert_eq!(h.state().dialog.as_ref().unwrap().values.get("name"), Some(&json!("a/b")), "rename draft remains intact");
// Plain Escape still dismisses only the message.
h.key_press(Key::Escape);
h.run_steps(3);
assert!(h.state().message.is_none());
assert!(h.state().dialog.is_some());
}
/// #2189: Holding Enter (OS key-repeat) after a failed rename keeps the error visible until a fresh press.
#[test]
fn held_enter_key_repeat_does_not_dismiss_error_message() {
let mut h = harness();
h.state_mut().open_dialog("renameSheet", json!({}));
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("name".into(), json!("a/b"));
// Press and hold Enter (no release event yet) so egui tracks Key::Enter in `keys_down`.
h.input_mut().events.push(egui::Event::Key {
key: Key::Enter,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
});
h.run_steps(3);
assert!(h.state().message.is_some(), "initial held Enter shows error");
assert!(h.state().dialog.is_some());
// Subsequent OS key-repeat events while Enter remains held must not dismiss the alert.
for _ in 0..2 {
h.input_mut().events.push(egui::Event::Key {
key: Key::Enter,
physical_key: None,
pressed: true,
repeat: true,
modifiers: egui::Modifiers::NONE,
});
h.run_steps(2);
assert!(h.state().message.is_some(), "key-repeat Enter must not dismiss the error alert");
assert!(h.state().dialog.is_some(), "key-repeat Enter must not close the dialog");
}
// Release the held Enter key, then press Enter fresh: dismisses the alert while keeping the dialog open.
h.input_mut().events.push(egui::Event::Key {
key: Key::Enter,
physical_key: None,
pressed: false,
repeat: false,
modifiers: egui::Modifiers::NONE,
});
h.run_steps(1);
h.key_press(Key::Enter);
h.run_steps(3);
assert!(h.state().message.is_none());
assert!(h.state().dialog.is_some());
}
+19 -2
View File
@@ -432,6 +432,11 @@ const DASHES: [(LineDash, &str); 11] = [
const EMU_PER_PT: f64 = 12_700.0;
/// Parses a legacy OOXML `<c:style val="..."/>` index (`1..=48`), trimming surrounding spaces.
fn parse_chart_style(val: &str) -> Option<u32> {
val.trim().parse::<u32>().ok().filter(|s| (1..=48).contains(s))
}
fn group_kind(g: &El) -> Option<ChartKind> {
let grouping = g.child_val("grouping").unwrap_or("standard");
let stacked = grouping == "stacked";
@@ -463,7 +468,8 @@ fn group_kind(g: &El) -> Option<ChartKind> {
}
}
}
"pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie,
"pieChart" | "pie3DChart" => ChartKind::Pie,
"ofPieChart" => ChartKind::Pie,
"doughnutChart" => ChartKind::Doughnut,
"areaChart" | "area3DChart" => {
if pct {
@@ -713,7 +719,18 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>, budget: &mut Chart
outline: t.outline,
}),
gridlines: dc.gridlines,
style: dc.style,
// Excel can wrap the legacy chart style in mc:AlternateContent.
// The c14 Choice uses different IDs, so read the c:style Fallback.
style: root
.and_then(|r| {
r.child_val("style").and_then(parse_chart_style).or_else(|| {
r.kids("AlternateContent")
.filter_map(|wrapper| wrapper.child("Fallback"))
.find_map(|fallback| fallback.child_val("style").and_then(parse_chart_style))
})
})
.or_else(|| (1..=48).contains(&dc.style).then_some(dc.style))
.unwrap_or(2),
hole_size,
first_slice_angle: dc.first_slice_angle,
x_title: axis_titles.0,
+19
View File
@@ -114,8 +114,26 @@ fn filter_op(s: Option<&str>) -> &'static str {
}
}
const GC_FILTER_EXT_URI: &str = "{D7C4E9A1-2943-4B8E-9A11-6F8B2C4D5E01}";
/// Parses an `<autoFilter>` element into model criteria, restoring any GridCraft checklist identity extension.
pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option<AutoFilter> {
let range = e.attr("ref").and_then(RangeRef::parse)?;
let mut ext_identities: HashMap<u32, Vec<String>> = HashMap::new();
for col_el in e
.kids("extLst")
.flat_map(|ext_lst| ext_lst.kids("ext"))
.filter(|ext| ext.attr("uri") == Some(GC_FILTER_EXT_URI))
.filter_map(|ext| ext.child("identities"))
.flat_map(|ids| ids.kids("col"))
{
if let Some(col_id) = col_el.attr_u32("colId") {
let ids: Vec<String> = col_el.kids("i").filter_map(|item| item.attr("v")).map(str::to_string).collect();
if !ids.is_empty() {
ext_identities.insert(col_id, ids);
}
}
}
let mut criteria = vec![];
for fc in e.kids("filterColumn") {
let Some(col) = fc.attr_u32("colId") else { continue };
@@ -123,6 +141,7 @@ pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option<AutoFilter> {
FilterCriterion::Values {
values: f.kids("filter").filter_map(|x| x.attr("val")).map(str::to_string).collect(),
blanks: f.flag("blank", false),
identities: ext_identities.remove(&col).unwrap_or_default(),
}
} else if let Some(cf) = fc.child("customFilters") {
let mut it = cf.kids("customFilter").map(|c| (filter_op(c.attr("operator")).to_string(), c.attr("val").unwrap_or("").to_string()));
+22 -1
View File
@@ -56,6 +56,9 @@ fn filter_operator(op: &str) -> &'static str {
}
}
const GC_FILTER_EXT_URI: &str = "{D7C4E9A1-2943-4B8E-9A11-6F8B2C4D5E01}";
const GC_FILTER_NS: &str = "https://gridcraft.app/ns/spreadsheetml/2026/filter";
pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)], out: &mut Out) -> String {
let mut s = format!("<autoFilter ref=\"{}\"", range.a1());
if criteria.is_empty() {
@@ -66,7 +69,7 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)
for (col, c) in criteria {
let _ = write!(s, "<filterColumn colId=\"{col}\">");
match c {
FilterCriterion::Values { values, blanks } => {
FilterCriterion::Values { values, blanks, .. } => {
let _ = write!(s, "<filters{}>", if *blanks { " blank=\"1\"" } else { "" });
for v in values {
let _ = write!(s, "<filter val=\"{}\"/>", esc_attr(v));
@@ -106,6 +109,24 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)
}
s.push_str("</filterColumn>");
}
let ext_cols: Vec<(u32, &[String])> = criteria
.iter()
.filter_map(|(col, c)| match c {
FilterCriterion::Values { identities, .. } if !identities.is_empty() => Some((*col, identities.as_slice())),
_ => None,
})
.collect();
if !ext_cols.is_empty() {
let _ = write!(s, "<extLst><ext uri=\"{GC_FILTER_EXT_URI}\" xmlns:gc=\"{GC_FILTER_NS}\"><gc:identities>");
for (col, ids) in ext_cols {
let _ = write!(s, "<gc:col colId=\"{col}\">");
for id in ids {
let _ = write!(s, "<gc:i v=\"{}\"/>", esc_attr(id));
}
s.push_str("</gc:col>");
}
s.push_str("</gc:identities></ext></extLst>");
}
s.push_str("</autoFilter>");
s
}
+1
View File
@@ -9,6 +9,7 @@ mod chart_data_table;
mod chart_line_percent_stacked;
mod chart_read_tests;
mod chart_ref_offsets;
mod chart_style_roundtrip;
mod controls_tests;
mod csv_tests;
mod encrypted_tests;
@@ -45,6 +45,44 @@ fn line_first_group_stays_a_line() {
assert_eq!(k[1], Some(ChartKind::ColumnClustered));
}
/// Verifies explicit `<c:style>` values round-trip unchanged through chart XML serialization.
#[test]
fn explicit_chart_style_survives_xml_roundtrip() {
use gridcraft_model::Workbook;
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] {
for style in [1, 9, 48] {
let mut chart = crate::chart::read_chart(
&parse(
format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\">\
<c:style val=\"{style}\"/>\
<c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>\
<c:ser><c:idx val=\"0\"/><c:order val=\"0\"/></c:ser>\
</c:barChart>\
</c:plotArea></c:chart></c:chartSpace>"
)
.as_bytes(),
)
.unwrap(),
)
.unwrap()
.0;
chart.kind = kind;
assert_eq!(chart.style, style);
let wb = Workbook::default();
let xml = crate::chart::write_chart(&wb, 0, &chart, "Book.xlsx");
let root = parse(xml.as_bytes()).unwrap();
let restored = crate::chart::read_chart(&root).unwrap().0;
assert_eq!(restored.style, style, "chart style changed for {kind:?}");
}
}
}
/// Outside a combo, a series keeps its own markers or lines where they differ from its chart's,
/// read and written. The chart's kind is its first series'.
#[test]
@@ -0,0 +1,193 @@
//! Explicit chart styles survive complete XLSX serialization.
use std::sync::Arc;
use gridcraft_core::CellRef;
use gridcraft_model::{Anchor, Chart, ChartKind, LegendPos, Series, Sheet, Workbook};
use crate::{read_xlsx, write_xlsx};
/// Verifies explicit chart styles survive full XLSX save and reload cycles.
#[test]
fn explicit_styles_survive_xlsx_save_and_reload() {
// Start from the XLSX reader so this fixture follows new optional Chart fields.
let template: Chart = crate::chart::read_chart(
&crate::xml::parse(
concat!(
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart">"#,
"<c:chart><c:plotArea><c:barChart>",
r#"<c:barDir val="col"/><c:grouping val="clustered"/>"#,
r#"<c:ser><c:idx val="0"/><c:order val="0"/></c:ser>"#,
"</c:barChart></c:plotArea></c:chart></c:chartSpace>",
)
.as_bytes(),
)
.unwrap(),
)
.unwrap()
.0;
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] {
for style in [1, 9, 48] {
let mut wb = Workbook::default();
let mut sheet = Sheet::new("Data");
let mut chart = template.clone();
chart.id = 1;
chart.kind = kind;
chart.anchor = Anchor { cell: CellRef::new(0, 3), width: 480.0, height: 300.0, ..Anchor::default() };
chart.title = Some("Style roundtrip".into());
chart.series = vec![Series {
name: Some("Series 1".into()),
categories: Some(r#"{"A","B","C"}"#.into()),
values: "{10,20,30}".into(),
..Series::default()
}];
chart.legend = LegendPos::Bottom;
chart.data_labels = false;
chart.gridlines = true;
chart.style = style;
chart.x_title = None;
chart.y_title = None;
chart.source = None;
chart.by_rows = false;
chart.pivot = None;
sheet.charts.push(chart);
wb.sheets = vec![Arc::new(sheet)];
let bytes = write_xlsx(&wb).unwrap();
let (reloaded, _) = read_xlsx(&bytes).unwrap();
assert_eq!(reloaded.sheets[0].charts.len(), 1);
assert_eq!(reloaded.sheets[0].charts[0].kind, kind);
assert_eq!(reloaded.sheets[0].charts[0].style, style);
let bytes2 = write_xlsx(&reloaded).unwrap();
let (reloaded2, _) = read_xlsx(&bytes2).unwrap();
assert_eq!(reloaded2.sheets[0].charts.len(), 1);
assert_eq!(reloaded2.sheets[0].charts[0].kind, kind);
assert_eq!(reloaded2.sheets[0].charts[0].style, style, "XLSX round-trip changed style {style} for {kind:?}");
}
}
}
/// Excel stores legacy styles 1 and 9 in mc:Fallback,
/// alongside c14 Choice values 101 and 109.
#[test]
fn excel_alternate_content_chart_styles_roundtrip() {
use crate::chart::{read_chart, write_chart};
use crate::xml::parse;
for (kind, group) in [
(
ChartKind::ColumnClustered,
r#"<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>"#,
),
(
ChartKind::BarClustered,
r#"<c:barChart><c:barDir val="bar"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>"#,
),
(
ChartKind::Line,
r#"<c:lineChart><c:grouping val="standard"/><c:marker val="0"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:lineChart>"#,
),
] {
for (legacy_style, modern_style) in [(1, 101), (9, 109)] {
let xml = format!(
r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14">
<c14:style val="{modern_style}"/>
</mc:Choice>
<mc:Fallback>
<c:style val="{legacy_style}"/>
</mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>{group}</c:plotArea>
</c:chart>
</c:chartSpace>"#
);
let root = parse(xml.as_bytes()).unwrap();
let chart = read_chart(&root).unwrap().0;
assert_eq!(chart.kind, kind);
assert_eq!(chart.style, legacy_style, "Excel AlternateContent style for {kind:?}");
let saved = write_chart(&Workbook::default(), 0, &chart, "Book.xlsx");
let reopened = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap().0;
assert_eq!(reopened.style, legacy_style, "Style changed when re-exporting {kind:?}");
}
}
}
/// Surrounding whitespace on `<c:style val="..."/>` trims cleanly, while out-of-range fallback values default to style 2.
#[test]
fn alternate_content_fallback_style_trims_and_validates_range() {
use crate::chart::read_chart;
use crate::xml::parse;
for (raw_val, expected) in [(" 9 ", 9), ("\t1\n", 1), ("0", 2), ("49", 2), ("200", 2)] {
let xml = format!(
r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="109"/></mc:Choice>
<mc:Fallback><c:style val="{raw_val}"/></mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>
</c:plotArea>
</c:chart>
</c:chartSpace>"#
);
let chart = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap().0;
assert_eq!(chart.style, expected, "raw fallback style {raw_val:?}");
}
}
/// Reads `<c:style>` from a later `mc:AlternateContent` wrapper when an earlier wrapper has no style fallback.
#[test]
fn later_alternate_content_wrapper_provides_fallback_style() {
use crate::chart::read_chart;
use crate::xml::parse;
let xml = r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:sketchOptions/></mc:Choice>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:dropZoneFilter val="0"/></mc:Choice>
<mc:Fallback><c:roundedCorners val="0"/></mc:Fallback>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="100"/></mc:Choice>
<mc:Fallback><c:style val="0"/></mc:Fallback>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="109"/></mc:Choice>
<mc:Fallback><c:style val="9"/></mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>
</c:plotArea>
</c:chart>
</c:chartSpace>"#;
let chart = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap().0;
assert_eq!(chart.style, 9);
}
+10 -6
View File
@@ -277,7 +277,7 @@ fn sample() -> Workbook {
s.autofilter = Some(AutoFilter {
range: rr("K1:N20"),
criteria: vec![
(0, FilterCriterion::Values { values: vec!["a".into(), "b".into()], blanks: true }),
(0, FilterCriterion::Values { values: vec!["a".into(), "b".into()], blanks: true, identities: vec![] }),
(1, FilterCriterion::Custom { a: (">=".into(), "5".into()), b: Some(("<".into(), "9".into())), and: true }),
(2, FilterCriterion::Top10 { bottom: true, percent: false, count: 3 }),
(3, FilterCriterion::FillColor(Color::Rgb(0xFF0000))),
@@ -352,7 +352,7 @@ fn sample() -> Workbook {
last_col: false,
filter_button: true,
filter: vec![
(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }),
(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] }),
(1, FilterCriterion::Icon { set: "3TrafficLights1".into(), id: Some(1) }),
],
table_type: None,
@@ -1982,8 +1982,10 @@ fn a_table_filter_criteria_survive_a_round_trip() {
});
// The dropdown of a table's header cell installs the sheet AutoFilter over the table's
// range, and `data.filterBy` stores its criteria there.
s.autofilter =
Some(AutoFilter { range: rr("A1:A4"), criteria: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })] });
s.autofilter = Some(AutoFilter {
range: rr("A1:A4"),
criteria: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
});
s.rows.entry(1).or_default().hidden = true;
let (back, rep) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
@@ -2025,8 +2027,10 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
table_type: None,
connection_id: None,
});
s.autofilter =
Some(AutoFilter { range: rr("B1:B3"), criteria: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })] });
s.autofilter = Some(AutoFilter {
range: rr("B1:B3"),
criteria: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
});
let (back, rep) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
+2 -2
View File
@@ -50,7 +50,7 @@ fn filtered(af_range: &str, af_col: u32) -> Workbook {
s.tables.push(t);
s.autofilter = Some(AutoFilter {
range: rr(af_range),
criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false })],
criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false, identities: vec![] })],
});
for row in [3, 5] {
s.rows.entry(row).or_default().hidden = true;
@@ -82,7 +82,7 @@ fn sheet_autofilter_starting_left_of_the_table_maps_its_columns() {
// filter and column 0 of the table; a criterion on the column outside the table is dropped.
let mut wb = filtered("A2:C6", 1);
if let Some(af) = wb.sheet_mut(0).unwrap().autofilter.as_mut() {
af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true }));
af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true, identities: vec![] }));
}
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
let t = &back.sheet(0).unwrap().tables[0];
+3 -11
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
@@ -41,6 +32,7 @@ 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`
-18
View File
@@ -45,9 +45,6 @@ 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.
(cd "$ROOT" && cargo build --release --locked -p gridcraft-cli --example man-and-completions ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"})
fi
BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release"
WORK="$CARGO_TARGET_DIR/freebsd-package"
@@ -58,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="$BIN/examples/man-and-completions"
if [[ ! -x "$CLI_DOCS" ]]; then
echo "error: $CLI_DOCS is not built (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)
-25
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" && 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 (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,13 +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
sed -e "s/gridcraft-cli/$NFPM_CLI/g" -e "s/gridcraft\\\\-cli/${NFPM_CLI//-/\\\\-}/g" "$f" >"${f//gridcraft-cli/$NFPM_CLI}.tmp"
rm -f "$f"
mv "${f//gridcraft-cli/$NFPM_CLI}.tmp" "${f//gridcraft-cli/$NFPM_CLI}"
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|" \