diff --git a/ROADMAP.md b/ROADMAP.md index 89693a77c5..c0b54620c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 | diff --git a/crates/calc/src/eval/array.rs b/crates/calc/src/eval/array.rs index 39a6e0f534..31fdeb8ab1 100644 --- a/crates/calc/src/eval/array.rs +++ b/crates/calc/src/eval/array.rs @@ -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), diff --git a/crates/calc/src/lib.rs b/crates/calc/src/lib.rs index 794a3f97f1..92aa9526cd 100644 --- a/crates/calc/src/lib.rs +++ b/crates/calc/src/lib.rs @@ -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; diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index a269f3a036..2048ce822c 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -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(); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 52b313b253..eebf010f50 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -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}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index a194f022b1..36b69e67ec 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -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); diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs new file mode 100644 index 0000000000..e17d949752 --- /dev/null +++ b/crates/engine/examples/bench.rs @@ -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, +} + +struct Outcome { + name: &'static str, + what: String, + times: Vec, + cells: usize, +} + +type R = Result; +/// A scenario: its name and the function that runs it. +type Scenario = (&'static str, fn(&Cfg) -> R); + +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 = 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 = 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 { + 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, name: &str) -> R> { + v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose() +} + +fn session() -> R { + 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 = (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 { + 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, 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, 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + let n = cfg.rows; + let mut s = session()?; + fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?; + let vals: Vec = (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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 }) +} diff --git a/crates/engine/examples/perf.rs b/crates/engine/examples/perf.rs deleted file mode 100644 index 61ecf56269..0000000000 --- a/crates/engine/examples/perf.rs +++ /dev/null @@ -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 = (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()); -} diff --git a/crates/engine/src/cmd/edit/cell.rs b/crates/engine/src/cmd/edit/cell.rs index 232c1152ce..b27955a1c4 100644 --- a/crates/engine/src/cmd/edit/cell.rs +++ b/crates/engine/src/cmd/edit/cell.rs @@ -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 { 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)?, diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index 9a736cb1d3..45b8472e7b 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -421,6 +421,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { 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); } diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 5fffeffa18..50441537d9 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index a3f0b03b32..0525e922a6 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -642,6 +642,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { 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. diff --git a/crates/engine/src/cmd/insert/links.rs b/crates/engine/src/cmd/insert/links.rs index c90fc946ad..b0b4892955 100644 --- a/crates/engine/src/cmd/insert/links.rs +++ b/crates/engine/src/cmd/insert/links.rs @@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result { 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) { diff --git a/crates/engine/src/cmd/insert/table.rs b/crates/engine/src/cmd/insert/table.rs index 2a517766c4..9cb6b72022 100644 --- a/crates/engine/src/cmd/insert/table.rs +++ b/crates/engine/src/cmd/insert/table.rs @@ -74,6 +74,13 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result { 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 = Vec::new(); // Lower-case names taken, and the next suffix for each header, so that thousands of equal // headers don't take cubic time. diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index e91a269fb3..d6646743db 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result { "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" }, diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 01e6cb8f03..615215bbb9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/print/layout.rs b/crates/engine/src/cmd/print/layout.rs index 1f2ec38ee7..30bf5842ba 100644 --- a/crates/engine/src/cmd/print/layout.rs +++ b/crates/engine/src/cmd/print/layout.rs @@ -70,7 +70,8 @@ impl SheetLayout { #[derive(Clone, Debug, Default)] pub struct PrintOptions { pub all_sheets: bool, - pub range: Option, + /// Areas of the active sheet to print instead of its print area, in order (Print Selection). + pub ranges: Vec, pub fit_to_page: Option, } @@ -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 { @@ -321,14 +343,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec { 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> = + 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 { diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index b506f0d2bd..4fca8ce705 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -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 { + 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() { diff --git a/crates/engine/src/links.rs b/crates/engine/src/links.rs index 4c2318f07f..2b26c925bf 100644 --- a/crates/engine/src/links.rs +++ b/crates/engine/src/links.rs @@ -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 { + 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::*; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 56e79955de..8529822480 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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. diff --git a/crates/engine/tests/it/command_sequence_fuzz.rs b/crates/engine/tests/it/command_sequence_fuzz.rs index 8b48ae0c44..0b1328685b 100644 --- a/crates/engine/tests/it/command_sequence_fuzz.rs +++ b/crates/engine/tests/it/command_sequence_fuzz.rs @@ -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()) { diff --git a/crates/engine/tests/it/sheet_copy_spill.rs b/crates/engine/tests/it/sheet_copy_spill.rs index aed68baf97..481f9889ee 100644 --- a/crates/engine/tests/it/sheet_copy_spill.rs +++ b/crates/engine/tests/it/sheet_copy_spill.rs @@ -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})); diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index 53186bb0e8..aca065c4d4 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -22,17 +22,17 @@ fn chars(s: &str) -> Vec { } fn check_len(s: String) -> R { - 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> { } } +/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it. fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { 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 { + 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 { 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 { && !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 { @@ -252,7 +265,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R { 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 { } 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. diff --git a/crates/functions/src/util.rs b/crates/functions/src/util.rs index 4e7853d2c1..d72cdf2fb5 100644 --- a/crates/functions/src/util.rs +++ b/crates/functions/src/util.rs @@ -11,7 +11,7 @@ pub(crate) type R = Result; /// 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 { 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), } diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 453c9bee90..014844238a 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -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, diff --git a/crates/ui-egui/src/backstage/print.rs b/crates/ui-egui/src/backstage/print.rs index 24178dba8a..a15c037064 100644 --- a/crates/ui-egui/src/backstage/print.rs +++ b/crates/ui-egui/src/backstage/print.rs @@ -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; } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4621736d92..f526861019 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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" }, diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index d11416d689..fdf3039304 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -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 { + 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() { diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 562e1d92ac..e1c5227a8c 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -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)); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 7be979474f..edb1bf64d0 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -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 diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index a573786782..0de9839cb2 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 513b26e069..cf3fdbfb42 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index e8a7bc70d7..6f5e09ddca 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -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" => "Αντιμετώπιση διαδοχικών διαχωριστικών ως ενός", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 73c969a38d..5ce8fad5b8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 631adff8c1..473834399e 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index c1db554178..41127f0bba 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index e93ee6e6d6..64c7570bb8 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -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 文字として扱う"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 116d95eac7..9490134eb5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -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} 페이지", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index d5ae1d4b6b..3840267385 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index c20e0d8a73..982e97676b 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index ce980ff5a5..ff54207a35 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -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ó", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index f13a4f3207..70e2fd0691 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 6be38aaaf7..0862e9acdc 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -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" => "Область комментариев", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index c5a60e89cd..dee5795c98 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index 8c175283fd..302bea1273 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -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}", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8b4a1d9589..2fb9e851f1 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index f7bb841da8..a870ca9fe9 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -1,5 +1,6 @@ -//! Vietnamese translations for the interface strings in i18n.rs. Labels follow the wording -//! Vietnamese spreadsheet users know; anything absent falls back to English. +//! Vietnamese translations for the interface strings in i18n.rs. +//! Clean-room translations written from the plain meaning of the English labels in natural +//! Vietnamese spreadsheet and computing terminology; anything absent falls back to English. /// Returns the Vietnamese translation for `text`, or `None` so callers fall back to English. pub(super) fn translate(text: &str) -> Option<&'static str> { @@ -19,26 +20,27 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Insert Copied Cells…" => "Chèn ô đã sao chép…", "Insert Cut Cells" => "Chèn ô đã cắt", "Insert Paste" => "Chèn và dán", - "Cut" => "Cắt", - "Copy" => "Sao chép", - "Format Painter (double-click to keep it on)" => "Sao định dạng (bấm đúp để giữ)", - "Bold" => "Đậm", - "Italic" => "Nghiêng", + "Cut (⌘X)" => "Cắt (⌘X)", + "Copy (⌘C)" => "Sao chép (⌘C)", + "Format Painter (double-click to keep it on)" => "Sao chép định dạng (nhấp đúp để giữ bật)", + "Bold (⌘B)" => "In đậm (⌘B)", + "Italic (⌘I)" => "In nghiêng (⌘I)", + "Underline (⌘U)" => "Gạch chân (⌘U)", "Double Underline" => "Gạch chân đôi", "Strikethrough" => "Gạch ngang", "Underline" => "Gạch chân", "Increase Font Size" => "Tăng cỡ chữ", "Decrease Font Size" => "Giảm cỡ chữ", - "Wrap Text" => "Xuống dòng tự động", - "Merge & Center" => "Hợp nhất và căn giữa", - "Merge Cells" => "Hợp nhất ô", - "Merge Across" => "Hợp nhất theo hàng", - "Unmerge Cells" => "Bỏ hợp nhất ô", + "Wrap Text" => "Ngắt dòng tự động", + "Merge & Center" => "Gộp & Căn giữa", + "Merge Cells" => "Gộp ô", + "Merge Across" => "Gộp theo hàng", + "Unmerge Cells" => "Tách ô", "Fill Color" => "Màu tô", "Font Color" => "Màu chữ", - "Borders" => "Viền", + "Borders" => "Đường viền", "Top\nAlign" => "Căn\ntrên", - "Middle\nAlign" => "Căn\ngiữa dọc", + "Middle\nAlign" => "Căn\ngiữa", "Bottom\nAlign" => "Căn\ndưới", "Left" => "Trái", "Right" => "Phải", @@ -48,23 +50,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Decrease Indent" => "Giảm thụt lề", "Increase Indent" => "Tăng thụt lề", "Orientation" => "Hướng chữ", - "Page Layout|Orientation" => "Hướng giấy", + "Page Layout|Orientation" => "Hướng trang", "Angle Counterclockwise" => "Xoay ngược chiều kim đồng hồ", - "Angle Clockwise" => "Xoay theo chiều kim đồng hồ", - "Rotate Text Up" => "Xoay chữ lên", - "Rotate Text Down" => "Xoay chữ xuống", + "Angle Clockwise" => "Xoay xuôi chiều kim đồng hồ", + "Rotate Text Up" => "Xoay chữ hướng lên", + "Rotate Text Down" => "Xoay chữ hướng xuống", "Accounting Number Format" => "Định dạng số kế toán", "Percent Style" => "Kiểu phần trăm", - "Comma Style" => "Kiểu dấu phân cách", - "Increase Decimal" => "Tăng số thập phân", - "Decrease Decimal" => "Giảm số thập phân", - "More Accounting Formats…" => "Định dạng kế toán khác…", + "Comma Style" => "Kiểu dấu phân cách hàng nghìn", + "Increase Decimal" => "Tăng chữ số thập phân", + "Decrease Decimal" => "Giảm chữ số thập phân", + "More Accounting Formats…" => "Thêm định dạng kế toán…", "Conditional\nFormatting" => "Định dạng\ncó điều kiện", "Conditional Formatting" => "Định dạng có điều kiện", "Format\nas Table" => "Định dạng\nthành bảng", "Cell\nStyles" => "Kiểu\nô", "Format Cells…" => "Định dạng ô…", - "Format Cell Alignment…" => "Căn chỉnh ô…", + "Format Cell Alignment…" => "Định dạng căn chỉnh ô…", "Format\nPane" => "Ngăn\nđịnh dạng", "Format" => "Định dạng", "Insert" => "Chèn", @@ -77,22 +79,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Delete Sheet Rows" => "Xóa hàng trang tính", "Delete Sheet Columns" => "Xóa cột trang tính", "Row Height…" => "Chiều cao hàng…", - "AutoFit Row Height" => "Tự động khớp chiều cao hàng", + "AutoFit Row Height" => "Tự khớp chiều cao hàng", "Column Width…" => "Độ rộng cột…", - "AutoFit Column Width" => "Tự động khớp độ rộng cột", + "AutoFit Column Width" => "Tự khớp độ rộng cột", "Default Width…" => "Độ rộng mặc định…", "Hide Rows" => "Ẩn hàng", - "Unhide Rows" => "Bỏ ẩn hàng", + "Unhide Rows" => "Hiện hàng", "Hide Columns" => "Ẩn cột", - "Unhide Columns" => "Bỏ ẩn cột", + "Unhide Columns" => "Hiện cột", "Lock Cell" => "Khóa ô", "Clear" => "Xóa", "Clear All" => "Xóa tất cả", "Clear Formats" => "Xóa định dạng", "Clear Contents" => "Xóa nội dung", - "Clear Comments and Notes" => "Xóa chú thích và ghi chú", + "Clear Comments and Notes" => "Xóa nhận xét và ghi chú", "Clear Hyperlinks" => "Xóa siêu liên kết", - "AutoSum" => "Tự động tính tổng", + "AutoSum" => "Tổng tự động", + "AutoSum (⌘⇧T)" => "Tổng tự động (⌘⇧T)", "Flash\nFill" => "Điền\nnhanh", "Flash Fill" => "Điền nhanh", "Fill" => "Điền", @@ -102,19 +105,19 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Replace…" => "Thay thế…", "Go To…" => "Đi tới…", "Go To Special…" => "Đi tới đặc biệt…", - "PivotTable" => "PivotTable", + "PivotTable" => "Bảng tổng hợp", "Recommended\nCharts" => "Biểu đồ\nđề xuất", "Table" => "Bảng", - "Pictures" => "Ảnh", - "Shapes" => "Hình", + "Pictures" => "Hình ảnh", + "Shapes" => "Hình dạng", "Icons" => "Biểu tượng", "Text\nBox" => "Hộp\nvăn bản", - "Comment" => "Chú thích", - "New\nComment" => "Chú thích\nmới", + "Comment" => "Nhận xét", + "New\nComment" => "Nhận xét\nmới", "New Note" => "Ghi chú mới", - "Show/Hide Note" => "Hiện/ẩn ghi chú", + "Show/Hide Note" => "Hiện/Ẩn ghi chú", "Header &\nFooter" => "Đầu trang &\nChân trang", - "Text to\nColumns" => "Tách\ncột", + "Text to\nColumns" => "Văn bản\nthành cột", "Link" => "Liên kết", "Symbol" => "Ký hiệu", "Equation" => "Phương trình", @@ -144,30 +147,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Bottom Margin" => "Lề dưới", "Header Margin" => "Lề đầu trang", "Footer Margin" => "Lề chân trang", - "Size" => "Khổ giấy", + "Size" => "Kích cỡ", "Print\nArea" => "Vùng\nin", "Set Print Area" => "Đặt vùng in", "Breaks" => "Ngắt trang", "Insert Page Break" => "Chèn ngắt trang", "Remove Page Break" => "Bỏ ngắt trang", "Reset All Page Breaks" => "Đặt lại tất cả ngắt trang", - "Print\nTitles" => "In\ntiêu đề", + "Print\nTitles" => "Tiêu đề\nin", "Sheet\nRight-to-Left" => "Trang tính\nphải sang trái", "Sheet Right-to-Left" => "Trang tính phải sang trái", "Narrow" => "Hẹp", "Wide" => "Rộng", - "Normal" => "Bình thường", + "Normal" => "Thường", "Portrait" => "Dọc", "Landscape" => "Ngang", "Custom Margins…" => "Lề tùy chỉnh…", "Insert\nFunction" => "Chèn\nhàm", "Name\nManager" => "Trình quản lý\ntên", - "Define Name" => "Xác định tên", + "Define Name" => "Đặt tên", "Use in Formula" => "Dùng trong công thức", "Create from Selection" => "Tạo từ vùng chọn", - "Trace Precedents" => "Truy tìm ô tham chiếu", + "Trace Precedents" => "Truy tìm ô tiền nhiệm", "Trace Dependents" => "Truy tìm ô phụ thuộc", - "Remove Arrows" => "Bỏ mũi tên", + "Remove Arrows" => "Xóa mũi tên", "Show Formulas" => "Hiện công thức", "Error Checking" => "Kiểm tra lỗi", "Trace Error" => "Truy tìm lỗi", @@ -176,24 +179,24 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Evaluate Formula" => "Đánh giá công thức", "Watch Window" => "Cửa sổ theo dõi", "Calculation\nOptions" => "Tùy chọn\ntính toán", - "Calculate Now" => "Tính ngay", - "Calculate Sheet" => "Tính trang tính", + "Calculate Now" => "Tính toán ngay", + "Calculate Sheet" => "Tính toán trang tính", "Automatic" => "Tự động", "Automatic Except for Data Tables" => "Tự động trừ bảng dữ liệu", "Manual" => "Thủ công", "Sort &\nFilter" => "Sắp xếp &\nLọc", "Sort" => "Sắp xếp", - "Sort A to Z" => "Sắp xếp từ A đến Z", - "Sort Z to A" => "Sắp xếp từ Z đến A", + "Sort A to Z" => "Sắp xếp A đến Z", + "Sort Z to A" => "Sắp xếp Z đến A", "Custom Sort…" => "Sắp xếp tùy chỉnh…", - "Filter" => "Lọc", + "Filter" => "Bộ lọc", "Reapply" => "Áp dụng lại", "Get Data\n(Text/CSV)" => "Lấy dữ liệu\n(Văn bản/CSV)", - "Remove\nDuplicates" => "Loại bỏ\ntrùng lặp", + "Remove\nDuplicates" => "Xóa\ntrùng lặp", "Data\nValidation" => "Xác thực\ndữ liệu", "Data Validation" => "Xác thực dữ liệu", "Data Validation…" => "Xác thực dữ liệu…", - "Circle Invalid Data" => "Khoanh dữ liệu không hợp lệ", + "Circle Invalid Data" => "Khoanh tròn dữ liệu không hợp lệ", "Clear Validation" => "Xóa xác thực", "Group" => "Nhóm", "Ungroup" => "Bỏ nhóm", @@ -202,61 +205,59 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Subtotal" => "Tổng phụ", "Data\nAnalysis" => "Phân tích\ndữ liệu", "Data Analysis" => "Phân tích dữ liệu", - "Solver" => "Solver", - "What-If\nAnalysis" => "Phân tích\nWhat-If", + "Solver" => "Bộ giải Solver", + "What-If\nAnalysis" => "Phân tích\ngiả định", "Data Table…" => "Bảng dữ liệu…", "Scenario Manager…" => "Trình quản lý kịch bản…", "Goal Seek…" => "Tìm mục tiêu…", "Forecast\nSheet" => "Trang tính\ndự báo", "Spelling" => "Chính tả", - "Check\nAccessibility" => "Kiểm tra\ntrợ năng", - "Threaded Comments" => "Chú thích dạng chuỗi", - "Show\nComments" => "Hiện\nchú thích", + "Check\nAccessibility" => "Kiểm tra\nkhả năng tiếp cận", + "Threaded Comments" => "Nhận xét theo luồng", + "Show\nComments" => "Hiện\nnhận xét", "Previous" => "Trước", "Next" => "Tiếp", - "Previous Comment" => "Chú thích trước", - "Next Comment" => "Chú thích tiếp theo", + "Previous Comment" => "Nhận xét trước", + "Next Comment" => "Nhận xét tiếp", "Show All Notes" => "Hiện tất cả ghi chú", - "Convert to Comments" => "Chuyển thành chú thích", + "Convert to Comments" => "Chuyển thành nhận xét", "Protect\nWorkbook" => "Bảo vệ\nsổ làm việc", - "Allow Edit\nRanges" => "Cho phép sửa\nphạm vi", - "Allow Edit Ranges" => "Cho phép sửa phạm vi", + "Allow Edit\nRanges" => "Cho phép sửa\nvùng", + "Allow Edit Ranges" => "Cho phép sửa vùng", "Unprotect\nSheet" => "Bỏ bảo vệ\ntrang tính", "Protect Sheet…" => "Bảo vệ trang tính…", - "Comments" => "Chú thích", + "Comments" => "Nhận xét", "Notes" => "Ghi chú", "Page Break\nPreview" => "Xem trước\nngắt trang", - "Page\nLayout" => "Bố trí\ntrang", + "Page\nLayout" => "Bố cục\ntrang", "Formula Bar" => "Thanh công thức", "Name Box" => "Hộp tên", "Cell Editor" => "Trình soạn thảo ô", "Font Size" => "Cỡ chữ", "Gridlines" => "Đường lưới", - "Headings" => "Tiêu đề hàng/cột", + "Headings" => "Tiêu đề hàng cột", "Zoom" => "Thu phóng", "100%" => "100%", - "Zoom to\nSelection" => "Phóng to\nvùng chọn", - "Freeze\nPanes" => "Cố định\nngăn", - "Freeze Panes" => "Cố định ngăn", - "Freeze Top Row" => "Cố định hàng trên cùng", - "Freeze First Column" => "Cố định cột đầu tiên", - "Unfreeze Panes" => "Bỏ cố định ngăn", + "Zoom to\nSelection" => "Thu phóng đến\nvùng chọn", + "Freeze\nPanes" => "Cố định\nkhung", + "Freeze Panes" => "Cố định khung", + "Freeze Top Row" => "Cố định hàng đầu", + "Freeze First Column" => "Cố định cột đầu", + "Unfreeze Panes" => "Bỏ cố định khung", "Dark Mode" => "Chế độ tối", - "Display theme" => "Chủ đề hiển thị", - "Animations" => "Hiệu ứng động", - "Glide the selection outline to the cell you move to instead of jumping there" => { - "Trượt khung vùng chọn tới ô bạn di chuyển đến thay vì nhảy ngay tới đó" - } + "Display theme" => "Giao diện hiển thị", + "Animations" => "Hiệu ứng chuyển động", + "Glide the selection outline to the cell you move to instead of jumping there" => "Trượt mượt khung chọn tới ô đích thay vì nhảy tức thì", "System" => "Hệ thống", "Light" => "Sáng", "Dark" => "Tối", "Interface language" => "Ngôn ngữ giao diện", - "Interface size" => "Kích thước giao diện", + "Interface size" => "Kích cỡ giao diện", "Auto" => "Tự động", "Drag to freeze columns" => "Kéo để cố định cột", "Drag to freeze rows" => "Kéo để cố định hàng", "Command\nPalette" => "Bảng\nlệnh", - "Agent\nControl" => "Điều khiển\nagent", + "Agent\nControl" => "Điều khiển\ntác tử", "Action\nJournal" => "Nhật ký\nthao tác", "About\nGridCraft" => "Giới thiệu\nGridCraft", "Share" => "Chia sẻ", @@ -276,12 +277,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Gridlines: Show" => "Đường lưới: Hiện", "Chart\nTitle" => "Tiêu đề\nbiểu đồ", "Delete\nChart" => "Xóa\nbiểu đồ", - "Convert\nto Range" => "Chuyển thành\nphạm vi", + "Convert\nto Range" => "Chuyển\nthành vùng", "Table\nStyles" => "Kiểu\nbảng", - "Top 10 Items" => "10 mục đầu", - "Top 10%" => "10% đầu", - "Bottom 10 Items" => "10 mục cuối", - "Bottom 10%" => "10% cuối", + "Top 10 Items" => "10 mục cao nhất", + "Top 10%" => "10% cao nhất", + "Bottom 10 Items" => "10 mục thấp nhất", + "Bottom 10%" => "10% thấp nhất", "Above Average" => "Trên trung bình", "Below Average" => "Dưới trung bình", "Clear Rules from Entire Sheet" => "Xóa quy tắc khỏi toàn bộ trang tính", @@ -290,9 +291,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Data Bars" => "Thanh dữ liệu", "Color Scales" => "Thang màu", "Icon Sets" => "Bộ biểu tượng", - "Home" => "Trang đầu", + "Home" => "Trang chủ", "Draw" => "Vẽ", - "Page Layout" => "Bố trí trang", + "Page Layout" => "Bố cục trang", "Formulas" => "Công thức", "Data" => "Dữ liệu", "Review" => "Xem lại", @@ -311,34 +312,32 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Currency" => "Tiền tệ", "Accounting" => "Kế toán", "Date" => "Ngày", - "Time" => "Giờ", + "Time" => "Thời gian", "Percentage" => "Phần trăm", "Fraction" => "Phân số", "Scientific" => "Khoa học", "Text" => "Văn bản", "Special" => "Đặc biệt", "Custom" => "Tùy chỉnh", - "Short Date" => "Ngày dạng ngắn", - "Long Date" => "Ngày dạng dài", - "More Number Formats…" => "Định dạng số khác…", + "Short Date" => "Ngày ngắn", + "Long Date" => "Ngày dài", + "More Number Formats…" => "Thêm định dạng số…", "Financial" => "Tài chính", + "Recently Used" => "Dùng gần đây", "Logical" => "Logic", - "Date & Time" => "Ngày & Giờ", - "Lookup & Reference" => "Tra cứu & Tham chiếu", - "Math & Trig" => "Toán & Lượng giác", - "More Functions" => "Hàm khác", - "Sheet Options|View" => "Xem", + "More Functions" => "Thêm hàm", + "Sheet Options|View" => "Hiển thị", "Print" => "In", "Print What" => "Nội dung in", // Page Layout view and the Header & Footer tab. - "Click to add data" => "Bấm để thêm dữ liệu", + "Click to add data" => "Nhấp để thêm dữ liệu", "Add header" => "Thêm đầu trang", "Add footer" => "Thêm chân trang", "(none)" => "(không có)", "Header" => "Đầu trang", "Footer" => "Chân trang", "Page\nNumber" => "Số\ntrang", - "Number\nof Pages" => "Tổng\nsố trang", + "Number\nof Pages" => "Tổng số\ntrang", "Current\nDate" => "Ngày\nhiện tại", "Current\nTime" => "Giờ\nhiện tại", "File\nPath" => "Đường dẫn\ntệp", @@ -354,8 +353,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "File Name" => "Tên tệp", "Sheet Name" => "Tên trang tính", "Go to Header" => "Đi tới đầu trang", - "Different First Page" => "Trang đầu khác", - "Different Odd & Even Pages" => "Trang chẵn lẻ khác nhau", + "Different First Page" => "Trang đầu khác biệt", + "Different Odd & Even Pages" => "Trang chẵn & lẻ khác nhau", "Scale with Document" => "Co giãn theo tài liệu", "Align with Page Margins" => "Căn theo lề trang", "Go to Footer" => "Đi tới chân trang", @@ -395,10 +394,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Sheets" => "Trang tính", "Protect Workbook" => "Bảo vệ sổ làm việc", "Sheet structure is locked: sheets can't be added, moved, renamed or deleted." => { - "Cấu trúc trang tính đã bị khóa: không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." + "Cấu trúc trang tính đã khóa: không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." } "Lock the sheet structure so sheets can't be added, moved, renamed or deleted." => { - "Khóa cấu trúc trang tính để không thể thêm, di chuyển, đổi tên hoặc xóa trang tính." + "Khóa cấu trúc trang tính để ngăn thêm, di chuyển, đổi tên hoặc xóa trang tính." } "Properties" => "Thuộc tính", "Title" => "Tiêu đề", @@ -410,63 +409,823 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "No workbook is open." => "Chưa mở sổ làm việc nào.", "Save as type" => "Lưu dưới dạng", "Excel Workbook (*.xlsx)" => "Sổ làm việc Excel (*.xlsx)", - "CSV UTF-8 (Comma delimited) (*.csv)" => "CSV UTF-8 (phân cách bằng dấu phẩy) (*.csv)", + "CSV UTF-8 (Comma delimited) (*.csv)" => "CSV UTF-8 (Phân cách bằng dấu phẩy) (*.csv)", "Web Page (*.html)" => "Trang web (*.html)", "PDF (*.pdf)" => "PDF (*.pdf)", "Download" => "Tải xuống", "A CSV file, web page or PDF is a copy: the workbook keeps its own file." => { - "Tệp CSV, trang web hoặc PDF chỉ là bản sao: sổ làm việc vẫn giữ tệp gốc." + "Tệp CSV, trang web hoặc PDF là bản sao: sổ làm việc vẫn giữ tệp gốc của nó." } "Save the workbook under another name or in another folder." => "Lưu sổ làm việc với tên khác hoặc vào thư mục khác.", - "Print Active Sheets" => "In các trang tính hiện hoạt", + "Print Active Sheets" => "In các trang tính đang chọn", "Print Entire Workbook" => "In toàn bộ sổ làm việc", - "Fit Sheet on One Page" => "Vừa trang tính trên một trang", + "Print Selection" => "In vùng chọn", + "Fit Sheet on One Page" => "Vừa trang tính trên một trang in", "Page Setup…" => "Thiết lập trang…", - "Page {page} of {pages}" => "Trang {page} / {pages}", - "Nothing to print." => "Không có gì để in.", + "Page {page} of {pages}" => "Trang {page} trên {pages}", + "Nothing to print." => "Không có nội dung để in.", "Previous page" => "Trang trước", - "Next page" => "Trang sau", + "Next page" => "Trang tiếp theo", "Create PDF" => "Tạo PDF", - "Save the sheet as a PDF document that keeps its page layout." => "Lưu trang tính thành tài liệu PDF, giữ nguyên bố trí trang.", - "Change File Type" => "Đổi kiểu tệp", - "CSV (Comma delimited)" => "CSV (phân cách bằng dấu phẩy)", - "Save the active sheet as comma-separated text." => "Lưu trang tính hiện hoạt thành văn bản phân cách bằng dấu phẩy.", + "Save the sheet as a PDF document that keeps its page layout." => "Lưu trang tính thành tài liệu PDF giữ nguyên bố cục trang.", + "Change File Type" => "Đổi loại tệp", + "CSV (Comma delimited)" => "CSV (Phân cách bằng dấu phẩy)", + "Save the active sheet as comma-separated text." => "Lưu trang tính hiện hành thành văn bản phân cách bằng dấu phẩy.", "Web Page (.html)" => "Trang web (.html)", "Save the workbook as a web page." => "Lưu sổ làm việc thành trang web.", "Options|General" => "Chung", "Options|Save" => "Lưu", "Show formula bar" => "Hiện thanh công thức", - "Enable AutoComplete for cell values" => "Bật tự động hoàn thành giá trị ô", + "Enable AutoComplete for cell values" => "Bật Tự động hoàn tất cho giá trị ô", "Save .xlsx workbooks automatically after every change" => "Tự động lưu sổ làm việc .xlsx sau mỗi thay đổi", "Workbook calculation" => "Tính toán sổ làm việc", "Enable iterative calculation" => "Bật tính toán lặp", - "Calculation settings are saved with the workbook." => "Thiết lập tính toán được lưu cùng sổ làm việc.", + "Maximum Iterations:" => "Số lần lặp tối đa:", + "Maximum Change:" => "Mức thay đổi tối đa:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Số lần lặp tối đa phải là số nguyên từ 1 đến 32767.", + "Maximum Change must be a number of 0 or more." => "Mức thay đổi tối đa phải là một số lớn hơn hoặc bằng 0.", + "Calculation settings are saved with the workbook." => "Thiết lập tính toán được lưu cùng với sổ làm việc.", + // Dialogs, menus, context menus and tooltips. + "OK" => "OK", + "Cancel" => "Hủy", + "Don't Save" => "Không lưu", + "Open…" => "Mở…", + "Show password" => "Hiện mật khẩu", + "Start a new workbook" => "Bắt đầu sổ làm việc mới", + "Household Budget" => "Ngân sách gia đình", + "Quarterly Sales Dashboard" => "Bảng điều khiển doanh số quý", + "Gradebook" => "Sổ điểm", + "this workbook" => "sổ làm việc này", + "This workbook" => "Sổ làm việc này", + "Do you want to save the changes you made to {title}?" => "Bạn có muốn lưu các thay đổi đã thực hiện cho {title} không?", + "Save a copy as .{format}" => "Lưu bản sao dưới dạng .{format}", + "Select a chart first." => "Hãy chọn một biểu đồ trước.", "Text Box" => "Hộp văn bản", + "Select Data" => "Chọn dữ liệu", + "Row Height" => "Chiều cao hàng", + "Column Width" => "Độ rộng cột", + "Standard Width" => "Độ rộng tiêu chuẩn", + "Rename Sheet" => "Đổi tên trang tính", + "Move or Copy" => "Di chuyển hoặc sao chép", + "Protect Sheet" => "Bảo vệ trang tính", + "Protect Structure and Windows" => "Bảo vệ cấu trúc và cửa sổ", + "Unprotect Workbook" => "Bỏ bảo vệ sổ làm việc", + "Unprotect Sheet" => "Bỏ bảo vệ trang tính", + "Password" => "Mật khẩu", + "Unhide" => "Hiện", + "Paste Special" => "Dán đặc biệt", + "Series" => "Chuỗi", + "New Comment" => "Nhận xét mới", + "Insert Hyperlink" => "Chèn siêu liên kết", + "Create Sparklines" => "Tạo biểu đồ thu nhỏ", + "Page Setup" => "Thiết lập trang", + "Convert Text to Columns" => "Chuyển văn bản thành cột", + "Remove Duplicates" => "Xóa trùng lặp", + "Goal Seek" => "Tìm mục tiêu", + "Create Forecast Worksheet" => "Tạo trang tính dự báo", + "Solver Parameters" => "Tham số Solver", + "Solver Results" => "Kết quả Solver", + "Edit Name" => "Sửa tên", + "New Name" => "Tên mới", + "Format Cells" => "Định dạng ô", + "Find and Replace" => "Tìm và Thay thế", + "Go To" => "Đi tới", + "Insert Calculated Field" => "Chèn trường tính toán", + "Go To Special" => "Đi tới đặc biệt", + "Name Manager" => "Trình quản lý tên", + "Conditional Formatting Rules Manager" => "Trình quản lý quy tắc định dạng có điều kiện", + "Search Commands" => "Tìm lệnh", + "Agent Control" => "Điều khiển tác tử", + "About GridCraft" => "Giới thiệu về GridCraft", + "Insert Chart" => "Chèn biểu đồ", + "Select Data Source" => "Chọn nguồn dữ liệu", + "Action Journal" => "Nhật ký thao tác", "Macros" => "Macro", - "Record Macro" => "Ghi Macro", - "Stop Recording" => "Dừng Ghi", - "Use Relative References" => "Dùng Tham chiếu Tương đối", - "Run\nMacro" => "Chạy Macro", - "Macros…" => "Macro…", - "Recording" => "Đang ghi", + "Workbook Statistics" => "Thống kê sổ làm việc", + "Accessibility" => "Khả năng tiếp cận", + "Chart Title" => "Tiêu đề biểu đồ", + "Place Picture in Cell" => "Đặt ảnh trong ô", + "Place Picture over Cells" => "Đặt ảnh đè lên các ô", + "Pick From List" => "Chọn từ danh sách", + "Save a Copy" => "Lưu bản sao", + "Save Changes?" => "Lưu thay đổi?", + "Shift cells right" => "Dịch các ô sang phải", + "Shift cells down" => "Dịch các ô xuống dưới", + "Shift cells left" => "Dịch các ô sang trái", + "Shift cells up" => "Dịch các ô lên trên", + "Entire row" => "Toàn bộ hàng", + "Entire column" => "Toàn bộ cột", + "Row height (pixels):" => "Chiều cao hàng (pixel):", + "Column width (characters):" => "Độ rộng cột (ký tự):", + "Standard column width (pixels):" => "Độ rộng cột tiêu chuẩn (pixel):", + "Name:" => "Tên:", + "Before sheet (position, 0 = first):" => "Trước trang tính (vị trí, 0 = đầu tiên):", + "Create a copy" => "Tạo một bản sao", + "Sheets: {sheets}" => "Trang tính: {sheets}", + "Password (optional):" => "Mật khẩu (tùy chọn):", + "Password:" => "Mật khẩu:", + "Allow all users of this sheet to:" => "Cho phép mọi người dùng trang tính này:", + "Format cells" => "Định dạng ô", + "Format columns" => "Định dạng cột", + "Format rows" => "Định dạng hàng", + "Insert rows" => "Chèn hàng", + "Delete rows" => "Xóa hàng", + "Use AutoFilter" => "Dùng Tự động lọc", + " (password, unlocked)" => " (có mật khẩu, đã mở khóa)", + " (password)" => " (có mật khẩu)", + "No ranges yet." => "Chưa có vùng nào.", + "Ranges that stay editable when the sheet is protected:" => "Các vùng vẫn cho phép chỉnh sửa khi trang tính được bảo vệ:", + "Action" => "Thao tác", + "Modify" => "Sửa đổi", + "Unlock with password" => "Mở khóa bằng mật khẩu", + "Title:" => "Tiêu đề:", + "Refers to cells:" => "Tham chiếu tới các ô:", + "Range password:" => "Mật khẩu vùng:", + "New title (Modify):" => "Tiêu đề mới (Sửa đổi):", + "Remove the password (Modify)" => "Gỡ mật khẩu (Sửa đổi)", + "'{file}' is protected." => "'{file}' được bảo vệ.", + "Unhide sheet:" => "Hiện trang tính:", + "Hidden: {sheets}" => "Đã ẩn: {sheets}", + "All" => "Tất cả", + "Formulas (F)" => "Công thức (F)", + "Values (V)" => "Giá trị (V)", + "Formats (T)" => "Định dạng (T)", + "Comments and notes (C)" => "Nhận xét và ghi chú (C)", + "Validation" => "Xác thực", + "All except borders" => "Tất cả trừ đường viền", + "Column widths" => "Độ rộng cột", + "Formulas and number formats" => "Công thức và định dạng số", + "Values and number formats" => "Giá trị và định dạng số", + "Operation" => "Phép tính", + "Add" => "Cộng", + "Paste Special|Add" => "Cộng", + "Subtract" => "Trừ", + "Multiply" => "Nhân", + "Divide" => "Chia", + "Skip blanks" => "Bỏ qua ô trống", + "Transpose (E)" => "Chuyển vị (E)", + "Series in" => "Chuỗi theo", + "Columns" => "Cột", + "Rows" => "Hàng", + "Type" => "Loại", + "Linear" => "Tuyến tính", + "Growth" => "Tăng trưởng", + "Date unit" => "Đơn vị ngày", + "Day" => "Ngày", + "Weekday" => "Ngày làm việc", + "Month" => "Tháng", + "Year" => "Năm", + "Step value:" => "Bước nhảy:", + "Stop value:" => "Giá trị dừng:", + "Start a conversation:" => "Bắt đầu cuộc trò chuyện:", + "Note:" => "Ghi chú:", + "Display:" => "Hiển thị:", + "Link to (web address, e-mail or Sheet!A1):" => "Liên kết tới (địa chỉ web, email hoặc Sheet!A1):", + "ScreenTip:" => "Chú giải màn hình:", + "Data Range:" => "Vùng dữ liệu:", + "Location Range:" => "Vùng vị trí:", + "Markers" => "Điểm đánh dấu", + "Footer:" => "Chân trang:", + "Left margin (in):" => "Lề trái (in):", + "Right margin (in):" => "Lề phải (in):", + "Top margin (in):" => "Lề trên (in):", + "Bottom margin (in):" => "Lề dưới (in):", + "Header (in):" => "Đầu trang (in):", + "Footer (in):" => "Chân trang (in):", + "Page order" => "Thứ tự trang", + "Down, then over" => "Xuống dưới, rồi sang phải", + "Over, then down" => "Sang phải, rồi xuống dưới", + "Tab" => "Tab", + "Semicolon" => "Dấu chấm phẩy", + "Comma" => "Dấu phẩy", + "Text to Columns|Comma" => "Dấu phẩy", + "Space" => "Dấu cách", + "Other:" => "Khác:", + "Treat consecutive delimiters as one" => "Gộp các dấu phân cách liên tiếp thành một", + "Destination:" => "Đích đến:", + "My data has headers" => "Dữ liệu của tôi có tiêu đề", + "Columns (blank = all, e.g. A,C):" => "Cột (để trống = tất cả, VD: A,C):", + "Timeline range (blank: first column of the selection):" => "Vùng mốc thời gian (để trống: cột đầu tiên của vùng chọn):", + "Values range (blank: second column of the selection):" => "Vùng giá trị (để trống: cột thứ hai của vùng chọn):", + "Confidence interval" => "Khoảng tin cậy", + "Confidence level (%):" => "Mức tin cậy (%):", + "Seasonality (auto, 0 for none, or a season length):" => "Tính mùa vụ (tự động, 0 là không có, hoặc độ dài chu kỳ):", + "Fill missing points using" => "Điền các điểm thiếu bằng", + "Interpolation" => "Nội suy", + "Zeros" => "Số 0", + "Aggregate duplicates using" => "Gộp các giá trị trùng bằng", + "Average" => "Trung bình", + "Count" => "Đếm", + "CountA" => "Đếm không trống (CountA)", + "Max" => "Lớn nhất", + "Median" => "Trung vị", + "Min" => "Nhỏ nhất", + "Sum" => "Tổng", + "Product" => "Tích", + "Include forecast statistics" => "Bao gồm thống kê dự báo", + "Chart" => "Biểu đồ", + "Line chart" => "Biểu đồ đường", + "Column chart" => "Biểu đồ cột", + "At each change in (column letter):" => "Tại mỗi thay đổi trong (chữ cái cột):", + "Use function" => "Sử dụng hàm", + "Add subtotal to (columns, e.g. C,D):" => "Thêm tổng phụ vào (các cột, VD: C,D):", + "Magnification" => "Độ phóng đại", + "Custom (%):" => "Tùy chỉnh (%):", + "Scope (Workbook or sheet name):" => "Phạm vi (Sổ làm việc hoặc tên trang tính):", + "Comment:" => "Nhận xét:", + "Refers to:" => "Tham chiếu tới:", + "Allow" => "Cho phép", + "Any value" => "Giá trị bất kỳ", + "Whole number" => "Số nguyên", + "Decimal" => "Số thập phân", + "List" => "Danh sách", + "Text length" => "Độ dài văn bản", + "between" => "nằm giữa", + "not between" => "không nằm giữa", + "equal to" => "bằng", + "not equal to" => "không bằng", + "greater than" => "lớn hơn", + "less than" => "nhỏ hơn", + "greater than or equal to" => "lớn hơn hoặc bằng", + "less than or equal to" => "nhỏ hơn hoặc bằng", + "Minimum / Source / Formula:" => "Tối thiểu / Nguồn / Công thức:", + "Maximum:" => "Tối đa:", + "Ignore blank" => "Bỏ qua ô trống", + "In-cell dropdown" => "Danh sách thả xuống trong ô", + "Input message:" => "Thông báo nhập:", + "Error style" => "Kiểu báo lỗi", "Stop" => "Dừng", - "New Macro" => "Macro Mới", - "Show" => "Hiện", - "Collapse dialog" => "Thu gọn hộp thoại", - "Expand dialog" => "Mở rộng hộp thoại", + "Warning" => "Cảnh báo", + "Information" => "Thông tin", + "Error message:" => "Thông báo lỗi:", + "Format cells that are (value):" => "Định dạng các ô có giá trị:", + "and:" => "và:", + "Format cells that contain the text:" => "Định dạng các ô chứa văn bản:", + "Format cells that contain a date occurring:" => "Định dạng các ô chứa ngày:", + "Today" => "Hôm nay", + "Tomorrow" => "Ngày mai", + "In the last 7 days" => "Trong 7 ngày qua", + "Last week" => "Tuần trước", + "This week" => "Tuần này", + "Next week" => "Tuần sau", + "Last month" => "Tháng trước", + "This month" => "Tháng này", + "Next month" => "Tháng sau", + "Format values where this formula is true:" => "Định dạng các giá trị khi công thức này đúng:", + "with" => "với", + "Light Red Fill with Dark Red Text" => "Tô đỏ nhạt với chữ đỏ đậm", + "Yellow Fill with Dark Yellow Text" => "Tô vàng với chữ vàng đậm", + "Green Fill with Dark Green Text" => "Tô xanh lục với chữ xanh lục đậm", + "Light Red Fill" => "Tô đỏ nhạt", + "Red Text" => "Chữ đỏ", + "Red Border" => "Viền đỏ", + "Formula:" => "Công thức:", + "Select" => "Chọn", + "Blanks" => "Ô trống", + "Errors" => "Lỗi", + "Numbers" => "Số", + "Current region" => "Vùng hiện tại", + "Last cell" => "Ô cuối cùng", + "Visible cells only" => "Chỉ các ô hiển thị", + "Conditional formats" => "Định dạng có điều kiện", + "Data validation" => "Xác thực dữ liệu", + "Horizontal axis title:" => "Tiêu đề trục ngang:", + "Vertical axis title:" => "Tiêu đề trục dọc:", + "No picture selected" => "Chưa chọn hình ảnh", + "Picture file path (PNG or JPEG):" => "Đường dẫn tệp ảnh (PNG hoặc JPEG):", + "Description (optional):" => "Mô tả (tùy chọn):", + "Fits inside the selected cell and moves with its content." => "Vừa khít trong ô đã chọn và di chuyển theo nội dung ô.", + "Choose a PNG or JPEG no larger than 16 MB." => "Chọn tệp PNG hoặc JPEG không quá 16 MB.", + "About" => "Giới thiệu", + "Contributors" => "Người đóng góp", + "Models" => "Mô hình", + "Version {version}" => "Phiên bản {version}", + "Join the ArtCraft Discord" => "Tham gia Discord của ArtCraft", + "This workbook has no scripts or macros." => "Sổ làm việc này không có tập lệnh hay macro nào.", + "(unnamed)" => "(chưa đặt tên)", + "— VBA project (preserved, not run)" => "— Dự án VBA (được bảo toàn, không chạy)", + "— 1 step" => "— 1 bước", + "— {steps} steps" => "— {steps} bước", + "Alignment" => "Căn chỉnh", + "Font" => "Phông chữ", + "Border" => "Đường viền", + "Format Cells|Fill" => "Tô nền", + "Protection" => "Bảo vệ", + "Category:" => "Danh mục:", + "Sample" => "Mẫu", + "Type (custom format code):" => "Loại (mã định dạng tùy chỉnh):", + "Vertical" => "Dọc", + "Justify" => "Căn đều", + "Center Across Selection" => "Căn giữa qua vùng chọn", + "Distributed" => "Căn đều phân tán", + "Top" => "Trên", + "Bottom" => "Dưới", + "Indent" => "Thụt lề", + "Orientation (degrees)" => "Góc xoay (độ)", + "Wrap text" => "Ngắt dòng tự động", + "Shrink to fit" => "Thu nhỏ vừa ô", + "Bold" => "In đậm", + "Italic" => "In nghiêng", + "None" => "Không có", + "Single" => "Đơn", + "Double" => "Đôi", + "Single Accounting" => "Kế toán đơn", + "Double Accounting" => "Kế toán đôi", + "Superscript" => "Chỉ số trên", + "Subscript" => "Chỉ số dưới", + "Color:" => "Màu:", + "Outline" => "Viền ngoài", + "Diagonal ↘" => "Chéo ↘", + "Diagonal ↗" => "Chéo ↗", + "none" => "không có", + "thin" => "mảnh", + "medium" => "vừa", + "thick" => "dày", + "dashed" => "nét đứt", + "dotted" => "nét chấm", + "double" => "nét đôi", + "Background Color:" => "Màu nền:", + "Locked" => "Đã khóa", + "Hidden" => "Ẩn", + "Search:" => "Tìm kiếm:", + "e.g. lookup, average, date" => "VD: tra cứu, trung bình, ngày", + "Date & Time" => "Ngày & Giờ", + "Lookup & Reference" => "Tra cứu & Tham chiếu", + "Math & Trig" => "Toán & Lượng giác", + "Statistical" => "Thống kê", + "Engineering" => "Kỹ thuật", + "Database" => "Cơ sở dữ liệu", + "Compatibility" => "Tương thích", + "Web" => "Web", + "Cube" => "Khối dữ liệu (Cube)", + "Add-in and Automation" => "Tiện ích bổ sung và Tự động hóa", + "Find" => "Tìm", + "Replace" => "Thay thế", + "Find what:" => "Tìm gì:", + "Replace with:" => "Thay bằng:", + "Match case" => "Khớp chữ hoa/thường", + "Match entire cell contents" => "Khớp toàn bộ nội dung ô", + "Within workbook" => "Trong toàn sổ làm việc", + "Replace All" => "Thay thế tất cả", + "Find All" => "Tìm tất cả", + "Find Next" => "Tìm tiếp", + "All done. We made {count} replacements." => "Hoàn tất. Đã thực hiện {count} lần thay thế.", + "{count} cell(s) found" => "Tìm thấy {count} ô", + "Reference:" => "Tham chiếu:", + "Special…" => "Đặc biệt…", + "My list has headers" => "Danh sách của tôi có tiêu đề", "Distinct Count" => "Đếm riêng biệt", "Summarize by Distinct Count" => "Tóm tắt theo Đếm riêng biệt", "A calculated field can't use Distinct Count." => "Trường tính toán không thể dùng Đếm riêng biệt.", "This workbook has a PivotTable with a Distinct Count value field. In the .xlsx file it is stored as a plain Count plus a marker that only GridCraft reads, so Excel's Refresh turns it into a plain count." => { "Sổ làm việc này có PivotTable với trường giá trị “Đếm riêng biệt”. Trong tệp .xlsx, trường này được lưu dưới dạng Đếm thông thường cùng một dấu hiệu mà chỉ GridCraft đọc, nên Làm mới trong Excel sẽ biến nó thành đếm thông thường." } - "My list has headers" => "Dữ liệu của tôi có tiêu đề", "Sort by" => "Sắp xếp theo", "Then by" => "Sau đó theo", "Cell Values" => "Giá trị ô", "Cell Color" => "Màu ô", "A to Z" => "A đến Z", "Z to A" => "Z đến A", + "+ Add Level" => "+ Thêm cấp", + "New…" => "Tạo mới…", + "Edit…" => "Sửa…", + "Name" => "Tên", + "Value" => "Giá trị", + "Refers To" => "Tham chiếu tới", + "Scope" => "Phạm vi", + "Workbook" => "Sổ làm việc", + "No names defined" => "Chưa định nghĩa tên nào", + "Recommended Charts" => "Biểu đồ đề xuất", + "All Charts" => "Tất cả biểu đồ", + "Clustered Column" => "Cột cụm", + "Stacked Column" => "Cột chồng", + "100% Stacked Column" => "Cột chồng 100%", + "Clustered Bar" => "Thanh cụm", + "Stacked Bar" => "Thanh chồng", + "100% Stacked Bar" => "Thanh chồng 100%", + "Line" => "Đường", + "Line with Markers" => "Đường có điểm đánh dấu", + "Stacked Line" => "Đường chồng", + "Pie" => "Tròn", + "Doughnut" => "Vành khuyên", + "Area" => "Miền", + "Stacked Area" => "Miền chồng", + "100% Stacked Area" => "Miền chồng 100%", + "Scatter" => "Phân tán", + "Scatter with Lines" => "Phân tán có đường nối", + "Radar" => "Radar", + "Histogram" => "Biểu đồ tần suất", + "Waterfall" => "Thác nước", + "Funnel" => "Phễu", + "Combo" => "Kết hợp", + "Chart data range:" => "Vùng dữ liệu biểu đồ:", + "Legend Entries (Series)" => "Mục chú giải (Chuỗi)", + "Series{n}" => "Chuỗi{n}", + "Keep" => "Giữ", + "Remove" => "Gỡ bỏ", + "Horizontal (Category) Axis Labels:" => "Nhãn trục ngang (Danh mục):", + "There are no conditional formatting rules on this sheet." => "Không có quy tắc định dạng có điều kiện nào trên trang tính này.", + "applies to" => "áp dụng cho", + "Type a command, e.g. freeze, chart, bold…" => "Nhập lệnh, VD: cố định, biểu đồ, in đậm…", + "Set cell:" => "Đặt ô:", + "To value:" => "Thành giá trị:", + "By changing cell:" => "Bằng cách thay đổi ô:", + "Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}", + "Analysis Tools" => "Công cụ phân tích", + "Anova: Single Factor" => "Anova: Một yếu tố", + "Correlation" => "Tương quan", + "Covariance" => "Hiệp phương sai", + "Descriptive Statistics" => "Thống kê mô tả", + "Exponential Smoothing" => "Làm mượt hàm mũ", + "F-Test Two-Sample for Variances" => "Kiểm định F hai mẫu cho phương sai", + "Moving Average" => "Trung bình trượt", + "Rank and Percentile" => "Thứ hạng và Bách phân vị", + "Regression" => "Hồi quy", + "t-Test: Paired Two Sample for Means" => "Kiểm định t: Hai mẫu ghép cặp cho trung bình", + "t-Test: Two-Sample Assuming Equal Variances" => "Kiểm định t: Hai mẫu giả định phương sai bằng nhau", + "t-Test: Two-Sample Assuming Unequal Variances" => "Kiểm định t: Hai mẫu giả định phương sai khác nhau", + "Output options" => "Tùy chọn đầu ra", + "Output Range:" => "Vùng đầu ra:", + "New Worksheet Ply:" => "Trang tính mới:", + "Grouped By:" => "Nhóm theo:", + "Labels in first row" => "Nhãn ở hàng đầu tiên", + "Input Range:" => "Vùng đầu vào:", + "Variable 1 Range:" => "Vùng biến 1:", + "Variable 2 Range:" => "Vùng biến 2:", + "Summary statistics" => "Thống kê tóm tắt", + "Confidence Level for Mean (%), blank for none:" => "Mức tin cậy cho trung bình (%), để trống nếu không dùng:", + "Kth Largest (blank for none):" => "Lớn thứ K (để trống nếu không dùng):", + "Kth Smallest (blank for none):" => "Nhỏ thứ K (để trống nếu không dùng):", + "Bin Range (blank for automatic bins):" => "Vùng chia lớp (để trống để chia tự động):", + "Pareto (sorted histogram)" => "Pareto (biểu đồ tần suất sắp xếp)", + "Cumulative Percentage" => "Phần trăm tích lũy", + "Alpha:" => "Alpha:", + "Input Y Range:" => "Vùng Y đầu vào:", + "Input X Range:" => "Vùng X đầu vào:", + "Constant is Zero" => "Hằng số bằng 0", + "Confidence Level (%):" => "Mức tin cậy (%):", + "Residuals" => "Phần dư", + "Standardized Residuals" => "Phần dư chuẩn hóa", + "Normal Probability" => "Xác suất chuẩn", + "Interval:" => "Khoảng:", + "Standard Errors" => "Sai số chuẩn", + "Damping factor:" => "Hệ số làm mượt:", + "Hypothesized Mean Difference:" => "Hiệu số trung bình giả thuyết:", + "Set Objective:" => "Đặt mục tiêu:", + "To:" => "Thành:", + "Value Of:" => "Giá trị bằng:", + "By Changing Variable Cells:" => "Bằng cách thay đổi các ô biến số:", + "Subject to the Constraints:" => "Tuân theo các ràng buộc:", + "Make Unconstrained Variables Non-Negative" => "Đặt các biến không ràng buộc là số không âm", + "Select a Solving Method:" => "Chọn phương pháp giải:", + "GRG Nonlinear" => "GRG Phi tuyến", + "Solve" => "Giải", + "Keep Solver Solution" => "Giữ nghiệm Solver", + "Restore Original Values" => "Khôi phục giá trị ban đầu", + "The spelling check is complete for the entire sheet." => "Đã hoàn tất kiểm tra chính tả cho toàn bộ trang tính.", + "Not in Dictionary ({cell}):" => "Không có trong từ điển ({cell}):", + "Suggestions:" => "Gợi ý:", + "(No suggestions)" => "(Không có gợi ý)", + "Ignore Once" => "Bỏ qua một lần", + "Add to Dictionary" => "Thêm vào từ điển", + "Change" => "Đổi", + "Change All" => "Đổi tất cả", + "$ English (United States)" => "$ Tiếng Anh (Hoa Kỳ)", + "Add Chart Element" => "Thêm thành phần biểu đồ", + "Align Left" => "Căn trái", + "Align Right" => "Căn phải", + "Bottom Align" => "Căn dưới", + "Calculate Now (F9)" => "Tính toán ngay (F9)", + "Calculate Sheet (⇧F9)" => "Tính toán trang tính (⇧F9)", + "Calculation Options" => "Tùy chọn tính toán", + "Cell Styles" => "Kiểu ô", + "Change Chart Type" => "Đổi kiểu biểu đồ", + "Check Accessibility" => "Kiểm tra khả năng tiếp cận", + "Clear Filter" => "Xóa bộ lọc", + "Column or Bar" => "Cột hoặc Thanh", + "Comments pane" => "Ngăn nhận xét", + "Convert the last ink stroke to a shape" => "Chuyển nét mực cuối thành hình dạng", + "Convert to Range" => "Chuyển thành vùng", + "Copy" => "Sao chép", + "Custom Sort" => "Sắp xếp tùy chỉnh", + "Cut" => "Cắt", + "Define Name…" => "Đặt tên…", + "Delete Comment" => "Xóa nhận xét", + "Delete Sheet" => "Xóa trang tính", + "Delete chart" => "Xóa biểu đồ", + "Delete…" => "Xóa…", + "Dismiss" => "Đóng", + "Down" => "Xuống", + "Edit chart title" => "Sửa tiêu đề biểu đồ", + "Erase ink strokes" => "Tẩy nét mực", + "Every command run in this session (replayable)" => "Mọi lệnh đã chạy trong phiên này (có thể phát lại)", + "Expand formula bar" => "Mở rộng thanh công thức", + "Filter (⌘⇧F)" => "Bộ lọc (⌘⇧F)", + "Filter by Selected Cell's Value" => "Lọc theo giá trị của ô đã chọn", + "Find & Select" => "Tìm & Chọn", + "Flash Fill (⌘E)" => "Điền nhanh (⌘E)", + "Forecast Sheet" => "Trang tính dự báo", + "Forecast end (date or number; blank: a third of the history):" => "Kết thúc dự báo (ngày hoặc số; để trống: một phần ba lịch sử):", + "Format Chart pane" => "Ngăn Định dạng biểu đồ", + "Format as Table" => "Định dạng thành bảng", + "Hide" => "Ẩn", + "Hide Sheet" => "Ẩn trang tính", + "Hierarchy & more" => "Phân cấp & khác", + "Highlighter" => "Bút tô sáng", + "How agents drive GridCraft (MCP / control channel)" => "Cách tác tử điều khiển GridCraft (MCP / kênh điều khiển)", + "Import a text or CSV file" => "Nhập tệp văn bản hoặc CSV", + "Insert Function" => "Chèn hàm", + "Insert Function (⇧F3)" => "Chèn hàm (⇧F3)", + "Insert Link (⌘K)" => "Chèn liên kết (⌘K)", + "Insert Sheet" => "Chèn trang tính", + "Insert Slicer" => "Chèn bộ cắt lát", + "Insert a picture" => "Chèn hình ảnh", + "Insert a slicer to filter a table" => "Chèn bộ cắt lát để lọc bảng", + "Insert an icon" => "Chèn biểu tượng", + "Insert…" => "Chèn…", + "Line or Area" => "Đường hoặc Miền", + "Link…" => "Liên kết…", + "Macros and scripts in this workbook (Alt+F8)" => "Macro và tập lệnh trong sổ làm việc này (Alt+F8)", + "Middle Align" => "Căn giữa theo chiều dọc", + "More commands" => "Thêm lệnh", + "Move or Copy Sheet…" => "Di chuyển hoặc sao chép trang tính…", + "New sheet (⇧F11)" => "Trang tính mới (⇧F11)", + "Next sheet" => "Trang tính tiếp theo", + "Page Breaks" => "Ngắt trang", + "Paper Size" => "Khổ giấy", + "Paste (⌘V)" => "Dán (⌘V)", + "Pick From Drop-down List…" => "Chọn từ danh sách thả xuống…", + "Pie or Doughnut" => "Tròn hoặc Vành khuyên", + "Previous sheet" => "Trang tính trước", + "Print Area" => "Vùng in", + "Print Titles" => "Tiêu đề in", + "Protect Workbook structure" => "Bảo vệ cấu trúc sổ làm việc", + "Redo (⌘Y)" => "Làm lại (⌘Y)", + "Save (⌘S)" => "Lưu (⌘S)", + "Scatter or Bubble" => "Phân tán hoặc Bong bóng", + "Search and run any command" => "Tìm và chạy bất kỳ lệnh nào", + "Search commands (⌘⇧Space)" => "Tìm lệnh (⌘⇧Space)", + "Select and move ink and shapes" => "Chọn và di chuyển nét mực và hình dạng", + "Series…" => "Chuỗi…", + "Share: export or save a copy" => "Chia sẻ: xuất hoặc lưu bản sao", + "Show Formulas (⌃`)" => "Hiện công thức (⌃`)", + "Slicer" => "Bộ cắt lát", + "Sort & Filter" => "Sắp xếp & Lọc", + "Spelling (F7)" => "Chính tả (F7)", + "Statistic" => "Thống kê", + "Switch Row/Column" => "Đổi hàng/cột", + "Table (⌘T)" => "Bảng (⌘T)", + "Table Styles" => "Kiểu bảng", + "Text to Columns" => "Văn bản thành cột", + "The output range already holds data. Replace it with the report?" => "Vùng đầu ra đã có dữ liệu. Thay thế bằng báo cáo?", + "Top Align" => "Căn trên", + "Undo (⌘Z)" => "Hoàn tác (⌘Z)", + "Undo list" => "Danh sách hoàn tác", + "Unhide Sheet…" => "Hiện trang tính…", + "Up" => "Lên", + "Version, contributors and the AI models that helped" => "Phiên bản, người đóng góp và các mô hình AI đã hỗ trợ", + "What-If Analysis" => "Phân tích giả định", + "Zoom In" => "Phóng to", + "Zoom Out" => "Thu nhỏ", + "Zoom to 100%" => "Thu phóng về 100%", + "Zoom to Selection" => "Thu phóng đến vùng chọn", + "Zoom…" => "Thu phóng…", + "£ English (United Kingdom)" => "£ Tiếng Anh (Vương quốc Anh)", + "¥ Japanese" => "¥ Tiếng Nhật", + "€ Euro" => "€ Euro", + "Tab|Insert" => "Chèn", + "AutoSave" => "Tự động lưu", + "Insert\nSlicer" => "Chèn bộ\ncắt lát", + "Pen\nBlack" => "Bút\nđen", + "Pen\nBlue" => "Bút\nxanh lam", + "Pen\nRed" => "Bút\nđỏ", + "Protect\nSheet" => "Bảo vệ\ntrang tính", + "Watch\nWindow" => "Cửa sổ\ntheo dõi", + "Workbook\nStatistics" => "Thống kê\nsổ làm việc", + // PivotTable Fields pane. + "PivotTable Fields" => "Các trường Bảng tổng hợp", + "Choose fields to add to report:" => "Chọn trường để thêm vào báo cáo:", + "Use a field's menu to move it between areas:" => "Dùng menu của trường để chuyển giữa các vùng:", + "Filters" => "Bộ lọc", + "Values" => "Giá trị", + "Move to Row Labels" => "Chuyển tới Nhãn hàng", + "Move to Column Labels" => "Chuyển tới Nhãn cột", + "Move to Report Filter" => "Chuyển tới Bộ lọc báo cáo", + "Move to Values" => "Chuyển tới Giá trị", + "Summarize by Sum" => "Tổng hợp theo Tổng", + "Summarize by Count" => "Tổng hợp theo Đếm", + "Summarize by Average" => "Tổng hợp theo Trung bình", + "Summarize by Max" => "Tổng hợp theo Lớn nhất", + "Summarize by Min" => "Tổng hợp theo Nhỏ nhất", + "Show as No Calculation" => "Hiển thị không tính toán", + "Show as % of Grand Total" => "Hiển thị theo % tổng chung", + "Show as Running Total" => "Hiển thị theo tổng lũy kế", + "Show as Rank" => "Hiển thị theo thứ hạng", + "Group by Years" => "Nhóm theo năm", + "Group by Quarters" => "Nhóm theo quý", + "Group by Months" => "Nhóm theo tháng", + "Remove Field" => "Gỡ trường", + "Refresh" => "Làm mới", + "Calculated Field…" => "Trường tính toán…", + "Report Layout" => "Bố cục báo cáo", + "Compact" => "Thu gọn", + "Tabular" => "Dạng bảng", + // Print settings, cell styles, conditional formatting, chart types, sheet tab menu & account. + "20% - Accent1" => "20% - Nhấn 1", + "20% - Accent2" => "20% - Nhấn 2", + "20% - Accent3" => "20% - Nhấn 3", + "20% - Accent4" => "20% - Nhấn 4", + "20% - Accent5" => "20% - Nhấn 5", + "20% - Accent6" => "20% - Nhấn 6", + "3 Arrows" => "3 mũi tên", + "3 Symbols" => "3 ký hiệu", + "3 Traffic Lights" => "3 đèn giao thông", + "4 Ratings" => "4 mức xếp hạng", + "40% - Accent1" => "40% - Nhấn 1", + "40% - Accent2" => "40% - Nhấn 2", + "40% - Accent3" => "40% - Nhấn 3", + "40% - Accent4" => "40% - Nhấn 4", + "40% - Accent5" => "40% - Nhấn 5", + "40% - Accent6" => "40% - Nhấn 6", + "5 Arrows" => "5 mũi tên", + "5 Quarters" => "5 phần tư", + "60% - Accent1" => "60% - Nhấn 1", + "60% - Accent2" => "60% - Nhấn 2", + "60% - Accent3" => "60% - Nhấn 3", + "60% - Accent4" => "60% - Nhấn 4", + "60% - Accent5" => "60% - Nhấn 5", + "60% - Accent6" => "60% - Nhấn 6", + "A Date Occurring…" => "Ngày xảy ra…", + "Accent1" => "Nhấn 1", + "Accent2" => "Nhấn 2", + "Accent3" => "Nhấn 3", + "Accent4" => "Nhấn 4", + "Accent5" => "Nhấn 5", + "Accent6" => "Nhấn 6", + "Account" => "Tài khoản", + "All Borders" => "Tất cả viền", + "All sheets" => "Tất cả trang tính", + "Apply" => "Áp dụng", + "Arrow" => "Mũi tên", + "AutoSave: save after every change (workbooks saved to a file)" => "Tự động lưu: lưu sau mỗi thay đổi (sổ làm việc đã lưu vào tệp)", + "Bad" => "Kém", + "Bar" => "Thanh ngang", + "Between…" => "Nằm giữa…", + "Blue" => "Xanh dương", + "Blue - White - Red" => "Xanh dương - Trắng - Đỏ", + "Bottom Border" => "Viền dưới", + "Bottom Double Border" => "Viền đôi dưới", + "Box & Whisker" => "Biểu đồ hộp và râu", + "Bubble" => "Bong bóng", + "Calculation" => "Tính toán", + "Check Cell" => "Ô kiểm tra", + "Clear Rules" => "Xóa quy tắc", + "Column" => "Cột", + "Comma [0]" => "Dấu phẩy [0]", + "Convert to Number" => "Chuyển đổi thành số", + "Copies" => "Số bản sao", + "Currency [0]" => "Tiền tệ [0]", + "Data and Model" => "Dữ liệu và mô hình", + "Drag to fill cells. Drag from inside a cell to select a range." => "Kéo để điền các ô. Kéo từ bên trong ô để chọn một vùng.", + "Duplicate" => "Nhân bản", + "Duplicate Values…" => "Giá trị trùng lặp…", + "End date:" => "Ngày kết thúc:", + "Equal To…" => "Bằng…", + "Error checking options" => "Tùy chọn kiểm tra lỗi", + "Explanatory Text" => "Văn bản giải thích", + "Export as CSV…" => "Xuất thành CSV…", + "Export as PDF…" => "Xuất thành PDF…", + "Export as Web Page (.html)…" => "Xuất thành Trang web (.html)…", + "Finding printers…" => "Đang tìm máy in…", + "Fit selection" => "Vừa với vùng chọn", + "Forecast start (a date or number in the history; blank: after the last point):" => { + "Bắt đầu dự báo (ngày hoặc số trong lịch sử; để trống: sau điểm cuối):" + } + "Format Chart Area…" => "Định dạng vùng biểu đồ…", + "Good" => "Tốt", + "Good, Bad and Neutral" => "Tốt, kém và trung tính", + "Grayscale" => "Thang độ xám", + "Greater Than…" => "Lớn hơn…", + "Green" => "Xanh lá", + "Green - White - Red" => "Xanh lá - Trắng - Đỏ", + "Green - Yellow - Red" => "Xanh lá - Vàng - Đỏ", + "Header (&L left, &C center, &R right; &P page, &N pages, &D date, &A sheet):" => { + "Đầu trang (&L trái, &C giữa, &R phải; &P trang, &N tổng trang, &D ngày, &A trang tính):" + } + "Heading 1" => "Tiêu đề 1", + "Heading 2" => "Tiêu đề 2", + "Heading 3" => "Tiêu đề 3", + "Heading 4" => "Tiêu đề 4", + "Hex" => "Thập lục phân", + "Highlight Cells Rules" => "Quy tắc tô sáng ô", + "Input" => "Đầu vào", + "Insert Link" => "Chèn liên kết", + "Inside Borders" => "Viền trong", + "Left Border" => "Viền trái", + "Less Than…" => "Nhỏ hơn…", + "Licence" => "Giấy phép", + "Light Blue" => "Xanh lam nhạt", + "Linked Cell" => "Ô liên kết", + "Manage Rules…" => "Quản lý quy tắc…", + "More Borders…" => "Thêm đường viền…", + "More Colors…" => "Thêm màu…", + "More Functions…" => "Thêm hàm…", + "Move or Copy…" => "Di chuyển hoặc sao chép…", + "Neutral" => "Trung tính", + "New Rule…" => "Quy tắc mới…", + "New Workbook" => "Sổ làm việc mới", + "No Border" => "Không viền", + "No Color" => "Không màu", + "No Fill" => "Không tô", + "No printers found. Configure a system printer or export a PDF." => "Không tìm thấy máy in. Hãy cấu hình máy in hệ thống hoặc xuất tệp PDF.", + "Note" => "Ghi chú", + "Number Format" => "Định dạng số", + "Number Stored as Text" => "Số được lưu dưới dạng văn bản", + "One-sided" => "In một mặt", + "Options|Editing" => "Chỉnh sửa", + "Orange" => "Cam", + "Output" => "Đầu ra", + "Outside Borders" => "Viền ngoài", + "Oval" => "Hình bầu dục", + "Page Break Preview" => "Xem trước ngắt trang", + "Paste formulas that refer to the copied cells" => "Dán công thức tham chiếu đến các ô đã sao chép", + "Percent" => "Phần trăm", + "Place in Cell" => "Đặt trong ô", + "Place over Cells" => "Đặt đè lên các ô", + "Platform" => "Nền tảng", + "Print failed: the printing worker stopped." => "In thất bại: tiến trình in đã dừng.", + "Print failed: {error}" => "In thất bại: {error}", + "Print job submitted." => "Đã gửi lệnh in.", + "Print job submitted: {receipt}" => "Đã gửi lệnh in: {receipt}", + "Printer" => "Máy in", + "Printer default" => "Mặc định của máy in", + "Printer discovery failed." => "Không thể tìm kiếm máy in.", + "Print…" => "In…", + "Product Information" => "Thông tin sản phẩm", + "Protect workbook for: Structure (sheets can't be added, moved, renamed, hidden or deleted)." => { + "Bảo vệ sổ làm việc cho: Cấu trúc (không thể thêm, di chuyển, đổi tên, ẩn hoặc xóa trang tính)." + } + "Purple" => "Tím", + "Recent Colors" => "Màu dùng gần đây", + "Rectangle" => "Hình chữ nhật", + "Red" => "Đỏ", + "Red - Yellow - Green" => "Đỏ - Vàng - Xanh lá", + "Redo" => "Làm lại", + "Refresh printers" => "Làm mới danh sách máy in", + "Rename" => "Đổi tên", + "Right Border" => "Viền phải", + "Rounded Rectangle" => "Hình chữ nhật bo góc", + "Save As…" => "Lưu thành…", + "Save a Copy as Excel Workbook (.xlsx)…" => "Lưu bản sao dưới dạng Sổ làm việc Excel (.xlsx)…", + "Search" => "Tìm kiếm", + "Search commands" => "Tìm lệnh", + "Select All Sheets" => "Chọn tất cả trang tính", + "Select Data…" => "Chọn dữ liệu…", + "Select a printer" => "Chọn máy in", + "Sort Ascending" => "Sắp xếp tăng dần", + "Sort Descending" => "Sắp xếp giảm dần", + "Source:" => "Nguồn:", + "Standard Colors" => "Màu chuẩn", + "Stock" => "Chứng khoán", + "Submitting print job…" => "Đang gửi lệnh in…", + "Sunburst" => "Biểu đồ vòng đồng tâm", + "Tab Color" => "Màu thẻ trang tính", + "Text that Contains…" => "Văn bản có chứa…", + "Theme Colors" => "Màu chủ đề", + "Themed Cell Styles" => "Kiểu ô theo chủ đề", + "Thick Bottom Border" => "Viền dưới dày", + "Thick Outside Borders" => "Viền ngoài dày", + "Titles and Headings" => "Tiêu đề và đề mục", + "Top Border" => "Viền trên", + "Top and Bottom Border" => "Viền trên và dưới", + "Top and Double Bottom Border" => "Viền trên và viền đôi dưới", + "Top and Thick Bottom Border" => "Viền trên và viền dưới dày", + "Top/Bottom Rules" => "Quy tắc trên/dưới cùng", + "Total" => "Tổng cộng", + "Treemap" => "Biểu đồ bản đồ cây", + "Triangle" => "Hình tam giác", + "Two-sided printing" => "In hai mặt", + "Two-sided: long edge" => "Hai mặt: lật theo cạnh dài", + "Two-sided: short edge" => "Hai mặt: lật theo cạnh ngắn", + "Type to filter…" => "Nhập để lọc…", + "Undo" => "Hoàn tác", + "Unhide…" => "Hiện…", + "Unprotect Sheet…" => "Bỏ bảo vệ trang tính…", + "Version" => "Phiên bản", + "Warning Text" => "Văn bản cảnh báo", + "White - Green" => "Trắng - Xanh lá", + "White - Red" => "Trắng - Đỏ", + "Win/Loss" => "Thắng/Thua", + "Record Macro" => "Ghi Macro", + "Stop Recording" => "Dừng ghi", + "Use Relative References" => "Dùng tham chiếu tương đối", + "Run\nMacro" => "Chạy Macro", + "Macros…" => "Macro…", + "Recording" => "Đang ghi", + "New Macro" => "Macro mới", + "Show" => "Hiện", + "Collapse dialog" => "Thu gọn hộp thoại", + "Expand dialog" => "Mở rộng hộp thoại", "Add Level" => "Thêm cấp", "Delete Level" => "Xóa cấp", "Copy Level" => "Sao chép cấp", @@ -506,12 +1265,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Macro “{name}” stopped: {message}" => "Macro “{name}” đã dừng: {message}", "Ran macro “{name}” ({steps} step)" => "Đã chạy macro “{name}” ({steps} bước)", "Ran macro “{name}” ({steps} steps)" => "Đã chạy macro “{name}” ({steps} bước)", - "Average" => "Trung bình", - "Count" => "Số đếm", - "Sum" => "Tổng", - "Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}", - "Sheets: {sheets}" => "Trang tính: {sheets}", - "Hidden: {sheets}" => "Đang ẩn: {sheets}", "Double superscript" => "Chỉ số trên bị lặp", "Double subscript" => "Chỉ số dưới bị lặp", "Extra }" => "Thừa }", @@ -595,9 +1348,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Fill Months" => "Điền theo tháng", "Fill Years" => "Điền theo năm", "Auto Fill Options" => "Tùy chọn tự động điền", - "Series…" => "Chuỗi…", - "Down" => "Xuống", - "Up" => "Lên", // Conditional formatting: colour scales. "New Formatting Rule" => "Quy tắc định dạng mới", "Edit Formatting Rule" => "Chỉnh sửa quy tắc định dạng", @@ -616,19 +1366,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Midpoint" => "Điểm giữa", "Lowest value" => "Giá trị thấp nhất", "Highest value" => "Giá trị cao nhất", - "Percent" => "Phần trăm", "Percentile" => "Bách phân vị", "Formula" => "Công thức", - "Format values where this formula is true:" => "Định dạng các giá trị mà công thức này đúng:", - "with" => "với", "More Rules…" => "Thêm quy tắc…", // Conditional formatting: the formatting presets the rule editor offers. - "Light Red Fill with Dark Red Text" => "Tô đỏ nhạt với chữ đỏ đậm", - "Yellow Fill with Dark Yellow Text" => "Tô vàng với chữ vàng đậm", - "Green Fill with Dark Green Text" => "Tô xanh lá nhạt với chữ xanh lá đậm", - "Light Red Fill" => "Tô đỏ nhạt", - "Red Text" => "Chữ đỏ", - "Red Border" => "Viền đỏ", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index ce0cfb3d48..738c19dbb1 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -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} 页", diff --git a/crates/ui-egui/tests/print_selection.rs b/crates/ui-egui/tests/print_selection.rs new file mode 100644 index 0000000000..f715ea043f --- /dev/null +++ b/crates/ui-egui/tests/print_selection.rs @@ -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>>>) -> 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"); +} diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index ce9ef5a658..87955432f5 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -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); } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index b4fd000b41..da537c1047 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -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() }; diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 2f59c863f5..39a76f3550 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -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 | diff --git a/docs/gaps.md b/docs/gaps.md index 27a7d7b6c2..9502ed64d7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -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 | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index ea4ac7833f..cec246dc1f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -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 | diff --git a/docs/roadmap.md b/docs/roadmap.md index 458af936af..8c0d279dbb 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 231711785e..3c89484a69 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a05bbaea3b..eef256a03d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -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`) | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index c40c976973..7e62711d9d 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -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 diff --git a/xtask/src/bench.rs b/xtask/src/bench.rs new file mode 100644 index 0000000000..4030f8e19f --- /dev/null +++ b/xtask/src/bench.rs @@ -0,0 +1,107 @@ +//! `cargo xtask bench`: runs the calculation benchmarks (`crates/engine/examples/bench.rs`) in a +//! release build, writes the results to `/bench/latest.json` and compares them with a +//! baseline (`/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 = 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 { + 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()); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fe54b0f4e8..26e3a77708 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -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 /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 ... 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),