mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-30 18:24:12 +01:00
Merge branch 'main' into charts/keep-unedited-chart-xml
This commit is contained in:
60 files changed
+2000
-293
No files matched your search
+4
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
|
||||
@@ -159,6 +159,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
|
||||
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
|
||||
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
|
||||
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
|
||||
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
|
||||
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
|
||||
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
|
||||
@@ -172,6 +173,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
|
||||
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
|
||||
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
|
||||
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
|
||||
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
|
||||
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
|
||||
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
|
||||
@@ -316,6 +318,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-26 | minor | Progress log: Arabic PDF text |
|
||||
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
|
||||
| 2026-10-26 | minor | Progress log: Arabic font fallback |
|
||||
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
|
||||
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
|
||||
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
|
||||
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
|
||||
|
||||
@@ -216,13 +216,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
|
||||
}
|
||||
}),
|
||||
BinOp::Concat => match (a.to_text(), b.to_text()) {
|
||||
(Ok(x), Ok(y)) => {
|
||||
if x.len() + y.len() > 32767 * 4 {
|
||||
Value::Error(CellError::Value)
|
||||
} else {
|
||||
Value::text(x + &y)
|
||||
}
|
||||
}
|
||||
(Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
},
|
||||
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
|
||||
|
||||
@@ -12,7 +12,7 @@ mod trimrange;
|
||||
|
||||
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
|
||||
pub use precision::DisplayedPrecision;
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -2762,6 +2762,19 @@ fn loan_schedule_residue_keeps_excels_sign() {
|
||||
assert_eq!(t.get("P7"), Value::Text("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concat_operator_cuts_at_the_cell_limit() {
|
||||
// Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))");
|
||||
t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")");
|
||||
t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))");
|
||||
t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")");
|
||||
t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))");
|
||||
assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0));
|
||||
assert_eq!(t.get("A5"), Value::Error(CellError::Value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() {
|
||||
let mut t = T::new();
|
||||
|
||||
@@ -16,4 +16,4 @@ pub use addr::{
|
||||
};
|
||||
pub use date::DateSystem;
|
||||
pub use region::Region;
|
||||
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
@@ -501,6 +501,31 @@ pub fn sci_text(n: f64, sig: usize) -> String {
|
||||
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
|
||||
}
|
||||
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub const MAX_TEXT_CHARS: usize = 32_767;
|
||||
|
||||
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
|
||||
pub fn cap_text(mut s: String) -> String {
|
||||
if s.len() > MAX_TEXT_CHARS {
|
||||
let mut units = 0;
|
||||
if let Some((i, _)) = s.char_indices().find(|(_, c)| {
|
||||
units += c.len_utf16();
|
||||
units > MAX_TEXT_CHARS
|
||||
}) {
|
||||
s.truncate(i);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through.
|
||||
pub fn cap_value(v: Value) -> Value {
|
||||
match v {
|
||||
Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -584,6 +609,16 @@ mod tests {
|
||||
assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() {
|
||||
let face = "😀";
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1));
|
||||
assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_diacritics_sort_with_their_base_letter() {
|
||||
assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less);
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! Calculation benchmarks on fixed workbooks built in code (release build). Run through
|
||||
//! `cargo xtask bench`, which builds this in release and compares against a saved baseline, or
|
||||
//! directly: `cargo run --release -p gridcraft-engine --example bench -- [--quick] [--rows N]
|
||||
//! [--reps N] [--filter NAME] [--json PATH]`.
|
||||
//!
|
||||
//! Every scenario builds its workbook untimed, runs one warm-up, then times `reps` runs of one
|
||||
//! operation through `Session::execute` (so a timing includes what an edit costs the user: undo
|
||||
//! history, graph update and recalculation). Results are checked so a scenario that silently
|
||||
//! stopped recalculating fails instead of getting fast.
|
||||
|
||||
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
struct Cfg {
|
||||
rows: usize,
|
||||
reps: usize,
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
name: &'static str,
|
||||
what: String,
|
||||
times: Vec<Duration>,
|
||||
cells: usize,
|
||||
}
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
/// A scenario: its name and the function that runs it.
|
||||
type Scenario = (&'static str, fn(&Cfg) -> R<Outcome>);
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
match run() {
|
||||
Ok(()) => std::process::ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("bench: {e}");
|
||||
std::process::ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> R<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
|
||||
let quick = args.iter().any(|a| a == "--quick");
|
||||
let cfg = Cfg {
|
||||
rows: count(flag("--rows"), "--rows")?.unwrap_or(if quick { 10_000 } else { 100_000 }).max(200),
|
||||
reps: count(flag("--reps"), "--reps")?.unwrap_or(if quick { 3 } else { 7 }).max(1),
|
||||
filter: flag("--filter"),
|
||||
};
|
||||
let scenarios: [Scenario; 10] = [
|
||||
("edit.chain", edit_chain),
|
||||
("edit.fanout", edit_fanout),
|
||||
("edit.sliding", edit_sliding),
|
||||
("edit.sumifs", edit_sumifs),
|
||||
("edit.lookup", edit_lookup),
|
||||
("enter.formulas", enter_formulas),
|
||||
("recalc.full", recalc_full),
|
||||
("data.sort", data_sort),
|
||||
("xlsx.save", xlsx_save),
|
||||
("xlsx.open", xlsx_open),
|
||||
];
|
||||
println!("GridCraft calc bench: {} rows, {} reps (median / min)\n", cfg.rows, cfg.reps);
|
||||
println!("{:<16} {:>10} {:>10} {:>9} workload", "scenario", "median", "min", "cells");
|
||||
let mut results = Vec::new();
|
||||
// A failed scenario is reported and the others still run, so one regression doesn't hide
|
||||
// the numbers for everything else.
|
||||
let mut failed = Vec::new();
|
||||
let selected: Vec<_> = scenarios.into_iter().filter(|(name, _)| cfg.filter.as_deref().is_none_or(|p| name.contains(p))).collect();
|
||||
if selected.is_empty() {
|
||||
// An empty run would otherwise save as a baseline with nothing in it.
|
||||
return Err(format!("--filter {} matches no scenario", cfg.filter.as_deref().unwrap_or("")));
|
||||
}
|
||||
for (name, f) in selected {
|
||||
let o = match f(&cfg) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
println!("{name:<16} {:>10} {e}", "FAILED");
|
||||
failed.push(name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (med, min) = stats(&o.times);
|
||||
let cells = if o.cells == 0 { "-".to_string() } else { o.cells.to_string() };
|
||||
println!("{:<16} {:>10} {:>10} {:>9} {}", o.name, ms(med), ms(min), cells, o.what);
|
||||
results.push(json!({"name": o.name, "what": o.what, "median_ms": med, "min_ms": min, "cells": o.cells}));
|
||||
}
|
||||
if let Some(path) = flag("--json") {
|
||||
let out = json!({"rows": cfg.rows, "reps": cfg.reps, "results": results, "failed": failed});
|
||||
let text = serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, text).map_err(|e| format!("{path}: {e}"))?;
|
||||
}
|
||||
if failed.is_empty() { Ok(()) } else { Err(format!("{} scenario(s) failed: {}", failed.len(), failed.join(", "))) }
|
||||
}
|
||||
|
||||
fn stats(times: &[Duration]) -> (f64, f64) {
|
||||
let mut v: Vec<f64> = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect();
|
||||
v.sort_by(f64::total_cmp);
|
||||
// An even count averages the two middle samples.
|
||||
let mid = v.len() / 2;
|
||||
let med = match (v.len() % 2, v.get(mid.wrapping_sub(1)), v.get(mid)) {
|
||||
(0, Some(a), Some(b)) => (a + b) / 2.0,
|
||||
(_, _, Some(m)) => *m,
|
||||
_ => 0.0,
|
||||
};
|
||||
(med, v.first().copied().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
fn ms(v: f64) -> String {
|
||||
if v >= 100.0 { format!("{v:.0} ms") } else { format!("{v:.2} ms") }
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Json) -> R<Json> {
|
||||
s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// A count flag's value; one that isn't a number is an error, not the default.
|
||||
fn count(v: Option<String>, name: &str) -> R<Option<usize>> {
|
||||
v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose()
|
||||
}
|
||||
|
||||
fn session() -> R<Session> {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Writes `rows` rows starting at `col` row 1, `make(i)` giving row i (0-based), in chunks.
|
||||
fn fill(s: &mut Session, col: &str, rows: usize, make: impl Fn(usize) -> Json) -> R<()> {
|
||||
let chunk = 10_000;
|
||||
let mut r = 0;
|
||||
while r < rows {
|
||||
let n = chunk.min(rows - r);
|
||||
let vals: Vec<Json> = (r..r + n).map(&make).collect();
|
||||
exec(s, "range.setValues", json!({"range": format!("{col}{}", r + 1), "values": vals}))?;
|
||||
r += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn num(s: &Session, at: &str) -> R<f64> {
|
||||
let c = CellRef::parse(at).ok_or_else(|| format!("bad ref {at}"))?;
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
match d.wb.sheet(0).map(|sh| sh.value(c)) {
|
||||
Some(Value::Number(n)) => Ok(n),
|
||||
other => Err(format!("{at} = {other:?}, expected a number")),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect(s: &Session, at: &str, want: f64) -> R<()> {
|
||||
let got = num(s, at)?;
|
||||
if (got - want).abs() <= 1e-6 * want.abs().max(1.0) { Ok(()) } else { Err(format!("{at} = {got}, expected {want}")) }
|
||||
}
|
||||
|
||||
fn recalc_cells(s: &Session) -> usize {
|
||||
s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Runs a warm-up then `reps` timed calls of `op(rep)`, then `check(rep)` (untimed) after each.
|
||||
fn time(
|
||||
cfg: &Cfg,
|
||||
s: &mut Session,
|
||||
op: impl FnMut(&mut Session, usize) -> R<()>,
|
||||
check: impl Fn(&Session, usize) -> R<()>,
|
||||
) -> R<(Vec<Duration>, usize)> {
|
||||
time_prepared(cfg, s, |_| Ok(()), op, check)
|
||||
}
|
||||
|
||||
/// [`time`] with `prep` run (untimed) before each call, to put back the state `op` starts from.
|
||||
fn time_prepared(
|
||||
cfg: &Cfg,
|
||||
s: &mut Session,
|
||||
mut prep: impl FnMut(&mut Session) -> R<()>,
|
||||
mut op: impl FnMut(&mut Session, usize) -> R<()>,
|
||||
check: impl Fn(&Session, usize) -> R<()>,
|
||||
) -> R<(Vec<Duration>, usize)> {
|
||||
let mut times = Vec::with_capacity(cfg.reps);
|
||||
let mut cells = 0;
|
||||
for rep in 0..=cfg.reps {
|
||||
prep(s)?;
|
||||
let t = Instant::now();
|
||||
op(s, rep)?;
|
||||
let dt = t.elapsed();
|
||||
check(s, rep)?;
|
||||
cells = recalc_cells(s);
|
||||
if rep > 0 {
|
||||
times.push(dt);
|
||||
}
|
||||
}
|
||||
Ok((times, cells))
|
||||
}
|
||||
|
||||
/// Value typed into A1 on rep `r`: alternates so every rep changes something.
|
||||
fn a1(r: usize) -> f64 {
|
||||
(r % 2 + 2) as f64
|
||||
}
|
||||
|
||||
/// A running sum `B[n] = B[n-1] + A[n]`: one edit at the top recalculates a dependency chain
|
||||
/// `rows` deep.
|
||||
fn edit_chain(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |_| json!([1]))?;
|
||||
fill(&mut s, "B", n, |i| json!([if i == 0 { "=A1".to_string() } else { format!("=B{i}+A{}", i + 1) }]))?;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{n}"), (n - 1) as f64 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.chain", what: format!("edit A1 under a {n}-deep running sum"), times, cells })
|
||||
}
|
||||
|
||||
/// `rows` formulas that each read `$A$1`: one edit, a wide and shallow dirty set.
|
||||
fn edit_fanout(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
exec(&mut s, "cell.set", json!({"cell": "A1", "input": "1"}))?;
|
||||
fill(&mut s, "B", n, |i| json!([format!("=$A$1*{}", i + 1)]))?;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{n}"), a1(r) * n as f64),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.fanout", what: format!("edit $A$1 read by {n} formulas"), times, cells })
|
||||
}
|
||||
|
||||
/// `rows` overlapping 100-row window sums; an edit in the middle dirties ~100 of them, so this
|
||||
/// measures the range index lookup, not evaluation.
|
||||
fn edit_sliding(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n + 99, |_| json!([1]))?;
|
||||
fill(&mut s, "B", n, |i| json!([format!("=SUM(A{}:A{})", i + 1, i + 100)]))?;
|
||||
let mid = n / 2;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": format!("A{mid}"), "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{mid}"), 99.0 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.sliding", what: format!("edit one cell under {n} 100-row SUM windows"), times, cells })
|
||||
}
|
||||
|
||||
/// 100 whole-column SUMIFS over `rows` rows of data, all dirtied by one data edit.
|
||||
fn edit_sumifs(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?;
|
||||
fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?;
|
||||
// Rows whose category is 0 (i % 100 == 0), A1 among them.
|
||||
let per = n.div_ceil(100) as f64;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, "D1", per - 1.0 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.sumifs", what: format!("edit data under 100 SUMIFS(A:A,B:B,k) over {n} rows"), times, cells })
|
||||
}
|
||||
|
||||
/// 100 exact-match XLOOKUPs over whole columns of `rows` keys, all dirtied by one key edit.
|
||||
fn edit_lookup(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?;
|
||||
let step = n / 100;
|
||||
fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B,0)", (k + 1) * step)]))?;
|
||||
let last = (2 * 100 * step) as f64;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
// D1 looks up the key in A{step}: removing it (-step) makes D1 fall back to 0, putting it
|
||||
// back finds it again. Every lookup reads A:A, so all 100 recalculate either way.
|
||||
|s, r| {
|
||||
let key = if r % 2 == 0 { format!("-{step}") } else { step.to_string() };
|
||||
exec(s, "cell.set", json!({"cell": format!("A{step}"), "input": key})).map(drop)
|
||||
},
|
||||
|s, r| {
|
||||
expect(s, "D1", if r % 2 == 0 { 0.0 } else { (2 * step) as f64 })?;
|
||||
expect(s, "D100", last)
|
||||
},
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells })
|
||||
}
|
||||
|
||||
/// Entering `rows` formulas in one command: parse, graph insertion and first evaluation.
|
||||
fn enter_formulas(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?;
|
||||
let vals: Vec<Json> = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect();
|
||||
let (times, cells) = time_prepared(
|
||||
cfg,
|
||||
&mut s,
|
||||
// Each run enters the formulas into empty cells, not over the previous run's.
|
||||
|s| exec(s, "edit.clearAll", json!({"range": format!("B1:B{n}")})).map(drop),
|
||||
|s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop),
|
||||
|s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0),
|
||||
)?;
|
||||
Ok(Outcome { name: "enter.formulas", what: format!("enter {n} formulas =An*2+1 in one paste"), times, cells })
|
||||
}
|
||||
|
||||
/// A model with 3 formulas per row (arithmetic and a row SUM), recalculated in full.
|
||||
fn model(n: usize) -> R<Session> {
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i % 97) as f64, format!("=A{}*2", i + 1), format!("=B{0}+A{0}", i + 1), format!("=SUM(A{0}:C{0})", i + 1)]))?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn recalc_full(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
// Manual calculation, and A[n] changed (untimed) before each run, so D[n] is stale until
|
||||
// Calculate Now recalculates: a Calculate Now that did nothing fails the check.
|
||||
exec(&mut s, "formulas.calculationOptions", json!({"mode": "manual"}))?;
|
||||
let mut rep = 0;
|
||||
let (times, cells) = time_prepared(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s| {
|
||||
rep += 1;
|
||||
exec(s, "cell.set", json!({"cell": format!("A{n}"), "input": (100 + rep).to_string()})).map(drop)
|
||||
},
|
||||
|s, _| exec(s, "formulas.calculateNow", json!({})).map(drop),
|
||||
|s, r| expect(s, &format!("D{n}"), (101 + r) as f64 * 6.0),
|
||||
)?;
|
||||
Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells })
|
||||
}
|
||||
|
||||
fn data_sort(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([format!("Item {i}"), (i % 97) as f64, ((i * 7919) % 1000) as f64]))?;
|
||||
let (times, _) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| {
|
||||
let cmd = if r % 2 == 0 { "data.sortDescending" } else { "data.sortAscending" };
|
||||
exec(s, cmd, json!({"range": format!("A1:C{n}"), "column": "B"})).map(drop)
|
||||
},
|
||||
|s, r| expect(s, "B1", if r % 2 == 0 { 96.0 } else { 0.0 }),
|
||||
)?;
|
||||
// A sort with no formulas recalculates nothing; 0 shows as "-".
|
||||
Ok(Outcome { name: "data.sort", what: format!("sort {n} rows x 3 columns by a numeric key"), times, cells: 0 })
|
||||
}
|
||||
|
||||
fn save_bytes(s: &mut Session) -> R<String> {
|
||||
let r = exec(s, "file.saveBytes", json!({"format": "xlsx"}))?;
|
||||
r.get("base64").and_then(Json::as_str).map(str::to_string).ok_or_else(|| "file.saveBytes: no base64".to_string())
|
||||
}
|
||||
|
||||
fn xlsx_save(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
let (times, _) = time(cfg, &mut s, |s, _| save_bytes(s).map(drop), |_, _| Ok(()))?;
|
||||
Ok(Outcome { name: "xlsx.save", what: format!("save the {n}-row model as XLSX"), times, cells: 0 })
|
||||
}
|
||||
|
||||
fn xlsx_open(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
let b64 = save_bytes(&mut s)?;
|
||||
let last = ((n - 1) % 97) as f64 * 6.0;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, _| exec(s, "file.open", json!({"name": "bench.xlsx", "base64": b64})).map(drop),
|
||||
|s, _| expect(s, &format!("D{n}"), last),
|
||||
)?;
|
||||
Ok(Outcome { name: "xlsx.open", what: format!("open the {n}-row model from XLSX (with full recalc)"), times, cells })
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
//! Performance scenarios on large workbooks (release build):
|
||||
//! `cargo run --release -p gridcraft-engine --example perf -- [rows]`
|
||||
|
||||
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn main() {
|
||||
let rows: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// Data: rows × 6 numeric columns, built through range.setValues in chunks.
|
||||
let t = Instant::now();
|
||||
let chunk = 10_000;
|
||||
let mut r = 0;
|
||||
while r < rows {
|
||||
let n = chunk.min(rows - r);
|
||||
let vals: Vec<serde_json::Value> = (0..n)
|
||||
.map(|i| json!([format!("Item {}", r + i), (r + i) as f64, ((r + i) % 97) as f64, ((r + i) % 13) as f64 * 1.5, 1.0, 2.0]))
|
||||
.collect();
|
||||
s.execute("range.setValues", json!({"range": format!("A{}", r + 1), "values": vals})).expect("set");
|
||||
r += n;
|
||||
}
|
||||
println!("fill {rows}x6 values: {:?}", t.elapsed());
|
||||
// Formulas: G = B*C+D, H = running sum of G (chain).
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "G1", "input": "=B1*C1+D1"})).expect("g1");
|
||||
s.execute("edit.autoFill", json!({"source": "G1", "target": format!("G1:G{rows}")})).expect("fill g");
|
||||
println!("fill {rows} formulas G=B*C+D: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "H1", "input": "=G1"})).expect("h1");
|
||||
s.execute("cell.set", json!({"cell": "H2", "input": "=H1+G2"})).expect("h2");
|
||||
s.execute("edit.autoFill", json!({"source": "H2", "target": format!("H2:H{rows}")})).expect("fill h");
|
||||
println!("fill {rows} chained running-sum formulas: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "J1", "input": format!("=SUM(G1:G{rows})")})).expect("sum");
|
||||
s.execute("cell.set", json!({"cell": "J2", "input": "=SUMIFS(B:B,C:C,\">50\")"})).expect("sumifs");
|
||||
s.execute("cell.set", json!({"cell": "J3", "input": "=XLOOKUP(\"Item 77777\",A:A,B:B)"})).expect("xlookup");
|
||||
println!("aggregate formulas: {:?}", t.elapsed());
|
||||
// Edit at the top: everything below recalculates.
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "5"})).expect("edit");
|
||||
println!("edit B1 → recalc {} cells: {:?}", s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0), t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("data.sortDescending", json!({"range": format!("A1:F{rows}"), "column": "C"})).expect("sort");
|
||||
println!("sort {rows} rows: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).expect("save");
|
||||
let b64 = r["base64"].as_str().unwrap_or("").to_string();
|
||||
println!("save xlsx ({} bytes): {:?}", r["bytes"], t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("file.open", json!({"name": "big.xlsx", "base64": b64})).expect("open");
|
||||
println!("open xlsx + full recalc: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("edit.undo", json!({})).ok();
|
||||
println!("undo: {:?}", t.elapsed());
|
||||
}
|
||||
@@ -27,7 +27,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
}
|
||||
let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@";
|
||||
if fmt_is_text {
|
||||
return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None }));
|
||||
return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style, py: None }));
|
||||
}
|
||||
let is_formula = is_formula_input(input);
|
||||
if is_formula && gridcraft_model::python::is_py_formula(input) {
|
||||
@@ -71,6 +71,8 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
return Ok(Some(cell));
|
||||
}
|
||||
let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system);
|
||||
// Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped).
|
||||
parsed.value = gridcraft_core::cap_value(parsed.value);
|
||||
// Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already
|
||||
// formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions.
|
||||
if parsed.format.is_none()
|
||||
@@ -317,7 +319,7 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
|
||||
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
|
||||
}
|
||||
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None })
|
||||
Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style, py: None })
|
||||
}
|
||||
}
|
||||
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
|
||||
|
||||
@@ -421,6 +421,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
|
||||
let nm = RangeRef::new(a, b);
|
||||
let sh = cx.sheet_mut(dest_sheet)?;
|
||||
// A table can't hold merged cells (Excel removes the table on open): the
|
||||
// cells are pasted there unmerged.
|
||||
if sh.tables.iter().any(|t| t.range.intersects(&nm)) {
|
||||
continue;
|
||||
}
|
||||
sh.merges.retain(|x| !x.intersects(&nm));
|
||||
sh.merges.push(nm);
|
||||
}
|
||||
|
||||
@@ -148,6 +148,27 @@ fn go_to_keeps_the_references_entered_newest_first() {
|
||||
assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_set_cuts_text_to_32767_characters() {
|
||||
// Excel cuts a 40,000-character entry to 32,767; a formula is left alone.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap();
|
||||
// An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text.
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
|
||||
for at in ["B1", "C1"] {
|
||||
assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}");
|
||||
}
|
||||
assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767));
|
||||
assert_eq!(get(&mut s, "A2"), json!(32767.0));
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap();
|
||||
assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_set_takes_numbers_for_input_and_value() {
|
||||
// #697: a JSON number for `input` used to clear the cell instead of entering it.
|
||||
@@ -208,6 +229,15 @@ fn set_values_can_store_strings_as_the_text_they_are() {
|
||||
assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err());
|
||||
// A line break still turns on Wrap Text.
|
||||
s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap();
|
||||
// Text stored as given still stops at Excel's 32,767-character cell limit.
|
||||
let long = "x".repeat(40_000);
|
||||
s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap();
|
||||
let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count()));
|
||||
assert_eq!(len.flatten(), Some(32_767));
|
||||
s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap();
|
||||
let emoji_len =
|
||||
s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count()));
|
||||
assert_eq!(emoji_len.flatten(), Some(32_766));
|
||||
assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo"));
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
|
||||
@@ -642,6 +642,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let how =
|
||||
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
|
||||
// Excel has no merged cells in a table (a file with one loses the table when Excel opens it):
|
||||
// merging there is refused, unmerging is still allowed.
|
||||
if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) {
|
||||
return Err(EngineError::Other("You can't merge cells in a table.".into()));
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let mut touched = Vec::new();
|
||||
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
|
||||
|
||||
@@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
None => {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
let Some(h) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.hyperlinks.get(&at)) else {
|
||||
let Some(h) = crate::links::cell_link(&s.doc()?.wb, sheet, at) else {
|
||||
return Err(EngineError::Other("There's no hyperlink in this cell.".into()));
|
||||
};
|
||||
h.target.clone()
|
||||
h.target
|
||||
}
|
||||
};
|
||||
match crate::links::classify(&target) {
|
||||
|
||||
@@ -74,6 +74,13 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
|
||||
};
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// As in Excel, the table unmerges the merged cells it covers: a table can't hold them.
|
||||
let merged = sh.merges.len();
|
||||
sh.merges.retain(|m| !m.intersects(&r));
|
||||
if sh.merges.len() != merged {
|
||||
cx.structural = true;
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
|
||||
// headers don't take cubic time.
|
||||
|
||||
@@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"style": style,
|
||||
"merge": sh.merge_at(c).map(|m| m.a1()),
|
||||
"comment": sh.comments.get(&c),
|
||||
"hyperlink": sh.hyperlinks.get(&c),
|
||||
"hyperlink": crate::links::cell_link(&d.wb, sheet, c),
|
||||
"python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({
|
||||
"code": py.code,
|
||||
"output": if py.object { "object" } else { "value" },
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export as PDF",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{path?, sheets?: active|all, range?: \"A1:F40\" (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
|
||||
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -70,7 +70,8 @@ impl SheetLayout {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PrintOptions {
|
||||
pub all_sheets: bool,
|
||||
pub range: Option<RangeRef>,
|
||||
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
|
||||
pub ranges: Vec<RangeRef>,
|
||||
pub fit_to_page: Option<bool>,
|
||||
}
|
||||
|
||||
@@ -81,14 +82,35 @@ impl PrintOptions {
|
||||
Some("all") | Some("workbook") => true,
|
||||
Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))),
|
||||
};
|
||||
let range = match str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) {
|
||||
Some(r) => Some(RangeRef::parse(split_sheet(r).1).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?),
|
||||
None => None,
|
||||
};
|
||||
Ok(PrintOptions { all_sheets, range, fit_to_page: bool_param(p, "fitToPage") })
|
||||
let mut ranges = Vec::new();
|
||||
if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) {
|
||||
for part in split_areas(r) {
|
||||
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
|
||||
}
|
||||
}
|
||||
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a multi-area reference at the commas outside quoted sheet names, so each area keeps
|
||||
/// its own optional `Sheet!` prefix.
|
||||
fn split_areas(r: &str) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let (mut start, mut quoted) = (0, false);
|
||||
for (i, c) in r.char_indices() {
|
||||
match c {
|
||||
'\'' => quoted = !quoted,
|
||||
',' if !quoted => {
|
||||
parts.push(&r[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
parts.push(&r[start..]);
|
||||
parts
|
||||
}
|
||||
|
||||
/// The range a sheet prints: its print area, else the used range grown to cover drawing
|
||||
/// objects. `None` when there is nothing to print.
|
||||
pub fn print_range(sh: &Sheet) -> Option<RangeRef> {
|
||||
@@ -321,14 +343,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
}
|
||||
let ovr = if si == wb.active_sheet() { opts.range } else { None };
|
||||
if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) {
|
||||
let areas: Vec<Option<RangeRef>> =
|
||||
if si == wb.active_sheet() && !opts.ranges.is_empty() { opts.ranges.iter().copied().map(Some).collect() } else { vec![None] };
|
||||
if opts.all_sheets && areas == [None] && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(mut l) = layout_sheet(wb, si, opts, ovr) {
|
||||
l.pages.truncate(MAX_PAGES - pages);
|
||||
pages += l.pages.len();
|
||||
out.push(l);
|
||||
for ovr in areas {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
}
|
||||
if let Some(mut l) = layout_sheet(wb, si, opts, ovr) {
|
||||
l.pages.truncate(MAX_PAGES - pages);
|
||||
pages += l.pages.len();
|
||||
out.push(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.is_empty() && opts.all_sheets {
|
||||
|
||||
@@ -248,7 +248,7 @@ fn rtl_sheet_sparkline_reflects_with_cell_geometry() {
|
||||
color: Color::rgb(255, 0, 0),
|
||||
markers: false,
|
||||
});
|
||||
let options = PrintOptions { range: RangeRef::parse("A1:B2"), ..PrintOptions::default() };
|
||||
let options = PrintOptions { ranges: RangeRef::parse("A1:B2").into_iter().collect(), ..PrintOptions::default() };
|
||||
let ltr = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes;
|
||||
wb.sheet_mut(0).unwrap().right_to_left = true;
|
||||
let rtl = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes;
|
||||
@@ -1387,6 +1387,38 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
|
||||
assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1)));
|
||||
}
|
||||
|
||||
fn preview_ranges(s: &mut Session, p: Json) -> Vec<String> {
|
||||
let r = s.execute("file.printPreview", p).unwrap();
|
||||
r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "H20", "input": "y"})).unwrap();
|
||||
s.execute("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
assert_eq!(preview_ranges(&mut s, json!({})), ["F10:H20"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]);
|
||||
// Several areas, like a multi-area selection: one run of pages each, in the order given.
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"}));
|
||||
assert_eq!(pages, 2);
|
||||
for bad in ["A1:B2,", "A1:B2,nope", ","] {
|
||||
assert!(s.execute("file.printPreview", json!({"range": bad})).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_qualifier_on_a_later_area_does_not_swallow_the_earlier_ones() {
|
||||
let mut s = s();
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
// A comma inside a quoted sheet name is not an area separator.
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,'a,b'!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
}
|
||||
|
||||
/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name.
|
||||
#[test]
|
||||
fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() {
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//! external addresses; only the host, after showing the address and getting OK from the user,
|
||||
//! opens one through [`crate::Session::open_confirmed_link`], which no command reaches.
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::{Hyperlink, Workbook};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::{EngineError, Result, Session, UiRequest};
|
||||
@@ -86,6 +88,50 @@ pub fn classify(target: &str) -> LinkKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The link of a cell: the one stored with it, or, for a cell whose formula is `HYPERLINK(target, …)`,
|
||||
/// the target that formula currently evaluates to. A scheme-less web address (`google.com`) is
|
||||
/// opened over `https`, as Excel does.
|
||||
pub fn cell_link(wb: &Workbook, sheet: usize, at: CellRef) -> Option<Hyperlink> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
if let Some(h) = sh.hyperlinks.get(&at) {
|
||||
return Some(h.clone());
|
||||
}
|
||||
let expr = sh.cell(at)?.formula.as_ref()?.expr()?;
|
||||
let Expr::Call(name, args) = &expr else { return None };
|
||||
if name != "HYPERLINK" {
|
||||
return None;
|
||||
}
|
||||
let value = gridcraft_calc::evaluate_expr(wb, sheet, at, args.first()?);
|
||||
let target = value.display().trim().to_string();
|
||||
if target.is_empty() || matches!(value, gridcraft_core::Value::Error(_)) {
|
||||
return None;
|
||||
}
|
||||
// a defined name or a table of that spelling (`sales.data`) stays an internal target
|
||||
let internal_name = wb.name(&target, sheet).is_some() || wb.table(&target).is_some();
|
||||
let target = if looks_like_web_address(&target) && !internal_name { format!("https://{target}") } else { target };
|
||||
let external = !matches!(classify(&target), LinkKind::Internal(_));
|
||||
Some(Hyperlink { target, tooltip: None, external })
|
||||
}
|
||||
|
||||
fn looks_like_web_address(t: &str) -> bool {
|
||||
if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!')) {
|
||||
return false;
|
||||
}
|
||||
// the host ends at the path, query or fragment (`google.com/x`, `google.com?q=1`, `google.com#top`)
|
||||
let host = t.split(['/', '?', '#']).next().unwrap_or(t);
|
||||
// with an optional port (`example.com:8443`); any other colon is a scheme or a sheet reference
|
||||
let host = match host.split_once(':') {
|
||||
Some((h, port)) if !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()) => h,
|
||||
Some(_) => return false,
|
||||
None => host,
|
||||
};
|
||||
let Some((_, tld)) = host.rsplit_once('.') else { return false };
|
||||
tld.len() >= 2
|
||||
&& tld.chars().all(|c| c.is_ascii_alphabetic())
|
||||
&& !["xlsx", "xlsm", "xlsb", "xls", "csv", "txt", "pdf", "doc", "docx"].contains(&tld.to_ascii_lowercase().as_str())
|
||||
&& RangeRef::parse(t).is_none()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -962,11 +962,13 @@ fn rich_clipboard_omits_html_for_large_ranges_without_truncating_text() {
|
||||
#[test]
|
||||
fn rich_clipboard_omits_html_when_escaping_exceeds_byte_budget() {
|
||||
let mut s = s();
|
||||
let text = "&".repeat(1_000_000);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[text]]})).unwrap();
|
||||
let copied = s.execute("edit.copy", json!({"range": "A1", "html": true})).unwrap();
|
||||
// Cells hold at most 32,767 characters, so 30 full cells of `&` (5 bytes each once escaped)
|
||||
// pass the 4 MiB HTML budget while the plain text stays far below it.
|
||||
let cell = "&".repeat(32_767);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [vec![cell; 30]]})).unwrap();
|
||||
let copied = s.execute("edit.copy", json!({"range": "A1:AD1", "html": true})).unwrap();
|
||||
assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML");
|
||||
assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001);
|
||||
assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30);
|
||||
assert!(copied["text"].as_str().unwrap().ends_with("&\n"));
|
||||
}
|
||||
|
||||
@@ -8170,6 +8172,99 @@ fn history_charges_the_storage_of_empty_comment_replies() {
|
||||
assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_never_hold_merged_cells() {
|
||||
// Excel removes a table that contains a merged cell when it opens the file. Merging in a
|
||||
// table is refused; making or resizing a table over merged cells unmerges them; pasting into
|
||||
// a table skips the merges.
|
||||
let base = || {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1:D4", "values": [["A", "B", "C", "D"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}))
|
||||
.unwrap();
|
||||
s
|
||||
};
|
||||
let merges = |s: &Session| s.doc().unwrap().wb.active().unwrap().merges.clone();
|
||||
|
||||
let mut s = base();
|
||||
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
|
||||
for id in ["home.mergeCells", "home.mergeCenter", "home.mergeAcross"] {
|
||||
for range in ["A2:B2", "A1:B1", "C3:D3"] {
|
||||
let e = s.execute(id, json!({"range": range})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't merge cells in a table"), "{id} {range}: {e}");
|
||||
}
|
||||
}
|
||||
assert!(merges(&s).is_empty());
|
||||
s.execute("home.mergeCells", json!({"range": "E2:F2"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F2").unwrap()]);
|
||||
|
||||
// A table over merged cells unmerges them; undo brings them back.
|
||||
let mut s = base();
|
||||
s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "C3:D4"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "F1:G1"})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("F1:G1").unwrap()]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(merges(&s).len(), 3);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
|
||||
// Resizing a table over merged cells is refused, as in Excel; the merge stays.
|
||||
let mut s = base();
|
||||
s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't overlap merged cells"), "{e}");
|
||||
s.execute("home.unmergeCells", json!({"range": "C2:D2"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap();
|
||||
|
||||
// Merged cells pasted into a table arrive unmerged; elsewhere they stay merged.
|
||||
s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "E2:F3"})).unwrap();
|
||||
s.execute("edit.paste", json!({"at": "A2"})).unwrap();
|
||||
s.execute("edit.paste", json!({"at": "H2"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F3").unwrap(), gridcraft_core::RangeRef::parse("H2:I3").unwrap()]);
|
||||
|
||||
// The saved file has no merge inside the table.
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
let bytes = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap();
|
||||
let (back, _) = crate::io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
let sh = back.active().unwrap();
|
||||
assert_eq!(sh.tables.len(), 1);
|
||||
assert_eq!(sh.tables[0].range, gridcraft_core::RangeRef::parse("A1:C4").unwrap());
|
||||
assert!(sh.merges.iter().all(|m| sh.tables.iter().all(|t| !t.range.intersects(m))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperlink_function_makes_a_cell_link() {
|
||||
let mut s = s();
|
||||
s.link_policy = crate::links::LinkPolicy::Allow;
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "https://example.com/x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "=HYPERLINK(A1,\"Go\")"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C3", "input": "=HYPERLINK(\"google.com\")"})).unwrap();
|
||||
s.take_ui_requests();
|
||||
s.execute("link.open", json!({"cell": "B2"})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://example.com/x".into())]);
|
||||
s.execute("link.open", json!({"cell": "C3"})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://google.com".into())]);
|
||||
assert!(s.execute("link.open", json!({"cell": "A1"})).is_err());
|
||||
// a scheme-less address with a query, fragment or port opens over https too
|
||||
for (cell, input, url) in [
|
||||
("D1", "=HYPERLINK(\"google.com?q=rust\")", "https://google.com?q=rust"),
|
||||
("D2", "=HYPERLINK(\"google.com#results\")", "https://google.com#results"),
|
||||
("D3", "=HYPERLINK(\"example.com:8443/x\")", "https://example.com:8443/x"),
|
||||
] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
s.execute("link.open", json!({"cell": cell})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl(url.into())], "{input}");
|
||||
}
|
||||
// a table named like an address stays an internal target
|
||||
s.execute("range.setValues", json!({"range": "F1:G2", "values": [["a", "b"], [1, 2]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "F1:G2", "name": "sales.data"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D4", "input": "=HYPERLINK(\"sales.data\")"})).unwrap();
|
||||
let link = crate::links::cell_link(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse("D4").unwrap()).unwrap();
|
||||
assert_eq!(link.target, "sales.data");
|
||||
}
|
||||
|
||||
/// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take
|
||||
/// a merged active cell whole, as a click on it does: a merge at A1 and one elsewhere. A
|
||||
/// selection the sheet remembers comes back as it was, even inside a merged cell.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! and saving, reloading or recalculating never panics either;
|
||||
//! - a non-undoable command never changes cell content (it would be lost to undo);
|
||||
//! - the structure stays valid: active sheet in range, sheet and table names valid and unique,
|
||||
//! merges and tables on the sheet and not overlapping, legacy arrays anchored at their
|
||||
//! merges and tables on the sheet and not overlapping (nor a merge inside a table), legacy arrays anchored at their
|
||||
//! top-left cell, the selection on the sheet;
|
||||
//! - a full recalculation from scratch gives the values the incremental recalculation left
|
||||
//! (catches stale dependency graphs);
|
||||
@@ -442,6 +442,10 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option
|
||||
if let Some(o) = sh.tables.iter().skip(k + 1).find(|o| overlaps(&t.range, &o.range)) {
|
||||
return Some(format!("{}: tables `{}` ({}) and `{}` ({}) overlap", sh.name, t.name, t.range, o.name, o.range));
|
||||
}
|
||||
// Excel removes a table that holds a merged cell when it opens the file.
|
||||
if let Some(m) = sh.merges.iter().find(|m| overlaps(&t.range, m)) {
|
||||
return Some(format!("{}: table `{}` ({}) holds merged cells {m}", sh.name, t.name, t.range));
|
||||
}
|
||||
}
|
||||
}
|
||||
if sel.ranges.is_empty() || !sel.active.is_valid() || sel.ranges.iter().any(|r| !r.start.is_valid() || !r.end.is_valid()) {
|
||||
|
||||
@@ -17,7 +17,7 @@ fn value(s: &Session, sheet: &str, cell: &str) -> Value {
|
||||
fn copied_sheet_keeps_spill_values_through_full_recalc() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"sample": "grades"}));
|
||||
run(&mut s, "home.mergeCells", json!({"range": "F:H"}));
|
||||
run(&mut s, "home.mergeCells", json!({"range": "F15:H20"}));
|
||||
run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"}));
|
||||
run(&mut s, "selection.set", json!({"range": "15:15"}));
|
||||
run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1}));
|
||||
|
||||
@@ -22,17 +22,17 @@ fn chars(s: &str) -> Vec<char> {
|
||||
}
|
||||
|
||||
fn check_len(s: String) -> R<Value> {
|
||||
if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT {
|
||||
if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
text_val(s)
|
||||
}
|
||||
|
||||
/// Pushes `piece` onto `out`, failing once the result exceeds the cell limit.
|
||||
fn push_capped(out: &mut String, piece: &str) -> R<()> {
|
||||
fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> {
|
||||
// Checked before copying, so one oversized piece is refused without being appended.
|
||||
if out.len().saturating_add(piece.len()) > MAX_TEXT * 4 {
|
||||
return Err(CellError::Value);
|
||||
return Err(over);
|
||||
}
|
||||
out.push_str(piece);
|
||||
Ok(())
|
||||
@@ -47,22 +47,35 @@ fn piece(v: &Value) -> R<std::borrow::Cow<'_, str>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it.
|
||||
fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let mut out = String::new();
|
||||
for x in a {
|
||||
push_capped(&mut out, &piece(&scalar(x))?)?;
|
||||
// Past the budget, later arguments are still converted so their errors propagate.
|
||||
let v = scalar(x);
|
||||
let piece = piece(&v)?;
|
||||
if out.len() <= MAX_TEXT * 4 {
|
||||
out.push_str(&piece);
|
||||
}
|
||||
}
|
||||
check_len(out)
|
||||
text_val(gridcraft_core::cap_text(out))
|
||||
}
|
||||
|
||||
fn check_calc(s: String) -> R<Value> {
|
||||
if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT {
|
||||
return Err(CellError::Calc);
|
||||
}
|
||||
text_val(s)
|
||||
}
|
||||
|
||||
fn concat(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let mut out = String::new();
|
||||
for x in a {
|
||||
for v in as_array(&x.value).iter() {
|
||||
push_capped(&mut out, &piece(v)?)?;
|
||||
push_capped(&mut out, &piece(v)?, CellError::Calc)?;
|
||||
}
|
||||
}
|
||||
check_len(out)
|
||||
check_calc(out)
|
||||
}
|
||||
|
||||
/// The error `v.to_text()` would give, found without building any text.
|
||||
@@ -98,12 +111,12 @@ fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
&& !delims.data.is_empty()
|
||||
&& let Some(d) = delims.data.get((joined - 1) % delims.data.len())
|
||||
{
|
||||
push_capped(&mut out, &piece(d)?)?;
|
||||
push_capped(&mut out, &piece(d)?, CellError::Calc)?;
|
||||
}
|
||||
push_capped(&mut out, &s)?;
|
||||
push_capped(&mut out, &s, CellError::Calc)?;
|
||||
joined += 1;
|
||||
}
|
||||
check_len(out)
|
||||
check_calc(out)
|
||||
}
|
||||
|
||||
fn count_arg(a: &[Arg], i: usize, default: f64) -> R<usize> {
|
||||
@@ -252,7 +265,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
let n = n.trunc();
|
||||
let total = s.chars().count() as f64 * n;
|
||||
let total = s.encode_utf16().count() as f64 * n;
|
||||
if total > MAX_TEXT as f64 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
@@ -772,7 +785,7 @@ fn arraytotext(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
} else if c > 0 {
|
||||
out.push_str(if strict { "," } else { ", " });
|
||||
}
|
||||
push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?;
|
||||
push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict), CellError::Value)?;
|
||||
}
|
||||
}
|
||||
if strict {
|
||||
@@ -1207,20 +1220,37 @@ mod tests {
|
||||
is_text(ev("TEXTJOIN", vec![t("-"), b(false), av(arr(vec![vec![tv("a"), tv(""), tv("b")]]))]), "a--b");
|
||||
is_text(ev("TEXTJOIN", vec![av(row_t(&[",", ";"])), b(true), t("a"), t("b"), t("c")]), "a,b;c");
|
||||
is_err(ev("CONCAT", vec![t("a"), e(CellError::NA)]), CellError::NA);
|
||||
// Past 32,767 characters: CONCAT and TEXTJOIN are #CALC!, CONCATENATE cuts like `&`
|
||||
// (checked in Excel: LEN(...) is #CALC!, #CALC! and 32767).
|
||||
let x = || t(&"x".repeat(20_000));
|
||||
is_err(ev("CONCAT", vec![x(), x()]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc);
|
||||
assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767)));
|
||||
assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000)));
|
||||
// An error after the cut still propagates.
|
||||
let big = || t(&"x".repeat(32_767));
|
||||
is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA);
|
||||
let emoji = "😀";
|
||||
is_err(ev("CONCAT", vec![t(&emoji.repeat(16_384))]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(""), b(false), t(&emoji.repeat(16_384))]), CellError::Calc);
|
||||
assert_eq!(ev("CONCATENATE", vec![t(&emoji.repeat(16_384))]), Value::text(emoji.repeat(16_383)));
|
||||
is_err(ev("REPT", vec![t(emoji), n(16_384.0)]), CellError::Value);
|
||||
assert_eq!(ev("REPT", vec![t(emoji), n(16_383.0)]), Value::text(emoji.repeat(16_383)));
|
||||
// Lifting: CONCATENATE over an array.
|
||||
assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]);
|
||||
}
|
||||
|
||||
/// Security: TEXTJOIN builds its result piece by piece and stops at the text cap, rather
|
||||
/// than first copying every input (100,000 references to one 32,767-character text were
|
||||
/// 3 GB of copies). Errors among the inputs still win, in argument order.
|
||||
/// 3 GB of copies), giving `#CALC!` there as past the cell limit. Errors among the inputs still
|
||||
/// win, in argument order.
|
||||
#[test]
|
||||
fn textjoin_stops_at_the_text_cap() {
|
||||
use gridcraft_core::Array;
|
||||
let long = tv(&"x".repeat(32_767));
|
||||
let many = || av(Array::filled(100_000, 1, long.clone()).into());
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Value);
|
||||
is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Value);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many(), e(CellError::Div0)]), CellError::Div0);
|
||||
is_err(ev("TEXTJOIN", vec![av(arr(vec![vec![tv(","), Value::Error(CellError::NA)]])), b(true), t("a")]), CellError::NA);
|
||||
// Delimiters cycle and are converted only where used.
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(crate) type R<T> = Result<T, CellError>;
|
||||
|
||||
/// Largest array a function may build.
|
||||
pub(crate) const MAX_CELLS: usize = 10_000_000;
|
||||
/// Longest text a cell can hold.
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub(crate) const MAX_TEXT: usize = 32_767;
|
||||
|
||||
/// Scalar-position lifting tables.
|
||||
@@ -20,11 +20,11 @@ pub(crate) const S: &[bool] = &[true];
|
||||
pub(crate) const A: &[bool] = &[false];
|
||||
|
||||
/// Turns an implementation result into a cell value: errors become error values, non-finite
|
||||
/// numbers become `#NUM!`, text longer than 32,767 characters becomes `#VALUE!`.
|
||||
/// numbers become `#NUM!`, text longer than 32,767 UTF-16 code units becomes `#VALUE!`.
|
||||
pub(crate) fn finish(r: R<Value>) -> Value {
|
||||
match r {
|
||||
Ok(Value::Number(n)) => Value::number(n),
|
||||
Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().count() > MAX_TEXT => Value::Error(CellError::Value),
|
||||
Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value),
|
||||
Ok(v) => v,
|
||||
Err(e) => Value::Error(e),
|
||||
}
|
||||
|
||||
@@ -98,6 +98,31 @@ impl Page {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a print preview was built for: document, revision, scope, the selection when it is
|
||||
/// the scope, and fit to page.
|
||||
type PreviewKey = (u64, u64, PrintScope, String, bool);
|
||||
|
||||
/// What File › Print › Settings prints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PrintScope {
|
||||
ActiveSheets,
|
||||
EntireWorkbook,
|
||||
/// The selected cells of the active sheet.
|
||||
Selection,
|
||||
}
|
||||
|
||||
impl PrintScope {
|
||||
const ALL: [PrintScope; 3] = [PrintScope::ActiveSheets, PrintScope::EntireWorkbook, PrintScope::Selection];
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
PrintScope::ActiveSheets => "Print Active Sheets",
|
||||
PrintScope::EntireWorkbook => "Print Entire Workbook",
|
||||
PrintScope::Selection => "Print Selection",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Document properties shown on the Info page: (`file.properties` key, label).
|
||||
const PROPERTIES: [(&str, &str); 6] = [
|
||||
("title", "Title"),
|
||||
@@ -116,14 +141,14 @@ pub struct Backstage {
|
||||
props: [String; 6],
|
||||
/// Focus at the end of the previous frame, before egui clears it on Esc.
|
||||
text_edit_focused: bool,
|
||||
/// Print: the whole workbook rather than the active sheet.
|
||||
pub print_all: bool,
|
||||
/// Print: what to print (the Settings menu's first choice).
|
||||
pub print_scope: PrintScope,
|
||||
/// Print: fit each sheet on one page.
|
||||
pub fit_to_page: bool,
|
||||
/// Print: the previewed page (0-based).
|
||||
preview_page: usize,
|
||||
/// Print: the preview for (document, revision, whole workbook, fit to page).
|
||||
preview: Option<((u64, u64, bool, bool), Json)>,
|
||||
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
|
||||
preview: Option<(PreviewKey, Json)>,
|
||||
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
|
||||
pub save_format: &'static str,
|
||||
/// Home and Open: when the recent workbooks were last changed.
|
||||
@@ -141,7 +166,7 @@ impl Backstage {
|
||||
page,
|
||||
props: Default::default(),
|
||||
text_edit_focused: false,
|
||||
print_all: false,
|
||||
print_scope: PrintScope::ActiveSheets,
|
||||
fit_to_page: false,
|
||||
preview_page: 0,
|
||||
preview: None,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::{
|
||||
Align2, Backstage, Icon, Json, Outcome, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme, vec2,
|
||||
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
|
||||
vec2,
|
||||
};
|
||||
|
||||
/// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
|
||||
@@ -10,11 +11,19 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
dim(ui, lang.tr("No workbook is open."));
|
||||
return;
|
||||
};
|
||||
let mut params = json!({"sheets": if bs.print_all { "all" } else { "active" }});
|
||||
let mut params = json!({"sheets": if bs.print_scope == PrintScope::EntireWorkbook { "all" } else { "active" }});
|
||||
// The selection is not part of the document revision, so it goes in the preview's key.
|
||||
let mut selection = String::new();
|
||||
if bs.print_scope == PrintScope::Selection
|
||||
&& let Some(d) = app.session.active()
|
||||
{
|
||||
selection = d.selection.a1();
|
||||
params["range"] = json!(selection);
|
||||
}
|
||||
if bs.fit_to_page {
|
||||
params["fitToPage"] = json!(true);
|
||||
}
|
||||
let key = (uid, revision, bs.print_all, bs.fit_to_page);
|
||||
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
|
||||
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
|
||||
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
|
||||
bs.preview = Some((key, preview));
|
||||
@@ -34,14 +43,13 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
out.close = app.services.print_native.is_none();
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" };
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
.width(230.0)
|
||||
.selected_text(lang.tr(scope))
|
||||
.selected_text(lang.tr(bs.print_scope.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for (all, label) in [(false, "Print Active Sheets"), (true, "Print Entire Workbook")] {
|
||||
if ui.selectable_label(bs.print_all == all, lang.tr(label)).clicked() {
|
||||
bs.print_all = all;
|
||||
for scope in PrintScope::ALL {
|
||||
if ui.selectable_label(bs.print_scope == scope, lang.tr(scope.label())).clicked() {
|
||||
bs.print_scope = scope;
|
||||
bs.preview_page = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,7 +531,13 @@ impl Dialog {
|
||||
Choice {
|
||||
key: "operation",
|
||||
label: "Operation",
|
||||
options: vec![("none", "None"), ("add", "Add"), ("subtract", "Subtract"), ("multiply", "Multiply"), ("divide", "Divide")],
|
||||
options: vec![
|
||||
("none", "None"),
|
||||
("add", "Paste Special|Add"),
|
||||
("subtract", "Subtract"),
|
||||
("multiply", "Multiply"),
|
||||
("divide", "Divide"),
|
||||
],
|
||||
},
|
||||
Check { key: "skipBlanks", label: "Skip blanks" },
|
||||
Check { key: "transpose", label: "Transpose (E)" },
|
||||
@@ -673,7 +679,7 @@ impl Dialog {
|
||||
vec![
|
||||
Check { key: "tab", label: "Tab" },
|
||||
Check { key: "semicolon", label: "Semicolon" },
|
||||
Check { key: "comma", label: "Comma" },
|
||||
Check { key: "comma", label: "Text to Columns|Comma" },
|
||||
Check { key: "space", label: "Space" },
|
||||
Text { key: "other", label: "Other:" },
|
||||
Check { key: "treatConsecutive", label: "Treat consecutive delimiters as one" },
|
||||
|
||||
@@ -410,6 +410,13 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
|
||||
}
|
||||
}
|
||||
|
||||
/// The link of cell `c` on the active sheet as the session holds it now: a click may have just
|
||||
/// committed an edit the frame's workbook snapshot predates (a `HYPERLINK` target cell).
|
||||
fn current_cell_link(app: &SheetApp, c: CellRef) -> Option<gridcraft_engine::model::Hyperlink> {
|
||||
let d = app.session.active()?;
|
||||
gridcraft_engine::links::cell_link(&d.wb, d.wb.active_sheet(), c)
|
||||
}
|
||||
|
||||
fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response);
|
||||
let (pos, mods, sel) = (input.position, input.modifiers, &input.selection);
|
||||
@@ -553,7 +560,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
}
|
||||
} else if mods.command || sel_mods.command {
|
||||
// Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection.
|
||||
if let Some(h) = sh.hyperlinks.get(&c).cloned()
|
||||
if let Some(h) = current_cell_link(app, c)
|
||||
&& acts
|
||||
&& !mods.alt
|
||||
&& p.x < geo.cell_rect(sh, c).left() + geo.cell_rect(sh, c).width() * 0.8
|
||||
@@ -570,7 +577,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let _ = app.run("cell.toggleCheckbox", json!({"cell": c.a1()}));
|
||||
}
|
||||
// A click on a hyperlink's text follows it (like Excel); elsewhere in the cell selects.
|
||||
if let Some(h) = sh.hyperlinks.get(&c).cloned()
|
||||
if let Some(h) = current_cell_link(app, c)
|
||||
&& acts
|
||||
&& !mods.any()
|
||||
{
|
||||
|
||||
@@ -781,7 +781,7 @@ pub(crate) fn paint_overlays(input: OverlayInput<'_>) {
|
||||
);
|
||||
}
|
||||
// Hyperlink tooltip.
|
||||
if let Some(h) = hover.and_then(|c| sh.hyperlinks.get(&c))
|
||||
if let Some(h) = hover.and_then(|c| gridcraft_engine::links::cell_link(wb, si, c))
|
||||
&& app.editor.is_none()
|
||||
{
|
||||
let tip = h.tooltip.clone().unwrap_or_else(|| format!("{}\nClick once to follow. Click and hold to select this cell.", h.target));
|
||||
|
||||
@@ -667,6 +667,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_special_add_and_text_to_columns_comma_have_their_own_keys() {
|
||||
// "Add" is also the Solver button and "Comma" also the cell style (Spanish Excel: Sumar
|
||||
// vs Agregar, Coma vs Millares), so the two dialog options are keyed by context. English
|
||||
// shows the plain label, and a catalog that translates the plain label translates the
|
||||
// keyed one too, so the dialog option doesn't fall back to English.
|
||||
for (keyed, plain) in [("Paste Special|Add", "Add"), ("Text to Columns|Comma", "Comma")] {
|
||||
assert_eq!(Language::En.tr(keyed), plain);
|
||||
for language in Language::ALL {
|
||||
let shown = language.tr(keyed);
|
||||
assert!(!shown.contains('|'), "{} shows a context prefix for {keyed}: {shown}", language.code());
|
||||
if language.tr(plain) != plain {
|
||||
assert_ne!(shown, plain, "{} translates {plain:?} but not {keyed:?}", language.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translations_never_show_the_context_prefix() {
|
||||
// `tr` returns a found translation as it is, so a catalog that keeps `context|` in its
|
||||
|
||||
@@ -337,6 +337,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Uloží sešit pod jiným názvem nebo do jiné složky.",
|
||||
"Print Active Sheets" => "Vytisknout aktivní listy",
|
||||
"Print Entire Workbook" => "Vytisknout celý sešit",
|
||||
"Print Selection" => "Vytisknout výběr",
|
||||
"Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku",
|
||||
"Page Setup…" => "Vzhled stránky…",
|
||||
"Page {page} of {pages}" => "Stránka {page} z {pages}",
|
||||
|
||||
@@ -356,6 +356,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
}
|
||||
"Print Active Sheets" => "Aktive Blätter drucken",
|
||||
"Print Entire Workbook" => "Gesamte Arbeitsmappe drucken",
|
||||
"Print Selection" => "Auswahl drucken",
|
||||
"Fit Sheet on One Page" => "Blatt auf einer Seite darstellen",
|
||||
"Page Setup…" => "Seite einrichten…",
|
||||
"Page {page} of {pages}" => "Seite {page} von {pages}",
|
||||
|
||||
@@ -315,6 +315,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Αποθηκεύστε το βιβλίο εργασίας με άλλο όνομα ή σε άλλον φάκελο.",
|
||||
"Print Active Sheets" => "Εκτύπωση ενεργών φύλλων",
|
||||
"Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας",
|
||||
"Print Selection" => "Εκτύπωση επιλογής",
|
||||
"Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα",
|
||||
"Page Setup…" => "Διαμόρφωση σελίδας…",
|
||||
"Page {page} of {pages}" => "Σελίδα {page} από {pages}",
|
||||
@@ -671,6 +672,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Τιμές και μορφές αριθμών",
|
||||
"Operation" => "Πράξη",
|
||||
"Add" => "Πρόσθεση",
|
||||
"Paste Special|Add" => "Πρόσθεση",
|
||||
"Subtract" => "Αφαίρεση",
|
||||
"Multiply" => "Πολλαπλασιασμός",
|
||||
"Divide" => "Διαίρεση",
|
||||
@@ -708,6 +710,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Στηλοθέτης",
|
||||
"Semicolon" => "Ερωτηματικό (;)",
|
||||
"Comma" => "Κόμμα",
|
||||
"Text to Columns|Comma" => "Κόμμα",
|
||||
"Space" => "Διάστημα",
|
||||
"Other:" => "Άλλο:",
|
||||
"Treat consecutive delimiters as one" => "Αντιμετώπιση διαδοχικών διαχωριστικών ως ενός",
|
||||
|
||||
@@ -343,6 +343,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Guarda el libro con otro nombre o en otra carpeta.",
|
||||
"Print Active Sheets" => "Imprimir hojas activas",
|
||||
"Print Entire Workbook" => "Imprimir todo el libro",
|
||||
"Print Selection" => "Imprimir selección",
|
||||
"Fit Sheet on One Page" => "Ajustar hoja en una página",
|
||||
"Page Setup…" => "Configurar página…",
|
||||
"Page {page} of {pages}" => "Página {page} de {pages}",
|
||||
|
||||
@@ -432,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Enregistrer le classeur sous un autre nom ou dans un autre dossier.",
|
||||
"Print Active Sheets" => "Imprimer les feuilles actives",
|
||||
"Print Entire Workbook" => "Imprimer tout le classeur",
|
||||
"Print Selection" => "Imprimer la sélection",
|
||||
"Fit Sheet on One Page" => "Ajuster la feuille sur une page",
|
||||
"Page Setup…" => "Mise en page…",
|
||||
"Page {page} of {pages}" => "Page {page} sur {pages}",
|
||||
|
||||
@@ -417,6 +417,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Salva la cartella di lavoro con un altro nome o in un'altra cartella.",
|
||||
"Print Active Sheets" => "Stampa fogli attivi",
|
||||
"Print Entire Workbook" => "Stampa intera cartella di lavoro",
|
||||
"Print Selection" => "Stampa selezione",
|
||||
"Fit Sheet on One Page" => "Adatta foglio a una pagina",
|
||||
"Page Setup…" => "Imposta pagina…",
|
||||
"Page {page} of {pages}" => "Pagina {page} di {pages}",
|
||||
@@ -552,6 +553,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Valori e formati numero",
|
||||
"Operation" => "Operazione",
|
||||
"Add" => "Aggiungi",
|
||||
"Paste Special|Add" => "Aggiungi",
|
||||
"Subtract" => "Sottrai",
|
||||
"Multiply" => "Moltiplica",
|
||||
"Divide" => "Dividi",
|
||||
@@ -591,6 +593,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulazione",
|
||||
"Semicolon" => "Punto e virgola",
|
||||
"Comma" => "Virgola",
|
||||
"Text to Columns|Comma" => "Virgola",
|
||||
"Space" => "Spazio",
|
||||
"Other:" => "Altro:",
|
||||
"Treat consecutive delimiters as one" => "Considera delimitatori consecutivi come uno solo",
|
||||
|
||||
@@ -420,6 +420,7 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"),
|
||||
("Print Active Sheets", "作業中のシートを印刷"),
|
||||
("Print Entire Workbook", "ブック全体を印刷"),
|
||||
("Print Selection", "選択した部分を印刷"),
|
||||
("Fit Sheet on One Page", "シートを 1 ページに印刷"),
|
||||
("Page Setup…", "ページ設定…"),
|
||||
("Page {page} of {pages}", "{page} / {pages} ページ"),
|
||||
@@ -569,6 +570,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Values and number formats", "値と数値の書式"),
|
||||
("Operation", "演算"),
|
||||
("Add", "加算"),
|
||||
("Paste Special|Add", "加算"),
|
||||
("Subtract", "減算"),
|
||||
("Multiply", "乗算"),
|
||||
("Divide", "除算"),
|
||||
@@ -608,6 +610,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Tab", "タブ"),
|
||||
("Semicolon", "セミコロン"),
|
||||
("Comma", "コンマ"),
|
||||
("Text to Columns|Comma", "コンマ"),
|
||||
("Space", "スペース"),
|
||||
("Other:", "その他:"),
|
||||
("Treat consecutive delimiters as one", "連続した区切り文字は 1 文字として扱う"),
|
||||
|
||||
@@ -432,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "통합 문서를 다른 이름 또는 다른 폴더에 저장합니다.",
|
||||
"Print Active Sheets" => "활성 시트 인쇄",
|
||||
"Print Entire Workbook" => "전체 통합 문서 인쇄",
|
||||
"Print Selection" => "선택 영역 인쇄",
|
||||
"Fit Sheet on One Page" => "한 페이지에 시트 맞추기",
|
||||
"Page Setup…" => "페이지 설정…",
|
||||
"Page {page} of {pages}" => "{page}/{pages} 페이지",
|
||||
|
||||
@@ -419,6 +419,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "De werkmap onder een andere naam of in een andere map opslaan.",
|
||||
"Print Active Sheets" => "Actieve bladen afdrukken",
|
||||
"Print Entire Workbook" => "Hele werkmap afdrukken",
|
||||
"Print Selection" => "Selectie afdrukken",
|
||||
"Fit Sheet on One Page" => "Blad op één pagina passen",
|
||||
"Page Setup…" => "Pagina-instelling…",
|
||||
"Page {page} of {pages}" => "Pagina {page} van {pages}",
|
||||
|
||||
@@ -409,6 +409,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Zapisz skoroszyt pod inną nazwą lub w innym folderze.",
|
||||
"Print Active Sheets" => "Drukuj aktywne arkusze",
|
||||
"Print Entire Workbook" => "Drukuj cały skoroszyt",
|
||||
"Print Selection" => "Drukuj zaznaczenie",
|
||||
"Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony",
|
||||
"Page Setup…" => "Ustawienia strony…",
|
||||
"Page {page} of {pages}" => "Strona {page} z {pages}",
|
||||
@@ -543,6 +544,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Wartości i formaty liczb",
|
||||
"Operation" => "Operacja",
|
||||
"Add" => "Dodaj",
|
||||
"Paste Special|Add" => "Dodaj",
|
||||
"Subtract" => "Odejmij",
|
||||
"Multiply" => "Pomnóż",
|
||||
"Divide" => "Podziel",
|
||||
@@ -582,6 +584,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulator",
|
||||
"Semicolon" => "Średnik",
|
||||
"Comma" => "Przecinek",
|
||||
"Text to Columns|Comma" => "Przecinek",
|
||||
"Space" => "Spacja",
|
||||
"Other:" => "Inny:",
|
||||
"Treat consecutive delimiters as one" => "Traktuj kolejne ograniczniki jako jeden",
|
||||
|
||||
@@ -426,6 +426,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Salve a pasta de trabalho com outro nome ou em outra pasta.",
|
||||
"Print Active Sheets" => "Imprimir planilhas ativas",
|
||||
"Print Entire Workbook" => "Imprimir toda a pasta de trabalho",
|
||||
"Print Selection" => "Imprimir seleção",
|
||||
"Fit Sheet on One Page" => "Ajustar planilha em uma página",
|
||||
"Page Setup…" => "Configurar página…",
|
||||
"Page {page} of {pages}" => "Página {page} de {pages}",
|
||||
@@ -579,6 +580,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Valores e formatos de número",
|
||||
"Operation" => "Operação",
|
||||
"Add" => "Adicionar",
|
||||
"Paste Special|Add" => "Adicionar",
|
||||
"Subtract" => "Subtrair",
|
||||
"Multiply" => "Multiplicar",
|
||||
"Divide" => "Dividir",
|
||||
@@ -618,6 +620,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulação",
|
||||
"Semicolon" => "Ponto e vírgula",
|
||||
"Comma" => "Vírgula",
|
||||
"Text to Columns|Comma" => "Vírgula",
|
||||
"Space" => "Espaço",
|
||||
"Other:" => "Outros:",
|
||||
"Treat consecutive delimiters as one" => "Considerar delimitadores consecutivos como um só",
|
||||
|
||||
@@ -416,6 +416,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Salvează registrul cu alt nume sau în alt folder.",
|
||||
"Print Active Sheets" => "Imprimare foi active",
|
||||
"Print Entire Workbook" => "Imprimare tot registrul",
|
||||
"Print Selection" => "Imprimare selecție",
|
||||
"Fit Sheet on One Page" => "Încadrare foaie pe o pagină",
|
||||
"Page Setup…" => "Configurare pagină…",
|
||||
"Page {page} of {pages}" => "Pagina {page} din {pages}",
|
||||
@@ -549,6 +550,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Valori și formate de număr",
|
||||
"Operation" => "Operație",
|
||||
"Add" => "Adăugare",
|
||||
"Paste Special|Add" => "Adăugare",
|
||||
"Subtract" => "Scădere",
|
||||
"Multiply" => "Înmulțire",
|
||||
"Divide" => "Împărțire",
|
||||
@@ -588,6 +590,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tab",
|
||||
"Semicolon" => "Punct și virgulă",
|
||||
"Comma" => "Virgulă",
|
||||
"Text to Columns|Comma" => "Virgulă",
|
||||
"Space" => "Spațiu",
|
||||
"Other:" => "Altele:",
|
||||
"Treat consecutive delimiters as one" => "Delimitatorii consecutivi se tratează ca unul singur",
|
||||
|
||||
@@ -431,6 +431,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Сохранить книгу под другим именем или в другой папке.",
|
||||
"Print Active Sheets" => "Напечатать активные листы",
|
||||
"Print Entire Workbook" => "Напечатать всю книгу",
|
||||
"Print Selection" => "Напечатать выделенный диапазон",
|
||||
"Fit Sheet on One Page" => "Вписать лист на одну страницу",
|
||||
"Page Setup…" => "Параметры страницы…",
|
||||
"Page {page} of {pages}" => "Страница {page} из {pages}",
|
||||
@@ -483,6 +484,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Action" => "Действие",
|
||||
"Action Journal" => "Журнал действий",
|
||||
"Add" => "Добавить",
|
||||
"Paste Special|Add" => "Добавить",
|
||||
"Add Chart Element" => "Добавить элемент диаграммы",
|
||||
"Add subtotal to (columns, e.g. C,D):" => "Добавить итоги по (столбцы, например C,D):",
|
||||
"Add to Dictionary" => "Добавить в словарь",
|
||||
@@ -545,6 +547,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Columns (blank = all, e.g. A,C):" => "Столбцы (пусто = все, например A,C):",
|
||||
"Combo" => "Комбинированная",
|
||||
"Comma" => "Запятая",
|
||||
"Text to Columns|Comma" => "Запятая",
|
||||
"Comment:" => "Комментарий:",
|
||||
"Comments and notes (C)" => "Комментарии и заметки (C)",
|
||||
"Comments pane" => "Область комментариев",
|
||||
|
||||
@@ -425,6 +425,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Sačuvaj radnu svesku pod drugim imenom ili u drugoj fascikli.",
|
||||
"Print Active Sheets" => "Štampaj aktivne listove",
|
||||
"Print Entire Workbook" => "Štampaj celu radnu svesku",
|
||||
"Print Selection" => "Štampaj izbor",
|
||||
"Fit Sheet on One Page" => "Uklopi list na jednu stranicu",
|
||||
"Page Setup…" => "Podešavanje stranice…",
|
||||
"Page {page} of {pages}" => "Stranica {page} od {pages}",
|
||||
|
||||
@@ -330,6 +330,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Çalışma kitabını başka bir adla veya başka bir klasöre kaydedin.",
|
||||
"Print Active Sheets" => "Etkin Sayfaları Yazdır",
|
||||
"Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır",
|
||||
"Print Selection" => "Seçimi Yazdır",
|
||||
"Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır",
|
||||
"Page Setup…" => "Sayfa Yapısı…",
|
||||
"Page {page} of {pages}" => "Sayfa {page} / {pages}",
|
||||
|
||||
@@ -414,6 +414,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Зберегти книгу під іншим іменем або в іншій теці.",
|
||||
"Print Active Sheets" => "Надрукувати активні аркуші",
|
||||
"Print Entire Workbook" => "Надрукувати всю книгу",
|
||||
"Print Selection" => "Надрукувати виділений діапазон",
|
||||
"Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку",
|
||||
"Page Setup…" => "Параметри сторінки…",
|
||||
"Page {page} of {pages}" => "Сторінка {page} з {pages}",
|
||||
@@ -547,6 +548,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Values and number formats",
|
||||
"Operation" => "Operation",
|
||||
"Add" => "Add",
|
||||
"Paste Special|Add" => "Add",
|
||||
"Subtract" => "Subtract",
|
||||
"Multiply" => "Multiply",
|
||||
"Divide" => "Divide",
|
||||
@@ -586,6 +588,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tab",
|
||||
"Semicolon" => "Semicolon",
|
||||
"Comma" => "Comma",
|
||||
"Text to Columns|Comma" => "Comma",
|
||||
"Space" => "Space",
|
||||
"Other:" => "Other:",
|
||||
"Treat consecutive delimiters as one" => "Treat consecutive delimiters as one",
|
||||
|
||||
+880
-139
File diff suppressed because it is too large.
Load diff
@@ -424,6 +424,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "以其他名称或在其他文件夹中保存工作簿。",
|
||||
"Print Active Sheets" => "打印活动工作表",
|
||||
"Print Entire Workbook" => "打印整个工作簿",
|
||||
"Print Selection" => "打印选定区域",
|
||||
"Fit Sheet on One Page" => "将工作表调整为一页",
|
||||
"Page Setup…" => "页面设置…",
|
||||
"Page {page} of {pages}" => "第 {page} 页,共 {pages} 页",
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! File › Print › Settings offers "Print Selection": only the selected cells are previewed and sent.
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::{Services, SheetApp};
|
||||
use serde_json::json;
|
||||
|
||||
fn contains(hay: &[u8], needle: &str) -> bool {
|
||||
hay.windows(needle.len()).any(|w| w == needle.as_bytes())
|
||||
}
|
||||
|
||||
/// A sheet whose print area (F10:H20, "Outside") is not where the selection (A1:B2, "Inside") is,
|
||||
/// so printing the selection and printing the sheet give different pages.
|
||||
fn harness(jobs: Rc<RefCell<Vec<Vec<u8>>>>) -> egui_kittest::Harness<'static, SheetApp> {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Services::default());
|
||||
app.run("cell.set", json!({"cell": "A1", "input": "Inside"})).unwrap();
|
||||
app.run("cell.set", json!({"cell": "D4", "input": "Second area"})).unwrap();
|
||||
app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
app.run("selection.set", json!({"range": "A1:B2"})).unwrap();
|
||||
app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec())));
|
||||
app.run("ui.backstage", json!({"page": "print"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn choose_selection(h: &mut egui_kittest::Harness<'static, SheetApp>) {
|
||||
h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("print scope combo").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Print Selection").click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_selection_previews_and_prints_only_the_selected_cells() {
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut h = harness(jobs.clone());
|
||||
assert!(h.query_by_label("Sheet1 · F10:H20").is_some(), "the sheet prints its print area by default");
|
||||
choose_selection(&mut h);
|
||||
assert!(h.query_by_label("Sheet1 · A1:B2").is_some(), "the preview shows the selection");
|
||||
assert!(h.query_by_label("Sheet1 · F10:H20").is_none());
|
||||
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(contains(&jobs[0], "(Inside) Tj"), "the selected cell is printed");
|
||||
assert!(!contains(&jobs[0], "(Outside) Tj"), "the print area is not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() {
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut h = harness(jobs.clone());
|
||||
choose_selection(&mut h);
|
||||
assert!(h.query_by_label("Sheet1 · A1:B2").is_some());
|
||||
|
||||
// Same document revision, other selection: the cached preview must not be reused.
|
||||
h.state_mut().run("selection.set", json!({"range": "D4:E5"})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Sheet1 · D4:E5").is_some(), "the preview is rebuilt for the new selection");
|
||||
assert!(h.query_by_label("Sheet1 · A1:B2").is_none());
|
||||
|
||||
// Two selected areas: Excel prints each area on its own page.
|
||||
h.state_mut().run("selection.set", json!({"range": "A1:B2,D4:E5"})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages");
|
||||
}
|
||||
@@ -300,9 +300,9 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook
|
||||
},
|
||||
None => StyleId::DEFAULT,
|
||||
};
|
||||
Cell { value: p.value, formula: None, style, py: None }
|
||||
Cell { value: gridcraft_core::cap_value(p.value), formula: None, style, py: None }
|
||||
} else {
|
||||
Cell::value(Value::Text(Arc::from(f)))
|
||||
Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f))))
|
||||
};
|
||||
sheet.cells.set(pos, cell);
|
||||
}
|
||||
|
||||
@@ -418,6 +418,19 @@ fn parser_stops_collecting_fields_at_max_cols() {
|
||||
assert_eq!(lens, vec![MAX_COLS as usize]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_over_32767_characters_is_cut() {
|
||||
let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000));
|
||||
for parse_values in [true, false] {
|
||||
let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap();
|
||||
assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767)));
|
||||
assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767)));
|
||||
}
|
||||
// The apostrophe is dropped before the cut when values are parsed.
|
||||
let wb = read_csv(src.as_bytes(), &CsvOptions::default()).unwrap();
|
||||
assert_eq!(v(&wb, 0, 2), Value::text("z".repeat(32_767)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_used_range_limit_is_enforced_while_reading() {
|
||||
let opts = |max| CsvOptions { max_used_cells: Some(max), ..Default::default() };
|
||||
|
||||
@@ -1013,8 +1013,8 @@ Fixtures are built in code and never committed as large binaries:
|
||||
|
||||
- `Session::new()` + `file.new {sample: "sales"|"budget"|"grades"}` for the three samples.
|
||||
- A 100,000-row × 6-column workbook built through `range.setValues` in 10,000-row chunks, plus
|
||||
formulas `G=B*C+D`, a chained running sum, `SUM`/`SUMIFS`/`XLOOKUP` and a sort, mirroring
|
||||
`crates/engine/examples/perf.rs`.
|
||||
formulas `G=B*C+D`, a chained running sum, `SUM`/`SUMIFS`/`XLOOKUP` and a sort, like the
|
||||
workloads in `crates/engine/examples/bench.rs` (`cargo xtask bench`).
|
||||
- A two-sheet workbook with a formula being pointed across sheets, a right-to-left sheet, frozen
|
||||
panes, merged cells, a table, a chart, comments/notes, validation and a cell picture.
|
||||
- Password-protected and corrupt-font fixtures through `gridcraft-xlsx`'s `test-support` feature
|
||||
@@ -1111,7 +1111,7 @@ Never report compile duration as UI performance.
|
||||
| Startup | fresh process → first painted frame / control channel ready | wall time, split font setup, wgpu renderer creation, first frame |
|
||||
| Grid scroll | `sales`/100k-row synthetic workbook, 1,000 frames of vertical/horizontal scroll | frame distribution, `grid_ms`, tessellation time, vertices/indices, uploads |
|
||||
| Cell edit | type/commit 1,000 cells via control channel | command latency, frame CPU, undo memory |
|
||||
| Recalc | `crates/engine/examples/perf` on the same workbook | engine-only latency, recalc cell count (not a UI number) |
|
||||
| Recalc | `cargo xtask bench` (`crates/engine/examples/bench.rs`, fixed in-code workbooks; `recalc.full` and the edit scenarios) | engine-only latency, recalc cell count (not a UI number) |
|
||||
| Dialog/ribbon | open/close Format Cells, switch tabs, type filter | CPU frame time, paint counts |
|
||||
| Text tessellation | fixed 120-ASCII-label scene + mixed color-glyph row | per-tessellate time/instructions; reproduce #8731 |
|
||||
| Fonts | 20 cold starts with the same font set | discovery/build/set_fonts time, peak RSS |
|
||||
|
||||
+9
-5
@@ -1,6 +1,6 @@
|
||||
# Gaps
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (§5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: File › Print › Settings: Print Selection; earlier: §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
|
||||
Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone
|
||||
@@ -28,9 +28,11 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
- **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md)
|
||||
|
||||
### 2. Large workbooks don't open; recalc is single-threaded (P, H)
|
||||
- **Missing:** streaming read for ~100 MB XLSX; multi-threaded recalc; 100k-dependent edit under
|
||||
100 ms (was ~0.4 s); whole-sheet operations bounded.
|
||||
- **Evidence:** #175; no threading in `crates/calc`; PR #152 (whole-sheet Fill/Remove Duplicates
|
||||
- **Missing:** streaming read for ~100 MB XLSX; multi-threaded recalc; faster whole-column
|
||||
SUMIFS and lookups (100 of either over 100k rows take 0.16–0.59 s per edit); whole-sheet
|
||||
operations bounded. A 100k-dependent edit measures 90–106 ms, around the 100 ms target
|
||||
(`cargo xtask bench`).
|
||||
- **Evidence:** #175; `cargo xtask bench`; no threading in `crates/calc`; PR #152 (whole-sheet Fill/Remove Duplicates
|
||||
out of memory), PR #151 (current region past 10,000 rows).
|
||||
- **Impact:** finance and data users routinely have big workbooks.
|
||||
- **Estimate:** 25–40 h. [target-app-parity.md](target-app-parity.md#performance), [hardware-parity.md](hardware-parity.md)
|
||||
@@ -147,7 +149,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
|
||||
### 14. Page Layout view and print polish (U, F)
|
||||
- Page Layout view landed (#329): paper view with rulers and in-place header/footer editing.
|
||||
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print ranges and driver tray/options UI remain. **Estimate:** 5–10 h.
|
||||
Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h.
|
||||
|
||||
### 15. Remaining functions and an oracle suite (F)
|
||||
- 9 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 15–25 h.
|
||||
@@ -209,7 +211,9 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
| 2026-10-26 | minor | §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry. Other script and UI gaps remain. |
|
||||
| 2026-10-26 | minor | Arabic shared bidi display/editing and persisted cell reading direction; other script and PDF work remain separate |
|
||||
| 2026-10-26 | minor | §5: Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work |
|
||||
| 2026-10-26 | minor | #2: measured with `cargo xtask bench`; 100k-dependent edit around 100 ms, whole-column SUMIFS/XLOOKUP added |
|
||||
| 2026-10-24 | minor | §8: PivotTable Enable show details: `pivot.options` `enableShowDetails` turns Show Details off for a PivotTable, read and written in XLSX as `enableDrill` |
|
||||
| 2026-10-23 | minor | §14: Print Selection landed in File › Print › Settings (several selected areas print one after the other); "print ranges" removed from the remainder |
|
||||
| 2026-10-23 | minor | §8: PivotTable Show Details: double-clicking a value cell lists its source records on a new sheet (#2364) |
|
||||
| 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) |
|
||||
| 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Localization parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (fill-handle and Home › Fill menu labels in every catalog); previously minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Brazilian Portuguese function help); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Paste Special's Add and Text to Columns' Comma get their own keys); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: fill-handle and Home › Fill menu labels in every catalog); previously minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Brazilian Portuguese function help); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Per-language status against Excel, which ships its UI in dozens of languages (Windows language
|
||||
packs cover 100+), with localized function names, argument separators, number and date formats,
|
||||
@@ -118,11 +118,10 @@ separators, number/date formats, machine translation with agent review, and scri
|
||||
| German | de | 266 (~12%) | no | Latin: yes | no | menus only | 4–8 h |
|
||||
| Italian | it | 971 (~44%) | dialogs, tooltips, pivot pane | Latin: yes | no | menus, File view, dialogs, pivot pane | 3–5 h |
|
||||
| Korean | ko | 266 (~12%) | no | Hangul via the CJK fallback; IME unverified | no | menus only | 6–10 h |
|
||||
| Vietnamese | vi | 0 (0%) | no | Latin with stacked diacritics: unverified | no | none | 6–10 h |
|
||||
| Vietnamese | vi | 1,170 (~53%) | dialogs, PivotTable pane and tooltips | Latin with stacked diacritics: unverified | no | menus, File view, dialogs, pivot pane | 2–4 h |
|
||||
| Turkish | tr | 382 (~17%) | no | Latin: yes | yes | menus only | 4–8 h |
|
||||
|
||||
Other shipped languages: Russian (ru), German (de), Czech (cs), French (fr) and Turkish (tr), menus only.
|
||||
| Vietnamese | vi | 398 (~18%) | no | Latin with stacked diacritics: unverified | no | menus, File view | 5–9 h |
|
||||
Other shipped languages: Russian (ru) and German (de), 266 labels each (~12%), menus only; Dutch (nl), 518 labels (~24%): ribbon, context menus, File view, dialog titles and the Options page.
|
||||
|
||||
**Total:** catalog work 10–20 h + languages 92–144 h ≈ **100–165 h**. Parallelizes almost fully
|
||||
@@ -153,11 +152,13 @@ language (none so far) and of localized function names.
|
||||
| 2026-11-09 | minor | Arabic PDF export no longer fails on a character the Arabic face lacks (it falls back like other text) or when no Arabic font is available (Arabic is set in the CID font, which has no Arabic glyphs, and a message says so) |
|
||||
| 2026-10-31 | minor | System and embedded CJK text fallbacks share the Latin baseline in cells, editors and window titles; other scripts, symbols and emoji keep their alignment |
|
||||
| 2026-11-08 | minor | Strings built with `format!` in English now translate their template first and fill it in once (`Language::tr_fill`): status bar statistics and the circular-reference note, the column width / row height drag tip, the formula bar text for a picture in a cell, the Move or Copy and Unhide notes, the Format Control title, the equation editor's error prefix and its own check messages (macro definitions, `%` with a link, nesting, length, matrix-cell and size limits; RaTeX parser errors stay English), and the Goal Seek and macro recorder/runner toasts (#3600, #3602, #3603, #3605, #3607–#3611). 24 new keys in every catalog; Average, Count, Sum and the three existing templates added to the 11 catalogs that lacked them, and Ukrainian's English placeholders for those six replaced. Numbers in these strings keep the `.` decimal point |
|
||||
| 2026-11-02 | minor | Vietnamese catalog (`i18n/vi.rs`) expanded to 1,170 entries (~53%), covering every key across all catalogs (dialogs, File backstage, PivotTable pane, print settings, cell styles, conditional formatting, chart types, macros, context menus and tooltips; 0 missing in `cargo xtask i18n-report`) |
|
||||
| 2026-10-26 | minor | Arabic PDF cells inherit explicit or contextual direction; wrapped lines retain paragraph direction, and RTL pages mirror cell and object geometry |
|
||||
| 2026-10-26 | minor | Shared bidi layout supports Arabic clusters, marks, visual cursor navigation and directional accessibility; cell Context/LTR/RTL is stored separately from sheet RTL and round-trips through XLSX |
|
||||
| 2026-10-26 | minor | Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work |
|
||||
| 2026-10-27 | minor | Number formats honour the `B1`/`B2` calendar prefixes: never shown; `B2` renders year, month, day and Arabic month and weekday names in the tabular Hijri calendar (1 Jan 2001 = 6 Shawwal 1421; leap years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26 and 29 of the 30-year cycle, which is what Excel shows). Checked against Excel 16.0 (build 20527, en-US) on every serial and about 1,700 format/value pairs: a locale or currency tag before `B2` keeps the date Gregorian, a misplaced `B` and digit or a prefix before a number format is rejected, serial 60 has no Hijri date, serial 0 shows as serial 1, two-word month names use a no-break space. Not matched: Excel's weekday/month-name mix-ups in one `B2` section and its weekday-only quirks |
|
||||
| 2026-10-27 | minor | AutoFit column width, wrapped-row height and PivotTable column fit estimate Arabic letters at ~0.48 em (measured 0.36–0.53 em shaped, Noto Sans/Naskh Arabic and DejaVu Sans) instead of 1 em, Arabic-Indic digits as wide as ASCII digits, and give vowel marks and direction marks no width; vowelled Arabic no longer fits ~3.5× too wide |
|
||||
| 2026-10-26 | minor | Paste Special's Add operation and Text to Columns' Comma delimiter are keyed `Paste Special\|Add` and `Text to Columns\|Comma`, so they can be translated apart from the Solver's Add button and the Comma cell style (Spanish: Sumar vs Agregar, Coma vs Millares); every catalog keeps the text it showed |
|
||||
| 2026-10-26 | minor | Arabic PDF cells, headers and chart labels support joined letters, combining marks, digits, bold/italic, rotation and grapheme wrapping |
|
||||
| 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay |
|
||||
| 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review |
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
# Roadmap detail
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (test command) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (`cargo xtask bench`: measured recalc baselines) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
Forward-looking plan. The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work
|
||||
list is [`gaps.md`](gaps.md); numbers and method are in
|
||||
@@ -107,12 +107,14 @@ to check our files, and Windows machines with the reported GPU drivers.
|
||||
- Function coverage: the script method in [function-parity.md](function-parity.md). A
|
||||
`cargo xtask functions` that diffs the registry against a checked-in Excel name list would make
|
||||
it a CI number (1–2 h).
|
||||
- No `cargo xtask scorecard` or `bench` yet.
|
||||
- `cargo xtask bench`: recalc, entry, sort and XLSX timings on fixed in-code workbooks, compared
|
||||
with a local baseline (`--save`). No `cargo xtask scorecard` yet.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-26 | minor | Measuring: `cargo xtask bench` |
|
||||
| 2026-10-23 | minor | Measuring: tests run through `cargo xtask test` |
|
||||
| 2026-10-11 | minor | PivotTable calculated fields landed |
|
||||
| 2026-10-10 | minor | Current focus and M15 updated for the 10-10 merges |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Target-app parity: GridCraft vs Microsoft Excel
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** minor (performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; no score change; earlier: form controls; catalog 281 / 296; earlier: insert objects: equations; earlier: what-if and analysis: Solver Sensitivity report; no score change; earlier: chart resizing no longer listed as missing; no score change; earlier: what-if and analysis: Analysis ToolPak has all 19 tools; earlier: page layout and print: Page Setup's page order; no score change; earlier: charts: data tables with XLSX round-trip and print/PDF; no score change; earlier: what-if and analysis: Solver Options; the Insert Function dialog is named as in Excel; no score change; earlier: Solver Load/Save Model and Reset All; automation: macro interface; catalog count 276 / 292, as `cargo xtask parity` measures; automation: typed macros in the engine; several windows: a native window per workbook window, New Window on the same workbook, Arrange All; no score change) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-15 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; no score change; earlier: form controls; catalog 281 / 296; earlier: insert objects: equations; earlier: what-if and analysis: Solver Sensitivity report; no score change; earlier: chart resizing no longer listed as missing; no score change; earlier: what-if and analysis: Analysis ToolPak has all 19 tools; earlier: page layout and print: Page Setup's page order; no score change; earlier: charts: data tables with XLSX round-trip and print/PDF; no score change; earlier: what-if and analysis: Solver Options; the Insert Function dialog is named as in Excel; no score change; earlier: Solver Load/Save Model and Reset All; automation: macro interface; catalog count 276 / 292, as `cargo xtask parity` measures; automation: typed macros in the engine; several windows: a native window per workbook window, New Window on the same workbook, Arrange All; no score change) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
This is the authoritative parity assessment. [`ROADMAP.md`](../ROADMAP.md) summarizes it,
|
||||
[`gaps.md`](gaps.md) lists every shortfall, and the area checklists hold the detail:
|
||||
@@ -203,14 +203,26 @@ Excel recalculates on every core (multi-threaded recalculation), streams large f
|
||||
|---|---|---|---|
|
||||
| Sheet size limits | 1,048,576 × 16,384 | same | measured (`crates/core/src/addr.rs`) |
|
||||
| Recalc threads | 1 | all cores | measured (no threading in `crates/calc`) |
|
||||
| Edit → recalc, 100k dependents | ~0.4 s (2026-10-07), target < 100 ms | tens of ms | measured on the owner's machine; #66 since made range-formula recalc linear, not re-timed |
|
||||
| Edit → recalc, 100k-deep chain | 90–106 ms (target < 100 ms) | tens of ms | measured (`cargo xtask bench`, `edit.chain`) |
|
||||
| Edit → recalc, 100k formulas reading one cell | 71–87 ms | tens of ms | measured (`edit.fanout`) |
|
||||
| Edit → 100 whole-column SUMIFS / XLOOKUP over 100k rows | 420–590 ms / 160–250 ms | not measured | measured (`edit.sumifs`, `edit.lookup`) |
|
||||
| Calculate Now, 300k formulas | 395–455 ms | not measured | measured (`recalc.full`) |
|
||||
| Save the 100k-row model (300k formulas) as XLSX | ~530 ms | not measured | measured (`xlsx.save`) |
|
||||
| Reopen that file | drops the last ~9,000 rows (element cap from #2413; fix in PR #2527, then ~1.3 s with full recalc) | opens | measured (`xlsx.open`) |
|
||||
| Grid scrolling | virtualised, O(log n) geometry with custom row heights | smooth | measured in code |
|
||||
| Open a ~100 MB XLSX | fails (#175) | opens | user report |
|
||||
| Whole-sheet operations | Fill and Remove Duplicates on a whole-sheet selection run out of memory or time (fix in PR #152) | fine | open PR |
|
||||
|
||||
Work: streaming XLSX reader with shared-string and style dedup, multi-threaded recalc of
|
||||
independent chains (native only; WASM stays single-threaded), whole-column reference
|
||||
clamping, a `cargo xtask bench` with fixed workbooks so the numbers become measured.
|
||||
clamping, and faster whole-column SUMIFS and lookups (each formula rescans the column on every
|
||||
edit).
|
||||
|
||||
Benchmarks: `cargo xtask bench` builds ten fixed workbooks in code, times each operation through
|
||||
`Session::execute` (median of 7 after a warm-up, results checked) and compares with a baseline
|
||||
saved by `--save`. The numbers above are ranges over several runs on an Apple M2 Pro, release
|
||||
build, 100,000 rows, 2026-10-26; recalculation is single-threaded, so core count doesn't change
|
||||
them.
|
||||
|
||||
## Platforms
|
||||
|
||||
@@ -328,7 +340,6 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
|
||||
|
||||
- Pixel comparison against Excel screenshots (planned; screenshots stay in `plan/excel/`).
|
||||
- Function results against Excel-computed oracles (a corpus repo is the planned home).
|
||||
- Recalc and open-time benchmarks on fixed workbooks (no `cargo xtask bench` yet).
|
||||
- Whether Excel opens our XLSX output without repair, across features.
|
||||
|
||||
## Revision history
|
||||
@@ -346,6 +357,7 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
|
||||
| 2026-10-31 | minor | The Insert Function dialog is named as in Excel (it was called Formula Builder); no score change |
|
||||
| 2026-10-31 | minor | What-if and analysis: Solver Options (no score change) |
|
||||
| 2026-10-31 | minor | What-if and analysis: Solver Load/Save Model and Reset All; Forecast Sheet moved from Missing to the list of tools, as gaps.md §13 records (no score change) |
|
||||
| 2026-10-26 | minor | Performance: `cargo xtask bench` measures recalc, entry, sort and XLSX save/open on fixed in-code workbooks; the 100k-dependent edit is 90–106 ms (was ~0.4 s, an old timing), around the 100 ms target for simple formulas; a 100k-row model doesn't reopen whole until PR #2527 lands (no score change) |
|
||||
| 2026-10-25 | minor | Automation: macro interface (Automate › Macros, the Macros and Record Macro dialogs, the step editor, shortcuts) (no score change) |
|
||||
| 2026-10-25 | trivial | Catalog count 276 / 292 in the summary table and the method, as `cargo xtask parity` measures (no score change) |
|
||||
| 2026-10-22 | minor | Several windows on the desktop: a native window per workbook window, New Window on the same workbook, Switch Windows and Arrange All; "one window" removed from UI/UX fidelity, Hardware and the interaction-fidelity discount; no score change |
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
|
||||
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
|
||||
@@ -35,7 +35,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes
|
||||
| Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing |
|
||||
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | template gallery missing |
|
||||
| Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239); icons, reference colours, primary buttons and the comments pane follow the theme, and a unit test holds every token pair to WCAG 2 contrast in both themes |
|
||||
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet or workbook, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
|
||||
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
|
||||
| Dark mode, system appearance | yes | yes | done (10-09) |
|
||||
| Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab, whose Different First Page and Different Odd & Even Pages give the first page and the even pages their own header and footer (#344), and whose Scale with Document and Align with Page Margins set whether header and footer text follows the print scale and the side margins, on paper and in the view | margins drag on the rulers (#792, with header and footer margins); header/footer pictures missing (1–3 h). Unverified: with Align with Page Margins off, header and footer text sits 0.7 in from the paper edge, a value not yet measured in the target app |
|
||||
| Multiple windows per workbook | yes | yes (10-22, desktop): each workbook window is a native window of its own (New, Open and New Window open one; titles "Book1", or "Book1:1" / "Book1:2" for a workbook's second window, with " — Edited" while unsaved). Each window keeps its own cell draft, dialog, Backstage view, message and grid state, and its ribbon acts on it; on macOS the menu bar acts on the window focused last. Leaving a window enters its draft as Enter would. A window's close button closes that window: one of several on a workbook closes without asking, a workbook's last asks Save / Don't Save / Cancel when unsaved. Quit asks about each unsaved workbook in its window, and Cancel stops it. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar until New or Open. View › Arrange All (dialog: Tiled, Horizontal, Vertical, Cascade, Windows of active workbook; `view.arrangeAll` tiles by default) lays the visible windows out over the main window's monitor, the active one first. Web: one window | Arrange All uses one monitor; a hidden window (View › Hide) has no native window; every window repaints when one does; see [hardware-parity.md](hardware-parity.md) |
|
||||
@@ -358,6 +358,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-24 | minor | Right-clicking a PivotTable's value, subtotal or grand total cell offers Show Details in the cell menu, as in Excel ("Right-click a field in the values area of the PivotTable, and then click Show Details"): it lists the cell's source records on a new sheet, as double-clicking the cell does (`pivot.showDetails`). Labels and headers of a current report don't offer it; in a report that is out of date every cell offers it, and choosing it asks for a refresh |
|
||||
| 2026-10-24 | minor | Sheet tabs: the handle at the horizontal scrollbar's left edge shows the resize cursor, and dragging it moves the boundary, as in Excel ("Hover the mouse pointer at the edge of the scrollbar until you see the double-headed arrow"). Dragging it right gives the tabs more of the bar, until the scrollbar is 100 px wide (the scrollbar stays 100 px wide after the window is narrowed); dragging it left gives the scrollbar more, down to the New sheet button. Room the tabs don't fill stays empty, with New sheet after the last tab. Each open workbook keeps its own share; a workbook starts at the default (tabs up to 60%) |
|
||||
| 2026-10-24 | minor | Outline Settings (Data ▸ Outline ▸ Settings, `data.outlineSettings`): clearing Summary rows below detail or Summary columns to right of detail puts the − / + buttons on the line above or left of each group, and Hide Detail, Show Detail and the level buttons mark that line collapsed. Changing a direction moves the marks of collapsed groups. Read and written as `outlinePr summaryBelow` / `summaryRight` |
|
||||
| 2026-10-23 | minor | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook: the preview and the printed PDF cover the selected cells, and a selection of several areas prints each area on its own pages, as in Excel (`file.print`, `file.exportPdf` and `file.printPreview` accept `range: "A1:B5,D1:E5"`). A single selected cell prints that cell |
|
||||
| 2026-10-23 | minor | F3, Formulas › Use in Formula › Paste Names… and Alt+M, S, P open the Paste Name dialog (F3 only when the workbook has names). It lists the workbook's names and the active sheet's own in alphabetical order, hidden names left out; OK or a double-click puts the selected name at the caret of the formula being edited, in place of selected text, or starts `=Name` in the active cell (`formulas.pasteName` `{name}`), and Paste List writes each name and the text of what it refers to in two columns from the active cell (`{list: true}`). While a dialog is open over the edit, the cell editor takes no keys, and Cancel leaves the selected text selected. The Use in Formula menu lists the same names and inserts at the caret too (`formulas.useInFormula`); it used to list hidden names and other sheets' names, the menu added the name at the end of the text, and the command replaced the text being edited |
|
||||
| 2026-10-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) |
|
||||
| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) |
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "GridCraft workspace tooling: cargo xtask ci | layers | assets | wasm | parity | i18n-report | version | stats | ico"
|
||||
description = "GridCraft workspace tooling: cargo xtask ci | layers | assets | wasm | parity | i18n-report | bench | version | stats | ico"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! `cargo xtask bench`: runs the calculation benchmarks (`crates/engine/examples/bench.rs`) in a
|
||||
//! release build, writes the results to `<target>/bench/latest.json` and compares them with a
|
||||
//! baseline (`<target>/bench/baseline.json` unless `--baseline PATH`). `--save` makes this run
|
||||
//! the baseline. Timings are machine-specific, so baselines stay in the target directory; the
|
||||
//! reference numbers in docs/target-app-parity.md name the machine they came from.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Flags passed through to the bench binary (the others are xtask's own).
|
||||
const PASS: [&str; 3] = ["--rows", "--reps", "--filter"];
|
||||
|
||||
pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
|
||||
// Cargo resolves a relative CARGO_TARGET_DIR against the directory it runs in, which for the
|
||||
// bench is the workspace root; resolve it the same way here.
|
||||
let target = std::env::var_os("CARGO_TARGET_DIR").map(|d| root.join(d)).unwrap_or_else(|| root.join("target"));
|
||||
let dir = target.join("bench");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let latest = dir.join("latest.json");
|
||||
let mut baseline = dir.join("baseline.json");
|
||||
let mut save = false;
|
||||
let mut pass: Vec<String> = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(&a) = it.next() {
|
||||
match a {
|
||||
"--save" => save = true,
|
||||
"--quick" => pass.push(a.into()),
|
||||
"--baseline" => baseline = it.next().map(PathBuf::from).ok_or("--baseline needs a path")?,
|
||||
_ if PASS.contains(&a) => {
|
||||
let v = it.next().ok_or_else(|| format!("{a} needs a value"))?;
|
||||
pass.extend([a.to_string(), v.to_string()]);
|
||||
}
|
||||
other => return Err(format!("bench: unknown flag `{other}`")),
|
||||
}
|
||||
}
|
||||
let mut cmd = crate::cargo();
|
||||
cmd.args(["run", "--release", "--quiet", "-p", "gridcraft-engine", "--example", "bench", "--"]).args(&pass).arg("--json").arg(&latest);
|
||||
// A stale file from an earlier run must not pass for this one's results.
|
||||
let _ = std::fs::remove_file(&latest);
|
||||
// The bench exits non-zero when a scenario fails but still writes the others' results:
|
||||
// compare those, then report the failure.
|
||||
let status = crate::run(cmd, "cargo run --release -p gridcraft-engine --example bench");
|
||||
let now = match read(&latest) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return status.and(Err(e)),
|
||||
};
|
||||
if save && status.is_err() {
|
||||
return status.map_err(|e| format!("{e}\nnot saved as the baseline: a scenario failed"));
|
||||
}
|
||||
if save {
|
||||
std::fs::copy(&latest, &baseline).map_err(|e| format!("{}: {e}", baseline.display()))?;
|
||||
println!("\nSaved as the baseline: {}", baseline.display());
|
||||
return Ok(());
|
||||
}
|
||||
if baseline.exists() {
|
||||
// A baseline that is there but unreadable is an error, not a missing one.
|
||||
compare(&read(&baseline)?, &now);
|
||||
} else {
|
||||
println!("\nNo baseline at {} (run `cargo xtask bench --save` to make one).", baseline.display());
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<Value, String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn results(v: &Value) -> Vec<(String, f64)> {
|
||||
v.get("results")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(|r| Some((r.get("name")?.as_str()?.to_string(), r.get("median_ms")?.as_f64()?))).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Prints the median change per scenario; a different row count makes the numbers incomparable.
|
||||
fn compare(base: &Value, now: &Value) {
|
||||
if base.get("rows") != now.get("rows") {
|
||||
println!("\nBaseline was run with {} rows, this run with {}: not compared.", base["rows"], now["rows"]);
|
||||
return;
|
||||
}
|
||||
let old = results(base);
|
||||
println!("\nAgainst the baseline (median):");
|
||||
for (name, ms) in results(now) {
|
||||
match old.iter().find(|(n, _)| *n == name) {
|
||||
Some((_, was)) if *was > 0.0 => {
|
||||
let pct = (ms - was) / was * 100.0;
|
||||
println!(" {name:<16} {was:>10.2} ms -> {ms:>10.2} ms {pct:+6.1}%");
|
||||
}
|
||||
_ => println!(" {name:<16} {:>13} -> {ms:>10.2} ms", "new"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn reads_results() {
|
||||
let v = json!({"rows": 10, "results": [{"name": "edit.chain", "median_ms": 1.5}, {"name": "bad"}]});
|
||||
assert_eq!(results(&v), vec![("edit.chain".to_string(), 1.5)]);
|
||||
assert!(results(&json!({})).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
|
||||
|
||||
mod assets;
|
||||
mod bench;
|
||||
mod i18n_report;
|
||||
mod ico;
|
||||
mod keytips;
|
||||
@@ -36,6 +37,9 @@ commands:
|
||||
regenerate crates/ui-egui/src/keytips/generated.rs from keytips.json (--check: fail if stale)
|
||||
version [set X.Y.Z[-pre]]
|
||||
print or set the workspace version ([workspace.package] in Cargo.toml)
|
||||
bench [--quick] [--rows N] [--reps N] [--filter NAME] [--save] [--baseline PATH]
|
||||
release-build calculation benchmarks on fixed in-code workbooks; compares
|
||||
with <target>/bench/baseline.json (--save: make this run the baseline)
|
||||
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
|
||||
ico <out.ico> <in.png>...
|
||||
pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh)
|
||||
@@ -51,6 +55,7 @@ fn main() -> ExitCode {
|
||||
Some("wasm") => cmd_wasm(),
|
||||
Some("test") => cmd_test().and_then(|()| cmd_doctest()),
|
||||
Some("ci") => cmd_ci(),
|
||||
Some("bench") => bench::run(&root(), &rest),
|
||||
Some("stats") => stats::run(&root(), rest.contains(&"--exact")),
|
||||
Some("parity") => parity::run(&root(), &rest),
|
||||
Some("keytips") => keytips::run(&root(), &rest),
|
||||
|
||||
Reference in new issue
Block a user