From fef1f4ddb1dd546f94de045318932d47fbc934d6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 20:25:14 +0200 Subject: [PATCH 01/71] Security: the --control server requires an auth token and closes bad connections (#777) Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 2 +- CLAUDE.md | 2 +- Cargo.lock | 2 + ROADMAP.md | 2 + apps/gridcraft/Cargo.toml | 3 + apps/gridcraft/src/control_server.rs | 139 +++++++++++++++++++++++++-- apps/gridcraft/src/main.rs | 10 +- crates/mcp/src/backend.rs | 35 ++++++- crates/mcp/src/control_auth.rs | 135 ++++++++++++++++++++++++++ crates/mcp/src/lib.rs | 1 + crates/mcp/src/tests.rs | 51 +++++++++- docs/control-protocol.md | 26 ++++- docs/mcp.md | 2 +- 13 files changed, 393 insertions(+), 17 deletions(-) create mode 100644 crates/mcp/src/control_auth.rs diff --git a/AGENTS.md b/AGENTS.md index 963fc6d74..ccead14c6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr ## Running and looking at the app - `cargo run --release -p gridcraft -- --sample sales --control 7979` (sample workbook + control channel). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. +- Drive it: `gridcraft-cli send 7979 ''` (reads the token file the app printed on stderr), or JSON lines on `127.0.0.1:7979` whose first line is `{"id":0,"method":"auth","params":{"token":"…"}}` (token: `$XDG_RUNTIME_DIR/gridcraft/control-7979.token`, or your own `GRIDCRAFT_CONTROL_TOKEN`), e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. - **Offscreen UI render** (no window, from a source checkout): `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. - Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli run --in book.xlsx --cmd 'home.bold={"range":"A1:C1"}' --out book.xlsx`, `gridcraft-cli mcp`. - **For UI work, look at the result** (snapshot PNG) and compare with `plan/excel/observed-ui.md`. diff --git a/CLAUDE.md b/CLAUDE.md index 280fe8bcb..2a7ee363e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr ## Running and looking at the app - `cargo run --release -p gridcraft -- --sample sales --control 7979` (sample workbook + control channel). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. +- Drive it: `gridcraft-cli send 7979 ''` (reads the token file the app printed on stderr), or JSON lines on `127.0.0.1:7979` whose first line is `{"id":0,"method":"auth","params":{"token":"…"}}` (token: `$XDG_RUNTIME_DIR/gridcraft/control-7979.token`, or your own `GRIDCRAFT_CONTROL_TOKEN`), e.g. `{"id":1,"method":"engine.execute","params":{"command":"cell.set","params":{"cell":"B2","input":"=SUM(A1:A9)"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. - **Offscreen UI render** (no window, from a source checkout): `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. - Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli run --in book.xlsx --cmd 'home.bold={"range":"A1:C1"}' --out book.xlsx`, `gridcraft-cli mcp`. - **For UI work, look at the result** (snapshot PNG) and compare with `plan/excel/observed-ui.md`. diff --git a/Cargo.lock b/Cargo.lock index ade3a5adb..c3fa06650 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,9 @@ dependencies = [ "eframe", "egui", "fmv-macos-events", + "getrandom 0.4.3", "gridcraft-engine", + "gridcraft-mcp", "gridcraft-ui-egui", "image", "log", diff --git a/ROADMAP.md b/ROADMAP.md index e8e1c06b3..930ded70d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-12 | Security: the `--control` server requires an auth token (random, kept in a 0600 file or chosen with `GRIDCRAFT_CONTROL_TOKEN`) on each connection's first line and closes bad connections (#777) | | 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available | | 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found | | 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) | @@ -178,6 +179,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | The control server requires an auth token and closes bad connections (#777); progress log row | | 2026-10-12 | minor | Desktop File > Print now discovers printers and submits PDF jobs through pinned craft-print with printer choice, copies, duplex and grayscale; browser printing and PDF export remain available. Remaining print parity includes page ranges and driver-specific tray/options UI; physical printer fidelity needs hardware validation. | | 2026-10-11 | minor | Password-encrypted workbooks open (#11); progress log row | | 2026-10-11 | minor | Forecast Sheet (#322); progress log row | diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index c867d24a2..14bc66b69 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -27,6 +27,9 @@ winresource = "0.1" craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d" } rfd = { workspace = true } arboard = { workspace = true } +gridcraft-mcp = { workspace = true } +# The control channel's token (OS random numbers); already in the tree. +getrandom = "0.4" [target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies] arboard = { workspace = true, features = ["wayland-data-control"] } diff --git a/apps/gridcraft/src/control_server.rs b/apps/gridcraft/src/control_server.rs index e9e05a2e6..ab2046e3c 100644 --- a/apps/gridcraft/src/control_server.rs +++ b/apps/gridcraft/src/control_server.rs @@ -1,34 +1,82 @@ //! Localhost JSON-lines control server. Each connection may send many requests; each line //! `{"id":…, "method":…, "params":…}` gets one reply line `{"id":…, "ok":…, …}`. +//! +//! The first line of a connection must authenticate with the app's token (#777; see +//! `gridcraft_mcp::control_auth`). A connection that doesn't, or later sends a line that isn't +//! JSON, is answered once and closed. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::Duration; +use gridcraft_mcp::control_auth; use gridcraft_ui_egui::ControlRequest; use serde_json::{Value as Json, json}; const MAX_LINE: usize = 64 * 1024 * 1024; +/// How long a new connection may take to send its token. +const AUTH_TIMEOUT: Duration = Duration::from_secs(10); -pub fn start(port: u16, ctx: egui::Context) -> std::io::Result> { +/// The secret of this run: the one the user chose (`--control-token`, `GRIDCRAFT_CONTROL_TOKEN`), +/// else 256 random bits from the operating system, written to a file only the user can read. +fn make_token(port: u16, chosen: Option) -> std::io::Result { + if let Some(t) = chosen.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) { + if t.len() < control_auth::MIN_TOKEN_LEN { + return Err(std::io::Error::other(format!("the control token must have at least {} characters", control_auth::MIN_TOKEN_LEN))); + } + eprintln!("gridcraft: control channel on 127.0.0.1:{port} requires the token you set (clients: GRIDCRAFT_CONTROL_TOKEN)"); + return Ok(t); + } + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|e| std::io::Error::other(format!("no random numbers for the control token: {e}")))?; + let token = control_auth::hex(&bytes); + let path = control_auth::write_token_file(port, &token)?; + eprintln!("gridcraft: control channel on 127.0.0.1:{port}; its token is in {} (gridcraft-cli reads it)", path.display()); + Ok(token) +} + +pub fn start(port: u16, chosen_token: Option, ctx: egui::Context) -> std::io::Result> { let listener = TcpListener::bind(("127.0.0.1", port))?; + let token: Arc = make_token(port, chosen_token)?.into(); let (tx, rx) = channel(); std::thread::Builder::new().name("control".into()).spawn(move || { for stream in listener.incoming().flatten() { let tx = tx.clone(); let ctx = ctx.clone(); - let _ = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, tx, ctx)); + let token = Arc::clone(&token); + let _ = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, &token, tx, ctx)); } })?; log::info!("control channel listening on 127.0.0.1:{port}"); Ok(rx) } -fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context) { +/// Read the connection's first line (at most [`control_auth::MAX_AUTH_LINE`] bytes, within +/// [`AUTH_TIMEOUT`]) and check the token. `true` when the peer may go on. +fn authenticate(reader: &mut BufReader, out: &mut TcpStream, token: &str) -> bool { + let _ = out.set_read_timeout(Some(AUTH_TIMEOUT)); + let mut first = String::new(); + let read = reader.by_ref().take(control_auth::MAX_AUTH_LINE as u64).read_line(&mut first); + let verdict = match read { + Ok(n) if n > 0 && first.ends_with('\n') => control_auth::check_first_line(&first, token), + _ => Err(json!({"ok": false, "error": "authentication required"})), + }; + let allowed = verdict.is_ok(); + let reply = verdict.unwrap_or_else(|e| e); + let _ = writeln!(out, "{reply}"); + let _ = out.set_read_timeout(None); + allowed +} + +fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context) { let Ok(read) = stream.try_clone() else { return }; let mut out = stream; - let reader = BufReader::new(read); + let mut reader = BufReader::new(read); + if !authenticate(&mut reader, &mut out, token) { + return; + } for line in reader.lines() { let Ok(line) = line else { break }; if line.trim().is_empty() { @@ -42,7 +90,7 @@ fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context) { Ok(v) => v, Err(e) => { let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("invalid JSON: {e}")})); - continue; + break; // Not a client of ours; don't keep reading. } }; let id = msg.get("id").cloned().unwrap_or(Json::Null); @@ -65,3 +113,82 @@ fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context) { } } } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + /// A server on a loopback port with a stand-in UI that echoes each method. + fn spawn() -> std::net::SocketAddr { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + std::thread::spawn(move || serve(stream, TOKEN, tx, egui::Context::default())); + } + }); + addr + } + + fn lines(addr: std::net::SocketAddr, send: &str) -> Vec { + let mut c = TcpStream::connect(addr).unwrap(); + c.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + c.write_all(send.as_bytes()).unwrap(); + // Replies up to the server closing the connection. + BufReader::new(c).lines().map_while(Result::ok).map(|l| serde_json::from_str(&l).unwrap()).collect() + } + + #[test] + fn the_token_opens_the_connection() { + let addr = spawn(); + let auth = control_auth::auth_line(1, TOKEN); + let mut c = TcpStream::connect(addr).unwrap(); + c.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + c.write_all(format!("{auth}\n{{\"id\":2,\"method\":\"ping\"}}\n").as_bytes()).unwrap(); + let mut r = BufReader::new(c); + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["ok"], json!(true)); + line.clear(); + r.read_line(&mut line).unwrap(); + let v: Json = serde_json::from_str(&line).unwrap(); + assert_eq!((v["id"].clone(), v["result"].clone()), (json!(2), json!("ping"))); + } + + #[test] + fn anything_but_the_token_first_closes_the_connection() { + let addr = spawn(); + let wrong = control_auth::auth_line(1, "ffffffffffffffffffffffffffffffff"); + for first in [wrong.as_str(), "{\"id\":1,\"method\":\"app.save\",\"params\":{\"path\":\"/tmp/x\"}}", "POST / HTTP/1.1", ""] { + // The second request is never served: one refusal, then end of stream. + let got = lines(addr, &format!("{first}\n{{\"id\":2,\"method\":\"ping\"}}\n")); + assert_eq!(got.len(), 1, "{first}: {got:?}"); + assert_eq!(got[0]["ok"], json!(false), "{first}"); + } + } + + #[test] + fn an_unparsable_line_after_auth_closes_the_connection() { + let addr = spawn(); + let auth = control_auth::auth_line(1, TOKEN); + let got = lines(addr, &format!("{auth}\nnot json\n{{\"id\":3,\"method\":\"ping\"}}\n")); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[1]["ok"], json!(false)); + } + + #[test] + fn a_chosen_token_must_be_long_enough() { + assert!(make_token(1, Some("short".into())).is_err()); + assert_eq!(make_token(1, Some(format!(" {TOKEN} "))).unwrap(), TOKEN); + } +} diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 8093205c4..18cff9844 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -1,9 +1,10 @@ //! GridCraft desktop app. //! -//! Usage: `gridcraft [--control ] [--sample ] [files…]` +//! Usage: `gridcraft [--control [--control-token ]] [--sample ] [files…]` //! //! `--control ` (or `GRIDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control //! server: `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`. +//! The first line of each connection must carry the token (`docs/control-protocol.md`). //! See `gridcraft_ui_egui::control` and `docs/control-protocol.md` for the methods. #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -242,6 +243,7 @@ fn main() -> eframe::Result<()> { return Ok(()); } let mut control_port: Option = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()); + let mut control_token: Option = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok(); let mut sample: Option = None; let mut files: Vec = Vec::new(); let mut i = 0; @@ -251,6 +253,10 @@ fn main() -> eframe::Result<()> { i += 1; control_port = args.get(i).and_then(|p| p.parse().ok()); } + "--control-token" => { + i += 1; + control_token = args.get(i).cloned(); + } "--sample" => { i += 1; sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into())); @@ -338,7 +344,7 @@ fn main() -> eframe::Result<()> { }; SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language); if let Some(port) = control_port { - match control_server::start(port, cc.egui_ctx.clone()) { + match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) { Ok(rx) => app.control_rx = Some(rx), Err(e) => log::error!("control channel on port {port}: {e}"), } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index adc866d2f..c77b612f7 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -25,14 +25,22 @@ const MAX_REPLY: u64 = 256 * 1024 * 1024; /// A running GridCraft app, reached through its loopback control port. pub struct Remote { addr: String, + token: String, conn: Option<(BufReader, TcpStream)>, next_id: u64, } impl Remote { - /// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. + /// Connect to `addr` (`127.0.0.1:7979`), failing fast when nothing is listening. The app + /// requires a token (#777): `GRIDCRAFT_CONTROL_TOKEN`, else the file the app wrote for this port. pub fn connect(addr: &str) -> std::io::Result { - let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 }; + let token = crate::control_auth::client_token(addr).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + Self::connect_with_token(addr, token) + } + + /// Like [`Remote::connect`] with a token the caller already has. + pub fn connect_with_token(addr: &str, token: String) -> std::io::Result { + let mut r = Self { addr: addr.to_string(), token, conn: None, next_id: 1 }; r.reconnect()?; Ok(r) } @@ -51,7 +59,9 @@ impl Remote { s.set_read_timeout(Some(IO_TIMEOUT)).ok(); s.set_write_timeout(Some(IO_TIMEOUT)).ok(); let read = s.try_clone()?; - self.conn = Some((BufReader::new(read), s)); + let mut conn = (BufReader::new(read), s); + Self::authenticate(&mut conn, &self.token)?; + self.conn = Some(conn); return Ok(()); } Err(e) => last = e, @@ -60,6 +70,25 @@ impl Remote { Err(last) } + /// The handshake every connection starts with: the app closes one that doesn't send the token first. + fn authenticate(conn: &mut (BufReader, TcpStream), token: &str) -> std::io::Result<()> { + let (reader, writer) = conn; + writer.write_all(crate::control_auth::auth_line(0, token).as_bytes())?; + writer.write_all(b"\n")?; + writer.flush()?; + let mut reply = String::new(); + let n = std::io::Read::take(reader, 64 * 1024).read_line(&mut reply)?; + let ok = n > 0 && serde_json::from_str::(reply.trim()).ok().and_then(|v| v.get("ok").and_then(Value::as_bool)) == Some(true); + if ok { + Ok(()) + } else { + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "the app refused the control token (is GRIDCRAFT_CONTROL_TOKEN or the app's token file for this port out of date?)", + )) + } + } + fn roundtrip(&mut self, line: &str) -> std::io::Result { if self.conn.is_none() { self.reconnect()?; diff --git a/crates/mcp/src/control_auth.rs b/crates/mcp/src/control_auth.rs new file mode 100644 index 000000000..7ff589353 --- /dev/null +++ b/crates/mcp/src/control_auth.rs @@ -0,0 +1,135 @@ +//! Authentication of the control channel (#777). +//! +//! Anything on the machine, and a web page that POSTs `text/plain` to `127.0.0.1:`, can +//! reach a loopback port. So the first line of every connection must be +//! `{"id":…,"method":"auth","params":{"token":"…"}}`, with the secret the app made at start. The +//! app keeps it in memory and writes it to a file only the user can read (or the user chooses it +//! with `GRIDCRAFT_CONTROL_TOKEN`); [`Remote`](crate::Remote) reads it from the same places. + +use std::path::PathBuf; + +use serde_json::{Value, json}; + +/// Environment variable holding a token chosen by the user. The app uses it instead of making +/// one (and writes no file); clients use it instead of reading the file. +pub const TOKEN_ENV: &str = "GRIDCRAFT_CONTROL_TOKEN"; +/// The method of the handshake line. +pub const AUTH_METHOD: &str = "auth"; +/// Shortest token the app accepts from the user (a made one has 256 bits). +pub const MIN_TOKEN_LEN: usize = 16; +/// Longest first line the app reads from a peer that hasn't authenticated yet. +pub const MAX_AUTH_LINE: usize = 4096; + +/// Compare two secrets without stopping at the first difference. Unequal lengths are unequal +/// at once (the length of a token isn't secret). +pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (x, y) in a.iter().zip(b) { + diff |= x ^ y; + } + // Keep the optimiser from turning the loop into an early exit. + std::hint::black_box(diff) == 0 +} + +/// A made token as lowercase hex (two characters per byte). +pub fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len().saturating_mul(2)); + for b in bytes { + s.push(char::from(DIGITS[usize::from(b >> 4)])); + s.push(char::from(DIGITS[usize::from(b & 15)])); + } + s +} + +/// The handshake line a client sends first. +pub fn auth_line(id: u64, token: &str) -> String { + json!({"id": id, "method": AUTH_METHOD, "params": {"token": token}}).to_string() +} + +/// Check a connection's first line. `Ok` is the reply to send before serving further requests; +/// `Err` is the reply for a refused connection, which the caller sends and then closes. The +/// refusal is the same whatever was wrong, so it tells a stranger nothing. +pub fn check_first_line(line: &str, token: &str) -> Result { + let refused = || json!({"ok": false, "error": "authentication required"}); + let msg: Value = serde_json::from_str(line.trim()).map_err(|_| refused())?; + if msg.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) { + return Err(refused()); + } + let given = msg.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or(""); + // Always compare, so a missing token costs the same as a wrong one. + if constant_time_eq(given.as_bytes(), token.as_bytes()) && !token.is_empty() { + Ok(json!({"id": msg.get("id").cloned().unwrap_or(Value::Null), "ok": true, "result": {"authenticated": true}})) + } else { + Err(refused()) + } +} + +/// Where the app writes the token it made for `port`, and where clients look for it: a folder +/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows +/// `%USERPROFILE%\.gridcraft`), file `control-.token`. `None` when no such folder is known. +pub fn token_path(port: u16) -> Option { + let dir = if cfg!(windows) { + PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft") + } else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) { + PathBuf::from(run).join("gridcraft") + } else { + PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft") + }; + Some(dir.join(format!("control-{port}.token"))) +} + +/// The port of a control address (`127.0.0.1:7979` → 7979). +fn port_of(addr: &str) -> Option { + addr.rsplit(':').next()?.parse().ok() +} + +/// The token a client uses for `addr`: [`TOKEN_ENV`] if set, else the file the app wrote. +pub fn client_token(addr: &str) -> Result { + if let Ok(t) = std::env::var(TOKEN_ENV) + && !t.trim().is_empty() + { + return Ok(t.trim().to_string()); + } + let path = port_of(addr).and_then(token_path).ok_or_else(|| format!("no control token: set {TOKEN_ENV}"))?; + match std::fs::read_to_string(&path) { + Ok(t) if !t.trim().is_empty() => Ok(t.trim().to_string()), + _ => Err(format!("no control token: set {TOKEN_ENV}, or start the app on this machine and user (it writes {})", path.display())), + } +} + +/// Write `token` to [`token_path`] for the app: the folder is made private (mode 0700 on Unix), +/// an older file is replaced, and the new one is created readable by the user only (mode 0600). +/// Returns the path. +pub fn write_token_file(port: u16, token: &str) -> std::io::Result { + use std::io::Write; + let path = token_path(port).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no user folder for the control token"))?; + let dir = path.parent().ok_or_else(|| std::io::Error::other("token path has no folder"))?; + std::fs::create_dir_all(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // Only our own folder: leave a shared one (`$XDG_RUNTIME_DIR` itself) as it is. + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + // Replace rather than open: a leftover file may have looser permissions, or be a link. + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts.open(&path)?; + f.write_all(token.as_bytes())?; + f.write_all(b"\n")?; + Ok(path) +} diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index de3e25044..7c66a26f9 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -15,6 +15,7 @@ #![forbid(unsafe_code)] mod backend; +pub mod control_auth; mod headless; mod server; mod tools; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index eb1f20503..df6c954e7 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -363,6 +363,11 @@ fn remote_backend_over_tcp() { let stream = stream.unwrap(); let mut w = stream.try_clone().unwrap(); let mut r = BufReader::new(stream); + // Every connection starts with the token, as the app requires. + let mut first = String::new(); + r.read_line(&mut first).unwrap(); + let hello = crate::control_auth::check_first_line(&first, "secret-token-0123456789").unwrap(); + w.write_all(format!("{hello}\n").as_bytes()).unwrap(); loop { let mut line = String::new(); if r.read_line(&mut line).unwrap_or(0) == 0 { @@ -382,7 +387,7 @@ fn remote_backend_over_tcp() { }); let addr = control_addr(&port.to_string()); assert_eq!(addr, format!("127.0.0.1:{port}")); - let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap())); + let mut s = Server::new(Box::new(Remote::connect_with_token(&addr, "secret-token-0123456789".into()).unwrap())); assert_eq!(ok(&mut s, "evaluate_formula", json!({"formula": "=1+1"}))["result"], json!(2.0)); // Second call reconnects transparently. ok(&mut s, "set_cell", json!({"cell": "A1", "input": "7"})); @@ -391,7 +396,49 @@ fn remote_backend_over_tcp() { assert!(msg.contains("unknown command"), "{msg}"); drop(s); handle.join().unwrap(); - assert!(Remote::connect("127.0.0.1:1").is_err()); + assert!(Remote::connect_with_token("127.0.0.1:1", "x".into()).is_err()); +} + +#[test] +fn control_auth_handshake_and_compare() { + use crate::control_auth::{auth_line, check_first_line, constant_time_eq, hex}; + let token = "0123456789abcdef0123456789abcdef"; + let ok = check_first_line(&auth_line(7, token), token).unwrap(); + assert_eq!((ok["id"].clone(), ok["ok"].clone()), (json!(7), json!(true))); + // Wrong or missing token, another method, and non-JSON are all refused the same way. + let wrong = check_first_line(&auth_line(1, "0123456789abcdef0123456789abcdee"), token).unwrap_err(); + for bad in [ + auth_line(1, ""), + r#"{"id":1,"method":"auth","params":{}}"#.into(), + r#"{"id":1,"method":"app.save","params":{"path":"/tmp/x","token":"0123456789abcdef0123456789abcdef"}}"#.into(), + "POST / HTTP/1.1".into(), + String::new(), + ] { + assert_eq!(check_first_line(&bad, token).unwrap_err(), wrong, "{bad}"); + } + // An empty configured token never matches an empty given one. + assert!(check_first_line(&auth_line(1, ""), "").is_err()); + assert!(constant_time_eq(b"abc", b"abc")); + assert!(!constant_time_eq(b"abc", b"abd")); + assert!(!constant_time_eq(b"abc", b"abcd")); + assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff"); +} + +#[cfg(unix)] +#[test] +fn control_token_file_is_private() { + use std::os::unix::fs::PermissionsExt; + // Unique port per run so parallel tests don't share a file; the folder is the real one. + let port = 40_000 + (std::process::id() % 20_000) as u16; + let path = crate::control_auth::write_token_file(port, "tok-0123456789abcdef").unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::metadata(path.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + // A looser leftover is replaced, not reused. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + crate::control_auth::write_token_file(port, "tok-1123456789abcdef").unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "tok-1123456789abcdef"); + std::fs::remove_file(&path).unwrap(); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7cc6ec230..39a3e5d67 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -6,7 +6,31 @@ Start the desktop app with a control port: gridcraft --control 7979 # or GRIDCRAFT_CONTROL_PORT=7979 ``` -Then send newline-delimited JSON to `127.0.0.1:7979`. Every request line gets one reply line: +## Authentication + +The control port is reachable by every program on the machine, and by a web page that POSTs +`text/plain` to `127.0.0.1:7979`, so every connection must prove it knows the app's token +(#777). **There is no way to turn this off.** + +- The app makes a token at start (256 random bits from the operating system, kept in memory) and + writes it to a file only you can read: `$XDG_RUNTIME_DIR/gridcraft/control-.token` (else + `~/.cache/gridcraft/…`; Windows: `%USERPROFILE%\.gridcraft\…`; the folder is mode 0700 and the + file 0600 on Unix). The path is printed on stderr. The token itself is never printed or logged. +- Or choose the token yourself: `GRIDCRAFT_CONTROL_TOKEN=…` (preferred) or `--control-token …` + (visible in the process list), at least 16 characters. The app then writes no file. +- The first line of a connection must be + `{"id":0,"method":"auth","params":{"token":"…"}}`; the reply is + `{"id":0,"ok":true,"result":{"authenticated":true}}`. Any other first line (a wrong or missing + token, another method, text that isn't JSON such as an HTTP request, no line within 10 s, or + one longer than 4 KiB) gets `{"ok":false,"error":"authentication required"}` and the + connection is closed. After that, a line that isn't JSON also closes the connection. +- `gridcraft-cli send`/`mcp --connect` and `gridcraft_mcp::Remote` do this themselves: they use + `GRIDCRAFT_CONTROL_TOKEN` if set, else the token file of that port (so they work for the same + user on the same machine without setup). Your own client reads the file or the variable. + +## Requests + +Then send newline-delimited JSON to `127.0.0.1:7979` (after the `auth` line). Every request line gets one reply line: ```json {"id": 1, "method": "engine.execute", "params": {"command": "cell.set", "params": {"cell": "B2", "input": "=SUM(A1:A9)"}}} diff --git a/docs/mcp.md b/docs/mcp.md index 3e6e7bc11..811fc9500 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9,7 +9,7 @@ Two backends: | Mode | Command | What it drives | |---|---|---| | Headless (default) | `gridcraft-cli mcp [--in book.xlsx \| --sample budget]` | An in-process engine session — no window. | -| Remote | `gridcraft-cli mcp --connect 7979` | A running app started with `gridcraft --control 7979` (TCP JSON lines on `127.0.0.1`). | +| Remote | `gridcraft-cli mcp --connect 7979` | A running app started with `gridcraft --control 7979` (TCP JSON lines on `127.0.0.1`, authenticated with the app's token: it is read from the app's token file or `GRIDCRAFT_CONTROL_TOKEN`, see [`control-protocol.md`](control-protocol.md)). | ## Claude Code From 5bd6cc3d04701b1f70442f2a2eaae5d285a0f3e8 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 00:57:17 -0500 Subject: [PATCH 02/71] Options: Maximum Iterations and Maximum Change in File > Options > Formulas The Formulas section had the calculation-mode radios and Enable iterative calculation but not the two limits that formulas.calculationOptions already takes. They now sit under the checkbox, disabled while iteration is off, and commit when the field loses focus. Like Excel, out-of-range entries (Maximum Iterations outside 1-32767, a negative or non-numeric Maximum Change) are refused with a message instead of being clamped by the command; the Enter that committed the field no longer also dismisses that message. Labels and messages are translated for every interface language. A kittest covers the disabled state, valid and invalid entries, and undo refreshing the field. Drops the stale "no Options dialog yet" from gaps.md and function-parity.md. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 3 +- crates/ui-egui/src/backstage.rs | 53 +++++++++++++++++++ crates/ui-egui/src/i18n.rs | 4 ++ crates/ui-egui/src/i18n/cs.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 6 +++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt.rs | 4 ++ crates/ui-egui/src/i18n/ru.rs | 4 ++ crates/ui-egui/src/i18n/sr.rs | 4 ++ crates/ui-egui/src/i18n/zh.rs | 4 ++ crates/ui-egui/tests/file_menu.rs | 88 ++++++++++++++++++++++++++++++- docs/function-parity.md | 5 +- docs/gaps.md | 6 ++- docs/ui-parity.md | 5 +- 16 files changed, 194 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07..2c06f07d9 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-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (Maximum Iterations and Maximum Change in File › Options) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 922baabc5..bc41222e1 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -992,10 +992,63 @@ fn options(app: &mut SheetApp, ui: &mut Ui) { if ui.checkbox(&mut iterative, lang.tr("Enable iterative calculation")).changed() { app.run_or_alert("formulas.calculationOptions", json!({"iterative": iterative})); } + // Maximum Iterations and Maximum Change apply only while iteration is on, as in Excel. + ui.add_enabled_ui(calc.iterative, |ui| { + ui.horizontal(|ui| { + ui.add_space(24.0); + egui::Grid::new("backstage_options_iteration").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { + ui.label(lang.tr("Maximum Iterations:")); + let id = ui.make_persistent_id("backstage_max_iterations"); + if let Some(text) = crate::widgets::committed_text(ui, id, &calc.max_iterations.to_string(), Some(80.0)) { + match parse_max_iterations(&text) { + Some(n) if n != calc.max_iterations => { + app.run_or_alert("formulas.calculationOptions", json!({"maxIterations": n})); + } + Some(_) => {} + None => refuse(app, ui, "Maximum Iterations must be a whole number from 1 to 32767."), + } + } + ui.end_row(); + ui.label(lang.tr("Maximum Change:")); + let id = ui.make_persistent_id("backstage_max_change"); + if let Some(text) = crate::widgets::committed_text(ui, id, &calc.max_change.to_string(), Some(80.0)) { + match parse_max_change(&text) { + Some(d) if d != calc.max_change => { + app.run_or_alert("formulas.calculationOptions", json!({"maxChange": d})); + } + Some(_) => {} + None => refuse(app, ui, "Maximum Change must be a number of 0 or more."), + } + } + ui.end_row(); + }); + }); + }); + // TODO: add "Set precision as displayed" here once `formulas.calculationOptions` takes + // `precisionAsDisplayed` (PR #1366); the model already stores it. ui.add_space(6.0); dim(ui, lang.tr("Calculation settings are saved with the workbook.")); } +/// Refuses a typed setting with a message, leaving the workbook as it was. The Enter that +/// committed the field is consumed so it doesn't also dismiss the message box in this frame. +fn refuse(app: &mut SheetApp, ui: &mut Ui, text: &str) { + ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)); + app.message = Some(("GridCraft".into(), app.ui.language.tr(text).into())); +} + +/// Maximum Iterations as typed: a whole number from 1 to 32767, or `None` (Excel refuses others). +fn parse_max_iterations(text: &str) -> Option { + let n = text.trim().parse::().ok()?; + (1..=gridcraft_engine::model::CalcSettings::MAX_ITERATIONS).contains(&n).then_some(n) +} + +/// Maximum Change as typed: a finite number of 0 or more, or `None`. +fn parse_max_change(text: &str) -> Option { + let d = text.trim().parse::().ok()?; + (d.is_finite() && d >= 0.0).then_some(d) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 061698df9..17b098de2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -587,6 +587,10 @@ const JAPANESE: &[(&str, &str)] = &[ ("Save .xlsx workbooks automatically after every change", "変更のたびに .xlsx ブックを自動的に保存する"), ("Workbook calculation", "ブックの計算"), ("Enable iterative calculation", "反復計算を行う"), + ("Maximum Iterations:", "最大反復回数:"), + ("Maximum Change:", "変化の最大値:"), + ("Maximum Iterations must be a whole number from 1 to 32767.", "最大反復回数には 1 から 32767 までの整数を指定してください。"), + ("Maximum Change must be a number of 0 or more.", "変化の最大値には 0 以上の数値を指定してください。"), ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), ]; diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 7ed8372c7..deaff822c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -323,6 +323,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Automaticky ukládat sešity .xlsx po každé změně", "Workbook calculation" => "Výpočet sešitu", "Enable iterative calculation" => "Povolit iterativní výpočet", + "Maximum Iterations:" => "Maximální počet iterací:", + "Maximum Change:" => "Maximální změna:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Maximální počet iterací musí být celé číslo od 1 do 32767.", + "Maximum Change must be a number of 0 or more." => "Maximální změna musí být číslo 0 nebo větší.", "Calculation settings are saved with the workbook." => "Nastavení výpočtů se ukládá se sešitem.", "100%" => "100 %", "Zoom to\nSelection" => "Přiblížit\nna výběr", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c20c7d1b3..efa20cac7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -323,6 +323,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => ".xlsx-Arbeitsmappen nach jeder Änderung automatisch speichern", "Workbook calculation" => "Arbeitsmappenberechnung", "Enable iterative calculation" => "Iterative Berechnung aktivieren", + "Maximum Iterations:" => "Maximale Iterationszahl:", + "Maximum Change:" => "Maximale Änderung:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Die maximale Iterationszahl muss eine ganze Zahl von 1 bis 32767 sein.", + "Maximum Change must be a number of 0 or more." => "Die maximale Änderung muss eine Zahl größer oder gleich 0 sein.", "Calculation settings are saved with the workbook." => "Berechnungseinstellungen werden mit der Arbeitsmappe gespeichert.", "Interface size" => "Größe der Benutzeroberfläche", "Auto" => "Automatisch", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4ce231bca..508f04945 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -322,6 +322,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Guardar automáticamente los libros .xlsx tras cada cambio", "Workbook calculation" => "Cálculo del libro", "Enable iterative calculation" => "Habilitar cálculo iterativo", + "Maximum Iterations:" => "Iteraciones máximas:", + "Maximum Change:" => "Cambio máximo:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Las iteraciones máximas deben ser un número entero de 1 a 32767.", + "Maximum Change must be a number of 0 or more." => "El cambio máximo debe ser un número igual o mayor que 0.", "Calculation settings are saved with the workbook." => "La configuración de cálculo se guarda con el libro.", "Interface size" => "Tamaño de la interfaz", "Auto" => "Automático", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5d20ab0ca..dec45571b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -409,6 +409,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Enregistrer automatiquement les classeurs .xlsx après chaque modification", "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Activer le calcul itératif", + "Maximum Iterations:" => "Nombre maximal d'itérations :", + "Maximum Change:" => "Écart maximal :", + "Maximum Iterations must be a whole number from 1 to 32767." => { + "Le nombre maximal d'itérations doit être un entier compris entre 1 et 32767." + } + "Maximum Change must be a number of 0 or more." => "L'écart maximal doit être un nombre supérieur ou égal à 0.", "Calculation settings are saved with the workbook." => "Les paramètres de calcul sont enregistrés avec le classeur.", _ => return None, }) diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1902ad301..566044d57 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -409,6 +409,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "변경할 때마다 .xlsx 통합 문서를 자동으로 저장", "Workbook calculation" => "통합 문서 계산", "Enable iterative calculation" => "반복 계산 사용", + "Maximum Iterations:" => "최대 반복 횟수:", + "Maximum Change:" => "변화 한도:", + "Maximum Iterations must be a whole number from 1 to 32767." => "최대 반복 횟수는 1에서 32767 사이의 정수여야 합니다.", + "Maximum Change must be a number of 0 or more." => "변화 한도는 0 이상의 숫자여야 합니다.", "Calculation settings are saved with the workbook." => "계산 설정은 통합 문서와 함께 저장됩니다.", _ => return None, }) diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index fb9236cdb..74d4c6268 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -409,6 +409,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Salvar pastas de trabalho .xlsx automaticamente após cada alteração", "Workbook calculation" => "Cálculo da pasta de trabalho", "Enable iterative calculation" => "Habilitar cálculo iterativo", + "Maximum Iterations:" => "Número Máximo de Iterações:", + "Maximum Change:" => "Alteração Máxima:", + "Maximum Iterations must be a whole number from 1 to 32767." => "O número máximo de iterações deve ser um número inteiro de 1 a 32767.", + "Maximum Change must be a number of 0 or more." => "A alteração máxima deve ser um número maior ou igual a 0.", "Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.", "OK" => "OK", "Cancel" => "Cancelar", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 765f6bb32..f53611517 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -409,6 +409,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Автоматически сохранять книги .xlsx после каждого изменения", "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", + "Maximum Iterations:" => "Предельное число итераций:", + "Maximum Change:" => "Относительная погрешность:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Предельное число итераций должно быть целым числом от 1 до 32767.", + "Maximum Change must be a number of 0 or more." => "Относительная погрешность должна быть числом не меньше 0.", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", _ => return None, }) diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index cbf18d4c4..8f724c22b 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -401,6 +401,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "Automatski sačuvaj .xlsx radne sveske posle svake izmene", "Workbook calculation" => "Izračunavanje radne sveske", "Enable iterative calculation" => "Omogući iterativno izračunavanje", + "Maximum Iterations:" => "Maksimalan broj iteracija:", + "Maximum Change:" => "Maksimalna promena:", + "Maximum Iterations must be a whole number from 1 to 32767." => "Maksimalan broj iteracija mora biti ceo broj od 1 do 32767.", + "Maximum Change must be a number of 0 or more." => "Maksimalna promena mora biti broj veći ili jednak 0.", "Calculation settings are saved with the workbook." => "Podešavanja izračunavanja se čuvaju sa radnom sveskom.", "Left Margin" => "Leva margina", "Right Margin" => "Desna margina", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 00175925e..8f77aeb6d 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -401,6 +401,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save .xlsx workbooks automatically after every change" => "每次更改后自动保存 .xlsx 工作簿", "Workbook calculation" => "工作簿计算", "Enable iterative calculation" => "启用迭代计算", + "Maximum Iterations:" => "最多迭代次数:", + "Maximum Change:" => "最大误差:", + "Maximum Iterations must be a whole number from 1 to 32767." => "最多迭代次数必须是 1 到 32767 之间的整数。", + "Maximum Change must be a number of 0 or more." => "最大误差必须是大于或等于 0 的数字。", "Calculation settings are saved with the workbook." => "计算设置随工作簿一起保存。", _ => return None, }) diff --git a/crates/ui-egui/tests/file_menu.rs b/crates/ui-egui/tests/file_menu.rs index 691eef367..33059c14e 100644 --- a/crates/ui-egui/tests/file_menu.rs +++ b/crates/ui-egui/tests/file_menu.rs @@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex}; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use gridcraft_engine::{Session, core::CellRef, core::Value}; use gridcraft_ui_egui::{Services, SheetApp}; @@ -217,3 +217,89 @@ fn a_cancelled_export_pdf_picker_writes_nothing() { assert!(h.state().message.is_none()); assert!(h.state_mut().session.take_ui_requests().is_empty()); } + +/// Options › Formulas: Maximum Iterations and Maximum Change, with the checkbox that enables them. +#[test] +fn options_sets_maximum_iterations_and_change_only_while_iteration_is_on() { + use egui::accesskit::Role; + let mut session = Session::new(); + session.new_workbook(); + // Tall enough that the Formulas section is on screen without scrolling. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 1400.0)).build_ui_state( + |ui, app: &mut SheetApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + SheetApp::new(session, Services::default()), + ); + h.run_steps(4); + h.state_mut().run("file.options", serde_json::json!({})).unwrap(); + h.run_steps(3); + let calc = |h: &egui_kittest::Harness<'static, SheetApp>| h.state().session.active().unwrap().wb.calc.clone(); + // The text field on the same row as `label`. + let field = |h: &egui_kittest::Harness<'static, SheetApp>, label: &str| { + let l = h.get_by_label(label).rect(); + h.get_all_by_role(Role::TextInput).map(|n| n.rect()).find(|r| r.left() > l.left() && (r.center().y - l.center().y).abs() < 8.0).unwrap() + }; + let disabled = |h: &egui_kittest::Harness<'static, SheetApp>, rect: egui::Rect| { + h.get_all_by_role(Role::TextInput).find(|n| n.rect() == rect).unwrap().accesskit_node().is_disabled() + }; + let retype = |h: &mut egui_kittest::Harness<'static, SheetApp>, rect: egui::Rect, text: &str| { + h.input_mut().events.push(egui::Event::PointerMoved(rect.center())); + h.run_steps(1); + h.get_all_by_role(Role::TextInput).find(|n| n.rect() == rect).unwrap().click(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for c in text.chars() { + h.input_mut().events.push(egui::Event::Text(c.to_string())); + h.run_steps(2); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + }; + + // Iteration is off: the two fields show the defaults, greyed out. + let (iterations, change) = (field(&h, "Maximum Iterations:"), field(&h, "Maximum Change:")); + assert!(disabled(&h, iterations) && disabled(&h, change), "the fields are disabled while iteration is off"); + assert_eq!(h.get_all_by_role(Role::TextInput).find(|n| n.rect() == iterations).unwrap().value().as_deref(), Some("100")); + assert_eq!(h.get_all_by_role(Role::TextInput).find(|n| n.rect() == change).unwrap().value().as_deref(), Some("0.001")); + + h.get_by_role_and_label(Role::CheckBox, "Enable iterative calculation").click(); + h.run_steps(3); + assert!(calc(&h).iterative); + let (iterations, change) = (field(&h, "Maximum Iterations:"), field(&h, "Maximum Change:")); + assert!(!disabled(&h, iterations) && !disabled(&h, change)); + + retype(&mut h, iterations, "500"); + assert_eq!(calc(&h).max_iterations, 500); + retype(&mut h, change, "0.01"); + assert_eq!(calc(&h).max_change, 0.01); + assert!(h.state().message.is_none()); + + // Out-of-range entries are refused with a message and change nothing (the command alone would clamp them). + for bad in ["0", "32768", "12.5", "lots"] { + retype(&mut h, iterations, bad); + assert_eq!(calc(&h).max_iterations, 500, "{bad}"); + assert!(h.state_mut().message.take().is_some(), "{bad} is reported"); + h.run_steps(2); + } + retype(&mut h, iterations, "32767"); + assert_eq!(calc(&h).max_iterations, 32767); + for bad in ["-1", "x"] { + retype(&mut h, change, bad); + assert_eq!(calc(&h).max_change, 0.01, "{bad}"); + assert!(h.state_mut().message.take().is_some(), "{bad} is reported"); + h.run_steps(2); + } + retype(&mut h, change, "0"); + assert_eq!(calc(&h).max_change, 0.0); + + // Undo puts the old value back in the field. + h.state_mut().run("edit.undo", serde_json::json!({})).unwrap(); + h.run_steps(3); + assert_eq!(calc(&h).max_change, 0.01); + let change = field(&h, "Maximum Change:"); + assert_eq!(h.get_all_by_role(Role::TextInput).find(|n| n.rect() == change).unwrap().value().as_deref(), Some("0.01")); +} diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac..7b2f5f03e 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (iterative calculation settings in File › Options) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -79,7 +79,7 @@ PIVOTBY, REGEXTEST…) are all present. | Implicit intersection `@`, legacy CSE array formulas | done; legacy array range fill (PR #156) | | Trim references `A1:.E10` (trailing), `A1.:E10` (leading), `A1.:.E10` (both), also on whole rows/columns (`A:.A`) | done; evaluated as `TRIMRANGE(range, code, code)`, adjusted on insert/delete; files store `_xlfn.TRIMRANGE(range,code,code)` (Excel's own file spelling unconfirmed in public docs), `_xlfn._TRO_ALL/_TRO_LEADING/_TRO_TRAILING(...)` read too | | LET, LAMBDA, named LAMBDAs, ISOMITTED, MAP/REDUCE/SCAN/BYROW/BYCOL/MAKEARRAY | done | -| Iterative calculation for circular references | done: with Enable Iterative Calculation on (`formulas.calculationOptions` `{iterative, maxIterations, maxChange}`, saved as ``), loops are evaluated again from their previous values (blank = 0) until no cell on a loop changes by Maximum Change or Maximum Iterations is reached; off, cycles give `#CIRC!`. Differences: no Options dialog yet (command only); GridCraft recalculates on open, so a loop that never settles (`=A1+1`) advances again each time the file is opened | +| Iterative calculation for circular references | done: with Enable Iterative Calculation on (`formulas.calculationOptions` `{iterative, maxIterations, maxChange}`, saved as ``), loops are evaluated again from their previous values (blank = 0) until no cell on a loop changes by Maximum Change or Maximum Iterations is reached; off, cycles give `#CIRC!`. Set in File › Options › Formulas (Enable iterative calculation, Maximum Iterations 1 to 32767, Maximum Change 0 or more; the two fields are disabled while iteration is off). Differences: GridCraft recalculates on open, so a loop that never settles (`=A1+1`) advances again each time the file is opened | | 15-significant-digit comparison semantics | **missing** (#57: `=0.1+0.2=0.3` is FALSE) | | External workbook references (`[Book.xlsx]Sheet1!A1`) | parsed; links dropped on open, no update | | Localized function names and `;` separators | **missing** (#45); en-US only | @@ -108,6 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Iterative calculation: Maximum Iterations and Maximum Change are set in File › Options › Formulas (dropped "no Options dialog yet") | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | diff --git a/docs/gaps.md b/docs/gaps.md index 03e8672c5..61b5f7422 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (§6: Maximum Iterations and Maximum Change in File › Options) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -62,7 +62,8 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- - **Missing:** 15-significant-digit equality; spill updates after structural edits and cleared blockers; 3-D span deletion; qualified names after sheet rename. - **Evidence:** #57, #133, #139, #140, #134; PRs #148, #155, #156, #157. Iterative calculation - for circular references landed (no Options dialog yet). + for circular references landed, set in File › Options › Formulas (Maximum Iterations, Maximum + Change). - **Impact:** wrong numbers are worse than missing features. - **Estimate:** 10–15 h. [function-parity.md](function-parity.md#formula-language) @@ -168,6 +169,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" | | 2026-10-12 | minor | rows auto-fit oversized fonts on open and whole-row/column formatting (#833) | | 2026-10-12 | minor | Page Layout view: dragging margins on the rulers (#792) removed from the §14 remainder | | 2026-10-12 | minor | §13: Forecast Sheet Forecast Start (hindcast) landed (#785) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 22e221e69..34b6ed1e4 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-10-13 · **Change:** minor (horizontal scrollbar in the sheet tab bar, #840) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (File › Options › Formulas: Maximum Iterations and Maximum Change) · **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 @@ -26,7 +26,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes | element-level Format pane for shapes and pictures missing | | Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | Options dialog and 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) | -| 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) 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) | 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) 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 | | 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 | margins drag on the rulers (#792, with header and footer margins); header/footer pictures, Different First Page / Odd & Even missing (1–3 h) | | Multiple windows per workbook | yes | no (#162) | see [hardware-parity.md](hardware-parity.md) | @@ -161,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | File › Options › Formulas: Maximum Iterations (1 to 32767) and Maximum Change (0 or more) under Enable iterative calculation, disabled while it is off; invalid entries are refused with a message | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | | 2026-10-13 | minor | Horizontal scrollbar in the sheet tab bar: drag, track click pages, frozen columns excluded from the page (#840) | | 2026-10-12 | minor | Ctrl+wheel zoom steps along a ladder of percentages about 20% apart that never skips 100%, gliding to each step with animations on, so a notch out undoes a notch in (it drifted: 100 → 122 → 101); Excel steps 15 points, see decisions.md | From 672c102eb2eb375b3b2752f1e446147aebd522dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 17 Oct 2026 15:12:02 -0700 Subject: [PATCH 03/71] Calc: a LAMBDA that calls itself without end answers #NUM! instead of overflowing the stack The evaluator stopped at MAX_DEPTH (400) nested eval calls. A LAMBDA call takes one of those levels but several stack frames (eval, eval_inner, call, builtin, apply_lambda, call_lambda_values), so on the 1 MiB main thread of the Windows build `=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))` overflowed the stack before it reached the limit, and the process ended. eval now also stops once a formula has used 512 KiB of stack below its first eval. Both limits answer #NUM!, the error Excel documents for too many recursive calls, and a defined name that holds the recursion passes that error on instead of answering #NAME?. Fixes #1662 --- crates/calc/src/eval.rs | 37 +++++++++++++++++++++++++++++-------- crates/calc/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 0f9cfb03d..2bbedd551 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -49,6 +49,18 @@ fn err(e: CellError) -> Ev { Ev::V(Value::Error(e)) } +/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it, +/// `eval` answers `#NUM!`. One level of `MAX_DEPTH` can take several stack frames. The Windows main +/// thread and the web build have 1 MiB of stack. +const STACK_BUDGET: usize = 512 * 1024; + +/// The address of a local variable, which shows how far down the native stack this call is. +#[inline(always)] +fn stack_position() -> usize { + let marker = 0u8; + std::hint::black_box(&marker) as *const u8 as usize +} + /// What the evaluator needs from its surroundings. pub trait Host { fn workbook(&self) -> &Workbook; @@ -84,6 +96,8 @@ pub struct Evaluator<'h> { pub at: CellRef, env: Vec<(String, Ev)>, depth: usize, + /// `stack_position()` at the outermost `eval`. + stack_top: usize, } struct FnCtx<'a, 'h> { @@ -121,14 +135,14 @@ impl Ctx for FnCtx<'_, '_> { _ => None, }) .collect(); - let mut ev = Evaluator { host: &mut *self.ev.host, sheet: area.sheet, at, env, depth: self.ev.depth }; + let mut ev = Evaluator { host: &mut *self.ev.host, sheet: area.sheet, at, env, depth: self.ev.depth, stack_top: self.ev.stack_top }; Some(matches!(ev.value(&shifted).scalar().to_bool(), Ok(true))) } } impl<'h> Evaluator<'h> { pub fn new(host: &'h mut dyn Host, sheet: usize, at: CellRef) -> Self { - Evaluator { host, sheet, at, env: Vec::new(), depth: 0 } + Evaluator { host, sheet, at, env: Vec::new(), depth: 0, stack_top: 0 } } /// Evaluates to a value (references are dereferenced; multi-cell → array). @@ -205,10 +219,16 @@ impl<'h> Evaluator<'h> { } pub fn eval(&mut self, e: &Expr) -> Ev { + let here = stack_position(); + if self.depth == 0 { + self.stack_top = here; + } else if self.stack_top.abs_diff(here) > STACK_BUDGET { + return err(CellError::Num); + } self.depth += 1; if self.depth > MAX_DEPTH { self.depth -= 1; - return err(CellError::Calc); + return err(CellError::Num); } let r = self.eval_inner(e); self.depth -= 1; @@ -492,7 +512,7 @@ impl<'h> Evaluator<'h> { } _ => { // A long chain such as A1+A2+…+A500 nests to the left: fold it in a loop instead - // of one level of recursion per operator (past the depth limit it was #CALC!). + // of one level of recursion per operator (past the depth limit it was an error). let mut rest = vec![(op, b)]; let mut left = a; while let Expr::Binary(o, l, r) = left @@ -801,10 +821,11 @@ impl<'h> Evaluator<'h> { fn builtin(&mut self, name: &str, args: &[Expr]) -> Ev { let Some(spec) = gridcraft_functions::lookup(name) else { // A defined name holding a LAMBDA, or a LET-bound lambda. - if let Ev::L(l) = self.name(name) { - return self.apply_lambda(&l, args); - } - return err(CellError::Name); + return match self.name(name) { + Ev::L(l) => self.apply_lambda(&l, args), + Ev::V(Value::Error(x)) => err(x), + _ => err(CellError::Name), + }; }; if args.len() < spec.min_args || args.len() > spec.max_args { return err(CellError::Value); diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de7..5cbbd5509 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -643,6 +643,38 @@ fn lambda_argument_count() { assert_eq!(t.get("A9"), Value::Bool(true)); } +#[test] +fn a_lambda_that_calls_itself_without_end_is_num_on_a_small_stack() { + // 1 MiB is the main thread's stack on Windows, where commands, recalculation and file open run. + let handle = std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(|| { + let mut t = T::new(); + t.wb.names.push(gridcraft_model::DefinedName { + name: "LOOP".into(), + scope: None, + formula: "LAMBDA(n,LOOP(n))".into(), + comment: String::new(), + hidden: false, + }); + t.calc.rebuild(&t.wb); + let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))"; + t.set("A1", endless); + t.set("A2", "=LOOP(1)"); + t.set("A3", "=LET(F,LAMBDA(me,n,IF(n<=0,0,1+SUM(MAP({1},LAMBDA(v,me(me,n-1)))))),F(F,100000))"); + t.set("A4", "=LET(F,LAMBDA(me,n,IF(n<=0,0,1+me(me,n-1))),F(F,50))"); + let evaluated = crate::evaluate(&t.wb, 0, c("B1"), endless); + [t.get("A1"), t.get("A2"), t.get("A3"), evaluated, t.get("A4")] + }) + .expect("spawn"); + let [endless, endless_name, through_map, evaluated, countdown] = handle.join().expect("recursion must not overflow the stack"); + assert_eq!(endless, Value::Error(CellError::Num)); + assert_eq!(endless_name, Value::Error(CellError::Num)); + assert_eq!(through_map, Value::Error(CellError::Num)); + assert_eq!(evaluated, Value::Error(CellError::Num)); + assert_eq!(countdown, Value::Number(50.0)); +} + #[test] fn names_and_sheets() { let mut t = T::new(); From 09973e7831ecdb03f8ee71ef9a3841cd26c6547f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 17 Oct 2026 15:12:19 -0700 Subject: [PATCH 04/71] Contributors: add dotCooCoo (Robert Lee) --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index d522b84e0..96bead93e 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -65,3 +65,7 @@ sync_github_name = true [people.Silvertree2010] display_name = "Netter" sync_github_name = false + +[people.dotCooCoo] +real_name = "Robert Lee" +sync_github_name = true From d0fdf948db4ad425b3fe19ec8ad8ee035d792059 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 18 Oct 2026 13:09:44 -0700 Subject: [PATCH 05/71] Calc: a recursive LAMBDA stops at a fixed count of 140 calls A LAMBDA recursion answered #NUM! once the formula had used 512 KiB of native stack, so the depth it reached depended on frame sizes. On a Windows release build the deepest countdown was F(F,94), where 0.7.0 reached F(F,131). The evaluator now counts the LAMBDA calls a formula has in progress, in call_lambda_values, which direct calls, defined names, MAP, REDUCE, SCAN, BYROW, BYCOL and MAKEARRAY all go through. The 141st call answers #NUM!. The countdown F(F,131), the deepest that the 400-level MAX_DEPTH allows, has 132 calls in progress and still runs. The stack check stays as a guard. Its budget rises to 896 KiB, which leaves 128 KiB of a 1 MiB thread for the frames above the formula. a_recursive_lambda_stops_at_the_same_call_on_any_stack_size runs recursions on each side of the limit on a 1 MiB and a 64 MiB thread and expects the same results. The 1 MiB test now runs the countdown F(F,131). --- crates/calc/src/eval.rs | 31 ++++++++++++++++++++++++++----- crates/calc/src/tests.rs | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 2bbedd551..bc60c5b7a 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -49,10 +49,16 @@ fn err(e: CellError) -> Ev { Ev::V(Value::Error(e)) } +/// LAMBDA calls that one formula may have in progress at once, counted the same way on every build. +/// The next call answers `#NUM!`. A countdown from 131, the deepest that `MAX_DEPTH` allows, has 132 +/// calls in progress, so it still runs. +const MAX_LAMBDA_CALLS: usize = 140; + /// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it, -/// `eval` answers `#NUM!`. One level of `MAX_DEPTH` can take several stack frames. The Windows main -/// thread and the web build have 1 MiB of stack. -const STACK_BUDGET: usize = 512 * 1024; +/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames +/// above the formula. A cell that another cell's formula computes on demand gets its own `Evaluator`, +/// which starts its own budget. +const STACK_BUDGET: usize = 896 * 1024; /// The address of a local variable, which shows how far down the native stack this call is. #[inline(always)] @@ -96,6 +102,8 @@ pub struct Evaluator<'h> { pub at: CellRef, env: Vec<(String, Ev)>, depth: usize, + /// LAMBDA calls in progress. + calls: usize, /// `stack_position()` at the outermost `eval`. stack_top: usize, } @@ -135,14 +143,22 @@ impl Ctx for FnCtx<'_, '_> { _ => None, }) .collect(); - let mut ev = Evaluator { host: &mut *self.ev.host, sheet: area.sheet, at, env, depth: self.ev.depth, stack_top: self.ev.stack_top }; + let mut ev = Evaluator { + host: &mut *self.ev.host, + sheet: area.sheet, + at, + env, + depth: self.ev.depth, + calls: self.ev.calls, + stack_top: self.ev.stack_top, + }; Some(matches!(ev.value(&shifted).scalar().to_bool(), Ok(true))) } } impl<'h> Evaluator<'h> { pub fn new(host: &'h mut dyn Host, sheet: usize, at: CellRef) -> Self { - Evaluator { host, sheet, at, env: Vec::new(), depth: 0, stack_top: 0 } + Evaluator { host, sheet, at, env: Vec::new(), depth: 0, calls: 0, stack_top: 0 } } /// Evaluates to a value (references are dereferenced; multi-cell → array). @@ -963,10 +979,15 @@ impl<'h> Evaluator<'h> { } fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev { + if self.calls >= MAX_LAMBDA_CALLS { + return err(CellError::Num); + } + self.calls += 1; let saved = std::mem::replace(&mut self.env, l.env.clone()); self.env.extend(bound); let r = self.eval(&l.body); self.env = saved; + self.calls -= 1; r } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 99ef117ce..d56bf0c13 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -662,7 +662,7 @@ fn a_lambda_that_calls_itself_without_end_is_num_on_a_small_stack() { t.set("A1", endless); t.set("A2", "=LOOP(1)"); t.set("A3", "=LET(F,LAMBDA(me,n,IF(n<=0,0,1+SUM(MAP({1},LAMBDA(v,me(me,n-1)))))),F(F,100000))"); - t.set("A4", "=LET(F,LAMBDA(me,n,IF(n<=0,0,1+me(me,n-1))),F(F,50))"); + t.set("A4", "=LET(F,LAMBDA(me,n,IF(n<=0,0,1+me(me,n-1))),F(F,131))"); let evaluated = crate::evaluate(&t.wb, 0, c("B1"), endless); [t.get("A1"), t.get("A2"), t.get("A3"), evaluated, t.get("A4")] }) @@ -672,7 +672,35 @@ fn a_lambda_that_calls_itself_without_end_is_num_on_a_small_stack() { assert_eq!(endless_name, Value::Error(CellError::Num)); assert_eq!(through_map, Value::Error(CellError::Num)); assert_eq!(evaluated, Value::Error(CellError::Num)); - assert_eq!(countdown, Value::Number(50.0)); + assert_eq!(countdown, Value::Number(131.0)); +} + +#[test] +fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() { + let run = |stack: usize| { + std::thread::Builder::new() + .stack_size(stack) + .spawn(|| { + let mut wb = Workbook::new(); + wb.names.push(gridcraft_model::DefinedName { + name: "CNT".into(), + scope: None, + formula: "LAMBDA(n,IF(n=0,0,1+CNT(n-1)))".into(), + comment: String::new(), + hidden: false, + }); + // F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step. + let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))"); + let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))"); + [tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f)) + }) + .expect("spawn") + .join() + .expect("recursion must not overflow the stack") + }; + let small = run(1 << 20); + assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]); + assert_eq!(run(64 << 20), small); } #[test] From 450f457535e3c8537e45986deff5b602cff00e76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 22 Oct 2026 11:06:01 -0700 Subject: [PATCH 06/71] Calc: a formula calculated inside another one shares its stack budget A cell that another cell's formula calculates on demand got its own evaluator, which started a new 896 KiB stack budget wherever it was called. Two cells that each count down from 131 with a LAMBDA, one read at the deepest call of the other, overflowed a 1 MiB thread. The budget of a formula calculated on demand is now counted from where the outermost formula started. When it runs out there, the formula is calculated again from the top, as a formula needed at the nesting limit is, so its value does not depend on the order cells are calculated in. --- crates/calc/src/eval.rs | 19 ++++++++++++++----- crates/calc/src/recalc.rs | 31 ++++++++++++++++++++++++++++++- crates/calc/src/tests.rs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 1d39fd818..f2f5f5ef4 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -60,13 +60,13 @@ const MAX_LAMBDA_CALLS: usize = 140; /// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it, /// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames -/// above the formula. A cell that another cell's formula computes on demand gets its own `Evaluator`, -/// which starts its own budget. +/// above the formula. A cell that another cell's formula computes on demand shares the budget of the +/// outermost formula ([`Host::stack_top`]). const STACK_BUDGET: usize = 896 * 1024; /// The address of a local variable, which shows how far down the native stack this call is. #[inline(always)] -fn stack_position() -> usize { +pub(crate) fn stack_position() -> usize { let marker = 0u8; std::hint::black_box(&marker) as *const u8 as usize } @@ -98,6 +98,13 @@ pub trait Host { fn visit_range(&mut self, _sheet: usize, _range: RangeRef, _f: &mut dyn FnMut(&Value) -> bool) -> bool { false } + /// While a formula is calculated on demand inside another one: `stack_position()` where the + /// outermost one started, which the stack budget is counted from. + fn stack_top(&self) -> Option { + None + } + /// Called when a formula's evaluation runs past the stack budget. + fn stack_exhausted(&mut self) {} } pub struct Evaluator<'h> { @@ -265,8 +272,10 @@ impl<'h> Evaluator<'h> { pub fn eval(&mut self, e: &Expr) -> Ev { let here = stack_position(); if self.depth == 0 { - self.stack_top = here; - } else if self.stack_top.abs_diff(here) > STACK_BUDGET { + self.stack_top = self.host.stack_top().unwrap_or(here); + } + if self.stack_top.abs_diff(here) > STACK_BUDGET { + self.host.stack_exhausted(); return err(CellError::Num); } self.depth += 1; diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 66374bed2..eabc29314 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -44,7 +44,7 @@ use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; use gridcraft_formula::Expr; use gridcraft_model::{CalcMode, Workbook}; -use crate::eval::{Area, Evaluator, Host, precedents}; +use crate::eval::{Area, Evaluator, Host, precedents, stack_position}; pub type Key = (usize, CellRef); @@ -432,6 +432,10 @@ struct PassHost<'a> { tainted: HashSet, /// Whether the formula being evaluated has read a previous value. taint: bool, + /// `stack_position()` where the outermost formula being calculated started. + stack_top: usize, + /// Whether an evaluation ran past the stack budget since the innermost formula started. + out_of_stack: bool, } impl<'a> PassHost<'a> { @@ -462,6 +466,8 @@ impl<'a> PassHost<'a> { members: HashSet::default(), tainted: HashSet::default(), taint: false, + stack_top: 0, + out_of_stack: false, } } } @@ -580,6 +586,9 @@ impl PassHost<'_> { self.suspend = Some(k); return Value::Error(CellError::Calc); } + if self.depth == 0 { + self.stack_top = stack_position(); + } self.in_progress.insert(k); self.depth += 1; let outer_taint = std::mem::replace(&mut self.taint, false); @@ -587,10 +596,24 @@ impl PassHost<'_> { self.stack.push(k); } let expr = std::sync::Arc::clone(expr); + let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false); let v = { let mut ev = Evaluator::new(self, k.0, k.1); ev.value(&expr) }; + let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack); + if out_of_stack && self.depth > 1 && self.suspend.is_none() { + // It ran out of the stack left below the formulas that read it: it is calculated + // from the top instead, as a formula needed at `MAX_NESTED` levels deep is. + self.suspend = Some(k); + self.depth -= 1; + self.in_progress.remove(&k); + if self.iterate { + self.stack.pop(); + } + self.taint = outer_taint; + return Value::Error(CellError::Calc); + } if self.suspend.is_some() { // Abandoned: `calculate` evaluates this formula again once the one it needs is done. self.depth -= 1; @@ -745,6 +768,12 @@ impl Host for PassHost<'_> { fn workbook(&self) -> &Workbook { self.wb } + fn stack_top(&self) -> Option { + (self.depth > 1).then_some(self.stack_top) + } + fn stack_exhausted(&mut self) { + self.out_of_stack = true; + } fn spill_range(&mut self, sheet: usize, anchor: CellRef) -> Option { let k = (sheet, anchor); if !(self.pending.contains(&k) || self.results.contains_key(&k)) { diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 608af9320..6106f1bfc 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -834,6 +834,40 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() { assert_eq!(run(64 << 20), small); } +#[test] +fn a_recursive_lambda_that_reads_another_cells_recursive_lambda_shares_the_stack() { + let run = |stack: usize| { + std::thread::Builder::new() + .stack_size(stack) + .spawn(|| { + // Row-major order calculates A1 first, so each cell below is calculated on demand + // at the deepest call of the one above it. + let countdown = |then: &str| format!("=LET(F,LAMBDA(me,n,IF(n<=0,{then},1+me(me,n-1))),F(F,131))"); + let mut wb = Workbook::new(); + let sheet = wb.sheet_mut(0).expect("sheet"); + for (at, f) in [ + ("A1", countdown("A2")), + ("A2", countdown("A3")), + ("A3", countdown("0")), + ("B1", countdown("B2")), + ("B2", "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string()), + ] { + sheet.cells.set(c(at), Cell::formula(Formula::new(&f))); + } + let mut calc = Calc::new(); + calc.recalc_all(&mut wb); + ["A1", "A2", "A3", "B1", "B2"].map(|at| wb.sheet(0).map(|s| s.value(c(at))).unwrap_or_default()) + }) + .expect("spawn") + .join() + .expect("recursion must not overflow the stack") + }; + let small = run(1 << 20); + let num = Value::Error(CellError::Num); + assert_eq!(small, [Value::Number(393.0), Value::Number(262.0), Value::Number(131.0), num.clone(), num]); + assert_eq!(run(64 << 20), small); +} + #[test] fn names_and_sheets() { let mut t = T::new(); From 1062604fee0a6f4bf9394dd9d578f3595ede44a5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:32:50 -0500 Subject: [PATCH 07/71] i18n: Russian Maximum Change reads as a change limit The Russian labels for Maximum Change said relative error, which is a different quantity. They now say maximum change. --- crates/ui-egui/src/i18n/ru.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 3101d4b35..97033fe4e 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -418,9 +418,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", "Maximum Iterations:" => "Предельное число итераций:", - "Maximum Change:" => "Относительная погрешность:", + "Maximum Change:" => "Максимальное изменение:", "Maximum Iterations must be a whole number from 1 to 32767." => "Предельное число итераций должно быть целым числом от 1 до 32767.", - "Maximum Change must be a number of 0 or more." => "Относительная погрешность должна быть числом не меньше 0.", + "Maximum Change must be a number of 0 or more." => "Максимальное изменение должно быть числом не меньше 0.", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", "Insert Sheet" => "Вставить лист", "Rename" => "Переименовать", From a80c7ff570ed25a72a86d921461f6abf3a5bd94e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:43:24 -0500 Subject: [PATCH 08/71] i18n: Japanese labels for the iteration settings live in ja.rs The merge from main moved the Japanese catalog into i18n/ja.rs, but the feature's old table stayed in i18n.rs and was never used, which failed clippy's dead-code lint. Drop the table and add the four new labels and messages to ja.rs. --- crates/ui-egui/src/i18n.rs | 421 ---------------------------------- crates/ui-egui/src/i18n/ja.rs | 4 + 2 files changed, 4 insertions(+), 421 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 5d3a831b1..345037b52 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -296,427 +296,6 @@ pub fn set_current(ctx: &egui::Context, language: Language) { ctx.data_mut(|d| d.insert_temp(lang_key(), language)); } -/// English label → Japanese. Keys are the exact interface strings (command ids, file names and -/// document text are never translated); anything absent falls back to English. -const JAPANESE: &[(&str, &str)] = &[ - ("Paste", "貼り付け"), - ("Paste Values", "値の貼り付け"), - ("Paste Formulas", "数式の貼り付け"), - ("Paste Formatting", "書式の貼り付け"), - ("Transpose", "行列を入れ替え"), - ("Paste Link", "リンクの貼り付け"), - ("Paste Special…", "形式を選択して貼り付け…"), - ("Insert Copied Cells", "コピーしたセルの挿入"), - ("Insert Copied Cells…", "コピーしたセルの挿入…"), - ("Insert Cut Cells", "切り取ったセルの挿入"), - ("Insert Paste", "挿入貼り付け"), - ("Cut (⌘X)", "切り取り (⌘X)"), - ("Copy (⌘C)", "コピー (⌘C)"), - ("Format Painter (double-click to keep it on)", "書式のコピー/貼り付け (ダブルクリックで固定)"), - ("Bold (⌘B)", "太字 (⌘B)"), - ("Italic (⌘I)", "斜体 (⌘I)"), - ("Underline (⌘U)", "下線 (⌘U)"), - ("Double Underline", "二重下線"), - ("Strikethrough", "取り消し線"), - ("Underline", "下線"), - ("Increase Font Size", "フォントの拡大"), - ("Decrease Font Size", "フォントの縮小"), - ("Wrap Text", "折り返して全体を表示"), - ("Merge & Center", "セルを結合して中央揃え"), - ("Merge Cells", "セルの結合"), - ("Merge Across", "横方向に結合"), - ("Unmerge Cells", "セル結合の解除"), - ("Fill Color", "塗りつぶしの色"), - ("Font Color", "フォントの色"), - ("Borders", "罫線"), - ("Top\nAlign", "上揃え"), - ("Middle\nAlign", "中央揃え (縦)"), - ("Bottom\nAlign", "下揃え"), - ("Left", "左"), - ("Right", "右"), - ("Center", "中央"), - ("Horizontal", "水平"), - ("Vertical Text", "縦書き"), - ("Decrease Indent", "インデントを減らす"), - ("Increase Indent", "インデントを増やす"), - ("Orientation", "方向"), - ("Page Layout|Orientation", "印刷の向き"), - ("Angle Counterclockwise", "左回りに回転"), - ("Angle Clockwise", "右回りに回転"), - ("Rotate Text Up", "文字列を上に回転"), - ("Rotate Text Down", "文字列を下に回転"), - ("Accounting Number Format", "通貨表示形式"), - ("Percent Style", "パーセント表示"), - ("Comma Style", "桁区切りスタイル"), - ("Increase Decimal", "小数点以下の桁数を増やす"), - ("Decrease Decimal", "小数点以下の桁数を減らす"), - ("More Accounting Formats…", "その他の通貨表示形式…"), - ("Conditional\nFormatting", "条件付き書式"), - ("Conditional Formatting", "条件付き書式"), - ("Format\nas Table", "テーブルとして書式設定"), - ("Cell\nStyles", "セルのスタイル"), - ("Format Cells…", "セルの書式設定…"), - ("Format Cell Alignment…", "セルの配置…"), - ("Format\nPane", "書式ウィンドウ"), - ("Format", "書式"), - ("Insert", "挿入"), - ("Insert Cells…", "セルの挿入…"), - ("Delete", "削除"), - ("Delete Cells…", "セルの削除…"), - ("Insert Sheet Rows", "シートの行を挿入"), - ("Insert Sheet Columns", "シートの列を挿入"), - ("Delete Sheet Rows", "シートの行を削除"), - ("Delete Sheet Columns", "シートの列を削除"), - ("Row Height…", "行の高さ…"), - ("AutoFit Row Height", "行の高さを自動調整"), - ("Column Width…", "列の幅…"), - ("AutoFit Column Width", "列の幅を自動調整"), - ("Default Width…", "標準の幅…"), - ("Hide Rows", "行を表示しない"), - ("Unhide Rows", "再表示"), - ("Hide Columns", "列の表示/非表示"), - ("Unhide Columns", "再表示"), - ("Lock Cell", "セルのロック"), - ("Clear", "クリア"), - ("Clear All", "すべてクリア"), - ("Clear Formats", "書式のクリア"), - ("Clear Contents", "数式と値のクリア"), - ("Clear Comments and Notes", "コメントとメモのクリア"), - ("Clear Hyperlinks", "ハイパーリンクのクリア"), - ("AutoSum", "オート SUM"), - ("AutoSum (⌘⇧T)", "オート SUM (⌘⇧T)"), - ("Flash\nFill", "フラッシュ フィル"), - ("Flash Fill", "フラッシュ フィル"), - ("Fill", "フィル"), - ("Clear Print Area", "印刷範囲のクリア"), - ("Find &\nSelect", "検索と選択"), - ("Find…", "検索…"), - ("Replace…", "置換…"), - ("Go To…", "ジャンプ…"), - ("Go To Special…", "セルを選択…"), - ("PivotTable", "ピボットテーブル"), - ("Recommended\nCharts", "推奨グラフ"), - ("Table", "テーブル"), - ("Pictures", "画像"), - ("Shapes", "図形"), - ("Icons", "アイコン"), - ("Text\nBox", "テキスト ボックス"), - ("Comment", "コメント"), - ("New\nComment", "新しいコメント"), - ("New Note", "新しいメモ"), - ("Show/Hide Note", "メモの表示/非表示"), - ("Header &\nFooter", "ヘッダーとフッター"), - ("Text to\nColumns", "区切り位置"), - ("Link", "リンク"), - ("Symbol", "記号"), - ("Sparklines", "スパークライン"), - ("Checkbox", "チェックボックス"), - ("Insert checkboxes in the selected cells", "選択したセルにチェックボックスを挿入"), - ("Header & Footer", "ヘッダーとフッター"), - ("Draw with ink", "インクで描画"), - ("Eraser", "消しゴム"), - ("Ink to\nShape", "インクを図形に変換"), - ("Select\nObjects", "オブジェクトの選択"), - ("Themes", "テーマ"), - ("Margins", "余白"), - ("Left Margin", "左余白"), - ("Right Margin", "右余白"), - ("Top Margin", "上余白"), - ("Bottom Margin", "下余白"), - ("Header Margin", "ヘッダーの余白"), - ("Footer Margin", "フッターの余白"), - ("Size", "サイズ"), - ("Print\nArea", "印刷範囲"), - ("Set Print Area", "印刷範囲の設定"), - ("Breaks", "改ページ"), - ("Insert Page Break", "改ページの挿入"), - ("Remove Page Break", "改ページの解除"), - ("Reset All Page Breaks", "すべての改ページを解除"), - ("Print\nTitles", "印刷タイトル"), - ("Sheet\nRight-to-Left", "シートを右から左へ"), - ("Sheet Right-to-Left", "シートを右から左へ"), - ("Narrow", "狭い"), - ("Wide", "広い"), - ("Normal", "標準"), - ("Portrait", "縦"), - ("Landscape", "横"), - ("Custom Margins…", "ユーザー設定の余白…"), - ("Insert\nFunction", "関数の挿入"), - ("Name\nManager", "名前の管理"), - ("Define Name", "名前の定義"), - ("Use in Formula", "数式で使用"), - ("Create from Selection", "選択範囲から作成"), - ("Trace Precedents", "参照元のトレース"), - ("Trace Dependents", "参照先のトレース"), - ("Remove Arrows", "矢印の解除"), - ("Show Formulas", "数式の表示"), - ("Error Checking", "エラーチェック"), - ("Evaluate Formula", "数式の検証"), - ("Watch Window", "ウォッチ ウィンドウ"), - ("Calculation\nOptions", "計算方法の設定"), - ("Calculate Now", "再計算実行"), - ("Calculate Sheet", "シートの再計算"), - ("Automatic", "自動"), - ("Automatic Except for Data Tables", "データ テーブル以外は自動"), - ("Manual", "手動"), - ("Sort &\nFilter", "並べ替えとフィルター"), - ("Sort", "並べ替え"), - ("Sort A to Z", "昇順"), - ("Sort Z to A", "降順"), - ("Custom Sort…", "ユーザー設定の並べ替え…"), - ("Filter", "フィルター"), - ("Reapply", "再適用"), - ("Get Data\n(Text/CSV)", "データの取得 (テキスト/CSV)"), - ("Remove\nDuplicates", "重複の削除"), - ("Data\nValidation", "データの入力規則"), - ("Data Validation", "データの入力規則"), - ("Data Validation…", "データの入力規則…"), - ("Circle Invalid Data", "無効なデータをマーク"), - ("Clear Validation", "入力規則のクリア"), - ("Group", "グループ化"), - ("Ungroup", "グループ解除"), - ("Show Detail", "詳細データの表示"), - ("Hide Detail", "詳細を表示しない"), - ("Subtotal", "小計"), - ("Data\nAnalysis", "データ分析"), - ("Data Analysis", "データ分析"), - ("Solver", "ソルバー"), - ("What-If\nAnalysis", "What-If 分析"), - ("Data Table…", "データ テーブル…"), - ("Scenario Manager…", "シナリオ マネージャー…"), - ("Goal Seek…", "ゴール シーク…"), - ("Forecast\nSheet", "予測シート"), - ("Spelling", "スペルチェック"), - ("Check\nAccessibility", "アクセシビリティ チェック"), - ("Threaded Comments", "スレッド化されたコメント"), - ("Show\nComments", "コメントの表示"), - ("Previous", "前へ"), - ("Next", "次へ"), - ("Previous Comment", "前のコメント"), - ("Next Comment", "次のコメント"), - ("Show All Notes", "すべてのメモを表示"), - ("Convert to Comments", "コメントに変換"), - ("Protect\nWorkbook", "ブックの保護"), - ("Allow Edit\nRanges", "範囲の編集を許可"), - ("Allow Edit Ranges", "範囲の編集を許可"), - ("Unprotect\nSheet", "シート保護の解除"), - ("Protect Sheet…", "シートの保護…"), - ("Comments", "コメント"), - ("Notes", "メモ"), - ("Page Break\nPreview", "改ページ プレビュー"), - ("Page\nLayout", "ページ レイアウト"), - ("Formula Bar", "数式バー"), - ("Gridlines", "目盛線"), - ("Headings", "見出し"), - ("Zoom", "ズーム"), - ("100%", "100%"), - ("Zoom to\nSelection", "選択範囲を拡大"), - ("Freeze\nPanes", "ウィンドウ枠の固定"), - ("Freeze Panes", "ウィンドウ枠の固定"), - ("Freeze Top Row", "最上行の固定"), - ("Freeze First Column", "最左列の固定"), - ("Unfreeze Panes", "ウィンドウ枠固定の解除"), - ("Dark Mode", "ダーク モード"), - ("Display theme", "表示テーマ"), - ("Animations", "アニメーション"), - ( - "Glide the selection outline to the cell you move to instead of jumping there", - "選択範囲の枠を、移動先のセルまで滑らかに動かします(瞬時には切り替えません)", - ), - ("System", "システム"), - ("Light", "ライト"), - ("Dark", "ダーク"), - ("Interface language", "表示言語"), - ("Interface size", "表示サイズ"), - ("Auto", "自動"), - ("Drag to freeze columns", "ドラッグして列を固定"), - ("Drag to freeze rows", "ドラッグして行を固定"), - ("Command\nPalette", "コマンド パレット"), - ("Agent\nControl", "エージェント制御"), - ("Action\nJournal", "操作ジャーナル"), - ("About\nGridCraft", "GridCraft について"), - ("Share", "共有"), - ("Add Chart\nElement", "グラフ要素を追加"), - ("Change\nChart Type", "グラフの種類の変更"), - ("Switch\nRow/Column", "行/列の切り替え"), - ("Select\nData", "データの選択"), - ("Data Labels: None", "データ ラベル: なし"), - ("Data Labels: Show", "データ ラベル: 表示"), - ("Legend: None", "凡例: なし"), - ("Legend: Bottom", "凡例: 下"), - ("Legend: Top", "凡例: 上"), - ("Legend: Right", "凡例: 右"), - ("Gridlines: None", "目盛線: なし"), - ("Gridlines: Show", "目盛線: 表示"), - ("Chart\nTitle", "グラフ タイトル"), - ("Delete\nChart", "グラフの削除"), - ("Convert\nto Range", "範囲に変換"), - ("Table\nStyles", "テーブル スタイル"), - ("Top 10 Items", "上位 10 項目"), - ("Top 10%", "上位 10%"), - ("Bottom 10 Items", "下位 10 項目"), - ("Bottom 10%", "下位 10%"), - ("Above Average", "平均より上"), - ("Below Average", "平均より下"), - ("Clear Rules from Entire Sheet", "シート全体からルールをクリア"), - ("Clear Rules from Selected Cells", "選択したセルからルールをクリア"), - ("Constants", "定数"), - ("Data Bars", "データ バー"), - ("Color Scales", "カラー スケール"), - ("Icon Sets", "アイコン セット"), - ("Home", "ホーム"), - ("Draw", "描画"), - ("Page Layout", "ページ レイアウト"), - ("Formulas", "数式"), - ("Data", "データ"), - ("Review", "レビュー"), - ("View", "表示"), - ("Automate", "自動化"), - ("Table Design", "テーブル デザイン"), - ("Chart Design", "グラフ デザイン"), - ("Ready", "準備完了"), - ("Enter", "入力"), - ("Edit", "編集"), - ("Point", "ポイント"), - ("Calculate", "計算"), - ("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"), - ("General", "標準"), - ("Number", "数値"), - ("Currency", "通貨"), - ("Accounting", "会計"), - ("Date", "日付"), - ("Time", "時刻"), - ("Percentage", "パーセンテージ"), - ("Fraction", "分数"), - ("Scientific", "指数"), - ("Text", "文字列"), - ("Special", "特殊"), - ("Custom", "ユーザー設定"), - ("Short Date", "日付"), - ("Long Date", "長い日付"), - ("More Number Formats…", "その他の表示形式…"), - ("Financial", "財務"), - ("Logical", "論理"), - ("Date &\nTime", "日付/時刻"), - ("Lookup &\nReference", "検索/行列"), - ("Math &\nTrig", "数学/三角"), - ("More\nFunctions", "その他の関数"), - ("Sheet Options|View", "画面"), - ("Print", "印刷"), - // Page Layout view and the Header & Footer tab. - ("Click to add data", "クリックしてデータを追加"), - ("Add header", "ヘッダーの追加"), - ("Add footer", "フッターの追加"), - ("(none)", "(なし)"), - ("Header", "ヘッダー"), - ("Footer", "フッター"), - ("Page\nNumber", "ページ\n番号"), - ("Number\nof Pages", "ページ数"), - ("Current\nDate", "現在の\n日付"), - ("Current\nTime", "現在の\n時刻"), - ("File\nPath", "ファイルの\nパス"), - ("File\nName", "ファイル名"), - ("Sheet\nName", "シート名"), - ("Go to\nHeader", "ヘッダーに\n移動"), - ("Go to\nFooter", "フッターに\n移動"), - ("Page Number", "ページ番号"), - ("Number of Pages", "ページ数"), - ("Current Date", "現在の日付"), - ("Current Time", "現在の時刻"), - ("File Path", "ファイルのパス"), - ("File Name", "ファイル名"), - ("Sheet Name", "シート名"), - ("Go to Header", "ヘッダーに移動"), - ("Different First Page", "先頭ページのみ別指定"), - ("Different Odd & Even Pages", "奇数/偶数ページ別指定"), - ("Go to Footer", "フッターに移動"), - ("Ruler", "ルーラー"), - // File › Backstage view. - ("File", "ファイル"), - ("Back", "戻る"), - ("New", "新規"), - ("Open", "開く"), - ("Info", "情報"), - ("Save", "上書き保存"), - ("Save As", "名前を付けて保存"), - ("Export", "エクスポート"), - ("Close", "閉じる"), - ("Options", "オプション"), - ("Blank workbook", "空白のブック"), - ("Recent", "最近使ったアイテム"), - ("No recent workbooks yet.", "最近使ったブックはまだありません。"), - ("More workbooks", "その他のブック"), - ("Modified", "更新日時"), - ("Not available", "利用できません"), - ("Just now", "たった今"), - ("Yesterday", "昨日"), - ("{n} min ago", "{n} 分前"), - ("{n} h ago", "{n} 時間前"), - ("{n} days ago", "{n} 日前"), - ("{n} weeks ago", "{n} 週間前"), - ("{n} months ago", "{n} か月前"), - ("{n} years ago", "{n} 年前"), - ("Browse…", "参照…"), - ("Not saved yet", "まだ保存されていません"), - ("Location", "場所"), - ("Sheets", "シート"), - ("Protect Workbook", "ブックの保護"), - ( - "Sheet structure is locked: sheets can't be added, moved, renamed or deleted.", - "シートの構成はロックされています。シートの追加、移動、名前の変更、削除はできません。", - ), - ( - "Lock the sheet structure so sheets can't be added, moved, renamed or deleted.", - "シートの構成をロックして、シートの追加、移動、名前の変更、削除をできないようにします。", - ), - ("Properties", "プロパティ"), - ("Title", "タイトル"), - ("Subject", "件名"), - ("Author", "作成者"), - ("Company", "会社名"), - ("Keywords", "キーワード"), - ("Description", "説明"), - ("No workbook is open.", "ブックが開かれていません。"), - ("Save as type", "ファイルの種類"), - ("Excel Workbook (*.xlsx)", "Excel ブック (*.xlsx)"), - ("CSV UTF-8 (Comma delimited) (*.csv)", "CSV UTF-8 (コンマ区切り) (*.csv)"), - ("Web Page (*.html)", "Web ページ (*.html)"), - ("PDF (*.pdf)", "PDF ファイル (*.pdf)"), - ("Download", "ダウンロード"), - ( - "A CSV file, web page or PDF is a copy: the workbook keeps its own file.", - "CSV ファイル、Web ページ、PDF はコピーです。ブックは元のファイルのままです。", - ), - ("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"), - ("Print Active Sheets", "作業中のシートを印刷"), - ("Print Entire Workbook", "ブック全体を印刷"), - ("Fit Sheet on One Page", "シートを 1 ページに印刷"), - ("Page Setup…", "ページ設定…"), - ("Page {page} of {pages}", "{page} / {pages} ページ"), - ("Nothing to print.", "印刷する内容がありません。"), - ("Previous page", "前のページ"), - ("Next page", "次のページ"), - ("Create PDF", "PDF の作成"), - ("Save the sheet as a PDF document that keeps its page layout.", "ページ レイアウトを保ったまま、シートを PDF ドキュメントとして保存します。"), - ("Change File Type", "ファイルの種類の変更"), - ("CSV (Comma delimited)", "CSV (コンマ区切り)"), - ("Save the active sheet as comma-separated text.", "作業中のシートをコンマ区切りのテキストとして保存します。"), - ("Web Page (.html)", "Web ページ (.html)"), - ("Save the workbook as a web page.", "ブックを Web ページとして保存します。"), - ("Options|General", "全般"), - ("Options|Save", "保存"), - ("Show formula bar", "数式バーを表示する"), - ("Enable AutoComplete for cell values", "セルの値にオートコンプリートを使用する"), - ("Save .xlsx workbooks automatically after every change", "変更のたびに .xlsx ブックを自動的に保存する"), - ("Workbook calculation", "ブックの計算"), - ("Enable iterative calculation", "反復計算を行う"), - ("Maximum Iterations:", "最大反復回数:"), - ("Maximum Change:", "変化の最大値:"), - ("Maximum Iterations must be a whole number from 1 to 32767.", "最大反復回数には 1 から 32767 までの整数を指定してください。"), - ("Maximum Change must be a number of 0 or more.", "変化の最大値には 0 以上の数値を指定してください。"), - ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), -]; - /// `name` lowercased with the Latin accents that occur in language names folded away, so a /// byte-wise sort reads alphabetically. Other scripts are left as they are. fn name_sort_key(name: &str) -> String { diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2df4cfc11..1a9ea50d4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -411,6 +411,10 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Save .xlsx workbooks automatically after every change", "変更のたびに .xlsx ブックを自動的に保存する"), ("Workbook calculation", "ブックの計算"), ("Enable iterative calculation", "反復計算を行う"), + ("Maximum Iterations:", "最大反復回数:"), + ("Maximum Change:", "変化の最大値:"), + ("Maximum Iterations must be a whole number from 1 to 32767.", "最大反復回数には 1 から 32767 までの整数を指定してください。"), + ("Maximum Change must be a number of 0 or more.", "変化の最大値には 0 以上の数値を指定してください。"), ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), ]; From 3557b9f6cd12b8cfc06d8261e86b94a05edd9ca9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 23 Oct 2026 22:15:48 -0700 Subject: [PATCH 09/71] Formulas: F3 opens Paste Name, which inserts a defined name or pastes the list of names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit formulas.pasteName lists the names the active sheet can use (workbook names and the sheet's own, without hidden names, in alphabetical order). With name it puts the name at the caret of the formula being edited, replacing selected text, or starts =Name; with list: true it writes each name and the text of what it refers to in two columns from the active cell. The Paste Name dialog opens from F3 when the workbook has names, from Use in Formula's new Paste Names… item and from Alt+M, S, P. While a dialog is open over the edit, the editor takes no keys. Use in Formula lists the same names, and formulas.useInFormula inserts at the caret instead of replacing the text being edited. --- crates/engine/src/cmd/extra.rs | 2 +- crates/engine/src/cmd/formulas.rs | 147 +++++++++++++++- crates/engine/src/lib.rs | 3 + crates/ui-egui/src/dialogs.rs | 79 +++++++++ crates/ui-egui/src/editor.rs | 44 +++++ crates/ui-egui/src/formula_bar.rs | 34 +++- crates/ui-egui/src/keymap.rs | 1 + .../src/keytips/keytip_table/generated.rs | 2 +- crates/ui-egui/src/keytips/keytips.json | 7 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/ribbon.rs | 22 ++- crates/ui-egui/tests/it/keytips_generated.rs | 5 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/paste_names.rs | 161 ++++++++++++++++++ docs/ui-parity.md | 8 +- 15 files changed, 492 insertions(+), 25 deletions(-) create mode 100644 crates/ui-egui/tests/it/paste_names.rs diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 009d77f2a..8ec8c795b 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -1265,7 +1265,7 @@ fn recently_used(s: &mut Session, _: &Json) -> Result { fn use_in_formula(s: &mut Session, p: &Json) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("formulas.useInFormula", "missing `name`"))?; - s.ui_requests.push(crate::UiRequest::EditCell(Some(format!("={name}")))); + s.ui_requests.push(crate::UiRequest::InsertName(name.to_string())); ok() } diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index 7718279b2..8a09d42f0 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -1,7 +1,7 @@ //! Formulas tab: AutoSum, Insert Function, names, auditing, calculation. use gridcraft_core::{CellError, CellRef, RangeRef, Value}; -use gridcraft_model::{CalcMode, DefinedName, Formula, Workbook}; +use gridcraft_model::{CalcMode, Cell, DefinedName, Formula, Workbook}; use serde_json::{Value as Json, json}; use super::*; @@ -55,6 +55,15 @@ pub fn specs() -> Vec { has_doc, create_from_selection ), + cmd!( + "formulas.pasteName", + "Paste Names…", + ["Formulas", "Defined Names"], + Some("F3"), + "{name?: \"Sales\" (OK: puts the name at the caret of the cell being edited, or starts `=Sales` in the active cell), list?: true (Paste List: writes each name and what it refers to in two columns, from `at`), at?: cell (default the active cell)} → {names: [{name, refersTo}]}: the names the Paste Name dialog lists (workbook names and the active sheet's own, hidden names left out, in alphabetical order). With neither nothing changes; the menu opens the dialog.", + has_doc, + paste_name + ), cmd!(query "formulas.tracePrecedents", "Trace Precedents", ["Formulas", "Formula Auditing"], None, "{cell?} → ranges", has_doc, trace_precedents), cmd!(query "formulas.traceDependents", "Trace Dependents", ["Formulas", "Formula Auditing"], None, "{cell?} → cells", has_doc, trace_dependents), cmd!(noundo "formulas.selectPrecedents", "Select Precedents", ["Formulas", "Formula Auditing"], Some("Ctrl+["), "{cell?, all?: true = every level (Ctrl+Shift+[)} → selects the precedent cells", has_doc, select_precedents), @@ -510,6 +519,58 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result { }) } +/// The names Paste Names lists, as (name, refers-to text with `=`): the workbook's names and the +/// active sheet's own, without hidden names, in alphabetical order. A sheet's name hides the +/// workbook name it shares. +pub fn pasteable_names(wb: &Workbook) -> Vec<(String, String)> { + let sheet = wb.active_sheet; + let shown = |local: bool| wb.names.iter().filter(move |n| !n.hidden && n.scope.is_some() == local && n.scope.is_none_or(|i| i == sheet)); + let local: Vec<&str> = shown(true).map(|n| n.name.as_str()).collect(); + let mut out: Vec<(String, String)> = shown(true).map(|n| (n.name.clone(), format!("={}", n.formula))).collect(); + for n in shown(false) { + if !local.iter().any(|x| gridcraft_formula::same_name(x, &n.name)) { + out.push((n.name.clone(), format!("={}", n.formula))); + } + } + out.sort_by_cached_key(|(n, _)| n.to_lowercase()); + out +} + +fn paste_name(s: &mut Session, p: &Json) -> Result { + let d = s.doc()?; + let names = pasteable_names(&d.wb); + let listed: Vec = names.iter().map(|(n, r)| json!({"name": n, "refersTo": r})).collect(); + if !bool_param(p, "list").unwrap_or(false) { + if let Some(name) = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) { + s.ui_requests.push(crate::UiRequest::InsertName(name.to_string())); + } + return Ok(json!({"names": listed})); + } + if names.is_empty() { + return Err(EngineError::Other("This workbook has no names to paste.".into())); + } + let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active); + let rows = u32::try_from(names.len()).unwrap_or(u32::MAX); + if at.row.saturating_add(rows) > gridcraft_core::MAX_ROWS || at.col.saturating_add(2) > gridcraft_core::MAX_COLS { + return Err(EngineError::Other("There isn't room on the sheet for the list of names.".into())); + } + let sheet = d.wb.active_sheet; + let range = RangeRef::new(at, CellRef::new(at.row + rows - 1, at.col + 1)); + edit(s, |cx| { + for (row, (name, refers)) in (at.row..).zip(&names) { + for (col, text) in [(at.col, name), (at.col + 1, refers)] { + let c = CellRef::new(row, col); + let sh = cx.sheet_mut(sheet)?; + let style = sh.style_id(c); + // The second column holds the refers-to text as a text value, with no formula. + sh.set_cell(c, Cell { value: Value::text(text.as_str()), formula: None, style }); + cx.touch(sheet, c); + } + } + Ok(json!({"names": listed, "range": range.a1()})) + }) +} + fn trace_precedents(s: &mut Session, p: &Json) -> Result { let d = s.doc()?; let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active); @@ -877,4 +938,88 @@ mod tests { // The union parses as one, so the preview is what the union gives in a cell, not #NAME?. assert_eq!(u["value"], json!({"error": "#VALUE!"})); } + + /// A workbook with `Sales` and `rate`, a hidden name, a name of Sheet1 that hides a workbook + /// `Tax`, and a name of another sheet. + fn named_workbook() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("formulas.defineName", json!({"name": "Sales", "refersTo": "=Sheet1!$A$1:$A$3"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "rate", "refersTo": "=0.07"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Tax", "refersTo": "=0.2"})).unwrap(); + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let name = |name: &str, scope, formula: &str, hidden| DefinedName { + name: name.into(), + scope, + formula: formula.into(), + comment: String::new(), + hidden, + }; + wb.names.push(name("_Filter", None, "Sheet1!$A$1:$B$9", true)); + wb.names.push(name("TAX", Some(0), "0.25", false)); + wb.names.push(name("Other", Some(1), "1", false)); + s + } + + fn text_at(s: &Session, cell: &str) -> Value { + s.doc().unwrap().wb.active().unwrap().value(CellRef::parse(cell).unwrap()) + } + + #[test] + fn paste_names_lists_the_names_the_active_sheet_can_use() { + let mut s = named_workbook(); + let r = s.execute("formulas.pasteName", json!({})).unwrap(); + assert_eq!( + r["names"], + json!([ + {"name": "rate", "refersTo": "=0.07"}, + {"name": "Sales", "refersTo": "=Sheet1!$A$1:$A$3"}, + {"name": "TAX", "refersTo": "=0.25"}, + ]) + ); + assert_eq!(text_at(&s, "A1"), Value::Empty, "listing the names writes nothing"); + } + + #[test] + fn paste_names_and_use_in_formula_ask_the_ui_to_insert_the_name() { + let mut s = named_workbook(); + s.take_ui_requests(); + s.execute("formulas.pasteName", json!({"name": "Sales"})).unwrap(); + s.execute("formulas.useInFormula", json!({"name": "rate"})).unwrap(); + assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::InsertName("Sales".into()), crate::UiRequest::InsertName("rate".into())]); + assert_eq!(text_at(&s, "A1"), Value::Empty, "the cell changes only when the edit is entered"); + } + + #[test] + fn paste_list_writes_each_name_and_what_it_refers_to() { + let mut s = named_workbook(); + s.execute("selection.set", json!({"range": "D2"})).unwrap(); + let r = s.execute("formulas.pasteName", json!({"list": true})).unwrap(); + assert_eq!(r["range"], json!("D2:E4")); + let rows = [("D2", "rate"), ("E2", "=0.07"), ("D3", "Sales"), ("E3", "=Sheet1!$A$1:$A$3"), ("D4", "TAX"), ("E4", "=0.25")]; + for (cell, text) in rows { + assert_eq!(text_at(&s, cell), Value::text(text), "{cell}"); + } + assert!(s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("E3").unwrap()).is_some_and(|c| c.formula.is_none()), "refers-to is text"); + s.execute("edit.undo", json!({})).unwrap(); + for (cell, _) in rows { + assert_eq!(text_at(&s, cell), Value::Empty, "{cell} after Undo"); + } + s.execute("formulas.pasteName", json!({"list": true, "at": "B7"})).unwrap(); + assert_eq!(text_at(&s, "B7"), Value::text("rate")); + } + + #[test] + fn paste_list_needs_names_and_room() { + let mut s = named_workbook(); + let last = format!("A{}", gridcraft_core::MAX_ROWS - 1); + assert!(s.execute("formulas.pasteName", json!({"list": true, "at": last})).is_err(), "three rows don't fit below the second-to-last row"); + let last_col = format!("{}1", gridcraft_core::col_to_letters(gridcraft_core::MAX_COLS - 1)); + assert!(s.execute("formulas.pasteName", json!({"list": true, "at": last_col})).is_err(), "two columns don't fit in the last column"); + let mut empty = Session::new(); + empty.new_workbook(); + assert!(empty.execute("formulas.pasteName", json!({"list": true})).is_err()); + assert_eq!(empty.execute("formulas.pasteName", json!({})).unwrap()["names"], json!([])); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a..a3929a02c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -372,6 +372,9 @@ pub enum UiRequest { Message(String), /// Start editing the active cell (F2) with optional initial text. EditCell(Option), + /// Put a defined name at the caret of the cell being edited, in place of selected text; with + /// no edit under way, start editing the active cell with `=` and the name. + InsertName(String), OpenUrl(String), } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e83db2fa1..3aa97aff9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -824,6 +824,17 @@ impl Dialog { Dialog::custom("sort", "Sort", json!({"header": true, "levels": [{"column": col, "order": "asc"}]})) } "nameManager" => Dialog::custom("nameManager", "Name Manager", json!({})), + "pasteName" => { + // F3 opens it only when the workbook has names to paste, as in Excel. + let names = pasteable_names(app); + if p("shortcut") == json!(true) && names.is_empty() { + return None; + } + // OK runs `formulas.pasteName` with the selected `name`, so `ui.dialog.confirm` does too. + let mut dialog = Dialog::custom("pasteName", "Paste Name", json!({"name": names.first()})); + dialog.command = Some("formulas.pasteName"); + dialog + } "manageRules" => Dialog::custom("manageRules", "Conditional Formatting Rules Manager", json!({})), "commandSearch" => Dialog::custom("commandSearch", "Search Commands", json!({})), "agents" => Dialog::custom("agents", "Agent Control", json!({})), @@ -1264,6 +1275,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { "zoom" => zoom(ui, &mut d, &mut confirm, &mut open), "sort" => sort(app, ui, &mut d, &mut confirm), "nameManager" => name_manager(app, ui, &mut d, &mut open), + "pasteName" => paste_name(app, ui, &mut d, &mut confirm, &mut open), "manageRules" => manage_rules(app, ui), "recommendedCharts" => recommended_charts(app, ui, &mut d, &mut confirm, &mut open), "selectData" => select_data(app, ui, &mut d, &mut confirm, &mut open), @@ -2496,6 +2508,73 @@ fn name_manager(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, open: &mu }); } +/// The names Paste Names offers in the active workbook. +fn pasteable_names(app: &SheetApp) -> Vec { + app.session + .active() + .map(|doc| gridcraft_engine::cmd::formulas::pasteable_names(&doc.wb).into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default() +} + +/// Puts a defined name into the formula being edited, at the caret. Without an edit under way it +/// starts one in the active cell with `=` and the name. +pub(crate) fn insert_name(app: &mut SheetApp, name: &str) { + match app.editor.as_mut() { + Some(ed) => ed.insert_at_caret(name), + None => app.begin_edit(Some(format!("={name}")), false), + } +} + +/// Paste Name (F3, Formulas › Use in Formula › Paste Names…): OK, or a double-click, inserts the +/// selected name (`formulas.pasteName` with `name`); Paste List writes every name and what it +/// refers to from the active cell. +fn paste_name(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) { + let names = pasteable_names(app); + // The `name` value is the selection, so `ui.dialog.set` can choose one too. + if let Some(i) = d.values.get("name").and_then(Json::as_str).and_then(|n| names.iter().position(|x| x == n)) { + d.list_index = i; + } + let (down, up) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, Key::ArrowUp))); + let last = names.len().saturating_sub(1); + if down { + d.list_index = (d.list_index + 1).min(last); + } + if up { + d.list_index = d.list_index.saturating_sub(1); + } + d.list_index = d.list_index.min(last); + ui.label(app.ui.language.tr("Paste name")); + egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + if names.is_empty() { + ui.label(egui::RichText::new(app.ui.language.tr("No names defined")).italics()); + } + for (i, n) in names.iter().enumerate() { + let r = ui.selectable_label(i == d.list_index, n); + if (down || up) && i == d.list_index && !ui.clip_rect().contains_rect(r.rect) { + r.scroll_to_me(Some(if down { egui::Align::Max } else { egui::Align::Min })); + } + if r.clicked() { + d.list_index = i; + } + if r.double_clicked() { + *confirm = true; + } + } + }); + ui.add_space(4.0); + // Paste List is disabled while a cell is being edited. + if ui.add_enabled(!names.is_empty() && app.editor.is_none(), egui::Button::new(app.ui.language.tr("Paste List"))).clicked() { + app.run_or_alert("formulas.pasteName", json!({"list": true})); + *open = false; + return; + } + if let Some(n) = names.get(d.list_index) { + d.values.insert("name".into(), json!(n)); + } + ok_cancel(ui, confirm, open); +} + /// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`. const ALL_CHARTS: [(&str, &str, &str); 20] = [ ("column", "", "Clustered Column"), diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 8984ad53c..3259ac4c4 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -28,6 +28,9 @@ pub struct EditState { pub from_formula_bar: bool, /// Caret position (char index), mirrored from the text widget. pub caret: usize, + /// The other end of the selected text (char index), mirrored like `caret`; equal to `caret` + /// when nothing is selected. + pub anchor: usize, /// The reference most recently inserted by point mode (byte range) — arrows/clicks replace it. pub point: Option<(usize, usize)>, /// Where point mode's keyboard cursor is. @@ -39,6 +42,9 @@ pub struct EditState { pub request_focus: bool, /// The text changed programmatically: push `caret` into the widget on the next frame. pub sync_caret: bool, + /// A dialog opened over the edit has the keyboard: when the editor takes it back without a + /// change to the caret, the selected text (`anchor`..`caret`) stays selected. + pub keep_selection: bool, /// Column AutoComplete: the full entry the typed text completes to. pub completion: Option, /// Move the caret to the end on the next frame. @@ -56,6 +62,7 @@ impl EditState { enter_mode, from_formula_bar, caret, + anchor: caret, point: None, point_cell: None, point_anchor: None, @@ -63,6 +70,7 @@ impl EditState { ac_index: 0, request_focus: true, sync_caret: true, + keep_selection: false, caret_to_end: true, completion: None, } @@ -112,6 +120,27 @@ impl EditState { self.sync_caret = true; } + /// Inserts `t` at the caret as typed text (Paste Names), in place of the selected text: the + /// caret ends after it, and point mode starts afresh. + pub fn insert_at_caret(&mut self, t: &str) { + // When code moved the caret this frame (`sync_caret`), the widget has not yet stored it, so `anchor` is out of + // date and the name goes in at the caret. + let (from, to) = if self.sync_caret { (self.caret, self.caret) } else { (self.anchor.min(self.caret), self.anchor.max(self.caret)) }; + let byte = |c: usize| self.text.char_indices().nth(c).map(|(i, _)| i).unwrap_or(self.text.len()); + let (Some(a), Some(b)) = (self.text.get(..byte(from)), self.text.get(byte(to)..)) else { return }; + self.text = format!("{a}{t}{b}"); + self.point = None; + self.caret = from + t.chars().count(); + self.anchor = self.caret; + // A function suggestion shown before the name went in no longer fits the text. + self.autocomplete.clear(); + self.ac_index = 0; + self.completion = None; + self.caret_to_end = false; + self.sync_caret = true; + self.request_focus = true; + } + /// Add another argument after the current pointed reference. Keep only the new reference /// replaceable, so a subsequent plain click does not remove earlier arguments or the separator. pub fn append_ref(&mut self, r: &str) { @@ -379,6 +408,21 @@ mod tests { assert!(!e2.can_point()); } + #[test] + fn a_pasted_name_replaces_the_selected_text() { + let mut e = EditState::new(0, CellRef::new(0, 0), "=OldName+1".into(), false, false); + e.sync_caret = false; + (e.anchor, e.caret) = (8, 1); + e.autocomplete = vec!["SUM".into()]; + e.insert_at_caret("Sales"); + assert_eq!((e.text.as_str(), e.caret, e.anchor), ("=Sales+1", 6, 6)); + assert!(e.autocomplete.is_empty(), "the earlier function suggestion is gone"); + // Nothing selected: the name goes in at the caret. + e.sync_caret = false; + e.insert_at_caret("Rate"); + assert_eq!((e.text.as_str(), e.caret), ("=SalesRate+1", 10)); + } + #[test] fn autocomplete_and_hints() { let names: Vec = ["SUM", "SUMIF", "SUMPRODUCT", "AVERAGE"].iter().map(|s| s.to_string()).collect(); diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index b88699f57..5ec8c4a87 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -184,7 +184,8 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: let mut cancel = false; // A message box over the editor (a data validation alert, a formula error) gets Enter and Esc; // the editor used to take them, so the first Esc cancelled the edit behind the message. - if has_focus && mine && app.message.is_none() { + // So does a dialog opened from the editor (Paste Name): its OK takes Enter. + if has_focus && mine && app.message.is_none() && app.dialog.is_none() { let (enter, tab, esc, alt_enter, cmd_enter, ctrl_shift_enter, shift) = ui.input_mut(|i| { let m = i.modifiers; let alt_enter = @@ -274,6 +275,10 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::F4)) { cycle_anchor(&mut ed); } + // F3 opens Paste Name when the workbook has names; OK puts the name at the caret. + if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::F3)) { + app.open_dialog("pasteName", json!({"shortcut": true})); + } // Ctrl+Shift+A (Control+Shift+A on a Mac) inserts the argument names. Consumed anywhere, // as in Excel, so it never falls through to the text's select-all. if ui.input_mut(|i| i.consume_key(egui::Modifiers::CTRL | egui::Modifiers::SHIFT, Key::A)) { @@ -315,6 +320,13 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: ui.fonts_mut(|f| f.layout_job(job)) }; let chars_before = ed.text.chars().count(); + // A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the + // editor takes it back afterwards. + let dialog_open = app.dialog.is_some(); + if dialog_open && mine { + ed.request_focus = true; + ed.keep_selection = true; + } // The in-cell editor is as tall as its lines (a multiline field reserves four rows). let in_cell = id == egui::Id::new("gridcraft.cell_editor"); let edit = if multiline || ed.text.contains('\n') { @@ -329,18 +341,26 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: .desired_width(width) .layouter(&mut layouter) .lock_focus(true) + .interactive(!dialog_open) .event_filter(egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }) .show(ui); let resp = output.response.clone(); - let synced = mine && (ed.request_focus || ed.sync_caret); + let synced = mine && !dialog_open && (ed.request_focus || ed.sync_caret); if synced { if ed.request_focus { resp.request_focus(); } ed.request_focus = false; + // Closing a dialog that changed nothing (Cancel) gives the selection back as it was. + let range = if ed.keep_selection && !ed.sync_caret { + egui::text::CCursorRange::two(egui::text::CCursor::new(ed.anchor), egui::text::CCursor::new(ed.caret)) + } else { + ed.anchor = ed.caret; + egui::text::CCursorRange::one(egui::text::CCursor::new(ed.caret)) + }; ed.sync_caret = false; - let cursor = egui::text::CCursor::new(ed.caret); - output.state.cursor.set_char_range(Some(egui::text::CCursorRange::one(cursor))); + ed.keep_selection = false; + output.state.cursor.set_char_range(Some(range)); output.state.store(ui.ctx(), id); } else if resp.clicked() || resp.gained_focus() { // Clicking into the other editor moves editing there. @@ -348,8 +368,12 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: ed.enter_mode = false; app.session.mode = gridcraft_engine::Mode::Edit; } - if !synced && let Some(r) = output.cursor_range { + if !synced + && !dialog_open + && let Some(r) = output.cursor_range + { ed.caret = r.primary.index.into(); + ed.anchor = r.secondary.index.into(); } if resp.changed() { ed.completion = None; diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 5840036a1..424ab0355 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -157,6 +157,7 @@ pub fn lookup(key: Key, physical: Option, m: Modifiers, mac: bool) -> Optio F3 if cmd && mac => Shortcut::Dialog("defineName", json!({})), F3 if cmd => Shortcut::Dialog("nameManager", json!({})), F3 if plain && s => Shortcut::Dialog("insertFunction", json!({})), + F3 if plain => Shortcut::Dialog("pasteName", json!({"shortcut": true})), F4 if cmd && !s => run("file.close"), F5 if plain && s => Shortcut::Dialog("find", json!({})), F5 if plain => Shortcut::Dialog("goTo", json!({})), diff --git a/crates/ui-egui/src/keytips/keytip_table/generated.rs b/crates/ui-egui/src/keytips/keytip_table/generated.rs index d94128de7..c35a3bbad 100644 --- a/crates/ui-egui/src/keytips/keytip_table/generated.rs +++ b/crates/ui-egui/src/keytips/keytip_table/generated.rs @@ -243,7 +243,7 @@ pub const SEQUENCES: &[(&str, Entry)] = &[ ("MP", Entry::Finish(Action::Command("formulas.tracePrecedents"))), // Excel: Trace Precedents ("MQ", Entry::Finish(Action::Control("formulas.moreFunctions"))), // Excel: More Functions Menu; group level: containment(More Functions) ("MS", Entry::Continue), // Excel: Use in Formula Menu; group level: containment(Use in Formula) - ("MSP", Entry::Finish(Action::Pending("formulas.pasteName"))), // pending; Excel: Paste Names; reserved until the command lands + ("MSP", Entry::Finish(Action::Dialog("pasteName"))), // Excel: Paste Names ("MT", Entry::Finish(Action::Control("formulas.text"))), // Excel: Text Menu; group level: containment(Text) ("MU", Entry::Continue), // Excel: AutoSum Menu; group level: ("MUA", Entry::Finish(Action::Command("formulas.autoSum"))), // Excel: Average; AutoSum: Average (variant TBD) diff --git a/crates/ui-egui/src/keytips/keytips.json b/crates/ui-egui/src/keytips/keytips.json index 96bdc075a..5be64f867 100644 --- a/crates/ui-egui/src/keytips/keytips.json +++ b/crates/ui-egui/src/keytips/keytips.json @@ -1666,11 +1666,10 @@ }, { "seq": "MSP", - "kind": "command", - "target": "formulas.pasteName", + "kind": "dialog", + "target": "pasteName", "excel": "Paste Names", - "note": "reserved until the command lands", - "pending": true + "note": "" }, { "seq": "MT", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 14c442331..9c5b560b4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -748,6 +748,7 @@ impl SheetApp { }); self.begin_edit(text, false); } + UiRequest::InsertName(name) => dialogs::insert_name(self, &name), UiRequest::OpenUrl(u) => { if let Some(f) = &self.services.open_url { f(&u); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index ab9cc311d..f6b098cf6 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1971,15 +1971,25 @@ fn formulas(app: &mut SheetApp, ui: &mut Ui) { app.open_dialog("defineName", json!({})); } let use_in = small_button(ui, Icon::Function, "Use in Formula", "Use in Formula", true); - anchor_keytip(app, ui, &use_in, &["formulas.pasteName"]); + anchor_keytip(app, ui, &use_in, &["dialog:pasteName"]); egui::Popup::menu(&use_in).show(|ui| { - let names: Vec = app.session.active().map(|d| d.wb.names.iter().map(|n| n.name.clone()).collect()).unwrap_or_default(); - for n in names { - if ui.button(&n).clicked() { - let cur = app.editor.as_ref().map(|e| e.text.clone()).unwrap_or_else(|| "=".into()); - app.begin_edit(Some(format!("{cur}{n}")), false); + // The menu lists the names Paste Names lists; clicking one runs `formulas.useInFormula`, which puts it at the caret. + let names: Vec = app + .session + .active() + .map(|d| gridcraft_engine::cmd::formulas::pasteable_names(&d.wb).into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default(); + for n in &names { + if ui.button(n).clicked() { + app.run_or_alert("formulas.useInFormula", json!({"name": n})); } } + if !names.is_empty() { + ui.separator(); + } + if ui.button(app.ui.language.tr("Paste Names…")).clicked() { + app.open_dialog("pasteName", json!({})); + } }); let __k = small_button(ui, Icon::Table, "Create from Selection", "Create from Selection", false); control_keytip(app, ui, &__k, "formulas.createFromSelection"); diff --git a/crates/ui-egui/tests/it/keytips_generated.rs b/crates/ui-egui/tests/it/keytips_generated.rs index d3cb84cf7..2dbcb8f29 100644 --- a/crates/ui-egui/tests/it/keytips_generated.rs +++ b/crates/ui-egui/tests/it/keytips_generated.rs @@ -1783,10 +1783,7 @@ fn keytip_ms_() { fn keytip_msp_() { let mut h = harness(blank()); sequence(&mut h, "MSP", false); - assert!(h.state().dialog.is_none(), "MSP must not open a dialog"); - assert!(h.state().message.is_none(), "MSP must not open a message box"); - assert!(h.state().toast.is_none(), "MSP must not raise a toast"); - assert!(h.state().session.journal.is_empty(), "MSP must not journal"); + assert!(h.state().dialog.is_some(), "MSP must open the pasteName dialog"); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a9769c1c..0b429cbf0 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -59,6 +59,7 @@ mod open_encrypted; mod outline; mod page_layout_view; mod page_setup_margins; +mod paste_names; mod paste_special_dialog; mod pivot_pane; mod pivot_show_details; diff --git a/crates/ui-egui/tests/it/paste_names.rs b/crates/ui-egui/tests/it/paste_names.rs new file mode 100644 index 000000000..79ef59936 --- /dev/null +++ b/crates/ui-egui/tests/it/paste_names.rs @@ -0,0 +1,161 @@ +//! F3 opens the Paste Name dialog when the workbook has names: OK puts the selected name into the +//! formula being edited, and Paste List writes every name and what it refers to, as in Excel. + +use egui::{Event, Key, vec2}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +use gridcraft_engine::core::{CellRef, Value}; +use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::control::{Outcome, handle}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +fn harness(names: bool) -> Harness { + let mut session = Session::new(); + session.new_workbook(); + if names { + session.execute("formulas.defineName", json!({"name": "Sales", "refersTo": "=Sheet1!$A$1:$A$3"})).unwrap(); + session.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=0.07"})).unwrap(); + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(6); + h +} + +fn dialog(h: &Harness) -> Option<&str> { + h.state().dialog.as_ref().map(|d| d.name()) +} + +fn editor_text(h: &Harness) -> Option { + h.state().editor.as_ref().map(|e| e.text.clone()) +} + +fn value(h: &Harness, cell: &str) -> Value { + h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse(cell).unwrap()) +} + +fn press(h: &mut Harness, key: Key) { + h.key_press(key); + h.run_steps(3); +} + +#[test] +fn f3_opens_paste_name_only_when_the_workbook_has_names() { + let mut h = harness(false); + press(&mut h, Key::F3); + assert_eq!(dialog(&h), None, "no names: F3 does nothing"); + let mut h = harness(true); + press(&mut h, Key::F3); + assert_eq!(dialog(&h), Some("pasteName")); + // The names are listed in alphabetical order. + let rate = h.get_by_label("Rate").rect().top(); + let sales = h.get_by_label("Sales").rect().top(); + assert!(rate < sales, "Rate is listed above Sales"); +} + +#[test] +fn ok_starts_a_formula_with_the_selected_name() { + let mut h = harness(true); + press(&mut h, Key::F3); + h.get_by_label("Sales").click(); + h.run_steps(2); + h.get_by_label(" OK ").click(); + h.run_steps(3); + assert_eq!(dialog(&h), None); + assert_eq!(editor_text(&h).as_deref(), Some("=Sales")); +} + +#[test] +fn the_control_channel_confirms_the_dialog_like_ok() { + let mut h = harness(true); + let ctx = h.ctx.clone(); + for (method, params) in + [("ui.dialog", json!({"name": "pasteName"})), ("ui.dialog.set", json!({"field": "name", "value": "Sales"})), ("ui.dialog.confirm", json!({}))] + { + match handle(h.state_mut(), &ctx, method, ¶ms) { + Outcome::Done(v) => assert_eq!(v["ok"], json!(true), "{method}: {v}"), + Outcome::Screenshot { .. } => panic!("{method} took a screenshot"), + } + } + h.run_steps(2); + assert_eq!(dialog(&h), None); + assert_eq!(editor_text(&h).as_deref(), Some("=Sales")); +} + +#[test] +fn arrow_keys_choose_the_name_and_leave_the_active_cell() { + let mut h = harness(true); + press(&mut h, Key::F3); + press(&mut h, Key::ArrowDown); + press(&mut h, Key::Enter); + assert_eq!(dialog(&h), None); + assert_eq!(editor_text(&h).as_deref(), Some("=Sales"), "Down moved from Rate to Sales"); + let active = h.state().session.active().unwrap().selection.active; + assert_eq!(active, CellRef::new(0, 0), "the arrow went to the dialog, not the grid"); +} + +#[test] +fn while_editing_the_name_goes_in_at_the_caret_and_the_edit_goes_on() { + let mut h = harness(true); + h.state_mut().begin_edit(Some("=SUM(".into()), false); + h.run_steps(4); + press(&mut h, Key::F3); + assert_eq!(dialog(&h), Some("pasteName"), "F3 in the cell editor opens the dialog"); + // While the dialog is open, typed text and arrow keys do not change the formula being edited. + h.input_mut().events.push(Event::Text("x".into())); + h.run_steps(2); + press(&mut h, Key::ArrowLeft); + assert_eq!(editor_text(&h).as_deref(), Some("=SUM("), "the formula is unchanged while the dialog is open"); + h.get_by_label("Sales").click(); + h.run_steps(2); + press(&mut h, Key::Enter); + assert_eq!(dialog(&h), None, "Enter is the dialog's OK"); + assert_eq!(editor_text(&h).as_deref(), Some("=SUM(Sales"), "the cell is still being edited"); + assert_eq!(value(&h, "A1"), Value::Empty, "nothing was entered yet"); +} + +#[test] +fn cancel_leaves_the_selected_text_selected() { + let mut h = harness(true); + h.state_mut().begin_edit(Some("=SUM(A1".into()), false); + // Edit mode (F2): the arrow keys move the caret instead of leaving the cell. + if let Some(ed) = h.state_mut().editor.as_mut() { + ed.enter_mode = false; + } + h.run_steps(4); + for _ in 0..2 { + h.key_press_modifiers(egui::Modifiers::SHIFT, Key::ArrowLeft); + h.run_steps(2); + } + press(&mut h, Key::F3); + assert_eq!(dialog(&h), Some("pasteName")); + h.get_by_label(" Cancel ").click(); + h.run_steps(3); + assert_eq!(dialog(&h), None); + h.input_mut().events.push(Event::Text("B2".into())); + h.run_steps(2); + assert_eq!(editor_text(&h).as_deref(), Some("=SUM(B2"), "typing replaces the text selected before the dialog opened"); +} + +#[test] +fn paste_list_writes_the_names_from_the_active_cell() { + let mut h = harness(true); + h.state_mut().run("selection.set", json!({"range": "C2"})).unwrap(); + h.run_steps(2); + press(&mut h, Key::F3); + h.get_by_label("Paste List").click(); + h.run_steps(3); + assert_eq!(dialog(&h), None); + assert_eq!(value(&h, "C2"), Value::text("Rate")); + assert_eq!(value(&h, "D2"), Value::text("=0.07")); + assert_eq!(value(&h, "C3"), Value::text("Sales")); + assert_eq!(value(&h, "D3"), Value::text("=Sheet1!$A$1:$A$3")); + assert_eq!(editor_text(&h), None); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efee..405a0c661 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-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (F3 Paste Name dialog with Paste List; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -84,7 +84,7 @@ this logic, with one undo step. | Shortcuts bound to commands | 200+ documented shortcuts per platform | audited below (#110): shortcuts whose feature exists are bound, with the exceptions listed; the rest wait for their features | | Ctrl+arrow, Ctrl+Shift+arrow, Ctrl+Home/End, Ctrl+Shift+Home/End, Page Up/Down, Alt+Page | yes | done | | Ctrl+1, Ctrl+; and Ctrl+Shift+; , Ctrl+D/R, Ctrl+E, Ctrl+T/L, Ctrl+K, Ctrl+Shift+L, Ctrl+Shift+~!@#$%^&_ | yes | done | -| F2, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F3 Paste Name, F4 Repeat missing | +| F2, F3, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F4 Repeat missing | | Mac-specific (Cmd variants, Control variants, Fn keys) | yes | done where a feature exists (`keymap.rs` picks the Mac variant) | | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | @@ -133,7 +133,8 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | Shift+F3, Ctrl+F3, Ctrl+Shift+F3 | Shift+F3, Cmd+F3 (Define Name), Cmd+Shift+F3 | Insert Function, Name Manager, Create from Selection | **added** | | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | -| F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | +| F3 | not checked | Paste Name dialog, only when the workbook has names: OK puts the name at the caret of the formula being edited (or starts `=Name`), Paste List writes each name and what it refers to from the active cell (`formulas.pasteName`) | **added** | +| F1, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | | Ctrl+Q, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | Quick Analysis, Function Arguments, formula bar height, tooltips | missing | | Ctrl+Shift+A after a function name | Control+Shift+A | argument names: `=SUMIF(` becomes `=SUMIF(range,criteria,sum_range)`, the `(` added when missing; one Undo takes them back | **added** | | Ctrl+6, Ctrl+Q, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, Quick Analysis, Function Arguments, formula bar height, tooltips | missing | @@ -178,6 +179,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 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-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From 983d3d7e6a5b4ccef631c1d8cb3d01c349769a04 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 01:01:32 -0700 Subject: [PATCH 10/71] Go To: lists the named ranges of every sheet and the references entered, and goes to several at once The Go To dialog lists the named ranges of the workbook and of every sheet, a name scoped to another sheet as Sheet2!Name, without hidden names, constants or formulas. After them it lists the references entered in the dialog, newest first, and a double-click on an entry goes there. edit.goTo takes several names or references separated by commas (Price, Type or B14:C22,F19:G30) and selects them all, follows a name that refers to several areas, and goes to Sheet2!Name on Sheet2. With record: true it keeps a reference that holds no name among the recent ones, and with list: true it returns the names and the recent references. --- ROADMAP.md | 1 + crates/engine/src/cmd/edit.rs | 270 ++++++++++++++++++++++-- crates/engine/src/lib.rs | 4 + crates/ui-egui/src/dialogs.rs | 28 ++- crates/ui-egui/tests/it/go_to_dialog.rs | 89 ++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/ui-parity.md | 6 +- 7 files changed, 377 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/tests/it/go_to_dialog.rs diff --git a/ROADMAP.md b/ROADMAP.md index da06359b5..2d999a0d9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 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) | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index edb0e2d7c..435cd7a3b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { cmd!(noundo "selection.currentRegion", "Select Current Region", [], Some("Ctrl+Shift+8"), "{}", has_doc, select_region), cmd!(noundo "selection.row", "Select Entire Row", [], Some("Shift+Space"), "{}", has_doc, select_row), cmd!(noundo "selection.column", "Select Entire Column", [], Some("Ctrl+Space"), "{}", has_doc, select_col), - cmd!(noundo "edit.goTo", "Go To…", ["Home", "Editing", "Find & Select"], Some("Ctrl+G"), "{reference: \"B5\" | \"Sheet2!A1:C3\" | name}", has_doc, go_to), + cmd!(noundo "edit.goTo", "Go To…", ["Home", "Editing", "Find & Select"], Some("Ctrl+G"), "{reference: \"B5\" | \"Sheet2!A1:C3\" | name | \"Sheet2!Name\" | \"B14:C22,F19:G30\" | \"Price, Type\", record?: bool} (record: keep a reference without names among the recent ones) or {list: true} → {names, recent}", has_doc, go_to), cmd!(noundo "edit.goToSpecial", "Go To Special…", ["Home", "Editing", "Find & Select"], None, "{kind: blanks|constants|formulas|comments|lastCell|currentRegion|visible|conditionalFormats|dataValidation|errors|numbers|text}", has_doc, go_to_special), cmd!(noundo "edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{steps?: 1}", can_undo, undo), cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Y"), "{steps?: 1}", can_redo, redo), @@ -577,26 +577,153 @@ fn select_col(s: &mut Session, _: &Json) -> Result { Ok(json!({"selection": d.selection.a1()})) } +/// How many references the Go To dialog keeps for going back to. +const GO_TO_RECENT: usize = 10; +/// The most areas one Go To selects. +const GO_TO_MAX_AREAS: usize = 2000; +/// How deep a name that refers to other names is followed. +const GO_TO_NAME_DEPTH: usize = 8; + pub(super) fn go_to(s: &mut Session, p: &Json) -> Result { + if bool_param(p, "list") == Some(true) { + let d = s.doc()?; + return Ok(json!({"names": go_to_names(&d.wb, d.wb.active_sheet), "recent": d.go_to_recent})); + } let Some(reference) = str_param(p, "reference").or_else(|| str_param(p, "range")) else { return Err(bad("edit.goTo", "missing `reference`")) }; - // A defined name or table? let d = s.doc()?; - let resolved = if RangeRef::parse(split_sheet(reference).1).is_none() { - let sheet = d.wb.active_sheet; - if let Some(n) = d.wb.name(reference, sheet) { - n.formula.clone() - } else if let Some((si, ti)) = d.wb.table(reference) { - // As in Excel, a table's name stands for its data, without the header and totals rows. - let t = d.wb.sheet(si).and_then(|sh| sh.tables.get(ti)).map(|t| t.data_range().unwrap_or(t.range).a1()).unwrap_or_default(); - format!("{}!{}", gridcraft_core::quote_sheet(&d.wb.sheet(si).map(|s| s.name.clone()).unwrap_or_default()), t) - } else { + let mut target: Option = None; + let mut areas: Vec = Vec::new(); + let mut named = false; + for part in reference_parts(reference) { + let Some((sheet, found, by_name)) = go_to_target(&d.wb, d.wb.active_sheet, part, 0) else { + return Err(EngineError::Other("Reference isn't valid.".into())); + }; + // One selection holds the areas of one sheet. + if target.is_some_and(|t| t != sheet) { return Err(EngineError::Other("Reference isn't valid.".into())); } - } else { - reference.to_string() + target = Some(sheet); + named |= by_name; + areas.extend(found); + if areas.len() > GO_TO_MAX_AREAS { + return Err(EngineError::Other(format!("Go To selects at most {GO_TO_MAX_AREAS} areas."))); + } + } + let Some(sheet) = target else { return Err(EngineError::Other("Reference isn't valid.".into())) }; + let range = areas.iter().map(RangeRef::a1).collect::>().join(","); + let out = selection_set(s, &json!({"sheet": sheet, "range": range}))?; + if bool_param(p, "record") == Some(true) && !named { + let d = s.doc_mut()?; + let prefix = gridcraft_core::quote_sheet(&d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default()); + let entry = areas.iter().map(|r| format!("{prefix}!{}", r.a1())).collect::>().join(","); + d.go_to_recent.retain(|r| !r.eq_ignore_ascii_case(&entry)); + d.go_to_recent.insert(0, entry); + d.go_to_recent.truncate(GO_TO_RECENT); + } + Ok(out) +} + +/// The parts of a Go To reference, split at the commas outside quoted sheet names and +/// parentheses: `Price, Type` or `B14:C22,F19:G30`. The parts are read one at a time, so a caller +/// that stops at an invalid part or at `GO_TO_MAX_AREAS` does not split the rest of the text. +fn reference_parts(text: &str) -> impl Iterator { + let (mut depth, mut quoted, mut start, mut done) = (0usize, false, 0, false); + let mut chars = text.char_indices(); + std::iter::from_fn(move || { + if done { + return None; + } + for (i, c) in chars.by_ref() { + match c { + '\'' => quoted = !quoted, + '(' if !quoted => depth += 1, + ')' if !quoted => depth = depth.saturating_sub(1), + ',' if !quoted && depth == 0 => { + let part = text.get(start..i).unwrap_or("").trim(); + start = i + 1; + return Some(part); + } + _ => {} + } + } + done = true; + Some(text.get(start..).unwrap_or("").trim()) + }) +} + +/// Where one part of a Go To reference points, seen from sheet `sheet`: the sheet, its areas, +/// and whether a defined name or a table gave them. `Sheet2!Name` is the name scoped to Sheet2. +/// A name counts when what it refers to is a reference; a constant or a formula is not one. +fn go_to_target(wb: &gridcraft_model::Workbook, sheet: usize, part: &str, depth: usize) -> Option<(usize, Vec, bool)> { + if part.is_empty() || depth > GO_TO_NAME_DEPTH { + return None; + } + let (prefix, body) = split_sheet(part); + let on = match &prefix { + Some(n) => wb.sheet_index(n)?, + None => sheet, }; - let resolved = resolved.replace('$', ""); - selection_set(s, &json!({"range": resolved})) + if let Some(r) = RangeRef::parse(&body.replace('$', "")) { + return Some((on, vec![r], false)); + } + let name = match prefix { + Some(_) => wb.names.iter().find(|n| n.scope == Some(on) && n.name.eq_ignore_ascii_case(body)), + None => wb.name(body, sheet), + }; + if let Some(n) = name { + return name_areas(wb, n, sheet, depth).map(|(t, areas)| (t, areas, true)); + } + if prefix.is_none() + && let Some((si, ti)) = wb.table(body) + { + // As in Excel, a table's name stands for its data, without the header and totals rows. + let t = wb.sheet(si)?.tables.get(ti)?; + return Some((si, vec![t.data_range().unwrap_or(t.range)], true)); + } + None +} + +/// The sheet and areas defined name `n` refers to, seen from sheet `sheet`, when that is a +/// reference. +fn name_areas(wb: &gridcraft_model::Workbook, n: &gridcraft_model::DefinedName, sheet: usize, depth: usize) -> Option<(usize, Vec)> { + let from = n.scope.unwrap_or(sheet); + let formula = n.formula.trim().trim_start_matches('='); + let mut target: Option = None; + let mut areas = Vec::new(); + for p in reference_parts(formula) { + let (s, found, _) = go_to_target(wb, from, p, depth + 1)?; + if target.is_some_and(|t| t != s) { + return None; + } + target = Some(s); + areas.extend(found); + if areas.len() > GO_TO_MAX_AREAS { + return None; + } + } + target.map(|t| (t, areas)) +} + +/// The names the Go To dialog lists, seen from sheet `sheet`: the named ranges of the workbook and +/// of every sheet, in alphabetical order. A name scoped to another sheet is written `Sheet2!Name`, +/// and the active sheet's own name hides the workbook name it shares. Hidden names and names that +/// do not refer to a range are left out. +pub fn go_to_names(wb: &gridcraft_model::Workbook, sheet: usize) -> Vec { + let own: std::collections::HashSet = wb.names.iter().filter(|n| n.scope == Some(sheet)).map(|n| n.name.to_ascii_lowercase()).collect(); + let mut out: Vec = wb + .names + .iter() + .filter(|n| !n.hidden && name_areas(wb, n, sheet, 0).is_some()) + .filter_map(|n| match n.scope { + None if own.contains(&n.name.to_ascii_lowercase()) => None, + None => Some(n.name.clone()), + Some(s) if s == sheet => Some(n.name.clone()), + Some(s) => Some(format!("{}!{}", gridcraft_core::quote_sheet(&wb.sheet(s)?.name), n.name)), + }) + .collect(); + out.sort_by_key(|n| n.to_lowercase()); + out.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + out } fn go_to_special(s: &mut Session, p: &Json) -> Result { @@ -1786,6 +1913,119 @@ fn begin_edit(s: &mut Session, _: &Json) -> Result { mod tests { use super::*; + /// Sheet1 and Sheet2 with a workbook range name, a name scoped to each sheet, a constant, a + /// formula and a hidden name. + fn go_to_workbook() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.insertSheet", json!({"name": "Sheet2"})).unwrap(); + s.execute("selection.set", json!({"sheet": 0})).unwrap(); + let define = |s: &mut Session, name: &str, refers: &str, scope: &str| { + s.execute("formulas.defineName", json!({"name": name, "refersTo": refers, "scope": scope})).unwrap(); + }; + define(&mut s, "Price", "=Sheet1!$B$2:$B$5", "Workbook"); + define(&mut s, "type", "=Sheet1!$D$2:$D$5", "Workbook"); + define(&mut s, "Areas", "=Sheet1!$A$1,Sheet1!$C$3:$C$4", "Workbook"); + define(&mut s, "Local", "=Sheet2!$C$3", "Sheet2"); + define(&mut s, "Own", "=Sheet1!$E$1", "Sheet1"); + define(&mut s, "Rate", "=0.07", "Workbook"); + define(&mut s, "Total", "=SUM(Sheet1!$B$2:$B$5)", "Workbook"); + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + wb.names.push(gridcraft_model::DefinedName { + name: "Secret".into(), + scope: None, + formula: "Sheet1!$Z$9".into(), + comment: String::new(), + hidden: true, + }); + s + } + + /// "The Go to popup window shows named ranges on every worksheet in your workbook." Names + /// that are not ranges, and hidden names, are not listed. + #[test] + fn go_to_lists_the_named_ranges_of_every_sheet() { + let mut s = go_to_workbook(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["names"], json!(["Areas", "Own", "Price", "Sheet2!Local", "type"]), "{list}"); + assert_eq!(list["recent"], json!([]), "{list}"); + // Seen from Sheet2, its own name is bare and Sheet1's is qualified. + s.execute("selection.set", json!({"sheet": 1})).unwrap(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["names"], json!(["Areas", "Local", "Price", "Sheet1!Own", "type"]), "{list}"); + } + + #[test] + fn go_to_a_name_scoped_to_another_sheet_goes_to_that_sheet() { + let mut s = go_to_workbook(); + let out = s.execute("edit.goTo", json!({"reference": "Sheet2!Local"})).unwrap(); + assert_eq!(out["selection"], "C3", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet, 1); + // A name of several areas selects all of them. + let out = s.execute("edit.goTo", json!({"reference": "Areas"})).unwrap(); + assert_eq!(out["selection"], "A1,C3:C4", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet, 0); + } + + /// "You can enter multiple named ranges or cell references in the Reference box. Separating + /// each with a comma ... Excel will highlight all the ranges." + #[test] + fn go_to_selects_every_reference_and_name_in_a_list() { + let mut s = go_to_workbook(); + let out = s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30,H21:H29"})).unwrap(); + assert_eq!(out["selection"], "B14:C22,F19:G30,H21:H29", "{out}"); + let out = s.execute("edit.goTo", json!({"reference": "Price, Type"})).unwrap(); + assert_eq!(out["selection"], "B2:B5,D2:D5", "{out}"); + let out = s.execute("edit.goTo", json!({"reference": "Sheet2!$A$1,Sheet2!B2"})).unwrap(); + assert_eq!(out["selection"], "A1,B2", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet, 1); + // Areas on two sheets, and a part that is not a reference, leave the selection alone. + for bad in ["A1,Sheet1!B2", "A1,Rate", "A1,", "Total"] { + assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().selection.a1(), "A1,B2", "{bad}"); + } + } + + #[test] + fn go_to_reads_the_parts_of_a_long_reference_one_at_a_time() { + let mut parts = reference_parts("A1, 'Q1, Q2'!B2,SUM(C3,D4)"); + assert_eq!(parts.next(), Some("A1")); + assert_eq!(parts.next(), Some("'Q1, Q2'!B2")); + assert_eq!(parts.next(), Some("SUM(C3,D4)")); + assert_eq!(parts.next(), None); + assert_eq!(reference_parts("").collect::>(), vec![""]); + let mut s = go_to_workbook(); + let err = s.execute("edit.goTo", json!({"reference": "A1,".repeat(GO_TO_MAX_AREAS + 1)})).unwrap_err(); + assert!(err.to_string().contains("at most"), "{err}"); + let bad = format!("Total{}", ",".repeat(1_000_000)); + assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err()); + } + + /// "The Go to box keeps track of ranges as you enter them, and you can return to any of them." + #[test] + fn go_to_keeps_the_references_entered_newest_first() { + let mut s = go_to_workbook(); + s.execute("edit.goTo", json!({"reference": "B14:C22,F19:G30", "record": true})).unwrap(); + s.execute("edit.goTo", json!({"reference": "Sheet2!A5", "record": true})).unwrap(); + // Names are listed already; a call without `record` (the Name Box) is not kept. + s.execute("edit.goTo", json!({"reference": "Price", "record": true})).unwrap(); + s.execute("edit.goTo", json!({"reference": "Z9"})).unwrap(); + s.execute("edit.goTo", json!({"reference": "b14:c22,f19:g30", "record": true})).unwrap(); + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["recent"], json!(["Sheet1!B14:C22,Sheet1!F19:G30", "Sheet2!A5"]), "{list}"); + // Going back from Sheet2 to a recent reference returns to its sheet. + s.execute("selection.set", json!({"sheet": 1})).unwrap(); + let out = s.execute("edit.goTo", json!({"reference": "Sheet1!B14:C22,Sheet1!F19:G30", "record": true})).unwrap(); + assert_eq!(out["selection"], "B14:C22,F19:G30", "{out}"); + assert_eq!(s.doc().unwrap().wb.active_sheet, 0); + for i in 0..GO_TO_RECENT + 2 { + s.execute("edit.goTo", json!({"reference": format!("A{}", i + 1), "record": true})).unwrap(); + } + let list = s.execute("edit.goTo", json!({"list": true})).unwrap(); + assert_eq!(list["recent"].as_array().map(Vec::len), Some(GO_TO_RECENT), "{list}"); + assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); + } + #[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. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a..4e811e285 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -199,6 +199,9 @@ pub struct DocState { /// workbook is opened from a file, carried by content pasted from such a workbook, and never /// changed by a trust decision. pub trust: Trust, + /// The references `edit.goTo` with `record: true` went to in this document, newest first, + /// without names, each area written with its sheet (`Sheet1!B14:C22,Sheet1!F19:G30`). + pub go_to_recent: Vec, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -285,6 +288,7 @@ impl DocState { content_kind: None, scripts_trusted, trust, + go_to_recent: vec![], } } pub fn is_dirty(&self) -> bool { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e83db2fa1..cb02a9f63 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2320,12 +2320,28 @@ fn zoom(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) } fn go_to(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) { - let names: Vec = app.session.active().map(|doc| doc.wb.names.iter().map(|n| n.name.clone()).collect()).unwrap_or_default(); - for n in names { - if ui.selectable_label(false, &n).clicked() { - d.values.insert("reference".into(), json!(n)); + // The named ranges of every sheet, then the references gone to before, newest first. + let entries: Vec = app + .session + .active() + .map(|doc| { + let mut v = gridcraft_engine::cmd::edit::go_to_names(&doc.wb, doc.wb.active_sheet); + v.extend(doc.go_to_recent.iter().cloned()); + v + }) + .unwrap_or_default(); + let current = d.values.get("reference").and_then(Json::as_str).unwrap_or("").to_string(); + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| { + for n in entries { + let resp = ui.selectable_label(current == n, &n); + if resp.clicked() || resp.double_clicked() { + d.values.insert("reference".into(), json!(n)); + } + if resp.double_clicked() { + *confirm = true; + } } - } + }); let mut r = d.values.get("reference").and_then(Json::as_str).unwrap_or("").to_string(); ui.horizontal(|ui| { ui.label("Reference:"); @@ -2339,7 +2355,7 @@ fn go_to(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bo let mut open = true; ok_cancel(ui, confirm, &mut open); if *confirm { - app.run_or_alert("edit.goTo", json!({"reference": r})); + app.run_or_alert("edit.goTo", json!({"reference": r, "record": true})); app.grid.ensure_visible = true; } if !open { diff --git a/crates/ui-egui/tests/it/go_to_dialog.rs b/crates/ui-egui/tests/it/go_to_dialog.rs new file mode 100644 index 000000000..0d005ad4b --- /dev/null +++ b/crates/ui-egui/tests/it/go_to_dialog.rs @@ -0,0 +1,89 @@ +//! The Go To dialog lists the named ranges of every sheet and the references entered before; a +//! double-click on an entry goes there. + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::control::{Outcome, handle}; +use serde_json::{Value as Json, json}; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +fn harness() -> Harness { + let mut session = Session::new(); + session.new_workbook(); + session.execute("home.insertSheet", json!({"name": "Sheet2"})).unwrap(); + session.execute("selection.set", json!({"sheet": 0})).unwrap(); + for (name, refers, scope) in [("Price", "=Sheet1!$B$2:$B$5", "Workbook"), ("Local", "=Sheet2!$C$3", "Sheet2"), ("Rate", "=0.07", "Workbook")] { + session.execute("formulas.defineName", json!({"name": name, "refersTo": refers, "scope": scope})).unwrap(); + } + let mut h = egui_kittest::Harness::builder().with_step_dt(1.0 / 60.0).with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +fn control(h: &mut Harness, method: &str, params: Json) -> Json { + let ctx = h.ctx.clone(); + let out = match handle(h.state_mut(), &ctx, method, ¶ms) { + Outcome::Done(v) => v, + Outcome::Screenshot { .. } => json!(null), + }; + h.run_steps(2); + out +} + +fn button(h: &mut Harness, pos: Pos2, pressed: bool) { + h.input_mut() + .events + .extend([Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + h.step(); +} + +fn double_click(h: &mut Harness, label: &str) { + let pos = h.get_by_label(label).rect().center(); + button(h, pos, true); + button(h, pos, false); + button(h, pos, true); + button(h, pos, false); + h.run_steps(2); +} + +fn place(h: &Harness) -> (usize, String) { + let d = h.state().session.active().unwrap(); + (d.wb.active_sheet, d.selection.a1()) +} + +#[test] +fn double_clicking_a_name_scoped_to_another_sheet_goes_there() { + let mut h = harness(); + control(&mut h, "ui.dialog", json!({"name": "goTo"})); + assert!(h.query_by_label("Price").is_some(), "a workbook range name is listed"); + assert!(h.query_by_label("Rate").is_none(), "a constant is not a named range"); + double_click(&mut h, "Sheet2!Local"); + assert!(h.state().dialog.is_none(), "the dialog closed"); + assert_eq!(place(&h), (1, "C3".to_string())); +} + +#[test] +fn a_reference_entered_is_listed_and_a_double_click_returns_to_it() { + let mut h = harness(); + control(&mut h, "ui.dialog", json!({"name": "goTo"})); + control(&mut h, "ui.dialog.set", json!({"field": "reference", "value": "B14:C22,F19:G30"})); + h.key_press(Key::Enter); + h.run_steps(2); + assert!(h.state().dialog.is_none(), "Enter went"); + assert_eq!(place(&h), (0, "B14:C22,F19:G30".to_string())); + + control(&mut h, "selection.set", json!({"sheet": 1})); + control(&mut h, "ui.dialog", json!({"name": "goTo"})); + double_click(&mut h, "Sheet1!B14:C22,Sheet1!F19:G30"); + assert!(h.state().dialog.is_none(), "the dialog closed"); + assert_eq!(place(&h), (0, "B14:C22,F19:G30".to_string())); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a9769c1c..4b3626570 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -38,6 +38,7 @@ mod formula_locale; mod formula_point_headers; mod formula_popup; mod freeze_handles; +mod go_to_dialog; mod header_autofit; mod header_column_drag; mod host_chrome; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efee..08c7d35de 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-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Go To lists the named ranges of every sheet and the references entered before, and takes several names or references separated by commas; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -152,6 +152,9 @@ Seek, Scenario Manager, Data Analysis, Forecast Sheet and others exist. Missing Solver, Power Query editor, Insert Object, Equation editor, Protect/Allow Edit Ranges, Workbook Links, Accessibility checker. Like Excel's, every dialog opens centred and moves by its title bar, keeping its place while it is open (#1250). +Go To lists the named ranges of every sheet (a name scoped to another sheet as `Sheet2!Name`) and +the references entered before; a double-click goes to one. Its Reference box takes several names +or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) and selects them all. New Formatting Rule's formula box points like the formula bar: a click on the grid writes the cell's absolute reference at the caret (`=$B$2`) and a drag a range, leaving the selection the rule applies to as it is (#2348). Other dialogs' reference fields don't take clicks yet. @@ -178,6 +181,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Go To lists the named ranges on every sheet, as Excel's does ("The Go to popup window shows named ranges on every worksheet in your workbook"): a name scoped to another sheet appears as `Sheet2!Name`, and hidden names, constants and formulas are left out. It keeps the references entered (newest first, ten at most), and a double-click on an entry goes there. The Reference box and `edit.goTo` take several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30,H21:H29`) and select them all; `edit.goTo {list: true}` returns the list | | 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-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From 14415f410d4c7338d35477f73b5867f0125330b7 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:16:03 +0200 Subject: [PATCH 11/71] Fix PERCENTRANK returning #NUM! for very large significance Found while testing crates/functions/src/stat.rs:257-260 (trunc_digits, used by percentrank_impl) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/functions/src/stat.rs b/crates/functions/src/stat.rs index 861c4768e..2ad331607 100644 --- a/crates/functions/src/stat.rs +++ b/crates/functions/src/stat.rs @@ -256,6 +256,9 @@ fn intercept(y: &[f64], x: &[f64]) -> R { fn trunc_digits(r: f64, sig: f64) -> f64 { let f = 10f64.powi(sig as i32); + if !f.is_finite() { + return r; + } ((r * f) + 1e-9).floor() / f } @@ -2486,6 +2489,11 @@ mod tests { close(ev("PERCENTRANK.EXC", vec![e9.clone(), n(7.0)]), 0.7); close(ev("PERCENTRANK.EXC", vec![e9.clone(), n(5.43)]), 0.381); close(ev("PERCENTRANK.EXC", vec![e9, n(5.43), n(1.0)]), 0.3); + let t = c(&[1.0, 2.0, 3.0]); + close(ev("PERCENTRANK", vec![t.clone(), n(2.0), n(400.0)]), 0.5); + close(ev("PERCENTRANK.INC", vec![t.clone(), n(2.0), n(400.0)]), 0.5); + close(ev("PERCENTRANK.INC", vec![t.clone(), n(1.0), n(400.0)]), 0.0); + close(ev("PERCENTRANK.EXC", vec![t, n(2.0), n(400.0)]), 0.5); } #[test] From 7bc390d0fbe790230d682acb6c97ba990760f6bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 02:29:49 -0700 Subject: [PATCH 12/71] Status bar: a right-click opens a statistics menu, with Numerical Count, Minimum and Maximum added The status bar always showed Average, Count and Sum for a selection of several cells and had no menu. A right-click on it now opens a menu with Average, Count, Numerical Count, Minimum, Maximum and Sum, as in Excel. Average, Count and Sum are on by default; the other three are off. The text on the status bar can no longer be selected, so a right-click on the mode text or a statistic opens the menu as well. The zoom and view controls handle their own clicks as before. The choice is a preference set with the new view.statusBar command and kept in prefs.json. A prefs.json without it keeps the defaults. --- ROADMAP.md | 1 + crates/engine/src/cmd/view.rs | 51 ++++++++ crates/engine/src/lib.rs | 22 ++++ crates/ui-egui/src/tabs.rs | 132 +++++++++++++++------ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/status_bar_menu.rs | 60 ++++++++++ docs/ui-parity.md | 5 +- 7 files changed, 237 insertions(+), 35 deletions(-) create mode 100644 crates/ui-egui/tests/it/status_bar_menu.rs diff --git a/ROADMAP.md b/ROADMAP.md index da06359b5..3b50a62be 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | | 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) | diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index b42aec9a6..3c343da76 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -44,6 +44,15 @@ pub fn specs() -> Vec { s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar); Ok(json!({"on": s.prefs.formula_bar})) }), + cmd!( + query "view.statusBar", + "Customize Status Bar", + [], + None, + "{average?, count?, numericalCount?, minimum?, maximum?, sum?: bool (the statistics shown for a selection; returns all six)}", + always, + status_bar + ), cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection), cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation), cmd!( @@ -187,6 +196,30 @@ fn show_objects(s: &mut Session, p: &Json) -> Result { }) } +fn status_bar(s: &mut Session, p: &Json) -> Result { + let st = &mut s.prefs.status_bar; + for (key, flag) in [ + ("average", &mut st.average), + ("count", &mut st.count), + ("numericalCount", &mut st.numerical_count), + ("minimum", &mut st.minimum), + ("maximum", &mut st.maximum), + ("sum", &mut st.sum), + ] { + if let Some(on) = bool_param(p, key) { + *flag = on; + } + } + Ok(json!({ + "average": st.average, + "count": st.count, + "numericalCount": st.numerical_count, + "minimum": st.minimum, + "maximum": st.maximum, + "sum": st.sum, + })) +} + fn zoom(s: &mut Session, p: &Json) -> Result { let z = f64_param(p, "percent").ok_or_else(|| bad("view.zoom", "missing `percent`"))?.clamp(10.0, 400.0) as u16; let d = s.doc_mut()?; @@ -478,4 +511,22 @@ mod tests { let old: crate::Prefs = serde_json::from_str(r#"{"userName": "Ann"}"#).unwrap(); assert!(old.formula_bar); } + + #[test] + fn status_bar_statistics_default_to_average_count_and_sum_and_turn_on_one_at_a_time() { + let mut s = Session::new(); + let all = json!({"average": true, "count": true, "numericalCount": false, "minimum": false, "maximum": false, "sum": true}); + assert_eq!(s.execute("view.statusBar", json!({})).unwrap(), all); + let r = s.execute("view.statusBar", json!({"minimum": true, "sum": false, "count": "yes"})).unwrap(); + assert_eq!(r, json!({"average": true, "count": true, "numericalCount": false, "minimum": true, "maximum": false, "sum": false})); + assert!(s.prefs.status_bar.minimum && !s.prefs.status_bar.sum); + // A prefs.json saved before the option existed, or with only some of the six, keeps the defaults for the rest. + let old: crate::Prefs = serde_json::from_str(r#"{"userName": "Ann"}"#).unwrap(); + assert_eq!(old.status_bar, crate::StatusBarStats::default()); + let part: crate::Prefs = serde_json::from_str(r#"{"statusBar": {"maximum": true}}"#).unwrap(); + assert!(part.status_bar.maximum && part.status_bar.average && part.status_bar.sum && !part.status_bar.minimum); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["statusBar"]["minimum"], true); + assert_eq!(saved["statusBar"]["numericalCount"], false); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a..b64eddcce 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -347,6 +347,27 @@ pub struct Prefs { pub user_dictionary: Vec, /// View › Show › Formula Bar (an application option in Excel, not saved in the file). pub formula_bar: bool, + /// The statistics the status bar shows for a selection (right-click the status bar). + pub status_bar: StatusBarStats, +} + +/// The selection statistics shown on the status bar, set with `view.statusBar`. Excel turns on +/// Average, Count and Sum by default. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct StatusBarStats { + pub average: bool, + pub count: bool, + pub numerical_count: bool, + pub minimum: bool, + pub maximum: bool, + pub sum: bool, +} + +impl Default for StatusBarStats { + fn default() -> Self { + StatusBarStats { average: true, count: true, numerical_count: false, minimum: false, maximum: false, sum: true } + } } impl Default for Prefs { @@ -361,6 +382,7 @@ impl Default for Prefs { r1c1: false, user_dictionary: vec![], formula_bar: true, + status_bar: StatusBarStats::default(), } } } diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index bc6fcc1d8..e7d352d7d 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -262,6 +262,13 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { egui::Panel::bottom("status_bar").exact_size(26.0).frame(egui::Frame::NONE.fill(t.status_bar).inner_margin(egui::Margin::symmetric(12, 0))).show( ui, |ui| { + // A right-click anywhere on the status bar opens the statistics menu, the text included, so its labels are not + // selectable. The zoom and view controls sense clicks and handle their own. + let background = ui.interact(ui.max_rect(), egui::Id::new("gridcraft.status_bar"), Sense::click()); + background.context_menu(|ui| status_bar_menu(app, ui)); + let text = |ui: &mut Ui, rich: egui::RichText| { + ui.add(egui::Label::new(rich).selectable(false)); + }; ui.horizontal_centered(|ui| { let mode = match app.session.mode { gridcraft_engine::Mode::Ready => "Ready", @@ -269,25 +276,26 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { gridcraft_engine::Mode::Edit => "Edit", gridcraft_engine::Mode::Point => "Point", }; - ui.label(egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim)); + text(ui, egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim)); if let Some(d) = app.session.active() { if d.wb.vba_project.is_some() { ui.add_space(12.0); - ui.label(egui::RichText::new("Macros preserved (not executed)").font(theme::ui_font(12.5)).color(t.danger)); + text(ui, egui::RichText::new("Macros preserved (not executed)").font(theme::ui_font(12.5)).color(t.danger)); } if d.wb.calc.mode == gridcraft_engine::model::CalcMode::Manual { ui.add_space(12.0); - ui.label(egui::RichText::new(app.ui.language.tr("Calculate")).font(theme::ui_font(12.5)).color(t.text_dim)); + text(ui, egui::RichText::new(app.ui.language.tr("Calculate")).font(theme::ui_font(12.5)).color(t.text_dim)); } if !d.calc.circular.is_empty() { ui.add_space(12.0); let (si, c) = d.calc.circular[0]; let name = d.wb.sheet(si).map(|s| s.name.clone()).unwrap_or_default(); - ui.label(egui::RichText::new(format!("Circular References: {name}!{}", c.a1())).font(theme::ui_font(12.5)).color(t.danger)); + text(ui, egui::RichText::new(format!("Circular References: {name}!{}", c.a1())).font(theme::ui_font(12.5)).color(t.danger)); } if app.session.clipboard.is_some() && app.editor.is_none() { ui.add_space(12.0); - ui.label( + text( + ui, egui::RichText::new(app.ui.language.tr("Select destination and press Enter or choose Paste")) .font(theme::ui_font(12.5)) .color(t.text_dim), @@ -336,34 +344,10 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { } } ui.add_space(16.0); - // Average / Count / Sum. - if let Some(d) = app.session.active() - && let Some(sh) = d.wb.active() - && !d.selection.is_single_cell() - { - let st = gridcraft_engine::display::stats(sh, &d.selection.ranges); - let fmt = |v: f64| { - let code = d.wb.styles.get(sh.style_id(d.selection.active)).num_fmt.as_str().to_string(); - let code = if code == "General" { "#,##0.##########".to_string() } else { code }; - gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(v), &code, &d.wb) - .text - .trim_end_matches('.') - .to_string() - }; - let mut parts = Vec::new(); - if st.numeric > 0 { - parts.push(format!("Sum: {}", fmt(st.sum))); - } - if st.count > 0 { - parts.push(format!("Count: {}", st.count)); - } - if let Some(a) = st.average { - parts.push(format!("Average: {}", fmt(a))); - } - for p in parts { - ui.label(egui::RichText::new(p).font(theme::ui_font(12.5)).color(t.text_dim)); - ui.add_space(10.0); - } + // The layout runs right to left, so the last statistic is drawn first. + for p in selection_statistics(app).into_iter().rev() { + text(ui, egui::RichText::new(p).font(theme::ui_font(12.5)).color(t.text_dim)); + ui.add_space(10.0); } }); }); @@ -371,6 +355,64 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { ); } +/// The statistics the status bar shows for a selection of more than one cell, left to right: Average, Count, +/// Numerical Count, Minimum, Maximum, Sum. Each one shows when it is turned on (`view.statusBar`) +/// and the selection has a value for it. +pub(crate) fn selection_statistics(app: &SheetApp) -> Vec { + let Some(d) = app.session.active() else { return vec![] }; + let Some(sh) = d.wb.active() else { return vec![] }; + if d.selection.is_single_cell() { + return vec![]; + } + let on = app.session.prefs.status_bar; + let st = gridcraft_engine::display::stats(sh, &d.selection.ranges); + let fmt = |v: f64| { + let code = d.wb.styles.get(sh.style_id(d.selection.active)).num_fmt.as_str().to_string(); + let code = if code == "General" { "#,##0.##########".to_string() } else { code }; + gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(v), &code, &d.wb).text.trim_end_matches('.').to_string() + }; + let mut parts = Vec::new(); + if on.average + && let Some(a) = st.average + { + parts.push(format!("Average: {}", fmt(a))); + } + if on.count && st.count > 0 { + parts.push(format!("Count: {}", st.count)); + } + if on.numerical_count && st.count > 0 { + parts.push(format!("Numerical Count: {}", st.numeric)); + } + if on.minimum && st.numeric > 0 { + parts.push(format!("Minimum: {}", fmt(st.min))); + } + if on.maximum && st.numeric > 0 { + parts.push(format!("Maximum: {}", fmt(st.max))); + } + if on.sum && st.numeric > 0 { + parts.push(format!("Sum: {}", fmt(st.sum))); + } + parts +} + +/// The status bar's context menu: a check item for each statistic, each one running `view.statusBar`. +fn status_bar_menu(app: &mut SheetApp, ui: &mut Ui) { + ui.set_min_width(180.0); + let st = app.session.prefs.status_bar; + for (key, label, mut on) in [ + ("average", "Average", st.average), + ("count", "Count", st.count), + ("numericalCount", "Numerical Count", st.numerical_count), + ("minimum", "Minimum", st.minimum), + ("maximum", "Maximum", st.maximum), + ("sum", "Sum", st.sum), + ] { + if ui.checkbox(&mut on, app.ui.language.tr(label)).changed() { + app.run_or_alert("view.statusBar", json!({ key: on })); + } + } +} + #[cfg(test)] mod tests { use super::{activate_sheet, drop_copies_sheet, navigator_items, rename_needs_focus, tab_drop}; @@ -396,6 +438,30 @@ mod tests { app.session.active().unwrap().wb.sheets.iter().map(|s| s.name.clone()).collect() } + #[test] + fn status_bar_shows_the_statistics_that_are_turned_on_in_order() { + let mut session = gridcraft_engine::Session::default(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + for (cell, input) in [("A1", "4"), ("A2", "-1"), ("A3", "x"), ("A4", "9")] { + app.run("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + app.run("selection.set", json!({"range": "A1:A5"})).unwrap(); + assert_eq!(super::selection_statistics(&app), ["Average: 4", "Count: 4", "Sum: 12"]); + app.run("view.statusBar", json!({"numericalCount": true, "minimum": true, "maximum": true})).unwrap(); + assert_eq!(super::selection_statistics(&app), ["Average: 4", "Count: 4", "Numerical Count: 3", "Minimum: -1", "Maximum: 9", "Sum: 12"]); + app.run("view.statusBar", json!({"average": false, "count": false, "sum": false})).unwrap(); + assert_eq!(super::selection_statistics(&app), ["Numerical Count: 3", "Minimum: -1", "Maximum: 9"]); + // Text only: Count and Numerical Count, nothing that needs a number. + app.run("view.statusBar", json!({"average": true, "count": true, "sum": true})).unwrap(); + app.run("cell.set", json!({"cell": "B1", "input": "a"})).unwrap(); + app.run("cell.set", json!({"cell": "B2", "input": "b"})).unwrap(); + app.run("selection.set", json!({"range": "B1:B2"})).unwrap(); + assert_eq!(super::selection_statistics(&app), ["Count: 2", "Numerical Count: 0"]); + app.run("selection.set", json!({"range": "A1"})).unwrap(); + assert!(super::selection_statistics(&app).is_empty(), "one cell shows no statistics"); + } + #[test] fn copy_drop_modifier_is_ctrl_or_cmd_or_option_on_mac() { // egui reports Ctrl as `command` too off macOS, and Cmd as `mac_cmd` and `command` on macOS. diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a9769c1c..e1323194c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -77,6 +77,7 @@ mod sheet_tabs; mod show_objects; mod shrink_to_fit; mod sort_dialog_columns; +mod status_bar_menu; mod symbol_glyphs; mod system_theme; mod table_headings; diff --git a/crates/ui-egui/tests/it/status_bar_menu.rs b/crates/ui-egui/tests/it/status_bar_menu.rs new file mode 100644 index 000000000..148824921 --- /dev/null +++ b/crates/ui-egui/tests/it/status_bar_menu.rs @@ -0,0 +1,60 @@ +//! Right-clicking the status bar opens a menu that turns its selection statistics on and off. + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +use gridcraft_ui_egui::SheetApp; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +fn harness() -> Harness { + let mut session = Session::new(); + session.new_workbook(); + for (cell, input) in [("A1", "4"), ("A2", "-1"), ("A3", "9")] { + session.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + session.execute("selection.set", json!({"range": "A1:A3"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +fn right_click(h: &mut Harness, pos: Pos2) { + h.input_mut().events.push(Event::PointerMoved(pos)); + h.run_steps(1); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); +} + +#[test] +fn right_clicking_the_status_bar_turns_on_minimum() { + let mut h = harness(); + assert!(h.query_by_label("Sum: 12").is_some(), "Sum is on by default"); + assert!(h.query_by_label("Minimum: -1").is_none(), "Minimum is off by default"); + // An empty stretch of the 26-point status bar, between the mode text and the statistics. + right_click(&mut h, pos2(300.0, 787.0)); + h.get_by_label("Minimum").click(); + h.run_steps(4); + assert!(h.state().session.prefs.status_bar.minimum); + assert!(h.query_by_label("Minimum: -1").is_some(), "the status bar shows the minimum of the selection"); +} + +#[test] +fn right_clicking_the_status_bar_text_opens_the_menu() { + for text in ["Sum: 12", "Ready"] { + let mut h = harness(); + let pos = h.get_by_label(text).rect().center(); + right_click(&mut h, pos); + assert!(h.query_by_label("Numerical Count").is_some(), "a right-click on {text:?} opens the statistics menu"); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efee..e9ee8d2ea 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-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (right-clicking the status bar opens a menu of its statistics, with Numerical Count, Minimum and Maximum added; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -26,7 +26,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Formula bar with Name Box, expand, function hints | yes | yes | done; dynamic-array spill children show the source formula muted and read-only, using current spill ownership | | Sheet tabs: rename, reorder, colour, hide, scroll | yes | yes | active tab revealed on navigation and resize (#681); manual wheel/trackpad browsing preserved; rename focus bug on macOS (#145) | | Sheet tabs: rename, reorder, colour, hide, scroll | yes | yes | active tab revealed on navigation and resize (#681); New sheet (+) right after the last tab, the strip capped at 60% of the bar (#943); manual wheel/trackpad browsing preserved; next/previous skips Hidden and VeryHidden sheets and retains the current sheet and selection when no visible destination exists; rename focus bug on macOS (#145) | -| Status bar: Sum/Count/Average and more, view buttons, zoom | yes | yes | customizable statistics partial | +| Status bar: Sum/Count/Average and more, view buttons, zoom | yes | yes; a right-click on the status bar opens a menu that turns the statistics on and off (Average, Count, Numerical Count, Minimum, Maximum, Sum; `view.statusBar`) | done for the statistics; the other status bar options are not customizable | | 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 | Options dialog and 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) | @@ -178,6 +178,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Right-clicking the status bar opens a menu of its statistics, as in Excel ("If you want to customize the status bar, right-click it, and then click the options that you want"): Average, Count and Sum are on by default, and Numerical Count, Minimum and Maximum are new and off by default. The choice is a preference (`view.statusBar`), kept in `prefs.json` | | 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-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From 07890b47f8545ea71385a6f4b996a4a0a1ae2fe7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 03:41:44 -0700 Subject: [PATCH 13/71] Keyboard: Ctrl+Shift+U expands and collapses the formula bar instead of underlining Ctrl+Shift+U ran the Ctrl+U shortcut on Windows and Linux and underlined the selection. In Excel it expands or collapses the formula bar, on Windows and as Control+Shift+U on a Mac. It now does that on the grid and in the cell editor or formula bar while editing, and the entry stays open. The new UI command view.expandFormulaBar {on?} sets the state, or toggles it without a parameter, and returns {on}. The chevron at the end of the formula bar is unchanged. --- ROADMAP.md | 1 + crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/formula_bar.rs | 4 + crates/ui-egui/src/keymap.rs | 2 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/it/formula_bar_expand.rs | 95 +++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/ui-parity.md | 8 +- 8 files changed, 113 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/tests/it/formula_bar_expand.rs diff --git a/ROADMAP.md b/ROADMAP.md index da06359b5..1d9cf5f48 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-24 | Ctrl+Shift+U (Control+Shift+U on a Mac) expands and collapses the formula bar, on the grid and while editing (`view.expandFormulaBar`); on Windows and Linux it used to underline | | 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) | diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 11d535ac4..8e29bccb4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -230,6 +230,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - for (id, label, params) in [ ("ui.ribbonTab", "Ribbon Tab", ""), ("view.collapseRibbon", "Collapse Ribbon", ""), + ("view.expandFormulaBar", "Expand Formula Bar", "{on?: bool} (toggles without it) → {on}"), ("view.darkMode", "Dark Mode", ""), ("view.theme", "Display Theme", ""), ("view.animations", "Animations", "{on?: bool} (toggles without it) → {on}"), diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index b88699f57..3a33f3867 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -290,6 +290,10 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: state.store(ui.ctx(), id); } } + // Ctrl+Shift+U (Control+Shift+U on a Mac) expands or collapses the formula bar while editing too. + if ui.input_mut(|i| i.consume_key(egui::Modifiers::CTRL | egui::Modifiers::SHIFT, Key::U)) { + app.run_or_alert("view.expandFormulaBar", json!({})); + } } // The text widget. let refs = formula_refs(&ed.text); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 5840036a1..03bd2d655 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -103,6 +103,8 @@ pub fn lookup(key: Key, physical: Option, m: Modifiers, mac: bool) -> Optio L if (cmd || ctrl) && s => run("data.filter"), L if cmd && mac => run("home.alignLeft"), L if ctrl && mac => Shortcut::Dialog("defineName", json!({})), + // Ctrl+Shift+U (Control+Shift+U in Excel for Mac) expands or collapses the formula bar. + U if ctrl && s => run("view.expandFormulaBar"), U if ctrl && mac && !s => Shortcut::Edit, L if cmd => run("insert.table"), E if cmd && mac && !s => run("home.alignCenter"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 14c442331..5b421a4db 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -632,6 +632,10 @@ impl SheetApp { self.ui.ribbon_collapsed = !self.ui.ribbon_collapsed; Ok(Json::Null) } + "view.expandFormulaBar" => { + self.ui.formula_bar_expanded = p.get("on").and_then(Json::as_bool).unwrap_or(!self.ui.formula_bar_expanded); + Ok(json!({"on": self.ui.formula_bar_expanded})) + } "view.darkMode" => { let current = if self.ui.system_theme { self.effective_dark } else { self.ui.dark }; self.ui.dark = p.get("on").and_then(Json::as_bool).unwrap_or(!current); diff --git a/crates/ui-egui/tests/it/formula_bar_expand.rs b/crates/ui-egui/tests/it/formula_bar_expand.rs new file mode 100644 index 000000000..95b4368e5 --- /dev/null +++ b/crates/ui-egui/tests/it/formula_bar_expand.rs @@ -0,0 +1,95 @@ +//! Ctrl+Shift+U (Control+Shift+U in Excel for Mac) expands and collapses the formula bar. + +use egui::{Event, Key, Modifiers}; +use gridcraft_engine::Session; +use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::keymap::{Shortcut, lookup}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +/// Ctrl+Shift on Windows and Linux sets `ctrl`, `command` and `shift`. +const CTRL_SHIFT: Modifiers = Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true }; +/// Control+Shift on a Mac: `ctrl` without `command`. +const MAC_CONTROL_SHIFT: Modifiers = Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: false }; + +fn harness() -> Harness { + let mut session = Session::new(); + session.new_workbook(); + session.execute("cell.set", json!({"cell": "A1", "input": "text"})).unwrap(); + session.execute("selection.set", json!({"range": "A1"})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +fn ctrl_shift_u(h: &mut Harness, m: Modifiers) { + h.input_mut().events.push(Event::Key { key: Key::U, physical_key: Some(Key::U), pressed: true, repeat: false, modifiers: m }); + h.input_mut().events.push(Event::Key { key: Key::U, physical_key: Some(Key::U), pressed: false, repeat: false, modifiers: m }); + h.run_steps(2); +} + +fn expanded(h: &Harness) -> bool { + h.state().ui.formula_bar_expanded +} + +fn underlined(h: &Harness) -> bool { + h.state().session.journal.iter().any(|(id, _)| id == "home.underline") +} + +#[test] +fn ctrl_shift_u_on_the_grid_expands_and_collapses_the_formula_bar() { + let mut h = harness(); + assert!(!expanded(&h)); + ctrl_shift_u(&mut h, CTRL_SHIFT); + assert!(expanded(&h), "the first Ctrl+Shift+U expands the formula bar"); + ctrl_shift_u(&mut h, CTRL_SHIFT); + assert!(!expanded(&h), "the second Ctrl+Shift+U collapses it"); + assert!(!underlined(&h), "Ctrl+Shift+U is not Underline"); +} + +#[test] +fn control_shift_u_expands_the_formula_bar_in_excel_for_mac() { + let mut h = harness(); + h.ctx.set_os(egui::os::OperatingSystem::Mac); + h.run_steps(2); + ctrl_shift_u(&mut h, MAC_CONTROL_SHIFT); + assert!(expanded(&h)); + assert!(h.state().editor.is_none(), "Control+Shift+U does not start editing as Control+U does"); + let expand = Some(Shortcut::Run("view.expandFormulaBar", json!({}))); + assert_eq!(lookup(Key::U, Some(Key::U), MAC_CONTROL_SHIFT, true), expand); + assert_eq!(lookup(Key::U, Some(Key::U), CTRL_SHIFT, false), expand); + // Control+U on a Mac still edits the active cell. + assert_eq!(lookup(Key::U, Some(Key::U), Modifiers::CTRL, true), Some(Shortcut::Edit)); +} + +#[test] +fn ctrl_shift_u_while_editing_keeps_the_entry() { + let mut h = harness(); + h.state_mut().begin_edit(Some("draft".into()), false); + h.run_steps(2); + ctrl_shift_u(&mut h, CTRL_SHIFT); + assert!(expanded(&h), "Ctrl+Shift+U works in the cell editor too"); + let ed = h.state().editor.as_ref().expect("the edit stays open"); + assert_eq!(ed.text, "draft"); + ctrl_shift_u(&mut h, CTRL_SHIFT); + assert!(!expanded(&h)); + assert!(h.state().editor.is_some()); +} + +#[test] +fn expand_formula_bar_command_sets_or_toggles_the_state() { + let mut h = harness(); + assert_eq!(h.state_mut().run("view.expandFormulaBar", json!({"on": true})), Ok(json!({"on": true}))); + assert!(expanded(&h)); + assert_eq!(h.state_mut().run("view.expandFormulaBar", json!({"on": true})), Ok(json!({"on": true}))); + assert_eq!(h.state_mut().run("view.expandFormulaBar", json!({})), Ok(json!({"on": false}))); + assert!(!expanded(&h)); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a9769c1c..06ffaac02 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -34,6 +34,7 @@ mod find_dialog_focus; mod floating_pictures; mod font_size_box; mod format_painter; +mod formula_bar_expand; mod formula_locale; mod formula_point_headers; mod formula_popup; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efee..17538e580 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-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Ctrl+Shift+U expands and collapses the formula bar; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -134,9 +134,10 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | | F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | -| Ctrl+Q, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | Quick Analysis, Function Arguments, formula bar height, tooltips | missing | +| Ctrl+Q, Ctrl+A after a function name, Ctrl+Alt+P | same | Quick Analysis, Function Arguments, tooltips | missing | | Ctrl+Shift+A after a function name | Control+Shift+A | argument names: `=SUMIF(` becomes `=SUMIF(range,criteria,sum_range)`, the `(` added when missing; one Undo takes them back | **added** | -| Ctrl+6, Ctrl+Q, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, Quick Analysis, Function Arguments, formula bar height, tooltips | missing | +| Ctrl+Shift+U | Control+Shift+U | expand or collapse the formula bar (`view.expandFormulaBar`), on the grid and while editing; on Windows and Linux it no longer underlines | **added** | +| Ctrl+6, Ctrl+Q, Ctrl+A after a function name, Ctrl+Alt+P | same | objects, Quick Analysis, Function Arguments, tooltips | missing | | Ctrl+Shift+Page Up / Down, Ctrl+Alt+5, Ctrl+Shift+F1, Ctrl+F5–F10, Alt+F8 / F11 / F12 | same | group sheets, shape cycling, full screen, window keys, macros, VBA, Power Query | missing | | — | Cmd+= (calculate), Cmd+T (references while editing; F4 works), Shift+F7, Cmd+Shift+L | Mac-only extras | missing (Cmd+= is egui's zoom key; no thesaurus or Modify Cell Style) | @@ -178,6 +179,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Ctrl+Shift+U (Control+Shift+U on a Mac) expands or collapses the formula bar, as in Excel ("Expand or collapse the formula bar. Ctrl+Shift+U"), on the grid and in the cell editor or formula bar while editing. On Windows and Linux it used to underline the selection, as Ctrl+U does. The command is `view.expandFormulaBar` (`{on?}`, toggles without it) | | 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-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From 6cb32201641eb8016ad57290e87e20b7ddf0b1c1 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:09:26 +0000 Subject: [PATCH 14/71] Scale MINVERSE rounding cutoff to the input matrix Found while testing crates/functions/src/math.rs:923 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/math.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/functions/src/math.rs b/crates/functions/src/math.rs index 53a92f00f..9824da7bf 100644 --- a/crates/functions/src/math.rs +++ b/crates/functions/src/math.rs @@ -918,7 +918,9 @@ fn minverse(a: &[Arg], _c: &mut dyn Ctx) -> R { } } } - let inv = inv.into_iter().map(|x| if x.abs() < 1e-15 { 0.0 } else { x }).collect(); + // Rounding noise in the inverse scales with 1/scale of the input matrix. + let noise = 1e-15 / scale; + let inv = inv.into_iter().map(|x| if x.abs() < noise { 0.0 } else { x }).collect(); to_value_array(n, n, inv) } @@ -1622,6 +1624,17 @@ mod tests { is_text(ev2("ROMAN", 99.0, 4.0), "IC"); } + #[test] + fn minverse_scale_relative() { + let big = ev("MINVERSE", vec![av(arr(vec![vec![nv(1e20), nv(0.0)], vec![nv(0.0), nv(1e20)]]))]); + let r = rows_of(&big); + close_tol(r[0][0].clone(), 1e-20, 1e-25); + close_tol(r[1][1].clone(), 1e-20, 1e-25); + let small = ev("MINVERSE", vec![av(arr(vec![vec![nv(1e-20), nv(0.0)], vec![nv(0.0), nv(1e-20)]]))]); + let r = rows_of(&small); + close_tol(r[0][0].clone(), 1e20, 1e10); + } + #[test] fn matrices() { let a = arr(vec![vec![nv(1.0), nv(2.0)], vec![nv(3.0), nv(4.0)]]); From d0fe8b6423694b9124e35cd8f283b7a58220dbe5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 04:50:46 -0700 Subject: [PATCH 15/71] Tests: the engine's file-system tests each use their own temporary folder save_fails_upfront_when_the_temp_name_is_taken, save_keeps_the_destination_access_restrictions and open_refuses_directories_and_unknowable_lengths in crates/engine/src/io.rs all worked in temp_dir()/gridcraft-fs-safety and removed it at the start and the end. cargo test runs them on parallel threads, so one test could delete the folder while another was writing to it, and the other test failed. Each test now uses its own folder, named with a short label and the process id, as the gridcraft-write and gridcraft-sandbox tests in the same file do. --- crates/engine/src/io.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index be47e0a67..92ab69038 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -770,7 +770,7 @@ mod tests { fn save_fails_upfront_when_the_temp_name_is_taken() { // Another local user who can write the directory must not be able to point the // save's predictable temporary name at their own file: creation is exclusive. - let dir = std::env::temp_dir().join("gridcraft-fs-safety"); + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-temp-name-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let victim = dir.join("victim.txt"); @@ -788,7 +788,7 @@ mod tests { #[test] fn save_keeps_the_destination_access_restrictions() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join("gridcraft-fs-safety"); + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-permissions-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let dest = dir.join("private.xlsx"); @@ -808,7 +808,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn open_refuses_directories_and_unknowable_lengths() { - let dir = std::env::temp_dir().join("gridcraft-fs-safety"); + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-open-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); assert!(read_file(dir.to_str().unwrap()).is_err(), "a directory is not a regular file"); From 276cd0fe78f543f6f5e5f82a4906970237a47aaf Mon Sep 17 00:00:00 2001 From: Arie Nugraha Date: Sat, 24 Oct 2026 13:00:37 +0000 Subject: [PATCH 16/71] web: parse ?chrome= so an embedding host can leave out the title bar and File tab #1877 added Chrome to SheetApp for hosts that embed the sheet natively, but the web build never set it: an iframe host that owns the files still draws the title bar it duplicates, and Backstage's Open/Save As can replace the document behind the host's back. Parse the flag where the other URL flags are parsed; the UI already honours Chrome, so nothing else changes. Co-Authored-By: Claude Code --- apps/gridcraft-web/src/main.rs | 5 +++-- apps/gridcraft-web/src/web.rs | 11 +++++++++++ packaging/web/README.md | 4 ++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/gridcraft-web/src/main.rs b/apps/gridcraft-web/src/main.rs index 36f3f3eca..68bee92e6 100644 --- a/apps/gridcraft-web/src/main.rs +++ b/apps/gridcraft-web/src/main.rs @@ -11,8 +11,9 @@ //! URL query flags: `?webgl` forces WebGL2; `?sample=sales|budget|grades` opens a sample; //! `?host=parent` (inside an `