mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-29 17:56:18 +01:00
Merge main into fix/pivot-chart-series
Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
commit
d89a3afd22
66 files changed
+3730
-413
No files matched your search
Generated
+12
-12
@@ -922,12 +922,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -935,7 +935,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"kurbo",
|
||||
@@ -984,7 +984,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
@@ -1001,7 +1001,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
@@ -1031,7 +1031,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
@@ -1067,7 +1067,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1114,7 +1114,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1133,7 +1133,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
@@ -1146,7 +1146,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
@@ -1158,7 +1158,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1167,7 +1167,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+9
-9
@@ -30,25 +30,25 @@ gridcraft-math = { path = "crates/math" }
|
||||
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
|
||||
# craft-libs revision.
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
|
||||
# turn them into workbooks.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
# SpreadsheetML string encoding/decoding; workbook model mapping stays in gridcraft-xlsx.
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -88,7 +88,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
epaint_default_fonts = "0.37"
|
||||
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
|
||||
# driver. Same craft-libs revision as craft-update above.
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", default-features = false, features = ["egui"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -181,6 +181,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-16 | Memory: floating pictures are decoded at about the size they are drawn, with limits, into a cache bounded by bytes and dropped with their workbook, instead of at full size into one that never let go; two open workbooks no longer show each other's picture. 12 large pictures scrolled through keep 40 MB of textures instead of 258 MB, and none once the workbook closes |
|
||||
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
|
||||
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
|
||||
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
|
||||
| 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-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
@@ -202,6 +203,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-13 | XLSX export writes a picture used on several sheets once, as one `xl/media` part every drawing points to (it wrote a copy per drawing: a 16-sheet workbook with one 112 KB logo grew from 0.4 to 1.9 MB) (#985) |
|
||||
| 2026-10-13 | XLSX: `[Content_Types].xml`, `_rels/.rels`, the workbook rels and `xl/workbook.xml` are the first zip entries (document properties last), so libmagic and PHP `finfo` detect the file type even with large properties (#1090) |
|
||||
| 2026-10-13 | Conditional formatting: a rule gathers range statistics only when it reads them (top/bottom, above average, duplicates, scales, bars, icons) and borrows them instead of copying them per cell, so the per-frame lookup of an expression or cell-value rule no longer visits its whole range (#1098, part 1) |
|
||||
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
|
||||
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
|
||||
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
|
||||
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
//! - `gridcraft:open` (from the host): `{ name, bytes }`. It opens like a workbook picked with
|
||||
//! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is
|
||||
//! copied.
|
||||
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes }` for every file GridCraft would
|
||||
//! otherwise download: Save and Save As (an .xlsx workbook) and Export as PDF. The host stores
|
||||
//! it and reports failures itself. GridCraft doesn't tell the host which saves make a file the
|
||||
//! document, so `saveAs` is always `false`.
|
||||
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes, export }` for every file GridCraft
|
||||
//! would otherwise download. With `export: false`, the host stores the XLSX workbook; with
|
||||
//! `export: true`, it stores a separate file (such as a PDF) without replacing the workbook.
|
||||
//! `saveAs` remains `false`; it does not distinguish Save from Save As here.
|
||||
//! - `gridcraft:dirty` whenever unsaved changes appear or go away, `gridcraft:failed` when the
|
||||
//! app couldn't start.
|
||||
//!
|
||||
@@ -27,16 +27,16 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use craft_web_host::{Mode, Outgoing, file_name, message_type};
|
||||
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
use crate::host_save::{SaveMessage, sync_saved};
|
||||
use crate::hostmode::open_name;
|
||||
|
||||
/// The app id in the host messages (`gridcraft:ready`).
|
||||
const APP: &str = "gridcraft";
|
||||
|
||||
/// Saved files that count as a workbook: the document is then clean under the name it was saved as.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
/// The largest workbook taken from the host page, refused before it is copied.
|
||||
const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
|
||||
@@ -46,6 +46,7 @@ const MAX_AUTHOR_CHARS: usize = 200;
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
host: Rc<Host>,
|
||||
save_target: Rc<SaveTarget>,
|
||||
/// Names of the files handed to the host since the last frame.
|
||||
saved: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
@@ -55,7 +56,19 @@ impl Bridge {
|
||||
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
|
||||
/// with downloads), or a parent on another origin.
|
||||
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), saved: Rc::default() })
|
||||
let host = Host::connect(APP, canvas)?;
|
||||
let save_target = match host.mode() {
|
||||
Mode::Parent => {
|
||||
// Host::connect already admitted only a same-origin parent. Keep that origin
|
||||
// as the postMessage target so later navigation can't receive workbook bytes.
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
let origin = window.location().origin().ok()?;
|
||||
SaveTarget::Parent { parent, origin }
|
||||
}
|
||||
Mode::Page => SaveTarget::Page(canvas.clone()),
|
||||
};
|
||||
Some(Self { host: Rc::new(host), save_target: Rc::new(save_target), saved: Rc::default() })
|
||||
}
|
||||
|
||||
/// Send saved and exported files to the host instead of downloading them, and hear files
|
||||
@@ -91,20 +104,13 @@ impl Bridge {
|
||||
/// crate does not repeat a state it already reported).
|
||||
pub fn sync(&self, app: &mut SheetApp) {
|
||||
let saved = std::mem::take(&mut *self.saved.borrow_mut());
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
&& let Some(doc) = app.session.active_mut()
|
||||
{
|
||||
doc.saved = doc.wb.clone();
|
||||
if doc.path.is_none() {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
sync_saved(&saved, app);
|
||||
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = file_name(path);
|
||||
self.host.post_save(&name, bytes, None, false)?;
|
||||
let name = file_name(Some(path), "document");
|
||||
self.save_target.post(SaveMessage::new(&name, bytes)).map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))?;
|
||||
self.saved.borrow_mut().push(name);
|
||||
Ok(())
|
||||
}
|
||||
@@ -118,6 +124,38 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// A save-only adapter: the pinned host crate's `post_save` cannot add app-specific fields.
|
||||
/// All other messages and transport detection still go through `Host`.
|
||||
enum SaveTarget {
|
||||
Parent { parent: web_sys::Window, origin: String },
|
||||
Page(web_sys::HtmlCanvasElement),
|
||||
}
|
||||
|
||||
impl SaveTarget {
|
||||
fn post(&self, save: SaveMessage<'_>) -> Result<(), JsValue> {
|
||||
let buffer = js_sys::Uint8Array::from(save.bytes).buffer();
|
||||
let kind = message_type(APP, Outgoing::Save.kind());
|
||||
let payload = js_sys::Object::new();
|
||||
let set = |key, value: JsValue| js_sys::Reflect::set(&payload, &JsValue::from_str(key), &value);
|
||||
set("name", save.name.into())?;
|
||||
set("bytes", buffer.clone().into())?;
|
||||
set("saveAs", JsValue::FALSE)?;
|
||||
set("export", JsValue::from_bool(save.export))?;
|
||||
match self {
|
||||
Self::Parent { parent, origin } => {
|
||||
set("type", kind.as_str().into())?;
|
||||
parent.post_message_with_transfer(&payload, origin, &js_sys::Array::of1(&buffer))
|
||||
}
|
||||
Self::Page(canvas) => {
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_detail(&payload.into());
|
||||
let event = web_sys::CustomEvent::new_with_event_init_dict(&kind, &init)?;
|
||||
canvas.dispatch_event(&event).map(|_| ())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message carries, pushed onto the inbox for the next frame, like a dropped
|
||||
/// file. A host's file is untrusted input: an oversized one is refused before it is copied into
|
||||
/// the app's memory (the data's own length, not the host's claim).
|
||||
@@ -133,11 +171,3 @@ fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData)
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((open_name(name), array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Host save payloads and workbook receipts, shared with native regression tests.
|
||||
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
|
||||
/// Only these outputs replace the editable workbook in the host.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
pub struct SaveMessage<'a> {
|
||||
pub name: &'a str,
|
||||
pub bytes: &'a [u8],
|
||||
pub export: bool,
|
||||
}
|
||||
|
||||
impl<'a> SaveMessage<'a> {
|
||||
pub fn new(name: &'a str, bytes: &'a [u8]) -> Self {
|
||||
// All other outputs are exports, not necessarily PDFs.
|
||||
Self { name, bytes, export: !is_workbook(name) }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
/// Preserve the bridge's existing rule: only a workbook receipt marks the document saved.
|
||||
pub fn sync_saved(saved: &[String], app: &mut SheetApp) {
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
&& let Some(doc) = app.session.active_mut()
|
||||
{
|
||||
doc.saved = doc.wb.clone();
|
||||
if doc.path.is_none() {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn save_payload_marks_exports_and_preserves_name_and_bytes() {
|
||||
let bytes = [0, 1, 127, 128, 255];
|
||||
for (name, export) in [("finance.xlsx", false), ("finance.XLSX", false), ("finance.pdf", true), ("finance.PDF", true)] {
|
||||
let message = SaveMessage::new(name, &bytes);
|
||||
assert_eq!(message.export, export, "{name}");
|
||||
assert_eq!(message.name, name);
|
||||
assert_eq!(message.bytes, bytes.as_slice());
|
||||
assert_eq!(message.bytes.as_ptr(), bytes.as_ptr(), "the payload borrows the original bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_outputs_are_exports_not_workbook_saves() {
|
||||
for name in ["finance.csv", "finance.bin", "finance", "finance.xlsx.pdf", "finance.xlsx.bak"] {
|
||||
assert!(SaveMessage::new(name, &[]).export, "{name}");
|
||||
}
|
||||
assert!(!SaveMessage::new("finance.pdf.xlsx", &[]).export);
|
||||
}
|
||||
|
||||
fn edited_app() -> Result<SheetApp, String> {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("cell.set", json!({"cell": "A1", "input": "42"})).map_err(|e| e.to_string())?;
|
||||
Ok(SheetApp::new(session, Default::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_receipts_leave_the_workbook_dirty_and_its_title_unchanged() -> Result<(), String> {
|
||||
for name in ["finance.pdf", "finance.PDF"] {
|
||||
let mut app = edited_app()?;
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(doc.is_dirty());
|
||||
let title = doc.title.clone();
|
||||
let saved = doc.saved.clone();
|
||||
sync_saved(&[name.to_string()], &mut app);
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(doc.is_dirty(), "{name}");
|
||||
assert!(Arc::ptr_eq(&saved, &doc.saved), "an export must not replace the saved snapshot");
|
||||
assert_eq!(doc.title, title);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workbook_receipts_mark_saved_and_later_exports_do_not_replace_them() -> Result<(), String> {
|
||||
for name in ["finance.xlsx", "finance.XLSX"] {
|
||||
let mut app = edited_app()?;
|
||||
assert!(app.session.active().ok_or("no active document")?.is_dirty());
|
||||
sync_saved(&[name.to_string(), "finance.pdf".to_string()], &mut app);
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(!doc.is_dirty());
|
||||
assert!(Arc::ptr_eq(&doc.saved, &doc.wb));
|
||||
assert_eq!(doc.title, name);
|
||||
app.session.execute("cell.set", json!({"cell": "A1", "input": "43"})).map_err(|e| e.to_string())?;
|
||||
sync_saved(&["finance.PDF".to_string()], &mut app);
|
||||
assert!(app.session.active().ok_or("no active document")?.is_dirty(), "a subsequent export leaves new edits unsaved");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod host_save;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod hostmode;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod prefs;
|
||||
|
||||
@@ -25,9 +25,6 @@ chrono = { workspace = true }
|
||||
# Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
+11
-20
@@ -17,6 +17,7 @@ mod graphics;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod opener;
|
||||
mod print;
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -218,16 +219,16 @@ fn open_with_system(target: &str) {
|
||||
log::warn!("refused to open {target:?}: only http, https and mailto links are opened");
|
||||
return;
|
||||
};
|
||||
let target = target.as_str();
|
||||
let cmd = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
// By absolute path where the platform has one (#2176): a bare `explorer` would be looked up
|
||||
// in the application's directory first.
|
||||
let env = |key: &str| std::env::var(key).ok();
|
||||
let (system_root, windir) = (env("SystemRoot"), env("windir"));
|
||||
let Some((program, arg)) = opener::opener_command(opener::Os::current(), &target, system_root.as_deref(), windir.as_deref()) else {
|
||||
log::warn!("refused to open {target:?}: it could be read as an option");
|
||||
return;
|
||||
};
|
||||
if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() {
|
||||
log::warn!("{cmd} {target}: {e}");
|
||||
if let Err(e) = std::process::Command::new(&program).arg(&arg).spawn() {
|
||||
log::warn!("{} {arg}: {e}", program.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,21 +359,11 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
let window_builder = viewport.clone();
|
||||
let options = eframe::NativeOptions { viewport, ..Default::default() };
|
||||
#[cfg(unix)]
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut options = options;
|
||||
// Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs).
|
||||
#[cfg(target_os = "macos")]
|
||||
graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64")));
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) && std::env::var_os("GRIDCRAFT_WAYLAND").is_none() {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when
|
||||
// DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! How a link is handed to the operating system's opener (#2176).
|
||||
//!
|
||||
//! The opener is spawned by absolute path where the platform has a fixed one: a bare program name
|
||||
//! on Windows is searched for in the application's own directory (and the current directory)
|
||||
//! before System32 and the Windows directory, so an `explorer.exe` planted next to a portable
|
||||
//! GridCraft would run with the user's session. The target never becomes an option of the opener,
|
||||
//! and on Windows the characters Explorer's own command-line parser treats specially are
|
||||
//! percent-encoded. Pure functions, so the tests run on every OS.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Whose opener to use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
Mac,
|
||||
Windows,
|
||||
/// Linux, the BSDs and other freedesktop systems: `xdg-open`.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Os {
|
||||
pub fn current() -> Os {
|
||||
if cfg!(target_os = "macos") {
|
||||
Os::Mac
|
||||
} else if cfg!(windows) {
|
||||
Os::Windows
|
||||
} else {
|
||||
Os::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Used when neither `SystemRoot` nor `windir` holds a usable path.
|
||||
const DEFAULT_WINDOWS_DIR: &str = "C:\\Windows";
|
||||
|
||||
/// The Windows directory: `SystemRoot`, else `windir`, else `C:\Windows`. A value is used only
|
||||
/// when it is a local drive path (`X:\…`) without `..` segments; relative or network values
|
||||
/// would bring back the search this exists to avoid.
|
||||
pub fn windows_dir(system_root: Option<&str>, windir: Option<&str>) -> String {
|
||||
[system_root, windir]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(str::trim)
|
||||
.find(|d| is_local_drive_path(d))
|
||||
.map_or(DEFAULT_WINDOWS_DIR, |d| d.trim_end_matches(['\\', '/']))
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// `X:\…` or `X:/…` (not the drive-relative `X:` or `X:dir`), with no `..` segment and no quote.
|
||||
fn is_local_drive_path(d: &str) -> bool {
|
||||
let mut chars = d.chars();
|
||||
let drive = chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':');
|
||||
let rest = chars.as_str();
|
||||
let rooted = rest.starts_with(['\\', '/']);
|
||||
drive && rooted && !d.contains('"') && !rest.split(['\\', '/']).any(|seg| seg == "..")
|
||||
}
|
||||
|
||||
/// Percent-encodes the characters Explorer's command-line parser (comma-separated switches such
|
||||
/// as `/select,`), the C runtime's quoting rules and `cmd` treat specially: space, `"`, `,` and
|
||||
/// `^`. Space, `"` and `^` may not appear unencoded in a URL, so encoding them leaves the address
|
||||
/// unchanged. A comma may, and RFC 3986 does not treat `%2C` as equivalent to it (a `mailto:`
|
||||
/// recipient list is comma-separated); it is encoded anyway because Explorer's parser separates
|
||||
/// switches at commas, and a handler that percent-decodes the address sees the comma again.
|
||||
pub fn escape_for_explorer(target: &str) -> String {
|
||||
let mut out = String::with_capacity(target.len());
|
||||
for c in target.chars() {
|
||||
match c {
|
||||
' ' => out.push_str("%20"),
|
||||
'"' => out.push_str("%22"),
|
||||
',' => out.push_str("%2C"),
|
||||
'^' => out.push_str("%5E"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The program and its single argument that open `target` (already accepted by
|
||||
/// `links::classify`) on `os`. `None` when the target could be read as an option: it starts with
|
||||
/// `-` or `/`, or is empty. `xdg-open` takes no `--`, so refusing is the only safe answer.
|
||||
pub fn opener_command(os: Os, target: &str, system_root: Option<&str>, windir: Option<&str>) -> Option<(PathBuf, String)> {
|
||||
if target.is_empty() || target.starts_with(['-', '/']) {
|
||||
return None;
|
||||
}
|
||||
Some(match os {
|
||||
Os::Mac => (PathBuf::from("/usr/bin/open"), target.to_string()),
|
||||
Os::Windows => {
|
||||
let exe = format!("{}\\explorer.exe", windows_dir(system_root, windir));
|
||||
(PathBuf::from(exe), escape_for_explorer(target))
|
||||
}
|
||||
// Found on PATH: its location differs between distributions and the BSDs.
|
||||
Os::Other => (PathBuf::from("xdg-open"), target.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn windows_opener_is_explorer_in_the_windows_directory() {
|
||||
let (exe, arg) = opener_command(Os::Windows, "https://a.example/x", Some("C:\\Windows"), None).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"));
|
||||
assert_eq!(arg, "https://a.example/x");
|
||||
// Never a bare name, whatever the environment says.
|
||||
for (root, windir) in [(None, None), (Some(""), Some("")), (Some("Windows"), None), (Some(".\\"), Some("explorer"))] {
|
||||
let (exe, _) = opener_command(Os::Windows, "https://a.example", root, windir).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"), "{root:?} {windir:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_dir_prefers_system_root_then_windir_then_default() {
|
||||
assert_eq!(windows_dir(Some("D:\\WINNT\\"), Some("E:\\Win")), "D:\\WINNT");
|
||||
assert_eq!(windows_dir(None, Some("E:\\Win")), "E:\\Win");
|
||||
assert_eq!(windows_dir(Some("relative\\dir"), Some("e:/win/")), "e:/win");
|
||||
assert_eq!(windows_dir(None, None), "C:\\Windows");
|
||||
assert_eq!(windows_dir(Some("D:\\"), None), "D:");
|
||||
for bad in ["\\\\host\\share", "//host/share", "C:", "C:Windows", "C:\\Windows\\..\\Users\\x", "C:\\\"x", "", " ", "1:\\x"] {
|
||||
assert_eq!(windows_dir(Some(bad), None), "C:\\Windows", "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explorer_switch_characters_are_percent_encoded() {
|
||||
let (_, arg) = opener_command(Os::Windows, "https://x/,/select,C:\\Windows\\a b\"^", None, None).unwrap_or_default();
|
||||
assert_eq!(arg, "https://x/%2C/select%2CC:\\Windows\\a%20b%22%5E");
|
||||
assert!(!arg.contains([' ', '"', ',', '^']));
|
||||
assert_eq!(escape_for_explorer("mailto:a@b.example?subject=Hi there"), "mailto:a@b.example?subject=Hi%20there");
|
||||
// Other platforms get the address as it is.
|
||||
let (_, arg) = opener_command(Os::Other, "https://x/a,b", None, None).unwrap_or_default();
|
||||
assert_eq!(arg, "https://x/a,b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_and_freedesktop_openers() {
|
||||
let (exe, arg) = opener_command(Os::Mac, "https://a.example", None, None).unwrap_or_default();
|
||||
assert_eq!((exe, arg.as_str()), (PathBuf::from("/usr/bin/open"), "https://a.example"));
|
||||
let (exe, _) = opener_command(Os::Other, "mailto:a@b.example", None, None).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("xdg-open"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_never_becomes_an_option() {
|
||||
for os in [Os::Mac, Os::Windows, Os::Other] {
|
||||
for bad in ["-a", "--help", "-e calc", "/select,C:\\x", "/root,C:\\", ""] {
|
||||
assert_eq!(opener_command(os, bad, None, None), None, "{os:?} {bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
-25
@@ -59,26 +59,29 @@ pub struct Calc {
|
||||
|
||||
/// Who gets the cells when two arrays want the same ones. Excel (measured by a reviewer on
|
||||
/// PR #2483) lets the spill that already exists keep its cells, whichever anchor comes first;
|
||||
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here:
|
||||
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here, for
|
||||
/// each cell both want:
|
||||
///
|
||||
/// 1. an anchor that held a spill before this calculation outranks one that did not;
|
||||
/// 2. otherwise the anchor first in reading order (row, then column) wins.
|
||||
/// 1. the anchor whose spill held that cell before this calculation keeps it, so an array that
|
||||
/// grows into another's area is `#SPILL!` even when it held a spill of its own;
|
||||
/// 2. otherwise an anchor that held a spill before this calculation outranks one that did not;
|
||||
/// 3. otherwise the anchor first in reading order (row, then column) wins.
|
||||
///
|
||||
/// Rule 2 alone decides when nothing is remembered, so the result never depends on hash order
|
||||
/// Rule 3 alone decides when nothing is remembered, so the result never depends on hash order
|
||||
/// or evaluation order. A full recalculation remembers the layout the sheet held before it
|
||||
/// started (rule 1), so it agrees with the incremental one; a workbook that is calculated for
|
||||
/// the first time has no such layout (rule 2 only).
|
||||
///
|
||||
/// Known limits: (a) the xlsx reader does not restore spill layouts, so a workbook opened from a
|
||||
/// file is laid out by rule 2 alone, although Excel keeps the layout the file records; (b) when
|
||||
/// both anchors held a spill and one grows into the other, rule 2 decides, where Excel keeps
|
||||
/// the cells the other already owns.
|
||||
/// started, so it agrees with the incremental one; a workbook that is calculated for the first
|
||||
/// time has no such layout (rule 3 only). The xlsx reader restores the area each dynamic array
|
||||
/// was saved spilling over, so a workbook opened from a file keeps the layout it was saved with.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Standing {
|
||||
/// `true`: `keys` are the anchors that held a spill (full recalculation, which lays every
|
||||
/// spill out afresh). `false`: `keys` are the formulas that held none (incremental).
|
||||
held: bool,
|
||||
keys: HashSet<Key>,
|
||||
/// The area each anchor that held a spill filled before this calculation, for the anchors the
|
||||
/// calculation lays out again (full: all of them; incremental: the formulas it recalculates).
|
||||
/// Any other anchor still fills the area the sheet shows.
|
||||
areas: HashMap<Key, RangeRef>,
|
||||
}
|
||||
|
||||
impl Standing {
|
||||
@@ -86,7 +89,7 @@ impl Standing {
|
||||
self.keys.contains(&k) == self.held
|
||||
}
|
||||
|
||||
/// Whether `a` takes cells from `b` when both want them.
|
||||
/// Whether `a` takes cells from `b` when both want them and neither held them (rules 2, 3).
|
||||
fn outranks(&self, a: Key, b: Key) -> bool {
|
||||
match (self.had_spill(a), self.had_spill(b)) {
|
||||
(true, false) => true,
|
||||
@@ -94,6 +97,22 @@ impl Standing {
|
||||
_ => (a.1.row, a.1.col) < (b.1.row, b.1.col),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `k`'s spill held `cell` before this calculation; `now` is the area the sheet
|
||||
/// shows for `k`.
|
||||
fn held_cell(&self, k: Key, now: Option<RangeRef>, cell: CellRef) -> bool {
|
||||
self.had_spill(k) && self.areas.get(&k).copied().or(now).is_some_and(|r| r.contains(cell))
|
||||
}
|
||||
|
||||
/// Whether `a` takes `cell` from `b` when both want it (rule 1, then [`Self::outranks`]). Each
|
||||
/// anchor comes with the area the sheet shows for it.
|
||||
fn outranks_at(&self, (a, a_now): (Key, Option<RangeRef>), (b, b_now): (Key, Option<RangeRef>), cell: CellRef) -> bool {
|
||||
match (self.held_cell(a, a_now, cell), self.held_cell(b, b_now, cell)) {
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => self.outranks(a, b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of cells by row, each row's columns in their own set: a window of rows and columns is
|
||||
@@ -313,12 +332,18 @@ impl Calc {
|
||||
self.rebuild(wb);
|
||||
// The layout the sheets hold now decides who keeps cells two arrays both want.
|
||||
// (A Python cell that holds a spill counts too, as it does in the incremental pass.)
|
||||
let mut held = HashSet::default();
|
||||
let mut areas: HashMap<Key, RangeRef> = HashMap::default();
|
||||
for i in 0..wb.sheets.len() {
|
||||
if let Some(sh) = wb.sheet(i) {
|
||||
held.extend(sh.spill_ranges.keys().filter(|a| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some())).map(|a| (i, *a)));
|
||||
areas.extend(
|
||||
sh.spill_ranges
|
||||
.iter()
|
||||
.filter(|(a, _)| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some()))
|
||||
.map(|(a, r)| ((i, *a), *r)),
|
||||
);
|
||||
}
|
||||
}
|
||||
let held = areas.keys().copied().collect();
|
||||
// Spills are laid out again from the formulas where they are now (a structural edit moves
|
||||
// or deletes the formulas, not the values they spilled).
|
||||
for i in 0..wb.sheets.len() {
|
||||
@@ -330,7 +355,7 @@ impl Calc {
|
||||
}
|
||||
}
|
||||
let all: Vec<Key> = self.graph.nodes.keys().copied().collect();
|
||||
self.standing = Standing { held: true, keys: held };
|
||||
self.standing = Standing { held: true, keys: held, areas };
|
||||
self.run(wb, all, true);
|
||||
self.standing = Standing::default();
|
||||
}
|
||||
@@ -542,8 +567,15 @@ impl Calc {
|
||||
if !full {
|
||||
// What each formula held before this calculation touched it.
|
||||
for &k in &dirty {
|
||||
if seen.insert(k) && wb.sheet(k.0).is_some_and(|s| !s.spill_ranges.contains_key(&k.1)) {
|
||||
self.standing.keys.insert(k);
|
||||
if seen.insert(k) {
|
||||
match wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) {
|
||||
Some(r) => {
|
||||
self.standing.areas.insert(k, *r);
|
||||
}
|
||||
None => {
|
||||
self.standing.keys.insert(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -664,7 +696,7 @@ impl Calc {
|
||||
let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1));
|
||||
let range = RangeRef::new(key.1, end);
|
||||
// Two arrays that want the same cells (see [`Standing`]): a spill already laid out
|
||||
// that this anchor outranks is taken over, and recalculated.
|
||||
// that this anchor outranks on every cell they share is taken over, and recalculated.
|
||||
let standing = &self.standing;
|
||||
// A spill can only be in the way where it has cells besides its anchor, and an
|
||||
// anchor itself blocks the array. When no spilled cell lies in the range, the owners
|
||||
@@ -675,13 +707,18 @@ impl Calc {
|
||||
sheet
|
||||
.spill_ranges
|
||||
.iter()
|
||||
.filter(|(o, r)| **o != key.1 && r.intersects(&range) && standing.outranks(*key, (key.0, **o)))
|
||||
.filter(|(o, r)| {
|
||||
**o != key.1
|
||||
&& r.intersection(&range).is_some_and(|shared| {
|
||||
shared.iter().all(|cell| standing.outranks_at((*key, old), ((key.0, **o), Some(**r)), cell))
|
||||
})
|
||||
})
|
||||
.map(|(o, r)| (*o, *r))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let blocked = spill_is_blocked(sheet, *key, range, end, standing);
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
|
||||
if !blocked {
|
||||
for (o, r) in outranked {
|
||||
for c in r.iter() {
|
||||
@@ -739,11 +776,22 @@ thread_local! {
|
||||
pub(crate) static OWNER_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether the array at `anchor` can't be laid out over `range`. A spill already laid out that
|
||||
/// `anchor` outranks does not block it: it is taken over when written back.
|
||||
fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: Key, range: RangeRef, end: CellRef, standing: &Standing) -> bool {
|
||||
let outranked =
|
||||
|cell: CellRef| sheet.spill_ranges.iter().any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks(anchor, (anchor.0, *o)));
|
||||
/// Whether the array at `anchor` (with the area the sheet showed for it) can't be laid out over
|
||||
/// `range`. A spill already laid out that `anchor` outranks does not block it: it is taken over
|
||||
/// when written back.
|
||||
fn spill_is_blocked(
|
||||
sheet: &gridcraft_model::Sheet,
|
||||
(anchor, now): (Key, Option<RangeRef>),
|
||||
range: RangeRef,
|
||||
end: CellRef,
|
||||
standing: &Standing,
|
||||
) -> bool {
|
||||
let outranked = |cell: CellRef| {
|
||||
sheet
|
||||
.spill_ranges
|
||||
.iter()
|
||||
.any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks_at((anchor, now), ((anchor.0, *o), Some(*r)), cell))
|
||||
};
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|
||||
|
||||
@@ -163,9 +163,9 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
|
||||
}
|
||||
|
||||
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it
|
||||
/// (see `Standing`; unless that formula is recalculated in this pass, and so may spill elsewhere
|
||||
/// now). A spill it outranks gives way to it when written back.
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
|
||||
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
|
||||
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
|
||||
fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
let Some(sh) = host.wb.sheet(sheet) else { return false };
|
||||
let end =
|
||||
@@ -182,7 +182,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
&& r.contains(c)
|
||||
&& !host.exprs.contains_key(&(sheet, *o))
|
||||
&& !host.python.contains_key(&(sheet, *o))
|
||||
&& standing.outranks((sheet, *o), (sheet, anchor))
|
||||
&& standing.outranks_at(((sheet, *o), Some(*r)), ((sheet, anchor), own.copied()), c)
|
||||
})
|
||||
};
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|
||||
@@ -368,6 +368,24 @@ fn iterative_calculation_of_text_and_errors() {
|
||||
assert_eq!(t.get("B1"), Value::Error(CellError::Div0));
|
||||
}
|
||||
|
||||
/// `&`, CONCAT and TEXTJOIN turn a number into at most 15 significant digits, decimal unless that
|
||||
/// would need 16 integer digits or more than 21 characters below 1.
|
||||
#[test]
|
||||
fn text_joins_convert_numbers_to_15_significant_digits() {
|
||||
let mut t = T::new();
|
||||
for (formula, text) in [
|
||||
("=(1E15-0.5)&\"\"", "1E+15"),
|
||||
("=(999999999999999)&\"\"", "999999999999999"),
|
||||
("=1234567890123456&\"\"", "1.23456789012346E+15"),
|
||||
("=(9.99999999999999E-9)&\"\"", "9.99999999999999E-09"),
|
||||
("=CONCAT(1/3*1E-5)", "3.33333333333333E-06"),
|
||||
("=TEXTJOIN(\",\",TRUE,1/3*1E-4,0.1+0.2)", "0.0000333333333333333,0.3"),
|
||||
] {
|
||||
t.set("A1", formula);
|
||||
assert_eq!(t.get("A1"), Value::from(text), "{formula}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circular_references_without_iterative_calculation() {
|
||||
let mut t = T::new();
|
||||
@@ -706,6 +724,53 @@ fn spill_into_the_old_area_of_a_blocked_neighbour() {
|
||||
assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() {
|
||||
// Both arrays spill; in manual calculation F13 then grows over F14:G14, which C14's array
|
||||
// fills. A full recalculation gives what an automatic one would: C14 keeps its cells and F13
|
||||
// is #SPILL!, although F13 comes first in reading order.
|
||||
let mut t = T::new();
|
||||
t.set("J1", "1");
|
||||
t.set("C14", "=SEQUENCE(1,7)");
|
||||
t.set("F13", "=SEQUENCE(J1,2)");
|
||||
assert_eq!([t.num("F13"), t.num("G13")], [1.0, 2.0]);
|
||||
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
|
||||
t.set("J1", "5");
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.get("F13"), Value::Error(CellError::Spill));
|
||||
assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_recalc_lays_out_arrays_as_an_automatic_one_when_one_shrinks_for_another() {
|
||||
// C1 grows into C3, which A3's array fills, and A3 grows into E3, which E1's array leaves.
|
||||
// Automatic recalculation lays them out in reading order with each former area still filled:
|
||||
// C1 is #SPILL! and A3 takes A3:E3. A full recalculation after the same edit in manual
|
||||
// calculation gives the same sheet.
|
||||
let build = |manual: bool| {
|
||||
let mut t = T::new();
|
||||
t.set("J1", "2");
|
||||
t.set("C1", "=SEQUENCE(J1)");
|
||||
t.set("A3", "=SEQUENCE(1,J1+1)");
|
||||
t.set("E1", "=SEQUENCE(5-J1)");
|
||||
assert_eq!([t.num("C2"), t.num("C3"), t.num("E3")], [2.0, 3.0, 3.0]);
|
||||
if manual {
|
||||
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
|
||||
}
|
||||
t.set("J1", "4");
|
||||
if manual {
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
}
|
||||
t
|
||||
};
|
||||
let (automatic, full) = (build(false), build(true));
|
||||
assert_eq!(automatic.get("C1"), Value::Error(CellError::Spill));
|
||||
assert_eq!([automatic.num("A3"), automatic.num("C3"), automatic.num("E3")], [1.0, 3.0, 5.0]);
|
||||
for cell in ["A1", "C1", "C2", "C3", "C4", "E1", "E2", "A3", "B3", "C3", "D3", "E3"] {
|
||||
assert_eq!(full.get(cell), automatic.get(cell), "{cell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formulas_reading_an_array_that_loses_a_spill_conflict_read_spill_errors() {
|
||||
// Two arrays of one recalculation want the same empty cell: the one laid out second is
|
||||
|
||||
@@ -444,14 +444,27 @@ pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
|
||||
}
|
||||
}
|
||||
|
||||
/// Number → text the way Excel converts in `&` and `TEXT(x,"General")`-free contexts: up to 15
|
||||
/// significant digits, scientific for very large or very small magnitudes.
|
||||
/// Number → text the way Excel converts in `&`, CONCAT and TEXTJOIN: at most 15 significant
|
||||
/// digits, rounded first; scientific from 1E+15, below 1E-9, and wherever the decimal would be
|
||||
/// longer than 21 characters, not counting the sign (`0.` plus 19 decimals). Excel-verified only
|
||||
/// for positive 15-digit mantissas: `0.0000692361330972509` stays decimal and
|
||||
/// `1.28233995888454E-06` does not, as Excel caches them. The limit for shorter mantissas from
|
||||
/// 1E-6 to 1E-9 (e.g. `0.0000099999999999999` decimal) and for negatives (sign excluded) are
|
||||
/// inferred.
|
||||
pub fn number_to_text(n: f64) -> String {
|
||||
if n == 0.0 || !n.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
// Round to 15 significant digits first, then pick decimal or scientific from the rounded
|
||||
// magnitude, so 999999999999999.5 reads `1E+15`, never a 16-digit integer.
|
||||
let a = n.abs();
|
||||
if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 {
|
||||
let sci = format!("{:.14e}", n);
|
||||
let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
|
||||
let mag: i32 = exp.parse().unwrap_or(0);
|
||||
let sig = mant.bytes().filter(u8::is_ascii_digit).count() - mant.bytes().rev().take_while(|&b| b == b'0').count();
|
||||
// Characters after `0.` for |n| < 1: the leading zeros, then the significant digits.
|
||||
let decimals_below_one = -mag - 1 + sig as i32;
|
||||
if !(-9..15).contains(&mag) || decimals_below_one > 19 {
|
||||
return sci_text(n, 15);
|
||||
}
|
||||
// A value just below 1e15 can round up to 1e15 at 15 significant digits. Only that narrow
|
||||
@@ -460,7 +473,6 @@ pub fn number_to_text(n: f64) -> String {
|
||||
return sci_text(n, 15);
|
||||
}
|
||||
// 15 significant digits, trailing zeros trimmed.
|
||||
let mag = a.log10().floor() as i32;
|
||||
let decimals = (14 - mag).clamp(0, 30) as usize;
|
||||
let s = format!("{:.*}", decimals, n);
|
||||
trim_decimal(&s)
|
||||
@@ -499,9 +511,44 @@ mod tests {
|
||||
assert_eq!(number_to_text(1234567890123456.0), "1.23456789012346E+15");
|
||||
assert_eq!(number_to_text(0.0001), "0.0001");
|
||||
assert_eq!(number_to_text(1e-10), "1E-10");
|
||||
assert_eq!(number_to_text(1e15 - 0.5), "1E+15");
|
||||
assert_eq!(number_to_text(1e15 - 0.1), "1E+15");
|
||||
assert_eq!(number_to_text(-(1e15 - 0.5)), "-1E+15");
|
||||
assert_eq!(number_to_text(999999999999999.0), "999999999999999");
|
||||
assert_eq!(number_to_text(9.999999999999999e-10), "0.000000001");
|
||||
assert_eq!(number_to_text(-9.999999999999999e-10), "-0.000000001");
|
||||
assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333");
|
||||
}
|
||||
|
||||
/// Excel switches to scientific when the 15-digit decimal would be longer than 21 characters
|
||||
/// (`0.` plus 19 decimals). Excel-verified: IMTAN, IMSECH, IMCSCH and IMEXP results cached by
|
||||
/// Excel for Mac in the `formulas` project's test.xlsx (ENGINEERING!S53, R47, S37, V37, V39).
|
||||
#[test]
|
||||
fn number_text_small_magnitudes() {
|
||||
assert_eq!(number_to_text(6.92361330972509e-5), "0.0000692361330972509");
|
||||
assert_eq!(number_to_text(2.41377759972715e-4), "0.000241377759972715");
|
||||
assert_eq!(number_to_text(1.28233995888454e-6), "1.28233995888454E-06");
|
||||
assert_eq!(number_to_text(-4.48088972789593e-6), "-4.48088972789593E-06");
|
||||
assert_eq!(number_to_text(5.98317105631764e-7), "5.98317105631764E-07");
|
||||
assert_eq!(number_to_text(-2.99158552811404e-7), "-2.99158552811404E-07");
|
||||
// Just below powers of ten: the 21-character limit, and the rounded magnitude.
|
||||
assert_eq!(number_to_text(9.99999999999999e-5), "0.0000999999999999999");
|
||||
assert_eq!(number_to_text(9.99999999999999e-6), "9.99999999999999E-06");
|
||||
assert_eq!(number_to_text(9.9999999999999e-6), "0.0000099999999999999");
|
||||
assert_eq!(number_to_text(9.99999999999999e-9), "9.99999999999999E-09");
|
||||
assert_eq!(number_to_text(-9.99999999999999e-9), "-9.99999999999999E-09");
|
||||
assert_eq!(number_to_text(9.99999999999999e-10), "9.99999999999999E-10");
|
||||
assert_eq!(number_to_text(9.999999999999999e-6), "0.00001");
|
||||
assert_eq!(number_to_text(0.00001), "0.00001");
|
||||
assert_eq!(number_to_text(0.000001), "0.000001");
|
||||
assert_eq!(number_to_text(1.5e-9), "0.0000000015");
|
||||
// Large side: 15 significant digits, scientific from 1E+15.
|
||||
assert_eq!(number_to_text(99999999999999.9), "99999999999999.9");
|
||||
assert_eq!(number_to_text(999999999999999.4), "999999999999999");
|
||||
assert_eq!(number_to_text(9999999999999998.0), "1E+16");
|
||||
assert_eq!(number_to_text(9.99999999999999e15), "9.99999999999999E+15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text_rounds_up_to_scientific_boundary() {
|
||||
assert_eq!(number_to_text(999999999999999.9), "1E+15");
|
||||
|
||||
+11
-2
@@ -4,7 +4,9 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value, compare};
|
||||
use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds};
|
||||
use gridcraft_model::{
|
||||
CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Table, Underline, Workbook, default_icon_thresholds,
|
||||
};
|
||||
|
||||
/// The conditional look of one cell.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -20,10 +22,12 @@ pub struct CfLook {
|
||||
pub hide_value: bool,
|
||||
}
|
||||
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates).
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates), and each
|
||||
/// table's visible edges. The grid and print keep one per paint.
|
||||
#[derive(Default)]
|
||||
pub struct CfCache {
|
||||
stats: HashMap<usize, RuleStats>,
|
||||
table_edges: HashMap<RangeRef, crate::tables::ShownEdges>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
@@ -275,6 +279,11 @@ impl CfCache {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// [`crate::tables::shown_edges`] of `t`, found once per cache.
|
||||
pub fn table_edges(&mut self, sh: &Sheet, t: &Table) -> crate::tables::ShownEdges {
|
||||
*self.table_edges.entry(t.range).or_insert_with(|| crate::tables::shown_edges(sh, t))
|
||||
}
|
||||
|
||||
/// Conditional look of `c`, or `None` when no rule applies.
|
||||
pub fn look(&mut self, wb: &Workbook, sheet: usize, c: CellRef) -> Option<CfLook> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
|
||||
@@ -35,7 +35,7 @@ use go_to::go_to_special;
|
||||
#[cfg(test)]
|
||||
use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts};
|
||||
use paste_special::paste_special;
|
||||
pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs};
|
||||
pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs};
|
||||
use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
@@ -566,10 +566,15 @@ fn paste_validations(
|
||||
|
||||
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
|
||||
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> {
|
||||
rewrite_all_formulas_many(wb, target, std::slice::from_ref(e))
|
||||
}
|
||||
|
||||
/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once.
|
||||
pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> {
|
||||
use gridcraft_formula::adjust::Edit;
|
||||
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
|
||||
// (a cut moves its arrays itself).
|
||||
let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
@@ -577,16 +582,29 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
if keys.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let on_target = moves_arrays && host.eq_ignore_ascii_case(target);
|
||||
let on_target = host.eq_ignore_ascii_case(target);
|
||||
let Some(sheet) = wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
// Borrows the tree and copies and prints only the formulas the edit changes. A formula
|
||||
// the edit leaves alone keeps its stored text, even if that text is not canonical.
|
||||
let Some(new) = f.with_expr(|x| gridcraft_formula::adjust::adjust_if_changed(x, &host, target, e)) else { continue };
|
||||
let array = match f.array {
|
||||
Some(a) if on_target => crate::cmd::sheet::map_range(a, e),
|
||||
a => a,
|
||||
// Borrows the tree and copies and prints only the formulas the edits change. A formula
|
||||
// the edits leave alone keeps its stored text, even if that text is not canonical.
|
||||
let Some(new) = f.with_expr(|x| {
|
||||
let mut cur: Option<gridcraft_formula::Expr> = None;
|
||||
for e in edits {
|
||||
if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) {
|
||||
cur = Some(n);
|
||||
}
|
||||
}
|
||||
cur
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let mut array = f.array;
|
||||
for e in edits {
|
||||
array = match array {
|
||||
Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e),
|
||||
a => a,
|
||||
};
|
||||
}
|
||||
let nf = match new {
|
||||
Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) },
|
||||
None if array != f.array => Formula { array, ..(*f).clone() },
|
||||
@@ -600,12 +618,12 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
for n in wb.names.iter_mut() {
|
||||
if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) {
|
||||
// Names are workbook-level: unqualified refs don't occur; qualified ones adjust.
|
||||
let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e);
|
||||
let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e));
|
||||
n.formula = gridcraft_formula::print(&new);
|
||||
}
|
||||
}
|
||||
rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e));
|
||||
rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e))
|
||||
rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)));
|
||||
rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)))
|
||||
}
|
||||
|
||||
/// Runs `f` over every reference a floating object holds (a chart's series values, categories,
|
||||
|
||||
@@ -177,7 +177,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
let mut pics = PicCache::default();
|
||||
for lay in layouts {
|
||||
let Some(sh) = wb.sheet(lay.sheet) else { continue };
|
||||
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
|
||||
let mut cf = crate::cf::CfCache::new();
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
|
||||
|
||||
@@ -25,12 +25,12 @@ pub(super) struct Look {
|
||||
pub(super) cf: Option<crate::cf::CfLook>,
|
||||
}
|
||||
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option<crate::cf::CfCache>) -> Look {
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut crate::cf::CfCache) -> Look {
|
||||
let mut style = match sh.table_at(c) {
|
||||
Some(t) => crate::tables::table_cell_style(wb, si, t, c),
|
||||
Some(t) => crate::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c),
|
||||
None => wb.styles.get(sh.style_id(c)).clone(),
|
||||
};
|
||||
let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c));
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(st) = cfl.as_ref().and_then(|l| l.style.as_ref()) {
|
||||
if st.align.reading_order.is_some() {
|
||||
style.align.reading_order = st.align.reading_order;
|
||||
@@ -319,7 +319,7 @@ impl<'a> Covered<'a> {
|
||||
}
|
||||
|
||||
/// Draws the cells of a block: fills, gridlines, data bars, borders and text.
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Option<crate::cf::CfCache>) {
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
|
||||
let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0));
|
||||
let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by);
|
||||
if bw <= 0.0 || bh <= 0.0 {
|
||||
|
||||
@@ -242,15 +242,20 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
/// Rewrites every formula reference (chart series included), sparkline source and PivotTable
|
||||
/// source for a structural edit on `target`.
|
||||
pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
cx.edits.push((target.to_string(), e.clone()));
|
||||
rewrite_many(cx, target, std::slice::from_ref(e))
|
||||
}
|
||||
|
||||
/// [`rewrite`] for several edits applied in order, parsing each reference once.
|
||||
fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> {
|
||||
cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone())));
|
||||
let wb = &mut cx.wb;
|
||||
super::edit::rewrite_all_formulas(wb, target, e)?;
|
||||
super::edit::rewrite_all_formulas_many(wb, target, edits)?;
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let Some(sh) = wb.sheet_mut(si) else { continue };
|
||||
let fix = |text: &str| -> String {
|
||||
match gridcraft_formula::parse(text) {
|
||||
Ok(expr) => gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)),
|
||||
Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))),
|
||||
Err(_) => text.to_string(),
|
||||
}
|
||||
};
|
||||
@@ -263,7 +268,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
let body = pt.source.trim().trim_start_matches('=');
|
||||
if let Ok(expr) = gridcraft_formula::parse(body) {
|
||||
let before = gridcraft_formula::print(&expr);
|
||||
let after = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e));
|
||||
let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e)));
|
||||
if after != before {
|
||||
pt.source = after;
|
||||
}
|
||||
@@ -378,23 +383,21 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
|
||||
cx.protection_checked = true;
|
||||
// Last area first, so the earlier ones keep their positions.
|
||||
for (at, count) in areas {
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let block = match axis {
|
||||
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
|
||||
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
|
||||
};
|
||||
sh.take_cells(block);
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
|
||||
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
|
||||
}
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// Cells move once, past every deleted area above or left of them.
|
||||
let ascending: Vec<(u32, u32)> = areas.iter().rev().copied().collect();
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.delete_rows(&ascending),
|
||||
Axis::Cols => sh.cells.delete_cols(&ascending),
|
||||
}
|
||||
// Last area first, so the earlier ones keep their positions.
|
||||
for &(at, count) in &areas {
|
||||
shift_sheet_features(sh, axis, at, count, false);
|
||||
}
|
||||
rewrite(cx, &name, &Edit::Delete { axis, at, count })?;
|
||||
}
|
||||
let edits: Vec<Edit> = areas.iter().map(|&(at, count)| Edit::Delete { axis, at, count }).collect();
|
||||
rewrite_many(cx, &name, &edits)?;
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})?;
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Mutex;
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Sheet, Workbook};
|
||||
use gridcraft_numfmt::{Formatted, NumberFormat, format_value};
|
||||
use gridcraft_numfmt::{Formatted, NumberFormat, format_value, format_value_full};
|
||||
|
||||
/// Parsed number formats are cached by code.
|
||||
pub(crate) fn parsed(code: &str) -> NumberFormat {
|
||||
@@ -116,7 +116,8 @@ pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
|
||||
wb.styles.get(sheet.style_id(at)).protection.hidden
|
||||
}
|
||||
|
||||
/// The text a cell shows (full precision General; the grid narrows General to fit the column).
|
||||
/// The text a cell shows (General up to the 11-character cell width; the grid narrows General
|
||||
/// further to fit the column).
|
||||
pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
if sheet.show_formulas
|
||||
&& let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref())
|
||||
@@ -124,20 +125,35 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
{
|
||||
return format!("={}", f.text);
|
||||
}
|
||||
value_text(wb, sheet, c)
|
||||
shown_text(wb, sheet, c)
|
||||
}
|
||||
|
||||
/// A cell's value with its number format applied, independent of column width: no `#####`
|
||||
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result.
|
||||
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number
|
||||
/// shown as General (also through a coloured or sectioned General, or a Text format) is written
|
||||
/// as [`format_value_full`] writes it, never with an exponent: `&`'s 15 significant digits below
|
||||
/// 1E+15 (`124412140710`, not `1.24412E+11`), the shortest round-trip digits from 1E+15 (every
|
||||
/// integer below 1e16 exactly). Excel writes the cell display.
|
||||
pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let style = wb.styles.get(sheet.style_id(c));
|
||||
with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system))
|
||||
}
|
||||
|
||||
/// A cell's value through its number format, General at the 11-character cell width.
|
||||
fn shown_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let style = wb.styles.get(sheet.style_id(c));
|
||||
value_text_as(wb, &sheet.value(c), style.num_fmt.as_str())
|
||||
}
|
||||
|
||||
/// [`value_text`] for a value and a format code given apart from a cell (print takes the code
|
||||
/// from the cell's effective look, which a conditional format can override).
|
||||
/// A value through a format code given apart from a cell, as a cell shows it (General at the
|
||||
/// 11-character cell width). Print takes the code from the cell's effective look, which a
|
||||
/// conditional format can override.
|
||||
pub fn value_text_as(wb: &Workbook, v: &Value, code: &str) -> String {
|
||||
let f = format(v, code, wb);
|
||||
with_fill_space(format(v, code, wb))
|
||||
}
|
||||
|
||||
/// The formatted text with a single space where a `*x` repeat fill would expand.
|
||||
fn with_fill_space(f: Formatted) -> String {
|
||||
match f.fill {
|
||||
Some((_, pos)) => {
|
||||
let mut t = f.text;
|
||||
|
||||
+12
-13
@@ -558,20 +558,13 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
|
||||
/// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all
|
||||
/// characters in each cell" (Microsoft Support, *Excel formatting and features that are not
|
||||
/// transferred to other file formats*): number formats applied, never column-width `#####`.
|
||||
/// One intentional difference: a number shown as General is not narrowed to the cell width and
|
||||
/// never gets an exponent (`gridcraft_numfmt::format_value_full`). Below 1E+15 it is written as
|
||||
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
|
||||
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
|
||||
/// that `&` writes in scientific notation as their 15 digits in full.
|
||||
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| {
|
||||
// General's grid-width formatting rounds large identifiers to scientific notation.
|
||||
// Delimited files have no column width, so preserve the whole numeric value instead.
|
||||
if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General")
|
||||
&& let gridcraft_core::Value::Number(number) = sh.value(c)
|
||||
&& number.is_finite()
|
||||
{
|
||||
number.to_string()
|
||||
} else {
|
||||
crate::display::value_text(wb, sh, c)
|
||||
}
|
||||
})
|
||||
.map_err(|e| EngineError::Other(e.to_string()))
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
|
||||
@@ -1062,6 +1055,12 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
// A brand-new file gets the restrictive default: no group/other write, whatever the umask.
|
||||
#[cfg(unix)]
|
||||
if prior.is_none() {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o644);
|
||||
}
|
||||
let mut f = opts.open(&tmp).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
|
||||
@@ -78,6 +78,34 @@ fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() {
|
||||
assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn fresh_save_drops_group_and_other_write_under_a_permissive_umask() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::env::var_os("GRIDCRAFT_UMASK_CHILD").is_none() {
|
||||
// Re-run this test in a child shell whose umask is 0002.
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let status = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("umask 0002 && exec \"$0\" --exact io::tests::fresh_save_drops_group_and_other_write_under_a_permissive_umask")
|
||||
.arg(exe)
|
||||
.env("GRIDCRAFT_UMASK_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-umask-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fresh = dir.join("new.xlsx");
|
||||
write_file(fresh.to_str().unwrap(), b"v").unwrap();
|
||||
let mode = std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(mode & 0o022 == 0, "mode {mode:o}");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn open_refuses_directories_and_unknowable_lengths() {
|
||||
@@ -586,9 +614,80 @@ fn delimited_exports_preserve_general_precision_and_explicit_number_formats() {
|
||||
sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() });
|
||||
// Every integer below 1e16 that f64 holds (also 2^53 and the even integers above it) keeps
|
||||
// every digit; larger numbers keep the shortest digits that read back as the same value,
|
||||
// and a number `&` would write with an exponent is written out in full, so reopening the
|
||||
// file can't give it a scientific format that then rounds it on the next save.
|
||||
let cells = [
|
||||
(1234567890123456.0, "1234567890123456"),
|
||||
(-9007199254740991.0, "-9007199254740991"),
|
||||
(9007199254740992.0, "9007199254740992"),
|
||||
(9007199254740994.0, "9007199254740994"),
|
||||
(9123456789012346.0, "9123456789012346"),
|
||||
(-9999999999999998.0, "-9999999999999998"),
|
||||
(12345678901234567.0, "12345678901234568"),
|
||||
(1e20, "100000000000000000000"),
|
||||
(1e15 - 0.5, "999999999999999.5"),
|
||||
(1.0 / 3.0 * 1e-6, "0.000000333333333333333"),
|
||||
(1.23456789012346e-10, "0.000000000123456789012346"),
|
||||
];
|
||||
for (col, (n, _)) in cells.iter().enumerate() {
|
||||
sheet.set_cell(CellRef::new(0, col as u32 + 3), Cell { value: Value::Number(*n), ..Default::default() });
|
||||
}
|
||||
for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] {
|
||||
let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap();
|
||||
assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n"));
|
||||
let tail: Vec<&str> = cells.iter().map(|(_, text)| *text).collect();
|
||||
assert_eq!(output, format!("124412140710{s}1.23456789012345{s}1.24E+11{s}{}\r\n", tail.join(separator), s = separator));
|
||||
// Reopening the file and saving it again changes nothing.
|
||||
let (reopened, _) = open_bytes(path, output.as_bytes()).unwrap();
|
||||
assert_eq!(String::from_utf8(save_bytes(&reopened, path).unwrap()).unwrap(), output);
|
||||
}
|
||||
}
|
||||
|
||||
/// A number shown as General is written as `&` converts it (15 significant digits), whatever
|
||||
/// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell
|
||||
/// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive
|
||||
/// (integers below 1e16 keep all their digits, and nothing gets an exponent; see the test above).
|
||||
#[test]
|
||||
fn delimited_exports_write_general_numbers_as_text_converts_them() {
|
||||
use gridcraft_core::Value;
|
||||
use gridcraft_model::{Cell, NumFmt, StyleId};
|
||||
let mut wb = Workbook::new();
|
||||
let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
|
||||
let (blue, signed, red, text, unit) =
|
||||
(styled("[Blue]General"), styled("General;-General"), styled("General;[Red]-General"), styled("@"), styled("General\" mm\""));
|
||||
let code = 124412140710.0;
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let cells = [
|
||||
(Value::Number(1.0 / 3.0), StyleId::DEFAULT),
|
||||
(Value::Number(0.1 + 0.2), StyleId::DEFAULT),
|
||||
(Value::Number(1e20), StyleId::DEFAULT),
|
||||
(Value::Number(code), blue),
|
||||
(Value::Number(9007199254740994.0), blue),
|
||||
(Value::Number(-1.0 / 3.0), blue),
|
||||
(Value::Number(-code), signed),
|
||||
(Value::Number(-code), red),
|
||||
(Value::Number(code), text),
|
||||
(Value::Number(code), unit),
|
||||
];
|
||||
for (col, (value, style)) in cells.into_iter().enumerate() {
|
||||
sh.set_cell(CellRef::new(0, col as u32), Cell { value, formula: None, py: None, style });
|
||||
}
|
||||
for (path, sep) in [("out.csv", ","), ("out.txt", "\t")] {
|
||||
let output = String::from_utf8(save_bytes(&wb, path).unwrap()).unwrap();
|
||||
let expected = [
|
||||
"0.333333333333333",
|
||||
"0.3",
|
||||
"100000000000000000000",
|
||||
"124412140710",
|
||||
"9007199254740994",
|
||||
"-0.333333333333333",
|
||||
"-124412140710",
|
||||
"-124412140710",
|
||||
"124412140710",
|
||||
"124412140710 mm",
|
||||
];
|
||||
assert_eq!(output, format!("{}\r\n", expected.join(sep)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+252
-86
@@ -2,7 +2,7 @@
|
||||
//! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip).
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Cell, Color, Fill, Formula, PatternType, Style, Table, Workbook};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Borders, Cell, Color, Fill, Formula, PatternType, Sheet, Style, Table, Workbook};
|
||||
|
||||
/// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2).
|
||||
pub fn parse_style_name(name: &str) -> (&'static str, u32) {
|
||||
@@ -22,113 +22,279 @@ fn accent_for(n: u32) -> Option<u8> {
|
||||
if k == 0 { None } else { Some(3 + k as u8) }
|
||||
}
|
||||
|
||||
/// Header/band/body colours for a table style.
|
||||
/// Fills, text colours and thin lines of a table style, per part of the table (the recipes in
|
||||
/// plan/excel/table-style-spec.json). Band 1 is the first data row; unbanded rows use band 2.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TableLook {
|
||||
pub header_fill: Option<Color>,
|
||||
pub header_font: Color,
|
||||
pub header_bold: bool,
|
||||
pub band_fill: Option<Color>,
|
||||
pub body_fill: Option<Color>,
|
||||
pub line: Option<Color>,
|
||||
pub total_top: Option<Color>,
|
||||
pub band1: Option<Color>,
|
||||
pub band2: Option<Color>,
|
||||
pub body_font: Color,
|
||||
pub top: Option<Color>,
|
||||
pub header_bottom: Option<Color>,
|
||||
pub inner_h: Option<Color>,
|
||||
pub inner_v: Option<Color>,
|
||||
pub sides: Option<Color>,
|
||||
pub bottom: Option<Color>,
|
||||
/// The totals row's double top rule (the gallery doesn't show totals).
|
||||
pub total_top: Color,
|
||||
}
|
||||
|
||||
pub fn look(style: &str) -> TableLook {
|
||||
let (fam, n) = parse_style_name(style);
|
||||
let acc = accent_for(n);
|
||||
let base = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(1, if tint == 0 { 0 } else { tint.clamp(-1000, 1000) }),
|
||||
// An accent tint, or the neutral column's colour.
|
||||
let a = |tint: i16, neutral: Color| acc.map_or(neutral, |a| Color::Theme(a, tint));
|
||||
let (black, white) = (Color::Theme(1, 0), Color::Theme(0, 0));
|
||||
let (grey, mid_grey) = (Color::Theme(0, -150), Color::Theme(0, -350));
|
||||
let main = a(0, black);
|
||||
let plain = TableLook {
|
||||
header_fill: None,
|
||||
header_font: black,
|
||||
band1: None,
|
||||
band2: None,
|
||||
body_font: black,
|
||||
top: None,
|
||||
header_bottom: None,
|
||||
inner_h: None,
|
||||
inner_v: None,
|
||||
sides: None,
|
||||
bottom: None,
|
||||
total_top: main,
|
||||
};
|
||||
let neutral_light = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(0, -((1000 - tint).clamp(0, 1000) / 6)),
|
||||
};
|
||||
match fam {
|
||||
"Light" => {
|
||||
let group = (n - 1) / 7; // 0: lines only, 1: banded header line, 2: grid
|
||||
match (fam, n.saturating_sub(1) / 7) {
|
||||
("Light", 0) => {
|
||||
let text = a(-250, black);
|
||||
let line = Some(main);
|
||||
TableLook { header_font: text, body_font: text, band1: Some(a(800, grey)), top: line, header_bottom: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", 1) => {
|
||||
let line = Some(main);
|
||||
TableLook { header_fill: line, header_font: white, top: line, inner_h: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", _) => {
|
||||
let line = Some(main);
|
||||
TableLook { band1: Some(a(800, grey)), top: line, header_bottom: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 0) => {
|
||||
let line = Some(a(400, black));
|
||||
TableLook { header_fill: Some(main), header_font: white, band1: Some(a(800, grey)), top: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 1) => TableLook {
|
||||
header_fill: Some(main),
|
||||
header_font: white,
|
||||
band1: Some(a(600, mid_grey)),
|
||||
band2: Some(a(800, grey)),
|
||||
header_bottom: Some(white),
|
||||
inner_v: Some(white),
|
||||
..plain
|
||||
},
|
||||
("Medium", 2) => {
|
||||
// Accent header over neutral grey bands and black rules; the neutral style adds a grid.
|
||||
let line = Some(black);
|
||||
let grid = if acc.is_none() { line } else { None };
|
||||
let header_fill = Some(main);
|
||||
TableLook {
|
||||
header_fill: None,
|
||||
header_font: if group == 0 { base(-250) } else { Color::Auto },
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: Some(base(0)),
|
||||
total_top: Some(base(0)),
|
||||
header_fill,
|
||||
header_font: white,
|
||||
band1: Some(grey),
|
||||
top: line,
|
||||
header_bottom: line,
|
||||
inner_v: grid,
|
||||
sides: grid,
|
||||
bottom: line,
|
||||
total_top: black,
|
||||
..plain
|
||||
}
|
||||
}
|
||||
"Dark" => TableLook {
|
||||
header_fill: Some(Color::Theme(1, 0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(base(-250)),
|
||||
body_fill: Some(base(0)),
|
||||
line: None,
|
||||
total_top: Some(Color::Theme(0, 0)),
|
||||
},
|
||||
_ => TableLook {
|
||||
header_fill: Some(base(0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: if (n - 1) / 7 == 0 { None } else { Some(base(400)) },
|
||||
total_top: Some(base(0)),
|
||||
("Medium", _) => {
|
||||
let line = Some(a(400, black));
|
||||
let pale = Some(a(800, grey));
|
||||
TableLook { header_fill: pale, band1: Some(a(600, mid_grey)), band2: pale, top: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Dark", 0) => TableLook {
|
||||
header_fill: Some(black),
|
||||
header_font: white,
|
||||
band1: Some(a(-250, Color::Theme(1, 250))),
|
||||
band2: Some(a(0, Color::Theme(1, 450))),
|
||||
body_font: white,
|
||||
header_bottom: Some(white),
|
||||
total_top: white,
|
||||
..plain
|
||||
},
|
||||
_ if n == 8 => TableLook { header_fill: Some(black), header_font: white, band1: Some(mid_grey), band2: Some(grey), ..plain },
|
||||
_ => {
|
||||
// Dark 9-11 pair accents 1+2, 3+4 and 5+6: the header takes the even one.
|
||||
let k = n.clamp(9, 11) as u8 - 8;
|
||||
let (head, body) = (Color::Theme(3 + 2 * k, 0), 2 + 2 * k);
|
||||
let band1 = Some(Color::Theme(body, 600));
|
||||
TableLook { header_fill: Some(head), header_font: white, band1, band2: Some(Color::Theme(body, 800)), total_top: head, ..plain }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills/fonts win).
|
||||
/// Which parts of a table are on (the Table Style Options checkboxes).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TableParts {
|
||||
pub header_row: bool,
|
||||
pub totals_row: bool,
|
||||
pub banded_rows: bool,
|
||||
pub banded_cols: bool,
|
||||
pub first_col: bool,
|
||||
pub last_col: bool,
|
||||
}
|
||||
|
||||
impl TableParts {
|
||||
pub fn of(t: &Table) -> TableParts {
|
||||
TableParts {
|
||||
header_row: t.header_row,
|
||||
totals_row: t.totals_row,
|
||||
banded_rows: t.banded_rows,
|
||||
banded_cols: t.banded_cols,
|
||||
first_col: t.first_col,
|
||||
last_col: t.last_col,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a table style paints on one cell of a `rows` x `cols` table (`row`, `col` from its
|
||||
/// top-left). Each line has one owner: a horizontal line is a cell's bottom (top only on the
|
||||
/// first row and the totals row), a vertical one a cell's right (left only on the first column).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CellLook {
|
||||
pub fill: Option<Color>,
|
||||
pub font: Color,
|
||||
pub bold: bool,
|
||||
pub borders: Borders,
|
||||
}
|
||||
|
||||
pub fn cell_look(lk: &TableLook, p: TableParts, row: u32, col: u32, rows: u32, cols: u32) -> CellLook {
|
||||
let last_row = rows.saturating_sub(1);
|
||||
let last_col = cols.saturating_sub(1);
|
||||
let is_header = p.header_row && row == 0;
|
||||
let is_total = p.totals_row && row == last_row && !is_header;
|
||||
let thin = |c: Option<Color>| c.map(|color| BorderLine { style: BorderStyle::Thin, color }).unwrap_or_default();
|
||||
let mut b = Borders::default();
|
||||
if row == 0 {
|
||||
b.top = thin(lk.top);
|
||||
}
|
||||
b.bottom = thin(if row == last_row {
|
||||
lk.bottom
|
||||
} else if is_header {
|
||||
lk.header_bottom
|
||||
} else if p.totals_row && row.saturating_add(1) == last_row {
|
||||
None // the totals row draws its own top rule
|
||||
} else {
|
||||
lk.inner_h
|
||||
});
|
||||
if col == 0 {
|
||||
b.left = thin(lk.sides);
|
||||
}
|
||||
b.right = thin(if col == last_col { lk.sides } else { lk.inner_v });
|
||||
let mut out = CellLook { borders: b, font: lk.body_font, ..Default::default() };
|
||||
if is_header {
|
||||
out.fill = lk.header_fill;
|
||||
out.font = lk.header_font;
|
||||
out.bold = true;
|
||||
} else if is_total {
|
||||
out.fill = lk.band2;
|
||||
out.bold = true;
|
||||
out.borders.top = BorderLine { style: BorderStyle::Double, color: lk.total_top };
|
||||
} else {
|
||||
let data_row = row.saturating_sub(p.header_row as u32);
|
||||
let band1 = (p.banded_rows && data_row.is_multiple_of(2)) || (p.banded_cols && col.is_multiple_of(2));
|
||||
out.fill = if band1 { lk.band1 } else { lk.band2 };
|
||||
}
|
||||
if (p.first_col && col == 0) || (p.last_col && col == last_col) {
|
||||
out.bold = true;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills, fonts and
|
||||
/// borders win).
|
||||
pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style {
|
||||
let own = wb.sheet(sheet).map(|sh| wb.styles.get(sh.style_id(c)).clone()).unwrap_or_default();
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let rows = end.row.saturating_sub(start.row).saturating_add(1);
|
||||
let cols = end.col.saturating_sub(start.col).saturating_add(1);
|
||||
let lk = cell_look(&look(&t.style), TableParts::of(t), c.row.saturating_sub(start.row), c.col.saturating_sub(start.col), rows, cols);
|
||||
let mut s = own.clone();
|
||||
let lk = look(&t.style);
|
||||
let is_header = t.header_row && c.row == t.range.start.row;
|
||||
let is_total = t.totals_row && c.row == t.range.end.row;
|
||||
let data_row = c.row.saturating_sub(t.range.start.row + t.header_row as u32);
|
||||
let data_col = c.col - t.range.start.col;
|
||||
let explicit_fill = own.fill.pattern != PatternType::None;
|
||||
if is_header {
|
||||
if let Some(f) = lk.header_fill
|
||||
&& !explicit_fill
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.header_font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.header_bold;
|
||||
if let Some(l) = lk.line {
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
}
|
||||
} else if is_total {
|
||||
s.font.bold = true;
|
||||
if let Some(l) = lk.total_top {
|
||||
s.borders.top = BorderLine { style: BorderStyle::Double, color: l };
|
||||
}
|
||||
} else {
|
||||
let band = (t.banded_rows && data_row.is_multiple_of(2)) || (t.banded_cols && data_col.is_multiple_of(2));
|
||||
if !explicit_fill {
|
||||
if band {
|
||||
if let Some(f) = lk.band_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
} else if let Some(f) = lk.body_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
}
|
||||
if let Some(l) = lk.line
|
||||
&& t.style.contains("Light")
|
||||
&& c.row == t.range.end.row
|
||||
{
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
if let Some(f) = lk.fill
|
||||
&& own.fill.pattern == PatternType::None
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.bold;
|
||||
for (side, line) in [
|
||||
(&mut s.borders.top, lk.borders.top),
|
||||
(&mut s.borders.bottom, lk.borders.bottom),
|
||||
(&mut s.borders.left, lk.borders.left),
|
||||
(&mut s.borders.right, lk.borders.right),
|
||||
] {
|
||||
if side.is_none() {
|
||||
*side = line;
|
||||
}
|
||||
}
|
||||
if (t.first_col && c.col == t.range.start.col) || (t.last_col && c.col == t.range.end.col) {
|
||||
s.font.bold = true;
|
||||
s
|
||||
}
|
||||
|
||||
/// A table's first and last visible row and column (hidden or filtered lines skipped).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ShownEdges {
|
||||
pub top: u32,
|
||||
pub bottom: u32,
|
||||
pub left: u32,
|
||||
pub right: u32,
|
||||
}
|
||||
|
||||
/// Finds [`ShownEdges`]. It scans the hidden lines at each edge, so the grid and print call it
|
||||
/// once per table per paint (through [`crate::cf::CfCache::table_edges`]), not once per cell.
|
||||
pub fn shown_edges(sh: &Sheet, t: &Table) -> ShownEdges {
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let row_shown = |r: &u32| sh.row_height(*r) > 0.0;
|
||||
let col_shown = |k: &u32| sh.col_width(*k) > 0.0;
|
||||
// With every row (or column) hidden, each cell takes both edges' lines; nothing is drawn.
|
||||
ShownEdges {
|
||||
top: (start.row..=end.row).find(row_shown).unwrap_or(end.row),
|
||||
bottom: (start.row..=end.row).rev().find(row_shown).unwrap_or(start.row),
|
||||
left: (start.col..=end.col).find(col_shown).unwrap_or(end.col),
|
||||
right: (start.col..=end.col).rev().find(col_shown).unwrap_or(start.col),
|
||||
}
|
||||
if t.style.starts_with("TableStyleDark") && !is_header && own.font.color == Color::Auto {
|
||||
s.font.color = Color::Theme(0, 0);
|
||||
}
|
||||
|
||||
/// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the
|
||||
/// table's outer frame follows hidden rows and columns: the last visible row takes the table's
|
||||
/// bottom line, the last visible column its right side, and the first visible row and column its
|
||||
/// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while
|
||||
/// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is.
|
||||
pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, e: ShownEdges, c: CellRef) -> Style {
|
||||
let mut s = table_cell_style(wb, sheet, t, c);
|
||||
let Some(sh) = wb.sheet(sheet) else { return s };
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let below = c.row < end.row && c.row >= e.bottom;
|
||||
let above = c.row > start.row && c.row <= e.top;
|
||||
let right = c.col < end.col && c.col >= e.right;
|
||||
let left = c.col > start.col && c.col <= e.left;
|
||||
if !(below || above || right || left) {
|
||||
return s;
|
||||
}
|
||||
let own = wb.styles.get(sh.style_id(c)).borders;
|
||||
if below && own.bottom.is_none() {
|
||||
s.borders.bottom = table_cell_style(wb, sheet, t, CellRef::new(end.row, c.col)).borders.bottom;
|
||||
}
|
||||
if above && own.top.is_none() {
|
||||
s.borders.top = table_cell_style(wb, sheet, t, CellRef::new(start.row, c.col)).borders.top;
|
||||
}
|
||||
if right && own.right.is_none() {
|
||||
s.borders.right = table_cell_style(wb, sheet, t, CellRef::new(c.row, end.col)).borders.right;
|
||||
}
|
||||
if left && own.left.is_none() {
|
||||
s.borders.left = table_cell_style(wb, sheet, t, CellRef::new(c.row, start.col)).borders.left;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -869,6 +869,65 @@ fn deleting_a_multi_area_row_selection_removes_every_area_and_undoes_once() {
|
||||
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "C1")), (Value::Number(2.0), Value::Number(4.0), Value::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::disallowed_methods)] // native-only test: timing the two deletes
|
||||
fn deleting_many_separate_rows_takes_about_as_long_as_one_block() {
|
||||
// #2287: every 10th row of a 12,000-row sheet, as 1,200 single-row areas.
|
||||
let (rows, step) = (12_000u32, 10u32);
|
||||
let values: Vec<serde_json::Value> = (0..rows).map(|r| json!([r, r + 100_000, r + 200_000])).collect();
|
||||
let deleted = |r: u32| r >= 1 && (r - 1).is_multiple_of(step);
|
||||
let list = (0..rows).filter(|&r| deleted(r)).map(|r| format!("{0}:{0}", r + 1)).collect::<Vec<_>>().join(",");
|
||||
let build = || {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1", "input": format!("=SUM(A1:A{rows})")})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E3", "input": "=B25"})).unwrap();
|
||||
s
|
||||
};
|
||||
let mut block = build();
|
||||
let t = std::time::Instant::now();
|
||||
block.execute("home.deleteRows", json!({"rows": format!("2:{}", rows / step + 1)})).unwrap();
|
||||
let block_time = t.elapsed();
|
||||
|
||||
let mut s = build();
|
||||
let t = std::time::Instant::now();
|
||||
s.execute("home.deleteRows", json!({"rows": list})).unwrap();
|
||||
let separate_time = t.elapsed();
|
||||
|
||||
let kept: Vec<u32> = (0..rows).filter(|&r| !deleted(r)).collect();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert_eq!(sh.used_range().unwrap().end.row as usize, kept.len() - 1);
|
||||
for (i, r) in kept.iter().enumerate() {
|
||||
assert_eq!(sh.value(CellRef::new(i as u32, 0)), Value::Number(*r as f64));
|
||||
assert_eq!(sh.value(CellRef::new(i as u32, 2)), Value::Number((*r + 200_000) as f64));
|
||||
}
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "E1"})).unwrap()["formula"], format!("=SUM(A1:A{})", kept.len()));
|
||||
// B25 loses rows 2, 12 and 22 above it; the formula itself moves from E3 to E2.
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "E2"})).unwrap()["formula"], "=B22");
|
||||
assert!(
|
||||
separate_time < block_time * 20 + std::time::Duration::from_millis(500),
|
||||
"separate rows took {separate_time:?}, one block took {block_time:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_many_separate_columns_matches_per_area_result() {
|
||||
let mut s = s();
|
||||
let values: Vec<serde_json::Value> = (0..50).map(|r| json!((0..40).map(|c| r * 100 + c).collect::<Vec<_>>())).collect();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A60", "input": "=SUM(A1:AN1)+H2"})).unwrap();
|
||||
// Columns B, E, H (refs) and F:G.
|
||||
s.execute("home.deleteColumns", json!({"cols": "B:B,E:E,H:H,F:G"})).unwrap();
|
||||
let kept: Vec<u32> = (0..40).filter(|c| ![1, 4, 5, 6, 7].contains(c)).collect();
|
||||
for r in 0..50u32 {
|
||||
for (i, c) in kept.iter().enumerate() {
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(r, i as u32)), Value::Number((r * 100 + c) as f64));
|
||||
}
|
||||
}
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A60"})).unwrap()["formula"], "=SUM(A1:AI1)+#REF!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_columns_reorders_without_overwriting_and_undoes_once() {
|
||||
let mut s = s();
|
||||
@@ -3078,9 +3137,10 @@ fn overlapping_spills_keep_the_one_that_exists_whichever_anchor_is_first() {
|
||||
#[test]
|
||||
fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
|
||||
use gridcraft_core::CellError::Spill;
|
||||
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, takes
|
||||
// its cells, shrinks back and lets it spill again, then the steps are undone, redone, edited
|
||||
// inside the contested area and cleared. Every state must match a full recalc.
|
||||
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, is
|
||||
// #SPILL! because E10 holds those cells (as in Excel), shrinks back and spills again, then the
|
||||
// steps are undone, redone, edited inside the contested area and cleared. Every state must
|
||||
// match a full recalc.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "H1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F8", "input": "=SEQUENCE(H1)"})).unwrap();
|
||||
@@ -3102,18 +3162,18 @@ fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
|
||||
s.execute(id, params.clone()).unwrap();
|
||||
assert_matches_full_recalc(&s);
|
||||
if i == 0 {
|
||||
// Both held a spill: reading order gives F8 the cells.
|
||||
assert_eq!(v(&s, "F12"), Value::Number(5.0));
|
||||
assert_eq!(v(&s, "E10"), Value::Error(Spill));
|
||||
// Both held a spill: E10 holds F10, so it keeps it and F8 is blocked.
|
||||
assert_eq!(v(&s, "F8"), Value::Error(Spill));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 2 {
|
||||
assert_eq!(v(&s, "E10"), Value::Number(10.0));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 3 {
|
||||
// Undone back to the grown F8.
|
||||
assert_eq!(v(&s, "F12"), Value::Number(5.0));
|
||||
assert_eq!(v(&s, "E10"), Value::Error(Spill));
|
||||
// Undone back to the grown F8, blocked again.
|
||||
assert_eq!(v(&s, "F8"), Value::Error(Spill));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 8 {
|
||||
assert_eq!((v(&s, "F8"), v(&s, "E10"), v(&s, "F9")), (Value::Empty, Value::Empty, Value::Empty));
|
||||
@@ -3355,6 +3415,21 @@ fn a_spill_that_goes_away_unblocks_another() {
|
||||
assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contested_spill_area_stays_with_its_array_after_reopening() {
|
||||
// F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file
|
||||
// can only cache #VALUE! for it; reopening (which recalculates) used to hand the area to F13
|
||||
// for coming first in reading order.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap();
|
||||
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
s.execute("file.open", json!({"name": "contested.xlsx", "base64": saved["base64"]})).unwrap();
|
||||
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
|
||||
assert_eq!((v(&s, "C14"), v(&s, "G14"), v(&s, "I14")), (Value::Number(1.0), Value::Number(5.0), Value::Number(7.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_reading_another_arrays_spill_is_updated() {
|
||||
// G5 is evaluated before D11 in the same pass, so it first reads D11's old spill.
|
||||
@@ -3379,6 +3454,19 @@ fn indirect_reads_a_spill_laid_out_in_the_same_pass() {
|
||||
assert_eq!(v(&s, "E5"), Value::Number(9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_rows_lays_out_spills_where_the_formulas_moved() {
|
||||
// D1's array grows with the inserted rows to D1:D10 and C10's array moves down to C12:E14:
|
||||
// the area C10:E12 it filled before the insertion blocks neither of them.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(ROWS(A2:A9))"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C8", "input": "=1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C10", "input": "=SEQUENCE(3,3)"})).unwrap();
|
||||
s.execute("home.insertRows", json!({"rows": "3:4"})).unwrap();
|
||||
assert_eq!((v(&s, "D1"), v(&s, "D10")), (Value::Number(1.0), Value::Number(10.0)));
|
||||
assert_eq!((v(&s, "C12"), v(&s, "D12"), v(&s, "E14")), (Value::Number(1.0), Value::Number(2.0), Value::Number(9.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_survives_empty_params() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -35,7 +35,7 @@ use std::sync::Arc;
|
||||
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, col_to_letters};
|
||||
use gridcraft_engine::calc::Calc;
|
||||
use gridcraft_engine::model::{CalcMode, Formula, Sheet, SheetViewMode, Workbook};
|
||||
use gridcraft_engine::{EngineError, Session, command_specs, find_command, io};
|
||||
use gridcraft_engine::{EngineError, HistoryEntry, Session, command_specs, find_command, io};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
const SAMPLES: [&str; 3] = ["sales", "budget", "grades"];
|
||||
@@ -219,8 +219,24 @@ fn shrink(sample: &str, steps: &[Step], kind: &str) -> Vec<Step> {
|
||||
|
||||
struct Harness {
|
||||
s: Session,
|
||||
/// The workbook at the start of the current episode (what undoing everything gives back).
|
||||
base: Arc<Workbook>,
|
||||
/// What undoing everything gives back: the workbook at the start of the current episode or,
|
||||
/// once the undo history has dropped its oldest steps (it is bounded by count and by the
|
||||
/// memory its snapshots hold), the state before the oldest step it kept.
|
||||
floor: Arc<Workbook>,
|
||||
/// The workbook of the oldest undo step when the history was last looked at, to notice the
|
||||
/// history dropping it.
|
||||
oldest: Option<Arc<Workbook>>,
|
||||
}
|
||||
|
||||
/// Where redoing the `n` steps just undone ends. The first of them went onto the redo history
|
||||
/// with the final workbook `end`. The redo history is bounded like undo and drops its oldest
|
||||
/// entries first, so when that entry is gone every older one is too, and redo stops after fewer
|
||||
/// than `n` steps at the oldest entry it kept.
|
||||
fn redo_target(end: &Arc<Workbook>, redo: &[HistoryEntry], n: usize) -> Arc<Workbook> {
|
||||
if n == 0 || redo.iter().rev().take(n).any(|e| Arc::ptr_eq(&e.wb, end)) {
|
||||
return end.clone();
|
||||
}
|
||||
redo.first().map_or_else(|| end.clone(), |e| e.wb.clone())
|
||||
}
|
||||
|
||||
fn fail(step: usize, kind: &'static str, what: impl Into<String>) -> Failure {
|
||||
@@ -243,8 +259,8 @@ impl Harness {
|
||||
fn new(sample: &str) -> Harness {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": sample})).expect("sample opens");
|
||||
let base = s.doc().expect("document").wb.clone();
|
||||
Harness { s, base }
|
||||
let floor = s.doc().expect("document").wb.clone();
|
||||
Harness { s, floor, oldest: None }
|
||||
}
|
||||
|
||||
fn wb(&self) -> Arc<Workbook> {
|
||||
@@ -262,6 +278,7 @@ impl Harness {
|
||||
return Err(fail(i, "documents", format!("`{id}` changed the number of open documents; exclude it in EXCLUDED")));
|
||||
}
|
||||
let after = self.wb();
|
||||
self.track_history();
|
||||
let spec = find_command(id).expect("generated ids are registered");
|
||||
if !spec.undoable
|
||||
&& !matches!(id, "edit.undo" | "edit.redo")
|
||||
@@ -293,6 +310,7 @@ impl Harness {
|
||||
/// and reload; the next episode starts from here with an empty history.
|
||||
fn end_episode(&mut self, i: usize) -> Result<(), Failure> {
|
||||
let end = self.wb();
|
||||
self.track_history();
|
||||
let mut n = 0;
|
||||
while !self.s.doc().expect("document").undo.is_empty() {
|
||||
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.undo", json!({})) {
|
||||
@@ -304,7 +322,7 @@ impl Harness {
|
||||
}
|
||||
}
|
||||
let undone = self.wb();
|
||||
if let Some(diff) = workbook_diff(&self.base, &undone) {
|
||||
if let Some(diff) = workbook_diff(&self.floor, &undone) {
|
||||
return Err(fail(i, "undo", format!("undoing all {n} steps doesn't give back the starting workbook: {diff}")));
|
||||
}
|
||||
if watch_list(&end) != watch_list(&undone) {
|
||||
@@ -312,23 +330,39 @@ impl Harness {
|
||||
}
|
||||
self.check_state(i)?;
|
||||
// Only the steps undone here: an `edit.undo {steps}` in the sequence may have left more.
|
||||
let target = redo_target(&end, &self.s.doc().expect("document").redo, n);
|
||||
for _ in 0..n {
|
||||
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.redo", json!({})) {
|
||||
return Err(fail(i, "panic", format!("`edit.redo` panicked while redoing everything: {msg}")));
|
||||
}
|
||||
}
|
||||
if let Some(diff) = workbook_diff(&end, &self.wb()) {
|
||||
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back the final workbook: {diff}")));
|
||||
if let Some(diff) = workbook_diff(&target, &self.wb()) {
|
||||
let what = if Arc::ptr_eq(&target, &end) { "the final workbook" } else { "the newest step the redo history kept" };
|
||||
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back {what}: {diff}")));
|
||||
}
|
||||
self.check_state(i)?;
|
||||
guarded(i, "xlsx roundtrip", || roundtrip_diff(&end))?;
|
||||
let d = self.s.active_mut().expect("document");
|
||||
d.undo.clear();
|
||||
d.redo.clear();
|
||||
self.base = d.wb.clone();
|
||||
self.floor = d.wb.clone();
|
||||
self.oldest = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notices the undo history dropping its oldest step: its oldest entry changed without the
|
||||
/// history emptying in between. From then on undoing everything stops at the new oldest entry,
|
||||
/// including after an `edit.undo` in the sequence has already used up what is left.
|
||||
fn track_history(&mut self) {
|
||||
let oldest = self.s.doc().expect("document").undo.first().map(|e| e.wb.clone());
|
||||
if let (Some(was), Some(now)) = (&self.oldest, &oldest)
|
||||
&& !Arc::ptr_eq(was, now)
|
||||
{
|
||||
self.floor = now.clone();
|
||||
}
|
||||
self.oldest = oldest;
|
||||
}
|
||||
|
||||
fn finish(&mut self, steps: usize) -> Result<(), Failure> {
|
||||
self.end_episode(steps)
|
||||
}
|
||||
@@ -1135,3 +1169,42 @@ fn view_mode_switch_is_not_an_undo_difference() {
|
||||
assert!(failure.is_none(), "`{id}`: {failure:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Review of #2332: once the undo history has dropped its oldest steps, an `edit.undo` in the
|
||||
/// sequence can use up everything it kept before the episode ends. Undoing everything then has
|
||||
/// nothing left to do, and the workbook is the state before the oldest step kept, not the
|
||||
/// episode's start.
|
||||
#[test]
|
||||
fn a_trimmed_history_undone_in_the_sequence_stops_at_its_oldest_step() {
|
||||
let mut h = Harness::new("sales");
|
||||
// Past the engine's 100-step undo limit, so it drops the oldest 5 steps.
|
||||
for i in 0..105 {
|
||||
h.s.execute("cell.set", json!({"cell": format!("Z{}", i + 1), "input": i.to_string()})).expect("cell.set");
|
||||
h.track_history();
|
||||
}
|
||||
assert_eq!(h.s.doc().expect("document").undo.len(), 100, "the history dropped its oldest steps");
|
||||
if let Err(f) = h.step(0, "edit.undo", &json!({"steps": 100})) {
|
||||
panic!("{f:?}");
|
||||
}
|
||||
assert!(h.s.doc().expect("document").undo.is_empty());
|
||||
if let Err(f) = h.end_episode(0) {
|
||||
panic!("{f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Review of #2332: the redo history is bounded too, so undoing `n` steps may leave fewer than
|
||||
/// `n` to redo, and redo then stops at the oldest entry it kept rather than at the final workbook.
|
||||
#[test]
|
||||
fn redo_stops_at_the_oldest_step_its_history_kept() {
|
||||
let h = Harness::new("sales");
|
||||
let selection = h.s.doc().expect("document").selection.clone();
|
||||
let entry = |wb: &Arc<Workbook>| HistoryEntry { label: String::new(), wb: wb.clone(), selection: selection.clone(), retained_bytes: 0 };
|
||||
let end = Arc::new((*h.wb()).clone());
|
||||
let kept = Arc::new((*h.wb()).clone());
|
||||
// Both steps kept: the first one undone went onto the redo history with the final workbook.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&end), entry(&kept)], 2), &end));
|
||||
// Its entry dropped: redo stops at the oldest entry left.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 2), &kept));
|
||||
// Nothing undone, so nothing to redo, whatever an earlier `edit.undo` left there.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 0), &end));
|
||||
}
|
||||
@@ -32,6 +32,7 @@ mod sparse_clear_invalidation;
|
||||
mod stored_list_shape;
|
||||
mod structural_edit_rewrite;
|
||||
mod table_resize_overlap;
|
||||
mod table_style_looks;
|
||||
mod table_total_row_last_row;
|
||||
mod trace_error;
|
||||
mod workbook_author;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Table styles look like the Format as Table gallery: every row of the gallery (Light 1-7, 8-14,
|
||||
//! 15-21, Medium 1-7, …) has its own fills and lines, as recorded in plan/excel/table-style-spec.json.
|
||||
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::model::*;
|
||||
use gridcraft_engine::tables::{ShownEdges, shown_edges, table_cell_shown_style, table_cell_style};
|
||||
use serde_json::json;
|
||||
|
||||
const ROWS: u32 = 6; // header + 5 data rows
|
||||
const COLS: u32 = 5;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c", "d", "e"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:E6", "header": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The look of every cell of a 6x5 table (header on, banded rows) in `style`, row by row.
|
||||
fn grid_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
fn grid(style: &str) -> Vec<Vec<Style>> {
|
||||
grid_with(&session(), style, |_| {})
|
||||
}
|
||||
|
||||
fn thin(color: Color) -> BorderLine {
|
||||
BorderLine { style: BorderStyle::Thin, color }
|
||||
}
|
||||
|
||||
const NONE: BorderLine = BorderLine { style: BorderStyle::None, color: Color::Auto };
|
||||
const BLACK: Color = Color::Theme(1, 0);
|
||||
const WHITE: Color = Color::Theme(0, 0);
|
||||
|
||||
#[test]
|
||||
fn each_row_of_the_gallery_has_its_own_look() {
|
||||
// Same accent (or neutral) across the gallery's rows, so only the row-group differs.
|
||||
for set in [
|
||||
&["Light1", "Light8", "Light15", "Medium1", "Medium8", "Medium15", "Medium22", "Dark1", "Dark8"][..],
|
||||
&["Light2", "Light9", "Light16", "Medium2", "Medium9", "Medium16", "Medium23", "Dark2", "Dark9"][..],
|
||||
] {
|
||||
let looks: Vec<_> = set.iter().map(|s| grid(s)).collect();
|
||||
for (i, a) in looks.iter().enumerate() {
|
||||
for (j, b) in looks.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(a, b, "{} and {} look the same", set[i], set[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_bands_are_visibly_grey() {
|
||||
let theme = Theme::default();
|
||||
let fill = |style: &str, row: usize| grid(style)[row][0].fill.fg.resolve(&theme).unwrap();
|
||||
// lt1 -150 (about #D9D9D9) and lt1 -350 (about #A6A6A6).
|
||||
for ch in fill("Light1", 1) {
|
||||
assert!((210..=225).contains(&ch), "Light1 band {:?}", fill("Light1", 1));
|
||||
}
|
||||
for ch in fill("Medium8", 1) {
|
||||
assert!((160..=172).contains(&ch), "Medium8 band1 {:?}", fill("Medium8", 1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light15_has_a_vertical_grid_and_no_row_lines() {
|
||||
let g = grid("Light15");
|
||||
assert_eq!(g[0][0].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, thin(BLACK), "header bottom");
|
||||
assert_eq!(g[2][1].borders.right, thin(BLACK), "inner vertical");
|
||||
assert_eq!(g[0][1].borders.right, thin(BLACK), "inner vertical in the header");
|
||||
assert_eq!(g[2][0].borders.left, thin(BLACK), "left side");
|
||||
assert_eq!(g[2][4].borders.right, thin(BLACK), "right side");
|
||||
assert_eq!(g[5][2].borders.bottom, thin(BLACK), "bottom");
|
||||
assert_eq!(g[2][1].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][1].borders.top, NONE, "no inner horizontal");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(0, -150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium2_has_a_pale_accent_frame_and_no_row_lines() {
|
||||
let g = grid("Medium2");
|
||||
let line = thin(Color::Theme(4, 400));
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[0][2].borders.top, line);
|
||||
assert_eq!(g[0][0].borders.left, line, "the sides run down the header too");
|
||||
assert_eq!(g[3][0].borders.left, line);
|
||||
assert_eq!(g[3][4].borders.right, line);
|
||||
assert_eq!(g[5][2].borders.bottom, line);
|
||||
assert_eq!(g[0][2].borders.bottom, NONE, "no header bottom");
|
||||
assert_eq!(g[2][2].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][2].borders.right, NONE, "no inner vertical");
|
||||
assert_eq!(g[1][2].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][2].fill.pattern, PatternType::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium9_has_white_verticals_and_header_bottom() {
|
||||
let g = grid("Medium9");
|
||||
assert_eq!(g[0][1].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[0][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.bottom, NONE);
|
||||
assert_eq!(g[3][0].borders.left, NONE, "no frame");
|
||||
assert_eq!(g[5][4].borders.bottom, NONE, "no frame");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark2_bands_in_shaded_and_full_accent_under_a_black_header() {
|
||||
let g = grid("Dark2");
|
||||
assert_eq!(g[0][0].fill.fg, BLACK);
|
||||
assert_eq!(g[0][0].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, -250));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[2][0].font.color, WHITE);
|
||||
assert_eq!(g[2][0].borders, Borders::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark9_pairs_two_accents() {
|
||||
let g = grid("Dark9");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(5, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].font.color, BLACK);
|
||||
let g = grid("Dark11");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(9, 0));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(8, 600));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_options_change_the_look() {
|
||||
let s = session();
|
||||
// Banded rows off: every data row looks like the second band.
|
||||
let g = grid_with(&s, "Medium9", |t| t.banded_rows = false);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
// Banded columns alternate by column.
|
||||
let g = grid_with(&s, "Medium9", |t| {
|
||||
t.banded_rows = false;
|
||||
t.banded_cols = true;
|
||||
});
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][1].fill.fg, Color::Theme(4, 800));
|
||||
// Header off: the top line moves to the first data row, and nothing is drawn as a header.
|
||||
let g = grid_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[0][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, NONE);
|
||||
assert!(!g[0][2].font.bold);
|
||||
// Totals row: bold, double top rule, no banding.
|
||||
let g = grid_with(&s, "Medium2", |t| t.totals_row = true);
|
||||
assert!(g[5][1].font.bold);
|
||||
assert_eq!(g[5][1].borders.top, BorderLine { style: BorderStyle::Double, color: Color::Theme(4, 0) });
|
||||
assert_eq!(g[5][1].borders.bottom, thin(Color::Theme(4, 400)));
|
||||
// First and last column bold.
|
||||
let g = grid_with(&s, "Medium2", |t| {
|
||||
t.first_col = true;
|
||||
t.last_col = true;
|
||||
});
|
||||
assert!(g[2][0].font.bold && g[2][4].font.bold && !g[2][2].font.bold);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_formatting_wins() {
|
||||
let mut s = session();
|
||||
s.execute("home.fillColor", json!({"range": "B3", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.fontColor", json!({"range": "B3", "color": "#00FF00"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "B3", "preset": "bottom"})).unwrap();
|
||||
let g = grid_with(&s, "Dark2", |_| {});
|
||||
assert_eq!(g[2][1].fill, Fill::solid(Color::Rgb(0xFF0000)));
|
||||
assert_eq!(g[2][1].font.color, Color::Rgb(0x00FF00));
|
||||
assert_eq!(g[2][1].borders.bottom.style, BorderStyle::Thin);
|
||||
assert_eq!(g[2][1].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_style_name_is_safe() {
|
||||
for name in ["Light0", "Light99", "Medium0", "Medium4000000000", "Dark0", "Dark12", "Dark99", "Bogus"] {
|
||||
let _ = grid(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the grid and print draw: like `grid_with`, but through the hidden-row/column aware
|
||||
/// `table_cell_shown_style`.
|
||||
fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
let e = shown_edges(wb.sheet(0).unwrap(), &t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_shown_style(wb, 0, &t, e, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_follows_the_last_visible_row_and_column() {
|
||||
let frame = thin(Color::Theme(4, 400));
|
||||
// Nothing hidden: the shown look is the table look.
|
||||
let s = session();
|
||||
assert_eq!(shown_with(&s, "Medium2", |_| {}), grid_with(&s, "Medium2", |_| {}));
|
||||
// Last data row (and the one before it) and last column hidden: the frame moves in.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "5:6"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "E:E"})).unwrap();
|
||||
let t = &s.doc().unwrap().wb.sheet(0).unwrap().tables[0];
|
||||
assert_eq!(shown_edges(s.doc().unwrap().wb.sheet(0).unwrap(), t), ShownEdges { top: 0, bottom: 3, left: 0, right: 3 });
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
for (c, cell) in g[3].iter().take(4).enumerate() {
|
||||
assert_eq!(cell.borders.bottom, frame, "bottom frame on row 4, col {c}");
|
||||
}
|
||||
for (r, row) in g.iter().take(4).enumerate() {
|
||||
assert_eq!(row[3].borders.right, frame, "right frame on col D, row {r}");
|
||||
}
|
||||
// Rows above the last visible one keep their inner look (Medium 2 has no row lines).
|
||||
assert_eq!(g[2][1].borders.bottom, NONE);
|
||||
// Convert to Range and friends still see the table as it is.
|
||||
assert_eq!(grid_with(&s, "Medium2", |_| {})[3][1].borders.bottom, NONE);
|
||||
// Header off and the first data row filtered out: the top line moves down.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "1:1"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "A:A"})).unwrap();
|
||||
let g = shown_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[1][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[2][1].borders.left, thin(BLACK));
|
||||
// Explicit borders still win.
|
||||
let mut s = session();
|
||||
s.execute("home.borders", json!({"range": "B5", "preset": "none"})).unwrap();
|
||||
s.execute("home.fillColor", json!({"range": "B5", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "C5", "preset": "bottom"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "6:6"})).unwrap();
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
assert_eq!(g[4][1].borders.bottom, frame);
|
||||
assert_eq!(g[4][2].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
@@ -617,6 +617,11 @@ mod tests {
|
||||
cx(ev("IMCSC", vec![t("4+3i")]), -0.075_489_832_915_863_7, 0.064_877_471_370_635_5);
|
||||
is_text(ev("IMSECH", vec![t("0")]), "1");
|
||||
is_err(ev("IMCSCH", vec![t("0")]), CellError::Num);
|
||||
// Excel-cached results (Excel for Mac, `formulas` project test.xlsx, ENGINEERING sheet): a
|
||||
// part needing more than 21 characters as a decimal is written in scientific notation.
|
||||
is_text(ev("IMCSCH", vec![t("13+5j")]), "1.28233995888454E-06+4.33496947416312E-06j");
|
||||
is_text(ev("IMEXP", vec![t("-13+25j")]), "2.24044486393732E-06-2.99158552811404E-07j");
|
||||
is_text(ev("IMSECH", vec![t("7+25j")]), "0.00180771853884451+0.000241377759972715j");
|
||||
// sech z · cosh z = 1
|
||||
let Value::Text(c) = ev("IMCOSH", vec![t("4+3i")]) else { panic!() };
|
||||
let Value::Text(sc) = ev("IMSECH", vec![t("4+3i")]) else { panic!() };
|
||||
|
||||
@@ -290,6 +290,44 @@ impl CellStore {
|
||||
let moved = self.take_rows(0..=u32::MAX, from..=u32::MAX);
|
||||
self.put_rows(moved.into_iter().map(|(row, cols)| (row, shift_keys(cols, delta))));
|
||||
}
|
||||
/// Deletes the rows in `spans` (`(first, count)`, ascending and disjoint) and closes the gaps
|
||||
/// in one pass: each later cell moves up once by the number of deleted rows above it.
|
||||
pub fn delete_rows(&mut self, spans: &[(u32, u32)]) {
|
||||
self.delete_lines(spans, true);
|
||||
}
|
||||
/// Column form of [`CellStore::delete_rows`].
|
||||
pub fn delete_cols(&mut self, spans: &[(u32, u32)]) {
|
||||
self.delete_lines(spans, false);
|
||||
}
|
||||
fn delete_lines(&mut self, spans: &[(u32, u32)], rows: bool) {
|
||||
let Some(&(first, _)) = spans.first() else { return };
|
||||
// Lines deleted before the end of each span, for mapping a kept line to its new place.
|
||||
let mut before = Vec::with_capacity(spans.len());
|
||||
let mut total = 0u32;
|
||||
for &(_, count) in spans {
|
||||
total = total.saturating_add(count);
|
||||
before.push(total);
|
||||
}
|
||||
let map = |v: u32| -> Option<u32> {
|
||||
let i = spans.partition_point(|&(at, _)| at <= v);
|
||||
let Some(i) = i.checked_sub(1) else { return Some(v) };
|
||||
let (at, count) = spans.get(i).copied().unwrap_or_default();
|
||||
if v - at < count { None } else { Some(v - before.get(i).copied().unwrap_or_default()) }
|
||||
};
|
||||
let keys: Vec<CellRef> = if rows {
|
||||
let r = RangeRef::new(CellRef::new(first, 0), CellRef::new(gridcraft_core::MAX_ROWS - 1, gridcraft_core::MAX_COLS - 1));
|
||||
self.iter_range(r).map(|(c, _)| c).collect()
|
||||
} else {
|
||||
self.iter().filter(|(c, _)| c.col >= first).map(|(c, _)| c).collect()
|
||||
};
|
||||
let moved: Vec<(CellRef, Cell)> = keys.into_iter().filter_map(|c| self.remove(c).map(|cell| (c, cell))).collect();
|
||||
for (c, cell) in moved {
|
||||
let to = if rows { map(c.row).map(|r| CellRef::new(r, c.col)) } else { map(c.col).map(|x| CellRef::new(c.row, x)) };
|
||||
if let Some(to) = to {
|
||||
self.set(to, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Shifts cells within rows `r0..=r1` and columns `>= from` horizontally (Insert/Delete Cells
|
||||
/// with shift right/left).
|
||||
pub fn shift_cols_in_rows(&mut self, r0: u32, r1: u32, from: u32, delta: i64) {
|
||||
|
||||
+40
-12
@@ -293,23 +293,22 @@ impl NumberFormat {
|
||||
}
|
||||
|
||||
/// Formats a number. The flag is true when the value cannot be shown (date out of range).
|
||||
fn format_number(&self, n: f64, sys: DateSystem) -> (Formatted, bool) {
|
||||
let general = |n: f64| Formatted {
|
||||
text: format_general_fit(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()),
|
||||
color: None,
|
||||
fill: None,
|
||||
numeric: true,
|
||||
};
|
||||
/// With `full`, General is not narrowed to the cell width but written by [`general_full`].
|
||||
fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) {
|
||||
let general_text = |n: f64, width: usize| if full { Some(general_full(n)) } else { format_general_fit(n, width) };
|
||||
let general =
|
||||
|n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true };
|
||||
if self.is_general() {
|
||||
return (general(n), false);
|
||||
}
|
||||
let Some((sec, drop_sign)) = self.select(n) else { return (general(n), false) };
|
||||
let minus = n < 0.0 && !drop_sign;
|
||||
let out: Option<Out> = match sec.kind {
|
||||
SecKind::Text => Some(render::render_text(sec, &format_general_fit(n, GENERAL_WIDTH).unwrap_or_default())),
|
||||
SecKind::Text => Some(render::render_text(sec, &general_text(n, GENERAL_WIDTH).unwrap_or_default())),
|
||||
SecKind::General => {
|
||||
let width = if minus { GENERAL_WIDTH - 1 } else { GENERAL_WIDTH };
|
||||
Some(render::render_general(sec, n.abs(), width))
|
||||
let text = general_text(n.abs(), width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)));
|
||||
Some(render::render_general(sec, &text))
|
||||
}
|
||||
SecKind::Date => {
|
||||
if minus {
|
||||
@@ -405,16 +404,45 @@ impl NumberFormat {
|
||||
|
||||
/// Formats a cell value for display.
|
||||
pub fn format_value(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
|
||||
format_value_with(v, fmt, sys, false)
|
||||
}
|
||||
|
||||
/// Formats a cell value as Save As CSV/Text writes it: like [`format_value`], except that a number
|
||||
/// shown as General (a General or Text section, with or without colour and literals) is not
|
||||
/// narrowed to the cell width but written by `general_full`: `124412140710`, not `1.24412E+11`.
|
||||
/// Excel writes the cell display here; GridCraft keeps the digits.
|
||||
pub fn format_value_full(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
|
||||
format_value_with(v, fmt, sys, true)
|
||||
}
|
||||
|
||||
/// General for Save As CSV/Text: the text `&` gives (15 significant digits), but never with an
|
||||
/// exponent, because reopening the file would give the cell a scientific format that rounds it
|
||||
/// on the next save. Where `&` writes an exponent, a number of 1 or more is written as the
|
||||
/// shortest digits that read back as the same value (every integer f64 holds below 1e16 exactly,
|
||||
/// so 16-digit card numbers survive), and a smaller one as its 15 significant digits in full.
|
||||
fn general_full(n: f64) -> String {
|
||||
let text = gridcraft_core::number_to_text(n);
|
||||
if !text.contains('E') {
|
||||
text
|
||||
} else if n.abs() >= 1.0 {
|
||||
format!("{n}")
|
||||
} else {
|
||||
let mag: i32 = format!("{n:.14e}").split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0);
|
||||
gridcraft_core::value::trim_decimal(&format!("{:.*}", (14 - mag).max(0) as usize, n))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_value_with(v: &Value, fmt: &NumberFormat, sys: DateSystem, full: bool) -> Formatted {
|
||||
match v {
|
||||
Value::Empty => Formatted::default(),
|
||||
Value::Number(n) if !n.is_finite() => Formatted { text: CellError::Num.as_str().into(), ..Formatted::default() },
|
||||
Value::Number(n) => fmt.format_number(*n, sys).0,
|
||||
Value::Number(n) => fmt.format_number(*n, sys, full).0,
|
||||
Value::Text(t) => fmt.format_text(t),
|
||||
Value::Bool(b) => Formatted { text: if *b { "TRUE" } else { "FALSE" }.into(), ..Formatted::default() },
|
||||
Value::Error(e) => Formatted { text: e.as_str().into(), ..Formatted::default() },
|
||||
Value::Array(a) => match a.data.first() {
|
||||
Some(Value::Array(_)) | None => Formatted::default(),
|
||||
Some(first) => format_value(first, fmt, sys),
|
||||
Some(first) => format_value_with(first, fmt, sys, full),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -525,7 +553,7 @@ pub fn text_function(v: &Value, code: &str, sys: DateSystem) -> Result<String, C
|
||||
if !n.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f, overflow) = fmt.format_number(n, sys);
|
||||
let (f, overflow) = fmt.format_number(n, sys, false);
|
||||
if overflow { Err(CellError::Value) } else { Ok(f.text) }
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use gridcraft_core::DateSystem;
|
||||
use gridcraft_core::date::{datetime_from_serial, max_serial};
|
||||
|
||||
use crate::calendar::Calendar;
|
||||
use crate::decimal::{decimal_digits, fixed, fixed_from_digits, format_general_fit};
|
||||
use crate::decimal::{decimal_digits, fixed, fixed_from_digits};
|
||||
use crate::parse::{DatePart, Section, Tok};
|
||||
|
||||
/// Text being built plus the first repeat-fill position.
|
||||
@@ -81,12 +81,13 @@ pub(crate) fn render_text_within(sec: &Section, text: &str, max_units: usize) ->
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Renders a number through a General section (literals around the General keyword).
|
||||
pub(crate) fn render_general(sec: &Section, v: f64, width: usize) -> Out {
|
||||
/// Renders a number through a General section: `general` (the number already written as General)
|
||||
/// with the section's literals around it.
|
||||
pub(crate) fn render_general(sec: &Section, general: &str) -> Out {
|
||||
let mut out = Out::default();
|
||||
for t in &sec.toks {
|
||||
match t {
|
||||
Tok::General => out.push(&format_general_fit(v, width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)))),
|
||||
Tok::General => out.push(general),
|
||||
Tok::Fill(c) => out.fill(*c),
|
||||
other => out.push_tok(other),
|
||||
}
|
||||
|
||||
@@ -668,7 +668,7 @@ fn text_uncached(v: &Value, code: &str, sys: DateSystem) -> Result<String, CellE
|
||||
if !n.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f, overflow) = fmt.format_number(n, sys);
|
||||
let (f, overflow) = fmt.format_number(n, sys, false);
|
||||
if overflow { Err(CellError::Value) } else { Ok(f.text) }
|
||||
}
|
||||
|
||||
|
||||
@@ -160,6 +160,11 @@ mod tests {
|
||||
assert_eq!(sig("IF", En, Language::Es), "IF(prueba_lógica, [valor_si_verdadero], [valor_si_falso])");
|
||||
assert_eq!(sig("SUM", En, Language::Es), "SUM(número1, [número2], ...)");
|
||||
assert_eq!(description("IF", En, Language::Es).as_deref(), Some("Devuelve un valor según una condición."));
|
||||
// Portuguese help, including brackets that open and close on different arguments.
|
||||
assert_eq!(sig("IF", En, Language::PtBr), "IF(teste_lógico, [valor_se_verdadeiro], [valor_se_falso])");
|
||||
assert_eq!(description("IF", En, Language::PtBr).as_deref(), Some("Retorna um valor quando uma condição é TRUE e outro quando é FALSE."));
|
||||
assert_eq!(sig("SWITCH", En, Language::PtBr), "SWITCH(expressão, valor1, resultado1, [padrão_ou_valor2, resultado2], ...)");
|
||||
assert_eq!(sig("LAMBDA", En, Language::PtBr), "LAMBDA([parâmetro1, ...], cálculo)");
|
||||
// Spanish names and separators, from a localized name.
|
||||
assert_eq!(sig("suma", Es, Language::Es), "SUMA(número1; [número2]; ...)");
|
||||
assert_eq!(description("SUMA", Es, Language::Es).as_deref(), Some("Suma los números."));
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) fn center_across_end(start: u32, limit: u32, continues: impl Fn(u32)
|
||||
pub(super) fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option<CfLook>) {
|
||||
let mut style = wb.styles.get(sh.style_id(c)).clone();
|
||||
if let Some(t) = sh.table_at(c) {
|
||||
style = gridcraft_engine::tables::table_cell_style(wb, si, t, c);
|
||||
style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c);
|
||||
}
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(l) = &cfl
|
||||
|
||||
@@ -32,6 +32,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
ctx.memory_mut(|m| {
|
||||
m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true })
|
||||
});
|
||||
request_grid_ime(app, ctx, resp, geo, sh);
|
||||
let events = grid_events(app, ctx, sh);
|
||||
// A shortcut key that also types a character (Shift+Space sends Text(" ")) must not start an edit.
|
||||
let shortcut_pressed = events.iter().any(|e| {
|
||||
@@ -43,6 +44,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// a shortcut ran, that text must not start an edit over what it just did.
|
||||
let mut shortcut_ran = false;
|
||||
for ev in events {
|
||||
// IME events are handled outside the match to keep this loop's complexity down. Any
|
||||
// non-commit IME event (preedit, delete-surrounding) falls through to `_ => {}` below.
|
||||
if handle_ime_commit(app, &ev, shortcut_pressed, shortcut_ran) {
|
||||
return;
|
||||
}
|
||||
match ev {
|
||||
egui::Event::Copy => {
|
||||
app.copy_to_clipboard(ctx, "edit.copy");
|
||||
@@ -58,11 +64,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// insert text at, so a middle click on a cell is deliberately not a paste.
|
||||
egui::Event::MiddleClickPaste { .. } => {}
|
||||
egui::Event::Text(_) if shortcut_pressed || shortcut_ran => {}
|
||||
// A space on a checkbox cell toggles it (the `Key::Space` arm below). The same key
|
||||
// press also arrives as text, and typing text starts editing the cell -- so the cell
|
||||
// toggled *and* opened an editor holding a space, which Enter then committed over the
|
||||
// checkbox (#1951).
|
||||
egui::Event::Text(text) if text == " " && is_checkbox(sh, app) => {}
|
||||
egui::Event::Text(text) if text.chars().all(|c| !c.is_control()) && !text.is_empty() => {
|
||||
app.begin_edit(Some(text), false);
|
||||
if let Some(ed) = app.editor.as_mut() {
|
||||
ed.caret = ed.text.chars().count();
|
||||
}
|
||||
seed_editor(app, text);
|
||||
return;
|
||||
}
|
||||
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
|
||||
@@ -146,7 +154,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
|
||||
_ if cmd && shift && !m.alt && crate::macro_ui::run_shortcut(app, key) => {}
|
||||
_ if cmd && !crate::keymap::altgr_text(ctx, m, ctx.os() == egui::os::OperatingSystem::Mac) => {
|
||||
crate::ribbon::shortcut(app, key, m)
|
||||
// The same key the English table reads: Ctrl+Shift+, typing `;` is Ctrl+;.
|
||||
let (key, shift) = crate::keymap::us_key(key, physical_key, shift).unwrap_or((key, shift));
|
||||
crate::ribbon::shortcut(app, key, egui::Modifiers { shift, ..m });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -156,6 +166,78 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the in-cell editor with typed or committed text and put the caret after it.
|
||||
fn seed_editor(app: &mut SheetApp, text: String) {
|
||||
app.begin_edit(Some(text), false);
|
||||
if let Some(ed) = app.editor.as_mut() {
|
||||
ed.caret = ed.text.chars().count();
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed the editor from a finished composition, if `ev` is one.
|
||||
///
|
||||
/// Only `ImeEvent::Commit` is finished text; a preedit is the input method's in-progress
|
||||
/// spelling and must not seed the editor. `Event::Ime` and `Event::Text` are mutually
|
||||
/// exclusive for one keystroke, so accepting a commit cannot double-insert a character.
|
||||
/// Returns whether the caller should stop handling this frame's events.
|
||||
fn handle_ime_commit(app: &mut SheetApp, ev: &egui::Event, shortcut_pressed: bool, shortcut_ran: bool) -> bool {
|
||||
let egui::Event::Ime(egui::ImeEvent::Commit(text)) = ev else { return false };
|
||||
if shortcut_pressed || shortcut_ran || text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
seed_editor(app, text.clone());
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the OS to route keystrokes through the input method while the grid owns keyboard input.
|
||||
///
|
||||
/// egui enables IME only for a widget that publishes `PlatformOutput::ime` in that frame. The
|
||||
/// in-cell `TextEdit` opens *after* the grid has consumed the first keystroke, so without this
|
||||
/// the first key of a CJK composition is delivered as raw `Event::Text` and lands in the cell
|
||||
/// (Wubi `xta` writes `x` and the input method only ever sees `ta`). The request must be
|
||||
/// published on every focused frame, not in response to a key: winit applies it at the end of
|
||||
/// the frame, so a key arriving while IME is still off cannot be recovered.
|
||||
///
|
||||
/// `PlatformOutput` is rebuilt every frame, so returning early (an editor, a dialog or another
|
||||
/// widget taking focus) simply leaves `ime` as `None` and the input method turns off.
|
||||
fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
|
||||
if !ctx.memory(|m| m.owns_ime_events(resp.id)) {
|
||||
return;
|
||||
}
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let active = d.selection.active;
|
||||
let merged = sh.merge_at(active);
|
||||
// `begin_edit` refuses a locked cell on a protected sheet. Publishing an IME request for
|
||||
// one would let the user compose text that is then discarded, so skip it up front, using
|
||||
// the same merged-cell anchor and protection check as `SheetApp::begin_edit`.
|
||||
let anchor = merged.map(|m| m.start).unwrap_or(active);
|
||||
if app.session.locked_cell_message(d.wb.active_sheet(), anchor).is_some() {
|
||||
return;
|
||||
}
|
||||
// `cell_rect`/`range_rect` are logical coordinates, but `IMEOutput` needs screen ones.
|
||||
// On a right-to-left sheet the grid is mirrored, so publishing the logical rect puts the
|
||||
// candidate window on the opposite side. After mirroring, `rect.min` is the screen-side
|
||||
// start of the cell in both layouts, which is where the caret belongs.
|
||||
let rect = match merged {
|
||||
Some(m) => geo.mirror_rect(geo.range_rect(sh, m)),
|
||||
None => geo.mirror_rect(geo.cell_rect(sh, active)),
|
||||
};
|
||||
let cursor_rect = egui::Rect::from_min_size(rect.min, egui::vec2(1.0, rect.height()));
|
||||
// egui 0.37 identifies an IME context by (owner, generation). The generation must change
|
||||
// when this owner gains focus and stay stable for ordinary text and selection updates.
|
||||
let gained_focus = resp.gained_focus();
|
||||
let generation = ctx.data_mut(|data| {
|
||||
let g: &mut u64 = data.get_temp_mut_or_default(egui::Id::unique("gridcraft.grid_ime_generation"));
|
||||
if gained_focus || *g == 0 {
|
||||
*g = g.wrapping_add(1);
|
||||
}
|
||||
*g
|
||||
});
|
||||
ctx.output_mut(|o| {
|
||||
o.ime = Some(egui::output::IMEOutput::new(resp.id, generation, egui::IMEPurpose::Normal, rect, cursor_rect));
|
||||
});
|
||||
}
|
||||
|
||||
/// This frame's input events, without those the focused form control took.
|
||||
fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec<egui::Event> {
|
||||
let events = ctx.input(|i| i.events.clone());
|
||||
|
||||
@@ -21,6 +21,7 @@ mod ko;
|
||||
mod nl;
|
||||
mod pl;
|
||||
mod pt;
|
||||
mod pt_functions;
|
||||
mod ro;
|
||||
mod ru;
|
||||
mod sr;
|
||||
@@ -252,6 +253,7 @@ impl Language {
|
||||
fn function_help(self) -> Option<(HelpTable, HelpTable)> {
|
||||
match self {
|
||||
Self::Es => Some((es_functions::DESCRIPTIONS, es_functions::ARGUMENTS)),
|
||||
Self::PtBr => Some((pt_functions::DESCRIPTIONS, pt_functions::ARGUMENTS)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -55,14 +55,54 @@ fn borders(preset: &str) -> Shortcut {
|
||||
Shortcut::Run("home.borders", json!({"preset": preset}))
|
||||
}
|
||||
|
||||
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
|
||||
/// layout (as Excel matches Ctrl+Shift+4 rather than the `$` character); `mac` selects the Excel
|
||||
/// for Mac variants where they differ. Navigation keys go by the logical key: with Num Lock off
|
||||
/// the numpad's arrows and Page Down report the digit keys (Num6, Num3) as their physical keys.
|
||||
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
|
||||
/// Navigation keys go by the logical key: with Num Lock off the numpad's arrows and Page Down
|
||||
/// report the digit keys (Num6, Num3) as their physical keys.
|
||||
fn is_navigation(key: Key) -> bool {
|
||||
use Key::*;
|
||||
let navigation = matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete);
|
||||
let key = if navigation { key } else { physical.unwrap_or(key) };
|
||||
matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete)
|
||||
}
|
||||
|
||||
/// The US key and Shift state a symbol or digit key press stands for in the English shortcuts.
|
||||
/// Digits go by position (Ctrl+Shift+4 is the currency format wherever `$` is). Punctuation keys
|
||||
/// go by the character the layout types, as Excel does: Shift+, types `;` on a Croatian or German
|
||||
/// keyboard, so Ctrl+Shift+, is Ctrl+; (today's date) there, and a lone `+` is the US Shift+=.
|
||||
/// A character egui has no key for (`č`, `ö`, `<`) arrives as the key's position, which stands
|
||||
/// in. `None` for every other key (letters, navigation, function keys).
|
||||
pub fn us_key(key: Key, physical: Option<Key>, shift: bool) -> Option<(Key, bool)> {
|
||||
use Key::*;
|
||||
if is_navigation(key) {
|
||||
return None;
|
||||
}
|
||||
let at = physical?;
|
||||
let symbol =
|
||||
|k: Key| matches!(k, Backtick | Minus | Equals | OpenBracket | CloseBracket | Backslash | Semicolon | Quote | Comma | Period | Slash);
|
||||
match at {
|
||||
Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7 | Num8 | Num9 => Some((at, shift)),
|
||||
_ if symbol(at) => Some(match key {
|
||||
// Characters a US keyboard types with Shift.
|
||||
Colon => (Semicolon, true),
|
||||
Plus => (Equals, true),
|
||||
Questionmark => (Slash, true),
|
||||
Pipe => (Backslash, true),
|
||||
OpenCurlyBracket => (OpenBracket, true),
|
||||
CloseCurlyBracket => (CloseBracket, true),
|
||||
// An unshifted US character, typed here with or without Shift.
|
||||
_ if key != at && symbol(key) => (key, false),
|
||||
_ => (key, shift),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
|
||||
/// layout: digits and letters go by it, punctuation by the character typed ([`us_key`]). `mac`
|
||||
/// selects the Excel for Mac variants where they differ. Navigation keys go by the logical key.
|
||||
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
|
||||
let (key, shift) = match us_key(key, physical, m.shift) {
|
||||
Some(us) => us,
|
||||
None if is_navigation(key) => (key, m.shift),
|
||||
None => (physical.unwrap_or(key), m.shift),
|
||||
};
|
||||
let ctx = LookupContext {
|
||||
key,
|
||||
modifiers: m,
|
||||
@@ -71,7 +111,7 @@ pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Optio
|
||||
alt: m.alt && !m.ctrl && !m.command,
|
||||
ctrl_alt: m.alt && (m.ctrl || m.command),
|
||||
plain: !m.ctrl && !m.command && !m.alt,
|
||||
shift: m.shift,
|
||||
shift,
|
||||
mac,
|
||||
};
|
||||
lookup_number_formats(ctx)
|
||||
|
||||
@@ -27,36 +27,55 @@ pub(super) fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from
|
||||
/// the same look the grid uses.
|
||||
pub(super) fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) {
|
||||
let lk = gridcraft_engine::tables::look(style);
|
||||
let res = |c: Option<gridcraft_engine::model::Color>| c.and_then(|c| c.resolve(&wb.theme)).map(theme::color32);
|
||||
use egui::emath::GuiRounding;
|
||||
use gridcraft_engine::tables::{TableParts, cell_look, look};
|
||||
let lk = look(style);
|
||||
let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false };
|
||||
let res = |c: gridcraft_engine::model::Color| c.resolve(&wb.theme).map(theme::color32);
|
||||
let p = ui.painter();
|
||||
let t = Tokens::get(ui.ctx());
|
||||
p.rect_filled(r, 0.0, t.grid_bg);
|
||||
let rows = 5;
|
||||
let rh = r.height() / rows as f32;
|
||||
for i in 0..rows {
|
||||
let rr = Rect::from_min_size(pos2(r.left(), r.top() + i as f32 * rh), vec2(r.width(), rh));
|
||||
let fill = if i == 0 {
|
||||
res(lk.header_fill)
|
||||
} else if i % 2 == 1 {
|
||||
res(lk.band_fill)
|
||||
} else {
|
||||
res(lk.body_fill)
|
||||
};
|
||||
if let Some(f) = fill {
|
||||
p.rect_filled(rr, 0.0, f);
|
||||
}
|
||||
if let Some(l) = res(lk.line) {
|
||||
p.line_segment([rr.left_bottom(), rr.right_bottom()], Stroke::new(1.0, l));
|
||||
}
|
||||
for k in 0..3 {
|
||||
let x = rr.left() + 4.0 + k as f32 * (r.width() - 8.0) / 3.0;
|
||||
let col = if i == 0 { res(Some(lk.header_font)).unwrap_or(t.cell_text) } else { t.sheet_control_border };
|
||||
p.line_segment([pos2(x, rr.center().y), pos2(x + 10.0, rr.center().y)], Stroke::new(1.0, col));
|
||||
let line = |l: gridcraft_engine::model::BorderLine| if l.is_none() { None } else { Some(res(l.color).unwrap_or(t.cell_text)) };
|
||||
let n = 5u32;
|
||||
let (cw, rh) = (r.width() / n as f32, r.height() / n as f32);
|
||||
// Cell edges on whole pixels keep the lines crisp and the rows evenly spaced.
|
||||
let ppp = ui.pixels_per_point();
|
||||
let at = |start: f32, size: f32, k: u32| (start + size * k as f32).round_to_pixels(ppp);
|
||||
for row in 0..n {
|
||||
for col in 0..n {
|
||||
let (x0, x1) = (at(r.left(), cw, col), at(r.left(), cw, col + 1));
|
||||
let cr = Rect::from_min_max(pos2(x0, at(r.top(), rh, row)), pos2(x1, at(r.top(), rh, row + 1)));
|
||||
let cl = cell_look(&lk, parts, row, col, n, n);
|
||||
if let Some(f) = cl.fill.and_then(res) {
|
||||
p.rect_filled(cr, 0.0, f);
|
||||
}
|
||||
let b = cl.borders;
|
||||
// Excel centres the dash in the space inside the cell's own lines, across about half of it.
|
||||
let inset = |l: gridcraft_engine::model::BorderLine| if l.is_none() { 0.0 } else { 1.0 };
|
||||
let inner = Rect::from_min_max(
|
||||
pos2(cr.left() + inset(b.left), cr.top() + inset(b.top)),
|
||||
pos2(cr.right() - inset(b.right), cr.bottom() - inset(b.bottom)),
|
||||
);
|
||||
// When the gap can't split evenly, Excel puts the spare pixel below the dash.
|
||||
let top = ((inner.center().y - 0.5) * ppp).floor() / ppp;
|
||||
let (mid, half) = (inner.center().x, cw * 0.26);
|
||||
let dash = Rect::from_min_max(pos2((mid - half).round_to_pixels(ppp), top), pos2((mid + half).round_to_pixels(ppp), top + 1.0));
|
||||
p.rect_filled(dash, 0.0, res(cl.font).unwrap_or(t.cell_text));
|
||||
for (side, edge) in [
|
||||
(b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))),
|
||||
(b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())),
|
||||
(b.left, Rect::from_min_max(cr.left_top(), pos2(cr.left() + 1.0, cr.bottom()))),
|
||||
(b.right, Rect::from_min_max(pos2(cr.right() - 1.0, cr.top()), cr.right_bottom())),
|
||||
] {
|
||||
if let Some(c) = line(side) {
|
||||
p.rect_filled(edge, 0.0, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
|
||||
@@ -70,7 +70,8 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
|
||||
None
|
||||
}
|
||||
},
|
||||
Key::Semicolon => {
|
||||
// Ctrl+Shift+; (the time) is in `keymap::lookup`; Cmd+Shift+; on a Mac does nothing.
|
||||
Key::Semicolon if !shift => {
|
||||
// Insert today's date.
|
||||
let text = app
|
||||
.session
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Space on a checkbox cell toggles it and nothing else (#1951).
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_engine::core::Value;
|
||||
use gridcraft_ui_egui::{SheetApp, grid::Geo};
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
fn harness(session: Session) -> Harness {
|
||||
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
|
||||
}
|
||||
|
||||
/// A space, as a keyboard reports it: the key press, the text it produces, then the release.
|
||||
fn space(h: &mut Harness) {
|
||||
let k = |pressed| Event::Key { key: Key::Space, physical_key: Some(Key::Space), pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
h.input_mut().events.push(k(true));
|
||||
h.input_mut().events.push(Event::Text(" ".into()));
|
||||
h.input_mut().events.push(k(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness, key: Key) {
|
||||
let k = |pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
h.input_mut().events.push(k(true));
|
||||
h.input_mut().events.push(k(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn value(h: &Harness, a1: &str) -> Option<Value> {
|
||||
let d = h.state().session.active().unwrap();
|
||||
d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_toggles_a_checkbox_cell_without_editing_it() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "FALSE"})).unwrap();
|
||||
s.execute("insert.checkbox", json!({"range": "B2"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
|
||||
|
||||
// The key press toggles the box; the text it also produces must not start editing, or Enter
|
||||
// commits that space over the checkbox and leaves the cell blank.
|
||||
space(&mut h);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)));
|
||||
assert!(h.state().editor.is_none(), "no editor opened");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "Enter moved on and left the checkbox");
|
||||
|
||||
// And again, back to unchecked. Reached without clicking the box, since a click on the box
|
||||
// toggles it in its own right (below): an ordinary cell, then across to it.
|
||||
click_cell(&mut h, "D2");
|
||||
press(&mut h, Key::ArrowLeft);
|
||||
press(&mut h, Key::ArrowLeft);
|
||||
assert_eq!(active(&h), "B2", "the arrows walked back to the checkbox");
|
||||
space(&mut h);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
|
||||
assert!(h.state().editor.is_none());
|
||||
|
||||
// A click on the box toggles it too, which is what the pointer path does with a checkbox
|
||||
// cell and the reason the walk above avoids it.
|
||||
click_cell(&mut h, "B2");
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "the click toggled the box");
|
||||
assert!(h.state().editor.is_none(), "no editor opened");
|
||||
|
||||
// A space still types on an ordinary cell.
|
||||
click_cell(&mut h, "C3");
|
||||
space(&mut h);
|
||||
assert!(h.state().editor.is_some(), "an ordinary cell starts editing");
|
||||
press(&mut h, Key::Escape);
|
||||
}
|
||||
|
||||
/// Click a cell, as a person selects one: the grid's own geometry gives where it is, so the
|
||||
/// click goes through hit-testing and whatever the grid does with focus, rather than the
|
||||
/// selection being set behind the app's back once it is running (#1960 review).
|
||||
fn click_cell(h: &mut Harness, cell: &str) {
|
||||
let pos = {
|
||||
let app = h.state();
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap();
|
||||
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
|
||||
geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center()
|
||||
};
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(2);
|
||||
// The click has to have landed: a selection that did not move would leave each assertion
|
||||
// after it testing the cell before it instead.
|
||||
assert_eq!(active(h), cell, "the click selected {cell}");
|
||||
}
|
||||
|
||||
/// The active cell, in A1 form.
|
||||
fn active(h: &Harness) -> String {
|
||||
h.state().session.active().unwrap().selection.active.to_string()
|
||||
}
|
||||
@@ -166,6 +166,54 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() {
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
|
||||
}
|
||||
|
||||
/// Where the title bar's icon button for `name` is. Its icon has no text, so it is found by
|
||||
/// hovering along the title bar until its tooltip ("Save (⌘S)") shows.
|
||||
fn title_bar_button(h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str) -> egui::Pos2 {
|
||||
let autosave = h.get_by_label("AutoSave").rect();
|
||||
let tip = format!("{name} (");
|
||||
let mut x = autosave.right();
|
||||
while x < autosave.right() + 300.0 {
|
||||
let at = egui::pos2(x, autosave.center().y);
|
||||
h.hover_at(at);
|
||||
h.run_steps(3);
|
||||
if h.query_by_label_contains(&tip).is_some() {
|
||||
return at;
|
||||
}
|
||||
x += 6.0;
|
||||
}
|
||||
panic!("no title bar button shows a {tip:?} tooltip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_bar_save_button_saves_the_cell_being_typed() {
|
||||
// Regression test for #223: the title bar's Save button saved the file without the cell the
|
||||
// user was still typing in.
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-title-bar-save-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.input_mut().events.push(egui::Event::Text("123".into()));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_some());
|
||||
let save = title_bar_button(&mut h, "Save");
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(egui::Event::PointerButton {
|
||||
pos: save,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none(), "Save commits the cell draft");
|
||||
let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0), "the saved file has the typed value");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Options opens, named Backstage pages are reachable and accessible, an invalid page errors, and both close and Back leave Backstage.
|
||||
fn file_options_opens_the_options_page_and_pages_are_reachable_by_command() {
|
||||
|
||||
@@ -287,7 +287,12 @@ fn table_filter_autofit_works_through_command_and_header_double_click() {
|
||||
let rect = geo.cell_rect(sheet, cell);
|
||||
let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell);
|
||||
let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell));
|
||||
let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z;
|
||||
// Measured as AutoFit measured it, with the app's fonts (they differ from machine to
|
||||
// machine). The app installs them before AutoFit runs; AutoFit without them, on the
|
||||
// engine's estimate, is `autofit_filter_buttons` in the engine's tests.
|
||||
let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts");
|
||||
let measured = measure("Quarterly Revenue", &style.font, true);
|
||||
let text_width = measured * geo.z;
|
||||
assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}");
|
||||
assert_eq!(app.session.active().unwrap().undo.len(), 1);
|
||||
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! IME composition at the grid level.
|
||||
//!
|
||||
//! With a CJK input method, the first keystroke of a composition must reach the input method,
|
||||
//! not be written straight into the cell as raw text. The grid publishes `PlatformOutput::ime`
|
||||
//! on every frame it owns keyboard input, so the OS delivers `ImeEvent`s; a `Commit` opens the
|
||||
//! in-cell editor with the finished text. Plain ASCII keeps using `Event::Text` (no regression).
|
||||
|
||||
use egui::{Event, ImeEvent};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
/// A warmed harness over `session`, with the grid holding keyboard input on the active cell.
|
||||
///
|
||||
/// The suite pins a font set with no Han face, so the harness draws tofu for the CJK commit
|
||||
/// text: these tests check input routing, not glyph coverage.
|
||||
fn fixture_with(session: Session) -> Harness {
|
||||
let builder = crate::common::builder().allow_missing_glyphs().with_size(egui::vec2(1200.0, 800.0));
|
||||
crate::common::harness_with(builder, crate::common::app(session), 4)
|
||||
}
|
||||
|
||||
/// A warmed harness over a blank workbook, with the grid holding keyboard input on `A1`.
|
||||
fn fixture() -> Harness {
|
||||
fixture_with(crate::support::blank_session())
|
||||
}
|
||||
|
||||
/// A protected sheet with `active` selected, optionally unlocking one cell first.
|
||||
fn protected_session(active: &str, unlock: Option<&str>) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
if let Some(cell) = unlock {
|
||||
s.execute("home.formatCells", json!({"range": cell, "style": {"protection": {"locked": false}}})).unwrap();
|
||||
}
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": active})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The text the in-cell editor currently holds, or `None` when no editor is open.
|
||||
fn editor_text(h: &Harness) -> Option<String> {
|
||||
h.state().editor.as_ref().map(|ed| ed.text.clone())
|
||||
}
|
||||
|
||||
/// The grid must request IME on every frame it owns keyboard input: winit applies
|
||||
/// `set_ime_allowed` at the end of the frame, so requesting it in response to the first key is
|
||||
/// already too late. The commit tests below only exercise the event handler and would still
|
||||
/// pass with `request_grid_ime` removed, so this asserts the actual fix.
|
||||
#[test]
|
||||
fn grid_publishes_ime_request_before_the_first_keystroke() {
|
||||
let mut h = fixture();
|
||||
h.run_steps(1);
|
||||
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
|
||||
assert!(matches!(ime.purpose, egui::IMEPurpose::Normal), "cell text is ordinary input");
|
||||
assert!(ime.rect.width() > 0.0 && ime.rect.height() > 0.0, "the IME rect must cover the active cell");
|
||||
assert_eq!(ime.cursor_rect.min, ime.rect.min, "the caret sits at the cell's start");
|
||||
assert!(ime.context_generation > 0, "egui 0.37 needs a non-zero IME context generation");
|
||||
}
|
||||
|
||||
/// When a dialog takes the keyboard, `PlatformOutput` must stop advertising a grid IME owner.
|
||||
/// The output is rebuilt each frame, so an early return is what turns IME off.
|
||||
#[test]
|
||||
fn grid_withholds_ime_request_when_it_does_not_own_keyboard_input() {
|
||||
let mut h = fixture();
|
||||
h.state_mut().message = Some(("GridCraft".into(), "busy".into()));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_none(), "a message dialog must take IME ownership away from the grid");
|
||||
}
|
||||
|
||||
/// A locked cell on a protected sheet cannot be edited, so inviting a composition there would
|
||||
/// only produce text that `SheetApp::begin_edit` discards.
|
||||
#[test]
|
||||
fn locked_cell_on_a_protected_sheet_does_not_request_ime() {
|
||||
let mut h = fixture_with(protected_session("A1", None));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_none(), "a composition on a locked cell is always refused");
|
||||
}
|
||||
|
||||
/// The protection guard must not disable IME for cells that are still editable.
|
||||
#[test]
|
||||
fn unlocked_cell_on_a_protected_sheet_still_requests_ime() {
|
||||
let mut h = fixture_with(protected_session("C2", Some("C2")));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_some(), "unlocked cells stay editable on a protected sheet");
|
||||
}
|
||||
|
||||
/// `IMEOutput::rect` is in screen coordinates, while `Geo::cell_rect` is in logical ones; on a
|
||||
/// right-to-left sheet the two differ, and the candidate window must follow the drawn cell.
|
||||
#[test]
|
||||
fn right_to_left_sheet_publishes_mirrored_ime_rects() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("view.rightToLeft", json!({"on": true})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": "B2"})).unwrap();
|
||||
let mut h = fixture_with(s);
|
||||
h.run_steps(1);
|
||||
|
||||
let geo = h.state().grid.geo.clone().expect("the grid has been drawn");
|
||||
let sheet = h.state().session.active().unwrap().wb.active().unwrap();
|
||||
let logical = geo.cell_rect(sheet, CellRef::parse("B2").unwrap());
|
||||
let expected = geo.mirror_rect(logical);
|
||||
assert!(geo.rtl, "the fixture must be right-to-left");
|
||||
assert!((expected.min.x - logical.min.x).abs() > 1.0, "the fixture must distinguish mirrored from logical x");
|
||||
|
||||
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
|
||||
assert!((ime.rect.min.x - expected.min.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
|
||||
assert!((ime.rect.max.x - expected.max.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
|
||||
assert!((ime.cursor_rect.min.x - ime.rect.min.x).abs() < 0.01, "the caret must sit at the mirrored cell's start");
|
||||
}
|
||||
|
||||
/// A committed composition opens the editor with its text and leaves the caret after it.
|
||||
#[test]
|
||||
fn ime_commit_opens_editor_with_committed_text() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
|
||||
h.run_steps(2);
|
||||
let ed = h.state().editor.as_ref().expect("an IME commit must open the in-cell editor");
|
||||
assert_eq!(ed.text, "张", "the committed text should seed the editor");
|
||||
assert_eq!(ed.caret, ed.text.chars().count(), "the caret should sit after the committed text");
|
||||
}
|
||||
|
||||
/// A preedit is not text yet: it must not open the editor on its own, only the commit does.
|
||||
#[test]
|
||||
fn ime_preedit_does_not_seed_editor() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Preedit { text: "zh".into(), active_range_chars: Some(0..2) }));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none(), "a preedit must not seed the editor on its own");
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("张"), "the commit after a preedit opens the editor");
|
||||
}
|
||||
|
||||
/// Plain ASCII never composes, so `Event::Text` still seeds the editor exactly as before.
|
||||
#[test]
|
||||
fn ascii_text_still_seeds_editor_no_regression() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Text("abc".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("abc"), "ASCII typing must still seed the editor");
|
||||
}
|
||||
@@ -19,6 +19,30 @@ fn blank() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_formulas_ribbon_keeps_watch_window_inside_the_ribbon() {
|
||||
// Regression test for #360 (#342): Watch Window was a fourth small button in a column of
|
||||
// three, so it hung below the ribbon and was cut off.
|
||||
fn texts(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, out)),
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = harness(blank());
|
||||
h.state_mut().ui.ribbon_tab = "Formulas".into();
|
||||
h.run_steps(3);
|
||||
// Ribbon button labels are painted text: find them among the frame's shapes.
|
||||
let mut painted = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| texts(&c.shape, &mut painted));
|
||||
let bottom_of = |word: &str| painted.iter().filter(|(s, _)| s.contains(word)).map(|(_, r)| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
|
||||
// "Calculation Options" is a big button whose second line sits at the foot of the ribbon.
|
||||
let (watch, foot) = (bottom_of("Window"), bottom_of("Options"));
|
||||
assert!(watch.is_finite() && foot.is_finite(), "the Formulas ribbon paints Watch Window and Calculation Options");
|
||||
assert!(watch <= foot + 0.5, "Watch Window's label ends at y={watch}, below the ribbon's last label row (y={foot})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_scrollbar_pages_and_drags_without_changing_selection() {
|
||||
let mut h = harness(blank());
|
||||
|
||||
@@ -212,6 +212,144 @@ fn alt_down_only_opens_enabled_table_filter_buttons() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A key press as a non-US layout reports it: `typed` is the character the layout types (egui's
|
||||
/// logical key), `at` the key's position named after a US keyboard.
|
||||
fn key_on_layout(h: &mut Harness, typed: Key, at: Key, m: Modifiers) {
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn editor_text(h: &Harness) -> Option<String> {
|
||||
h.state().editor.as_ref().map(|e| e.text.clone())
|
||||
}
|
||||
|
||||
fn today(h: &Harness) -> String {
|
||||
let d = h.state().session.active().unwrap();
|
||||
let now = gridcraft_engine::core::date::serial_in_system(d.wb.date_system, gridcraft_engine::calc::now_serial());
|
||||
gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(now.floor()), "m/d/yyyy", &d.wb).text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_shortcuts_follow_the_character_the_layout_types() {
|
||||
// Croatian and German keyboards type `;` with Shift+, and `:` with Shift+. (US positions).
|
||||
// `+` is unshifted, on the US `=` key (Croatian) or `]` key (German); `'` is the US `-` key
|
||||
// (Croatian) or Shift+# on the US `\` key (German); Shift+0 types `=` on both.
|
||||
for (layout, plus_at, quote_at, quote_shift) in [("hr", Key::Equals, Key::Minus, false), ("de", Key::CloseBracket, Key::Backslash, true)] {
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
// Ctrl+; (Ctrl+Shift+,): today's date, not Decrease Font Size.
|
||||
key_on_layout(&mut h, Key::Semicolon, Key::Comma, CTRL_SHIFT);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+; changed the font size");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl+: (Ctrl+Shift+.): the time, not Increase Font Size.
|
||||
key_on_layout(&mut h, Key::Colon, Key::Period, CTRL_SHIFT);
|
||||
let time = editor_text(&h).unwrap_or_default();
|
||||
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+: changed the font size");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl+': the formula of the cell above.
|
||||
key_on_layout(&mut h, Key::Quote, quote_at, if quote_shift { CTRL_SHIFT } else { CTRL });
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("=A1*2"), "{layout}: Ctrl+'");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl++: Insert, as Ctrl+Shift+= on a US keyboard.
|
||||
key_on_layout(&mut h, Key::Plus, plus_at, CTRL);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"), "{layout}: Ctrl++");
|
||||
h.state_mut().dialog = None;
|
||||
// Digits go by position: Ctrl+Shift+0 unhides columns although it types `=`.
|
||||
h.state_mut().session.run("selection.set", json!({"range": "B:B"})).unwrap();
|
||||
h.state_mut().session.run("home.hideColumns", json!({})).unwrap();
|
||||
h.state_mut().session.run("selection.set", json!({"range": "A1:C1"})).unwrap();
|
||||
key_on_layout(&mut h, Key::Equals, Key::Num0, CTRL_SHIFT);
|
||||
assert!(h.state().dialog.is_none(), "{layout}: Ctrl+Shift+0 opened {:?}", h.state().dialog.as_ref().map(|d| d.name()));
|
||||
let d = h.state().session.active().unwrap();
|
||||
assert!(!d.wb.active().unwrap().is_col_hidden(1), "{layout}: Ctrl+Shift+0 didn't unhide column B");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_and_time_shortcuts_on_azerty_and_czech_keyboards() {
|
||||
// French AZERTY types `;` and `:` unshifted on the US `,` and `.` keys; Czech QWERTZ types `;`
|
||||
// unshifted on the US backtick key and `:` with Shift+. (US positions).
|
||||
for (layout, semi_at, semi_m, colon_m) in [("fr", Key::Comma, CTRL, CTRL), ("cs", Key::Backtick, CTRL, CTRL_SHIFT)] {
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
key_on_layout(&mut h, Key::Semicolon, semi_at, semi_m);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
key_on_layout(&mut h, Key::Colon, Key::Period, colon_m);
|
||||
let time = editor_text(&h).unwrap_or_default();
|
||||
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: the font size changed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_keys_type_their_character_in_a_cell_being_edited() {
|
||||
// While a cell is edited the grid reads no shortcuts, so `;` and `:` (Shift+, and Shift+. on
|
||||
// Croatian and German keyboards) are typed, and nothing changes the font size.
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
h.input_mut().events.push(Event::Text("x".into()));
|
||||
h.run_steps(2);
|
||||
for (typed, at, text) in [(Key::Semicolon, Key::Comma, ";"), (Key::Colon, Key::Period, ":")] {
|
||||
let m = Modifiers::SHIFT;
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
|
||||
h.input_mut().events.push(Event::Text(text.into()));
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
|
||||
h.run_steps(2);
|
||||
}
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("x;:"));
|
||||
assert_eq!(style(&h, "C2").font.size, size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn us_symbol_shortcuts_keep_their_keys() {
|
||||
let mut h = harness(book("C2"));
|
||||
// Ctrl+;: the date. Ctrl+Shift+; arrives as `:` on Windows and as `;` with Shift elsewhere.
|
||||
key(&mut h, Key::Semicolon, CTRL);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)));
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
for typed in [Key::Colon, Key::Semicolon] {
|
||||
key_on_layout(&mut h, typed, Key::Semicolon, CTRL_SHIFT);
|
||||
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Ctrl+Shift+; as {typed:?}");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
}
|
||||
// Ctrl+Shift+, and Ctrl+Shift+. (`<` and `>` have no egui key) change the font size.
|
||||
let size = style(&h, "C2").font.size;
|
||||
key(&mut h, Key::Period, CTRL_SHIFT);
|
||||
assert!(style(&h, "C2").font.size > size);
|
||||
key(&mut h, Key::Comma, CTRL_SHIFT);
|
||||
assert_eq!(style(&h, "C2").font.size, size);
|
||||
// Ctrl+Shift+= arrives as `+`: Insert.
|
||||
key_on_layout(&mut h, Key::Plus, Key::Equals, CTRL_SHIFT);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"));
|
||||
let run = |id: &'static str| Some(Shortcut::Run(id, json!({})));
|
||||
// The lookup itself: `;` typed with Shift is Ctrl+; (handled with the Ctrl letters), not the
|
||||
// key's position (Decrease Font Size).
|
||||
assert_eq!(lookup(Key::Semicolon, Some(Key::Comma), CTRL_SHIFT, false), None);
|
||||
assert_eq!(lookup(Key::Colon, Some(Key::Period), CTRL_SHIFT, false), Some(Shortcut::Time));
|
||||
assert_eq!(lookup(Key::Comma, Some(Key::Comma), CTRL_SHIFT, false), run("home.decreaseFontSize"));
|
||||
// A character egui has no key for (`č` on the US `;` key) leaves the position.
|
||||
assert_eq!(lookup(Key::Semicolon, Some(Key::Semicolon), CTRL_SHIFT, false), Some(Shortcut::Time));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_shift_semicolon_on_a_mac_does_not_insert_the_date() {
|
||||
// The Mac table has Cmd+; (the time) and Control+; (the date), and nothing for Cmd+Shift+;. It
|
||||
// arrives as `:` on the US `;` key, or on the US `.` key of a Croatian or German keyboard.
|
||||
let mut h = harness(book("C2"));
|
||||
h.ctx.set_os(egui::os::OperatingSystem::Mac);
|
||||
let cmd_shift = Modifiers { shift: true, mac_cmd: true, command: true, ..Modifiers::NONE };
|
||||
for at in [Key::Semicolon, Key::Period] {
|
||||
key_on_layout(&mut h, Key::Colon, at, cmd_shift);
|
||||
assert_eq!(editor_text(&h), None, "Cmd+Shift+; at {at:?}");
|
||||
}
|
||||
key(&mut h, Key::Semicolon, Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE });
|
||||
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Cmd+; is still the time");
|
||||
}
|
||||
|
||||
/// #1443: Ctrl+Q (also with Shift or Alt, which is what AltGr+Q reports on Windows) must not
|
||||
/// close the window and lose unsaved input; macOS keeps Cmd+Q as the app's Quit.
|
||||
#[test]
|
||||
|
||||
@@ -59,6 +59,7 @@ mod header_column_drag;
|
||||
mod host_chrome;
|
||||
mod hyperlink_ctrl_click;
|
||||
mod hyperlink_dialog;
|
||||
mod ime_composition;
|
||||
mod in_cell_editor_size;
|
||||
mod in_cell_editor_wrap;
|
||||
mod ink_render;
|
||||
|
||||
@@ -57,3 +57,47 @@ fn pivot_field_button_surfaces_follow_the_active_theme() {
|
||||
assert_eq!(field_button_fill(&shapes, "Region ▾"), expected, "dark mode: {dark}");
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(shape: Shape, out: &mut Vec<Shape>) {
|
||||
match shape {
|
||||
Shape::Vec(shapes) => shapes.into_iter().for_each(|s| flatten(s, out)),
|
||||
s => out.push(s),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_field_list_scrollbar_sits_at_the_pane_edge() {
|
||||
// Regression test for #1485: with enough source fields to scroll, the field list's scrollbar
|
||||
// sat just right of the longest (short) field name instead of at the pane's right edge.
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
let names: Vec<String> = (1..=14).map(|i| format!("F{i}")).collect();
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("range.setValues", json!({"range": "A1", "values": [names.clone(), (1..=14).collect::<Vec<i32>>()]})).unwrap();
|
||||
session.execute("insert.pivotTable", json!({"source": "Sheet1!A1:N2", "destination": "Sheet1!A5", "rows": ["F1"], "values": ["F2"]})).unwrap();
|
||||
session.execute("selection.set", json!({"cell": "A5"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(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);
|
||||
let first = h.get_by_label("F1").rect();
|
||||
// A floating scrollbar is drawn while the pointer is over its area.
|
||||
h.get_by_label("F1").hover();
|
||||
h.run_steps(3);
|
||||
let mut shapes = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| flatten(c.shape.clone(), &mut shapes));
|
||||
let bar = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 12.0 && r.rect.height() >= 20.0 && r.rect.left() > first.left() => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.max_by(|a, b| a.right().total_cmp(&b.right()))
|
||||
.expect("the field list draws a scrollbar");
|
||||
assert!(bar.right() > 1200.0 - 20.0, "the scrollbar {bar:?} sits at the pane's right edge, not beside the field names ({first:?})");
|
||||
}
|
||||
@@ -335,6 +335,18 @@ mod tests {
|
||||
assert!(checked > gridcraft_functions::all().len() * 10, "only {checked} formulas parsed");
|
||||
}
|
||||
|
||||
/// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list: saved without
|
||||
/// `_xlfn.` (LibreOffice gives #NAME? for the prefixed spelling), and the prefixed spelling of a
|
||||
/// file written by an older version still reads (#3517, #2775).
|
||||
#[test]
|
||||
fn intl_day_functions_are_saved_without_the_prefix() {
|
||||
let f = Formula::new("NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)");
|
||||
assert_eq!(to_file(&f), "NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)");
|
||||
assert_eq!(text_to_file("=WORKDAY.INTL(A1,3,1)"), "WORKDAY.INTL(A1,3,1)");
|
||||
assert_eq!(from_file("_xlfn.NETWORKDAYS.INTL(A1,B1,1)+_xlfn.WORKDAY.INTL(A1,3,1)"), "NETWORKDAYS.INTL(A1,B1,1)+WORKDAY.INTL(A1,3,1)");
|
||||
assert_eq!(from_file("NETWORKDAYS.INTL(A1,B1,1)"), "NETWORKDAYS.INTL(A1,B1,1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spill_references() {
|
||||
assert_eq!(to_file(&Formula::new("SUM(Sheet1!$D$1#)+B2#")), "SUM(_xlfn.ANCHORARRAY(Sheet1!$D$1))+_xlfn.ANCHORARRAY(B2)");
|
||||
|
||||
+17
-2
@@ -233,6 +233,7 @@ struct Import {
|
||||
text: u64,
|
||||
formats: Vec<(&'static str, StyleId)>,
|
||||
spreadsheet_seen: bool,
|
||||
names: crate::read::SheetNames,
|
||||
}
|
||||
|
||||
impl Import {
|
||||
@@ -241,7 +242,20 @@ impl Import {
|
||||
wb.sheets.clear();
|
||||
let mut report = ReadReport::default();
|
||||
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
|
||||
Self { wb, report, stack: vec![], sheet: None, row: None, cell: None, cells: 0, merges: 0, text: 0, formats: vec![], spreadsheet_seen: false }
|
||||
Self {
|
||||
wb,
|
||||
report,
|
||||
stack: vec![],
|
||||
sheet: None,
|
||||
row: None,
|
||||
cell: None,
|
||||
cells: 0,
|
||||
merges: 0,
|
||||
text: 0,
|
||||
formats: vec![],
|
||||
spreadsheet_seen: false,
|
||||
names: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(&mut self, bytes: &[u8]) -> Result<(), IoError> {
|
||||
@@ -317,9 +331,10 @@ impl Import {
|
||||
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
|
||||
}
|
||||
let original = attr(reader, e, TABLE, b"name")?.unwrap_or_default();
|
||||
let mut name = crate::read::SheetNames::of(&self.wb).unique(original.trim_matches('\''), self.wb.sheets.len());
|
||||
let mut name = self.names.unique(original.trim_matches('\''), self.wb.sheets.len());
|
||||
if self.wb.check_sheet_name(&name, None).is_err() {
|
||||
name = self.wb.next_sheet_name();
|
||||
self.names.insert(&name);
|
||||
}
|
||||
if name != original {
|
||||
self.report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
CellRef, Ctx, DateSystem, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout,
|
||||
PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet, same,
|
||||
PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet,
|
||||
};
|
||||
|
||||
// ================================================================ reading
|
||||
@@ -118,8 +118,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
};
|
||||
let sys = cx.date_system;
|
||||
let mut fields = Vec::new();
|
||||
let mut truncated = false;
|
||||
if let Some(cf) = x.child("cacheFields") {
|
||||
for f in cf.kids("cacheField").take(MAX_FIELDS) {
|
||||
for f in capped(cf.kids("cacheField"), &mut truncated) {
|
||||
let items = f.child("sharedItems").map(|si| si.children.iter().map(|e| item_label_el(e, sys)).collect()).unwrap_or_default();
|
||||
let group = f.child("fieldGroup").map(|g| {
|
||||
let base = g.attr_u32("base").map(|b| b as usize);
|
||||
@@ -142,6 +143,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
});
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
cx.warn(format!("{part}: cache fields past {MAX_FIELDS} were dropped; its PivotTables may be incomplete"));
|
||||
}
|
||||
if fields.is_empty() {
|
||||
cx.warn("a PivotTable's cache has no fields; kept as plain cells");
|
||||
return None;
|
||||
@@ -231,14 +235,25 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
cx.warn(format!("PivotTable \"{}\" has no valid location; kept as plain cells", pt.name));
|
||||
return None;
|
||||
};
|
||||
let pfs: Vec<&El> = x.child("pivotFields").map(|p| p.kids("pivotField").collect()).unwrap_or_default();
|
||||
// Field lists are capped, and a field is used once (Excel puts a field on one axis, once):
|
||||
// each use walks the field's items.
|
||||
// A list cut at the cap is reported, so an incomplete PivotTable can be told apart.
|
||||
let mut truncated = false;
|
||||
let pfs: Vec<&El> = x.child("pivotFields").map(|p| capped(p.kids("pivotField"), &mut truncated)).unwrap_or_default();
|
||||
let pf = |i: usize| pfs.get(i).copied();
|
||||
let idx_list = |name: &str, attr: &str| -> Vec<i64> {
|
||||
x.child(name).map(|e| e.children.iter().filter_map(|f| f.attr_i64(attr)).collect()).unwrap_or_default()
|
||||
let mut used_fields = std::collections::HashSet::new();
|
||||
let mut idx_list = |name: &str, attr: &str| -> Vec<i64> {
|
||||
x.child(name)
|
||||
.map(|e| capped(e.children.iter().filter_map(|f| f.attr_i64(attr)).filter(|&i| i < 0 || used_fields.insert(i)), &mut truncated))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let row_x = idx_list("rowFields", "x");
|
||||
let col_x = idx_list("colFields", "x");
|
||||
let pages: Vec<&El> = x.child("pageFields").map(|p| p.kids("pageField").collect()).unwrap_or_default();
|
||||
let mut page_fields = std::collections::HashSet::new();
|
||||
let pages: Vec<&El> = x
|
||||
.child("pageFields")
|
||||
.map(|p| capped(p.kids("pageField").filter(|f| f.attr_i64("fld").is_none_or(|i| page_fields.insert(i))), &mut truncated))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Layout from the first axis field (pivotField defaults: compact and outline on).
|
||||
let first_axis = row_x.iter().chain(col_x.iter()).find(|i| **i >= 0).and_then(|i| pf(*i as usize));
|
||||
@@ -268,8 +283,11 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
|
||||
let mut filters: Vec<PivotFilter> = Vec::new();
|
||||
|
||||
// Lower-cased names of the fields already filtered on an axis, the first of which wins (as
|
||||
// `same` compares them): scanning the filters for each field would be quadratic.
|
||||
let mut axis_filtered: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
// (fields, position of Σ Values (`-2`) among them)
|
||||
let axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec<PivotFilter>| -> (Vec<PivotField>, Option<usize>) {
|
||||
let mut axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec<PivotFilter>| -> (Vec<PivotField>, Option<usize>) {
|
||||
let mut v = Vec::new();
|
||||
let mut values_at = None;
|
||||
for &i in list {
|
||||
@@ -282,7 +300,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
let i = i as usize;
|
||||
let Some((name, group)) = field_ref(cx, cache, i) else { continue };
|
||||
let labels = cache.fields.get(i).map(|f| f.labels().to_vec()).unwrap_or_default();
|
||||
let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]);
|
||||
let mut f = PivotField { source_col: name.clone(), date_group: group, sort: PivotSort::None, collapsed_items: vec![] };
|
||||
if let Some(e) = pf(i) {
|
||||
f.sort = match e.attr("sortType") {
|
||||
@@ -293,11 +311,9 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
let items = items_of(e);
|
||||
let lab = |it: &El| it.attr_u32("x").and_then(|k| labels.get(k as usize)).cloned();
|
||||
f.collapsed_items = items.iter().filter(|it| !it.flag("sd", true)).filter_map(|it| lab(it)).collect();
|
||||
if items.iter().any(|it| it.flag("h", false)) {
|
||||
if items.iter().any(|it| it.flag("h", false)) && axis_filtered.insert(name.to_lowercase()) {
|
||||
let shown: Vec<String> = items.iter().filter(|it| !it.flag("h", false)).filter_map(|it| lab(it)).collect();
|
||||
if !filters.iter().any(|ff| same(&ff.source_col, &name)) {
|
||||
filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) });
|
||||
}
|
||||
filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) });
|
||||
}
|
||||
}
|
||||
v.push(f);
|
||||
@@ -308,7 +324,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
for p in &pages {
|
||||
let Some(i) = p.attr_i64("fld").filter(|i| *i >= 0).map(|i| i as usize) else { continue };
|
||||
let Some((name, _)) = field_ref(cx, cache, i) else { continue };
|
||||
let labels = cache.fields.get(i).map(|f| f.labels().to_vec()).unwrap_or_default();
|
||||
let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]);
|
||||
let selected = if let Some(k) = p.attr_u32("item") {
|
||||
labels.get(k as usize).map(|l| vec![l.clone()])
|
||||
} else {
|
||||
@@ -341,7 +357,8 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
|
||||
// Values.
|
||||
if let Some(df) = x.child("dataFields") {
|
||||
for d in df.kids("dataField") {
|
||||
truncated |= df.kids("dataField").nth(MAX_FIELDS).is_some();
|
||||
for d in df.kids("dataField").take(MAX_FIELDS) {
|
||||
let Some(i) = d.attr_u32("fld").map(|i| i as usize) else { continue };
|
||||
let Some(f) = cache.fields.get(i) else { continue };
|
||||
let func = match d.attr("subtotal") {
|
||||
@@ -382,11 +399,13 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
}
|
||||
|
||||
// Calculated fields of the cache (each PivotTable on it can use them).
|
||||
// Calculated fields of the cache (each PivotTable on it can use them); the first of a
|
||||
// lower-cased name wins, looked up in a set rather than by scanning the fields kept so far.
|
||||
let mut calc_names: std::collections::HashSet<String> = pt.calculated_fields.iter().map(|c| c.name.to_lowercase()).collect();
|
||||
for f in &cache.fields {
|
||||
if let Some(formula) = &f.formula
|
||||
&& !f.name.trim().is_empty()
|
||||
&& !pt.calculated_fields.iter().any(|c| same(&c.name, &f.name))
|
||||
&& calc_names.insert(f.name.to_lowercase())
|
||||
{
|
||||
let formula = formula.trim();
|
||||
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
|
||||
@@ -394,8 +413,21 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
}
|
||||
|
||||
if truncated {
|
||||
cx.warn(format!("PivotTable \"{}\": field lists past {MAX_FIELDS} entries were dropped; the table is incomplete", pt.name));
|
||||
}
|
||||
pt.anchor = loc.start;
|
||||
let above = if pages.is_empty() { 0 } else { pages.len() as u32 + 1 };
|
||||
pt.last_range = Some(RangeRef::new(CellRef::new(loc.start.row.saturating_sub(above), loc.start.col), loc.end));
|
||||
Some(pt)
|
||||
}
|
||||
|
||||
/// The first [`MAX_FIELDS`] items; sets `truncated` when there were more.
|
||||
fn capped<T>(items: impl Iterator<Item = T>, truncated: &mut bool) -> Vec<T> {
|
||||
let mut v: Vec<T> = items.take(MAX_FIELDS.saturating_add(1)).collect();
|
||||
if v.len() > MAX_FIELDS {
|
||||
v.truncate(MAX_FIELDS);
|
||||
*truncated = true;
|
||||
}
|
||||
v
|
||||
}
|
||||
+69
-44
@@ -51,6 +51,57 @@ pub struct Ctx<'a> {
|
||||
pub known_function: Option<&'a dyn Fn(&str) -> bool>,
|
||||
/// The code of the workbook's Python cells, from its Python part.
|
||||
pub python: crate::python_part::ScriptsIn,
|
||||
/// Cell elements read so far, across every sheet (capped by `sheet_read::MAX_CELLS`).
|
||||
pub cells: u64,
|
||||
}
|
||||
|
||||
/// The most worksheets read from one workbook (as the XLS reader allows).
|
||||
const MAX_SHEETS: usize = 4096;
|
||||
/// The most shared strings read from one workbook (as the XLS reader allows): each is an
|
||||
/// `Arc<str>` of its own, so a hundred million tiny `<si/>` would ask for gigabytes.
|
||||
const MAX_STRINGS: usize = 4_000_000;
|
||||
|
||||
/// Sheet names taken while reading, compared as `Workbook::sheet_index` compares them (ASCII case
|
||||
/// folded), with the next `(n)` suffix to try for each base, so renaming duplicates stays linear.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SheetNames {
|
||||
taken: HashSet<String>,
|
||||
next_suffix: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl SheetNames {
|
||||
/// Records `name` as taken.
|
||||
pub(crate) fn insert(&mut self, name: &str) {
|
||||
self.taken.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
|
||||
/// A valid name for the `i`-th sheet based on `name`, not yet taken; it is recorded as taken.
|
||||
pub(crate) fn unique(&mut self, name: &str, i: usize) -> String {
|
||||
let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect();
|
||||
if base.trim().is_empty() {
|
||||
base = format!("Sheet{}", i + 1);
|
||||
}
|
||||
if self.taken.insert(base.to_ascii_lowercase()) {
|
||||
return base;
|
||||
}
|
||||
let key: String = base.chars().take(25).collect::<String>().to_ascii_lowercase();
|
||||
let mut n = self.next_suffix.get(&key).copied().unwrap_or(2);
|
||||
loop {
|
||||
// 25 characters of the base, fewer once the suffix grows past ` (999)`, so the name
|
||||
// stays within 31 characters however many duplicates there are.
|
||||
let suffix = format!(" ({n})");
|
||||
let short: String = base.chars().take(31usize.saturating_sub(suffix.len()).min(25)).collect();
|
||||
let candidate = format!("{short}{suffix}");
|
||||
n = n.saturating_add(1);
|
||||
if self.taken.insert(candidate.to_ascii_lowercase()) {
|
||||
self.next_suffix.insert(key, n);
|
||||
return candidate;
|
||||
}
|
||||
if n == usize::MAX {
|
||||
return base;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
@@ -125,6 +176,9 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError>
|
||||
let mut phonetics = Vec::new();
|
||||
let mut dropped = 0usize;
|
||||
let res = xml::parse_streaming(&b, &["si"], &mut |si| {
|
||||
if sst.len() >= MAX_STRINGS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_STRINGS} shared strings")));
|
||||
}
|
||||
let text = xml::rich_text(&si);
|
||||
let raw = si.kids("rPh").count();
|
||||
let (runs, props) = xml::phonetic_data(&si, &text);
|
||||
@@ -135,8 +189,10 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError>
|
||||
sst.push(Arc::from(text));
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = res {
|
||||
cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len()));
|
||||
match res {
|
||||
Ok(_) => {}
|
||||
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
|
||||
Err(e) => cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len())),
|
||||
}
|
||||
if dropped > 0 {
|
||||
cx.warn(format!("shared strings: {dropped} phonetic runs were dropped (bad sb/eb or no reading)"));
|
||||
@@ -274,6 +330,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
shared_formula_bytes: 0,
|
||||
known_function,
|
||||
python: Default::default(),
|
||||
cells: 0,
|
||||
};
|
||||
let root_rels = cx.pkg.rels("")?;
|
||||
let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into());
|
||||
@@ -325,11 +382,19 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
// Legacy formula cells per model sheet, rewritten once names and tables are known.
|
||||
let mut legacy_formulas: Vec<(usize, Vec<gridcraft_core::CellRef>)> = vec![];
|
||||
let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels);
|
||||
let sheet_els: Vec<El> = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default();
|
||||
let sheet_els: Vec<&El> = wb_xml.child("sheets").map(|s| s.kids("sheet").collect()).unwrap_or_default();
|
||||
if sheet_els.len() > MAX_SHEETS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_SHEETS} sheets")));
|
||||
}
|
||||
let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(wb_rels.len());
|
||||
for r in &wb_rels {
|
||||
// The first of duplicate ids wins, as a linear search would find it.
|
||||
rel_by_id.entry(r.id.as_str()).or_insert(r);
|
||||
}
|
||||
let mut names = SheetNames::default();
|
||||
for (i, se) in sheet_els.iter().enumerate() {
|
||||
let name = se.attr("name").unwrap_or("").to_string();
|
||||
let rel = se.attr("id").and_then(|id| wb_rels.iter().find(|r| r.id == id)).cloned();
|
||||
let rel = se.attr("id").and_then(|id| rel_by_id.get(id).copied()).cloned();
|
||||
let Some(rel) = rel else {
|
||||
cx.warn(format!("sheet \"{name}\" has no part; skipped"));
|
||||
file_to_model.push(None);
|
||||
@@ -485,46 +550,6 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
Ok((wb, cx.report))
|
||||
}
|
||||
|
||||
/// The sheet names an import has assigned so far, for repairing repeated ones.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SheetNames {
|
||||
/// Assigned names, ASCII-lowercased.
|
||||
taken: HashSet<String>,
|
||||
/// For each lowercased stem, the next suffix to try: a file full of repeated names would
|
||||
/// otherwise retry every occupied suffix for every sheet.
|
||||
next: HashMap<String, u64>,
|
||||
}
|
||||
|
||||
impl SheetNames {
|
||||
pub(crate) fn of(wb: &Workbook) -> Self {
|
||||
SheetNames { taken: wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect(), next: HashMap::new() }
|
||||
}
|
||||
|
||||
/// A valid name for the i-th sheet, unique among the names assigned so far, which it joins.
|
||||
pub(crate) fn unique(&mut self, name: &str, i: usize) -> String {
|
||||
let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect();
|
||||
if base.trim().is_empty() {
|
||||
base = format!("Sheet{}", i + 1);
|
||||
}
|
||||
let name = if self.taken.contains(&base.to_ascii_lowercase()) {
|
||||
let stem: String = base.chars().take(25).collect();
|
||||
let next = self.next.entry(stem.to_ascii_lowercase()).or_insert(2);
|
||||
let found = (*next..).find(|n| !self.taken.contains(&format!("{stem} ({n})").to_ascii_lowercase()));
|
||||
match found {
|
||||
Some(n) => {
|
||||
*next = n + 1;
|
||||
format!("{stem} ({n})")
|
||||
}
|
||||
None => base,
|
||||
}
|
||||
} else {
|
||||
base
|
||||
};
|
||||
self.taken.insert(name.to_ascii_lowercase());
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
/// Strips a sheet qualifier (`'My Sheet'!$A$1` → `$A$1`).
|
||||
fn strip_sheet(s: &str) -> &str {
|
||||
match s.rfind('!') {
|
||||
|
||||
@@ -134,6 +134,9 @@ fn settle_python_spills_past_budget(st: &RowState, sheet: &mut Sheet) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most cell elements read from one workbook, across its sheets: the reader's own cap.
|
||||
/// (`calc::eval::MAX_CELLS` has the same value but limits one array result, not a workbook.)
|
||||
pub(crate) const MAX_CELLS: u64 = 16_000_000;
|
||||
/// Target and tooltip bytes kept for hyperlinks of one sheet, over all cells: the same URL is
|
||||
/// copied for every cell of its range, so length × cells must stay bounded whatever the file.
|
||||
const MAX_HYPERLINK_BYTES: u64 = 8 * 1024 * 1024;
|
||||
@@ -191,12 +194,10 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
let rels = cx.pkg.rels(part)?;
|
||||
let mut sheet = Sheet::new(name);
|
||||
let mut st = RowState::default();
|
||||
let res = xml::parse_streaming(&bytes, &["row"], &mut |row| {
|
||||
read_row(cx, &mut sheet, &mut st, &row);
|
||||
Ok(())
|
||||
});
|
||||
let res = xml::parse_streaming(&bytes, &["row"], &mut |row| read_row(cx, &mut sheet, &mut st, &row));
|
||||
let root = match res {
|
||||
Ok(r) => r,
|
||||
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
|
||||
Err(e) => {
|
||||
cx.warn(format!("sheet \"{name}\" is damaged ({e}); kept {} rows", st.rows));
|
||||
El::default()
|
||||
@@ -208,6 +209,12 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
settle_python_spills_past_budget(&st, &mut sheet);
|
||||
drop(bytes);
|
||||
|
||||
// Relationships by id: hyperlinks, drawings and tables each look one up.
|
||||
let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(rels.len());
|
||||
for r in &rels {
|
||||
// The first of duplicate ids wins, as a linear search would find it.
|
||||
rel_by_id.entry(r.id.as_str()).or_insert(r);
|
||||
}
|
||||
let mut fit_to_page = false;
|
||||
let mut link_budget = LinkBudget::default();
|
||||
let mut cf_kept_cells = 0u64;
|
||||
@@ -245,7 +252,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
}
|
||||
}
|
||||
}
|
||||
"hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_budget),
|
||||
"hyperlinks" => read_hyperlinks(cx, name, e, &rel_by_id, &mut sheet, &mut link_budget),
|
||||
"autoFilter" => sheet.autofilter = read_autofilter(cx, e),
|
||||
"printOptions" => {
|
||||
sheet.print.gridlines = e.flag("gridLines", false);
|
||||
@@ -319,14 +326,14 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
});
|
||||
}
|
||||
"drawing" => {
|
||||
if let Some(rel) = e.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) {
|
||||
if let Some(rel) = e.attr("id").and_then(|id| rel_by_id.get(id).copied()) {
|
||||
let target = rel.target.clone();
|
||||
crate::drawing::read_drawing(cx, &target, &mut sheet)?;
|
||||
}
|
||||
}
|
||||
"tableParts" => {
|
||||
for tp in e.kids("tablePart") {
|
||||
if let Some(rel) = tp.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) {
|
||||
if let Some(rel) = tp.attr("id").and_then(|id| rel_by_id.get(id).copied()) {
|
||||
let target = rel.target.clone();
|
||||
if let Some(x) = cx.optional_xml(&target)?
|
||||
&& let Some(mut t) = read_table(cx, &x)
|
||||
@@ -496,19 +503,30 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
/// Charges `n` cell elements against the workbook's [`MAX_CELLS`].
|
||||
fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> {
|
||||
cx.cells = cx.cells.saturating_add(n);
|
||||
if cx.cells > MAX_CELLS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_CELLS} cells")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One `<row>`. Every `<c>` in it counts against [`MAX_CELLS`], also in a row that is dropped
|
||||
/// for a bad row number: one worksheet part read for many sheets can't parse cells uncounted.
|
||||
fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) -> Result<(), IoError> {
|
||||
st.rows += 1;
|
||||
let r = match row.attr_u32("r") {
|
||||
Some(r) if r >= 1 => r - 1,
|
||||
Some(_) => {
|
||||
st.dropped += 1;
|
||||
return;
|
||||
return charge_cells(cx, row.kids("c").count() as u64);
|
||||
}
|
||||
None => st.next_row,
|
||||
};
|
||||
if r >= MAX_ROWS {
|
||||
st.dropped += 1;
|
||||
return;
|
||||
return charge_cells(cx, row.kids("c").count() as u64);
|
||||
}
|
||||
st.next_row = r + 1;
|
||||
let mut info = LineInfo::default();
|
||||
@@ -532,6 +550,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
}
|
||||
let mut next_col = 0u32;
|
||||
for c in row.kids("c") {
|
||||
charge_cells(cx, 1)?;
|
||||
let pos = match c.attr("r") {
|
||||
Some(a) => match CellRef::parse(a.trim()) {
|
||||
Some(p) => p,
|
||||
@@ -549,6 +568,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
next_col = pos.col + 1;
|
||||
read_cell(cx, sheet, st, c, pos);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos: CellRef) {
|
||||
@@ -657,6 +677,14 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos
|
||||
Some(_) => Value::Empty,
|
||||
None => value,
|
||||
};
|
||||
// A dynamic array keeps the area it was saved spilling over (`ref`): when two arrays want the
|
||||
// same cells, recalculating gives them to this one again, as before saving.
|
||||
if dynamic
|
||||
&& formula.as_ref().is_some_and(|f| f.array.is_none())
|
||||
&& let Some(r) = st.dynamic.last().filter(|r| r.start == pos)
|
||||
{
|
||||
sheet.spill_ranges.insert(pos, *r);
|
||||
}
|
||||
sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style, py });
|
||||
}
|
||||
|
||||
@@ -921,6 +949,57 @@ mod tests {
|
||||
assert_eq!(parse_iso_datetime("2024-13-01", DateSystem::D1900), None);
|
||||
}
|
||||
|
||||
fn ctx(pkg: crate::package::Package<'_>) -> Ctx<'_> {
|
||||
Ctx {
|
||||
pkg,
|
||||
report: Default::default(),
|
||||
sst: vec![],
|
||||
phonetics: vec![],
|
||||
xf_map: vec![],
|
||||
dxfs: vec![],
|
||||
palette: vec![],
|
||||
date_system: DateSystem::D1900,
|
||||
styles: Default::default(),
|
||||
persons: Default::default(),
|
||||
next_id: 1,
|
||||
num_fmts: Default::default(),
|
||||
cell_pictures: vec![],
|
||||
cf_ext_ids: vec![],
|
||||
known_function: None,
|
||||
python: Default::default(),
|
||||
cells: 0,
|
||||
shared_formula_bytes: 0,
|
||||
legacy_formulas: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// #2159: the workbook-wide cell cap refuses the open once passed, across sheets.
|
||||
#[test]
|
||||
fn cells_past_the_workbook_cap_are_refused() {
|
||||
let bytes = crate::tests::minimal(r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="B1"><v>2</v></c></row></sheetData>"#, &[], "", "");
|
||||
let pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let mut cx = ctx(pkg);
|
||||
cx.cells = MAX_CELLS - 2;
|
||||
let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap();
|
||||
assert_eq!(sheet.cells.len(), 2);
|
||||
assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_))));
|
||||
}
|
||||
|
||||
/// #2159: the cells of a row dropped for its row number still count against the cap, so a
|
||||
/// part read for many sheets can't parse cells uncounted.
|
||||
#[test]
|
||||
fn cells_of_dropped_rows_count_against_the_cap() {
|
||||
let rows = r#"<sheetData><row r="0"><c><v>1</v></c><c><v>2</v></c></row><row r="2000000"><c><v>3</v></c></row></sheetData>"#;
|
||||
let bytes = crate::tests::minimal(rows, &[], "", "");
|
||||
let pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let mut cx = ctx(pkg);
|
||||
let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap();
|
||||
assert!(sheet.cells.is_empty(), "both rows are dropped");
|
||||
assert_eq!(cx.cells, 3);
|
||||
cx.cells = MAX_CELLS - 2;
|
||||
assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqref_keeps_more_than_ten_thousand_ranges() {
|
||||
let sq = (1..=12_000).map(|r| format!("A{r}")).collect::<Vec<_>>().join(" ");
|
||||
|
||||
@@ -4,12 +4,12 @@ use super::{
|
||||
from_file, truncate_chars, xml,
|
||||
};
|
||||
|
||||
/// `budget` counts the cells and bytes this sheet's hyperlinks have copied so far, across
|
||||
/// `<hyperlinks>` blocks.
|
||||
pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, budget: &mut LinkBudget) {
|
||||
/// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the
|
||||
/// cells and bytes this sheet's hyperlinks have copied so far, across `<hyperlinks>` blocks.
|
||||
pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) {
|
||||
for h in e.kids("hyperlink") {
|
||||
let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue };
|
||||
let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or("");
|
||||
let rel_target = h.attr("id").and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or("");
|
||||
let location = h.attr("location").filter(|l| !l.is_empty());
|
||||
// Each covered cell gets its own copy of the link: refuse oversized targets before copying.
|
||||
if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET {
|
||||
|
||||
@@ -854,6 +854,11 @@ fn write_cell(s: &mut String, input: CellWriteInput<'_>, sid: &dyn Fn(gridcraft_
|
||||
Value::Number(n) => {
|
||||
let _ = write!(s, "><v>{}</v></c>", num(*n));
|
||||
}
|
||||
// Text inside a spill or array range is a cached formula result: Excel writes it as `t="str"`
|
||||
// and shows #VALUE! for a shared string there when it trusts the saved values.
|
||||
Value::Text(t) if extra.is_some() => {
|
||||
let _ = write!(s, " t=\"str\"><v>{}</v></c>", esc(&encode_xstring(t)));
|
||||
}
|
||||
Value::Text(t) => {
|
||||
let i = out.sst.index(t);
|
||||
let _ = write!(s, " t=\"s\"><v>{i}</v></c>");
|
||||
|
||||
@@ -111,6 +111,7 @@ pub fn paper_id(name: &str) -> Option<u32> {
|
||||
|
||||
/// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with
|
||||
/// `_xlws.` get `_xlfn._xlws.`.
|
||||
/// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list, so they're saved without `_xlfn.` (#3517).
|
||||
const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"ACOT",
|
||||
"ACOTH",
|
||||
@@ -207,7 +208,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"MODE.SNGL",
|
||||
"MUNIT",
|
||||
"NEGBINOM.DIST",
|
||||
"NETWORKDAYS.INTL",
|
||||
"NORM.DIST",
|
||||
"NORM.INV",
|
||||
"NORM.S.DIST",
|
||||
@@ -270,7 +270,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"VSTACK",
|
||||
"WEBSERVICE",
|
||||
"WEIBULL.DIST",
|
||||
"WORKDAY.INTL",
|
||||
"WRAPCOLS",
|
||||
"WRAPROWS",
|
||||
"XLOOKUP",
|
||||
@@ -381,8 +380,8 @@ mod tests {
|
||||
assert_eq!(file_function_name("stockhistory").as_deref(), Some("_xlfn.STOCKHISTORY"));
|
||||
assert_eq!(file_function_name("TRANSLATE").as_deref(), Some("_xlfn.TRANSLATE"));
|
||||
assert_eq!(file_function_name("DETECTLANGUAGE").as_deref(), Some("_xlfn.DETECTLANGUAGE"));
|
||||
assert_eq!(file_function_name("NETWORKDAYS.INTL").as_deref(), Some("_xlfn.NETWORKDAYS.INTL"));
|
||||
assert_eq!(file_function_name("WORKDAY.INTL").as_deref(), Some("_xlfn.WORKDAY.INTL"));
|
||||
assert_eq!(file_function_name("NETWORKDAYS.INTL"), None);
|
||||
assert_eq!(file_function_name("WORKDAY.INTL"), None);
|
||||
// Excel 16.0 build 20527 saves COPILOT as plain `COPILOT(...)` (it does not know the name yet).
|
||||
assert_eq!(file_function_name("COPILOT"), None);
|
||||
assert_eq!(file_function_name("SUM"), None);
|
||||
|
||||
@@ -623,3 +623,24 @@ fn long_flat_chains_are_scalar_formulas() {
|
||||
assert_dynamic(&sheet, "B4", "B4");
|
||||
assert_eq!(cell(&sheet, "B1").child("f").unwrap().text, refs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spilled_text_is_written_as_a_cached_string_not_a_shared_string() {
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let mut anchor = Cell::formula(Formula::new("SORT({\"b\";\"a\";\"c\"})"));
|
||||
anchor.value = Value::text("a");
|
||||
sh.cells.set(at("K4"), anchor);
|
||||
sh.spill_ranges.insert(at("K4"), range("K4:K6"));
|
||||
sh.spill.insert(at("K5"), Value::text("b"));
|
||||
sh.spill.insert(at("K6"), Value::text("c"));
|
||||
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut pkg = Package::open(&bytes).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
for (address, text) in [("K4", "a"), ("K5", "b"), ("K6", "c")] {
|
||||
let c = cell(&sheet, address);
|
||||
assert_eq!(c.attr("t"), Some("str"), "{address}");
|
||||
assert_eq!(c.child("v").unwrap().text, text, "{address}");
|
||||
}
|
||||
}
|
||||
@@ -360,6 +360,43 @@ fn the_cap_counts_the_bytes_the_cells_hold_and_accepted_exports_keep_every_posit
|
||||
assert_eq!(tabs.len(), 14);
|
||||
}
|
||||
|
||||
/// #2159: a record keeps at most one field per sheet column while it is read, not after; the rest
|
||||
/// of the line is still read through, so the next line starts the next record.
|
||||
#[test]
|
||||
fn fields_past_the_last_column_are_not_collected() {
|
||||
let src = format!("{}last\nnext,row\n", "x,".repeat(100_000));
|
||||
let mut records = vec![];
|
||||
parse_records(&src, ',', '"', MAX_COLS as usize, |rec| {
|
||||
records.push(rec);
|
||||
true
|
||||
});
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!(records[0].len(), 16_384);
|
||||
assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]);
|
||||
// The same through the reader, and a quoted delimiter past the cap doesn't split the line.
|
||||
let src = format!("{}\"a,\nb\",z\nnext\n", "x,".repeat(20_000));
|
||||
let wb = read_csv(src.as_bytes(), &CsvOptions { delimiter: b',', ..CsvOptions::default() }).unwrap();
|
||||
assert_eq!(v(&wb, 0, 16_383), Value::text("x"));
|
||||
assert_eq!(v(&wb, 1, 0), Value::text("next"));
|
||||
assert_eq!(wb.sheet(0).unwrap().cells.len(), 16_385);
|
||||
}
|
||||
|
||||
/// #2159: a long field past the last column is skipped character by character, not collected
|
||||
/// and then thrown away; a quote inside it is a plain character, as in a kept field.
|
||||
#[test]
|
||||
fn a_long_field_past_the_last_column_is_not_stored() {
|
||||
let src = format!("{}{}a\"b,{}\nnext,row\n", "x,".repeat(16_384), "y".repeat(1_000_000), "z".repeat(1_000));
|
||||
let mut records = vec![];
|
||||
parse_records(&src, ',', '"', MAX_COLS as usize, |rec| {
|
||||
records.push(rec);
|
||||
true
|
||||
});
|
||||
assert_eq!(records.len(), 2, "the quote didn't open a quoted field across the line end");
|
||||
assert_eq!(records[0].len(), 16_384);
|
||||
assert!(records[0].iter().all(|f| f == "x"));
|
||||
assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_stops_collecting_fields_at_max_cols() {
|
||||
let extra = 50;
|
||||
|
||||
@@ -280,6 +280,119 @@ fn hostile_formula_text_does_not_overflow_the_stack() {
|
||||
assert_eq!(a_value, gridcraft_core::Value::Number(3.0));
|
||||
}
|
||||
|
||||
/// A one-sheet-per-entry workbook: `names` are the sheet names, every sheet sharing one part.
|
||||
fn many_sheets(names: &[String]) -> Vec<u8> {
|
||||
let sheets: String = names.iter().enumerate().map(|(i, n)| format!(r#"<sheet name="{n}" sheetId="{}" r:id="rId1"/>"#, i + 1)).collect();
|
||||
let wb = format!(
|
||||
r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>{sheets}</sheets></workbook>"#
|
||||
);
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#;
|
||||
let sheet = r#"<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>"#;
|
||||
make_zip(&[
|
||||
("[Content_Types].xml", super::CT.as_bytes()),
|
||||
("_rels/.rels", super::ROOT_RELS.as_bytes()),
|
||||
("xl/workbook.xml", wb.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", sheet.as_bytes()),
|
||||
])
|
||||
}
|
||||
|
||||
/// #2159: a row of endless `<c>` is not built in memory: the part's kept-element cap
|
||||
/// ([`crate::xml::MAX_XML_NODES`]) stops it, and the sheet is reported as damaged.
|
||||
#[test]
|
||||
fn a_row_wider_than_the_grid_is_refused() {
|
||||
let row = |n: usize| format!(r#"<sheetData><row r="1">{}</row></sheetData>"#, "<c/>".repeat(n));
|
||||
let (wb, rep) = read_xlsx(&minimal(&row(crate::xml::MAX_XML_NODES + 1), &[], "", "")).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cells.is_empty());
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings);
|
||||
assert!(read_xlsx(&minimal(&row(16_384), &[], "", "")).is_ok());
|
||||
// Every other part has the cap too (a merge list of more than a million entries).
|
||||
let merges = format!("<sheetData/><mergeCells>{}</mergeCells>", r#"<mergeCell ref="A1:B2"/>"#.repeat(crate::xml::MAX_XML_NODES + 1));
|
||||
let (wb, rep) = read_xlsx(&minimal(&merges, &[], "", "")).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().merges.is_empty());
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// #2159: overlapping `<col min=1 max=16384>` entries share one budget of column writes.
|
||||
#[test]
|
||||
fn overlapping_column_entries_have_a_budget() {
|
||||
let parts = [("xl/styles.xml", r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>"#)];
|
||||
let rels = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#;
|
||||
let cols = format!("<cols>{}</cols><sheetData/>", r#"<col min="1" max="16384" width="20" customWidth="1"/>"#.repeat(300));
|
||||
assert!(matches!(read_xlsx(&minimal(&cols, &parts, rels, "")), Err(IoError::TooLarge(_))));
|
||||
// A normal list reads with no warning.
|
||||
let (wb, rep) = read_xlsx(&minimal(r#"<cols><col min="2" max="4" width="20" customWidth="1"/></cols><sheetData/>"#, &parts, rels, "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().cols.len(), 3);
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// #2159: the sheet count is capped, and renaming duplicate sheet names stays linear.
|
||||
#[test]
|
||||
fn sheet_count_is_capped_and_duplicate_names_are_renamed() {
|
||||
let names: Vec<String> = (0..4097).map(|i| format!("S{i}")).collect();
|
||||
assert!(matches!(read_xlsx(&many_sheets(&names)), Err(IoError::TooLarge(_))));
|
||||
let dups: Vec<String> = (0..300).map(|i| if i % 2 == 0 { "a".to_string() } else { "A".to_string() }).collect();
|
||||
let (wb, _) = read_xlsx(&many_sheets(&dups)).unwrap();
|
||||
assert_eq!(wb.sheets.len(), 300);
|
||||
assert_eq!(wb.sheets[0].name, "a");
|
||||
assert_eq!(wb.sheets[1].name, "A (2)");
|
||||
assert_eq!(wb.sheets[299].name, "A (300)");
|
||||
let distinct: std::collections::HashSet<String> = wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect();
|
||||
assert_eq!(distinct.len(), 300);
|
||||
// The name set alone: thousands of duplicates, with a suffixed name already taken.
|
||||
let mut taken = crate::read::SheetNames::default();
|
||||
assert_eq!(taken.unique("x (3)", 0), "x (3)");
|
||||
let got: Vec<String> = (0..4096).map(|i| taken.unique("X", i)).collect();
|
||||
assert_eq!(got[0], "X");
|
||||
assert_eq!(got[1], "X (2)");
|
||||
assert_eq!(got[2], "X (4)");
|
||||
assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::<std::collections::HashSet<_>>().len(), 4096);
|
||||
assert_eq!(taken.unique("", 9), "Sheet10");
|
||||
// A 25-character name repeated past ` (999)` shortens its prefix so every name fits 31.
|
||||
let mut taken = crate::read::SheetNames::default();
|
||||
let base = "N".repeat(25);
|
||||
let got: Vec<String> = (0..4096).map(|i| taken.unique(&base, i)).collect();
|
||||
assert!(got.iter().all(|n| n.chars().count() <= 31), "{:?}", got.iter().find(|n| n.chars().count() > 31));
|
||||
assert_eq!(got[998], format!("{base} (999)"));
|
||||
assert_eq!(got[999], format!("{} (1000)", "N".repeat(24)));
|
||||
assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::<std::collections::HashSet<_>>().len(), 4096);
|
||||
}
|
||||
|
||||
/// #2159: the shared-string count is capped (each string is an allocation of its own).
|
||||
#[test]
|
||||
fn too_many_shared_strings_are_refused() {
|
||||
let sst = |n: usize| format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">{}</sst>"#, "<si/>".repeat(n));
|
||||
let rels = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>"#;
|
||||
let big = sst(4_000_001);
|
||||
assert!(matches!(read_xlsx(&minimal("<sheetData/>", &[("xl/sharedStrings.xml", &big)], rels, "")), Err(IoError::TooLarge(_))));
|
||||
let small = sst(3);
|
||||
assert!(read_xlsx(&minimal("<sheetData/>", &[("xl/sharedStrings.xml", &small)], rels, "")).is_ok());
|
||||
}
|
||||
|
||||
/// #2159: hyperlinks find their relationship by id (a map, not a scan per hyperlink); the first
|
||||
/// of duplicate ids wins, as before.
|
||||
#[test]
|
||||
fn hyperlinks_resolve_relationships_by_id() {
|
||||
let n = 5_000;
|
||||
let mut rels = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for i in 0..n {
|
||||
rels.push_str(&format!(
|
||||
r#"<Relationship Id="h{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/{i}" TargetMode="External"/>"#
|
||||
));
|
||||
}
|
||||
rels.push_str(r#"<Relationship Id="h0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/second" TargetMode="External"/>"#);
|
||||
rels.push_str("</Relationships>");
|
||||
let links: String = (0..n).map(|i| format!(r#"<hyperlink ref="A{}" r:id="h{i}"/>"#, i + 1)).collect();
|
||||
let body = format!(r#"<sheetData/><hyperlinks>{links}<hyperlink ref="B1" r:id="missing"/></hyperlinks>"#);
|
||||
let (wb, _) = read_xlsx(&minimal(&body, &[("xl/worksheets/_rels/sheet1.xml.rels", &rels)], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
assert_eq!(s.hyperlinks.len(), n);
|
||||
let link = |a: &str| s.hyperlinks.get(&gridcraft_core::CellRef::parse(a).unwrap()).map(|h| h.target.clone());
|
||||
assert_eq!(link("A1").as_deref(), Some("https://example.com/0"));
|
||||
assert_eq!(link("A5000").as_deref(), Some("https://example.com/4999"));
|
||||
assert_eq!(link("B1"), None);
|
||||
}
|
||||
|
||||
/// #2173: a hyperlink is copied into every cell it covers, so oversized targets are dropped,
|
||||
/// ScreenTips are cut to 255 characters and the cell cap holds across `<hyperlinks>` blocks.
|
||||
#[test]
|
||||
|
||||
@@ -545,6 +545,68 @@ fn hostile_pivot_parts_warn_not_panic() {
|
||||
assert!(report.warnings.iter().any(|w| w.contains("index")), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
/// #2159: a field repeated on the axes or as a page field is used once (each use walks the
|
||||
/// field's items and copied its labels), and the lists are capped.
|
||||
#[test]
|
||||
fn repeated_pivot_fields_are_used_once() {
|
||||
let items: String = (0..2_000).map(|_| r#"<item x="0" sd="0"/>"#).collect();
|
||||
let rows = r#"<field x="0"/>"#.repeat(20_000);
|
||||
let pages = r#"<pageField fld="0"/>"#.repeat(20_000);
|
||||
let table = format!(
|
||||
r#"<pivotTableDefinition name="P" cacheId="1"><location ref="D5:F9"/><pivotFields count="1"><pivotField axis="axisRow"><items>{items}</items></pivotField></pivotFields><rowFields>{rows}<field x="-2"/></rowFields><colFields>{rows}</colFields><pageFields>{pages}</pageFields></pivotTableDefinition>"#
|
||||
);
|
||||
let (wb, report) = read_xlsx(&with_pivot(&table, Some(GOOD_CACHE))).unwrap();
|
||||
let pt = &wb.sheet(0).unwrap().pivots[0];
|
||||
assert_eq!(pt.rows.len(), 1, "{:?}", report.warnings);
|
||||
assert!(pt.columns.is_empty());
|
||||
assert_eq!(pt.rows[0].collapsed_items.len(), 2_000);
|
||||
assert_eq!(pt.filters.iter().filter(|f| f.source_col == "K").count(), 1);
|
||||
// One page field: the table's range starts two rows above its location.
|
||||
assert_eq!(pt.last_range, Some(rr("D3:F9")));
|
||||
}
|
||||
|
||||
/// #2159: a field list cut at the 16,384-entry cap is reported, so an incomplete PivotTable can be
|
||||
/// told apart from a complete one.
|
||||
#[test]
|
||||
fn capped_pivot_field_lists_warn() {
|
||||
let fields = r#"<pivotField/>"#.repeat(16_385);
|
||||
let table = format!(
|
||||
r#"<pivotTableDefinition name="P" cacheId="1"><location ref="D5:F9"/><pivotFields count="16385">{fields}</pivotFields></pivotTableDefinition>"#
|
||||
);
|
||||
let (_, report) = read_xlsx(&with_pivot(&table, Some(GOOD_CACHE))).unwrap();
|
||||
assert!(report.warnings.iter().any(|w| w.contains("field lists past 16384 entries")), "{:?}", report.warnings);
|
||||
let table = r#"<pivotTableDefinition name="P" cacheId="1"><location ref="D5:F9"/><pivotFields count="1"><pivotField/></pivotFields></pivotTableDefinition>"#;
|
||||
let (_, report) = read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap();
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("field lists past")), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
/// #2159: a cache cut at 16,384 fields is reported too, as the table field lists are.
|
||||
#[test]
|
||||
fn capped_cache_fields_warn() {
|
||||
let fields = r#"<cacheField name="F"><sharedItems/></cacheField>"#.repeat(16_385);
|
||||
let cache = format!(
|
||||
r#"<pivotCacheDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><cacheSource type="worksheet"><worksheetSource ref="A1:B3"/></cacheSource><cacheFields count="16385">{fields}</cacheFields></pivotCacheDefinition>"#
|
||||
);
|
||||
let table = r#"<pivotTableDefinition name="P" cacheId="1"><location ref="D5:F9"/><pivotFields count="1"><pivotField/></pivotFields></pivotTableDefinition>"#;
|
||||
let (_, report) = read_xlsx(&with_pivot(table, Some(&cache))).unwrap();
|
||||
assert!(report.warnings.iter().any(|w| w.contains("cache fields past 16384")), "{:?}", report.warnings);
|
||||
let (_, report) = read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap();
|
||||
assert!(!report.warnings.iter().any(|w| w.contains("cache fields past")), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
/// #2159: axis filters and calculated fields are deduplicated through a set of lower-cased names;
|
||||
/// the first of names equal but for case still wins, as with the scan it replaced.
|
||||
#[test]
|
||||
fn axis_filters_and_calculated_fields_dedupe_ignoring_case() {
|
||||
let cache = r#"<pivotCacheDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><cacheSource type="worksheet"><worksheetSource ref="A1:B3"/></cacheSource><cacheFields count="4"><cacheField name="K"><sharedItems><s v="a"/><s v="b"/></sharedItems></cacheField><cacheField name="k"><sharedItems><s v="a"/><s v="b"/></sharedItems></cacheField><cacheField name="Price" formula="1" databaseField="0"/><cacheField name="PRICE" formula="2" databaseField="0"/></cacheFields></pivotCacheDefinition>"#;
|
||||
let table = r#"<pivotTableDefinition name="P" cacheId="1"><location ref="D5:F9"/><pivotFields count="2"><pivotField axis="axisRow"><items><item x="0"/><item x="1" h="1"/></items></pivotField><pivotField axis="axisCol"><items><item x="0" h="1"/><item x="1"/></items></pivotField></pivotFields><rowFields><field x="0"/></rowFields><colFields><field x="1"/></colFields></pivotTableDefinition>"#;
|
||||
let (wb, report) = read_xlsx(&with_pivot(table, Some(cache))).unwrap();
|
||||
let pt = &wb.sheet(0).unwrap().pivots[0];
|
||||
assert_eq!((pt.rows.len(), pt.columns.len()), (1, 1), "{:?}", report.warnings);
|
||||
assert_eq!(pt.filters, vec![PivotFilter { source_col: "K".into(), selected: Some(vec!["a".into()]) }]);
|
||||
assert_eq!(pt.calculated_fields, vec![PivotCalcField { name: "Price".into(), formula: "=1".into() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_found_by_workbook_cache_id() {
|
||||
let rels_extra = r#"<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition" Target="pivotCache/pivotCacheDefinition1.xml"/>"#;
|
||||
|
||||
@@ -1061,12 +1061,14 @@ fn legacy_and_dynamic_formulas_keep_their_kind() {
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
assert!(xml.contains("<c r=\"B2\"><f>TANH(A1:A3)+A1:A3</f>"), "{xml}");
|
||||
assert!(xml.contains("<c r=\"B3\"><f>SUM(A1:A3)</f>"), "{xml}");
|
||||
// Uncalculated, the spill range is not known yet; the formula stays dynamic.
|
||||
assert!(xml.contains("<c r=\"C2\" cm=\"1\"><f t=\"array\" ref=\"C2\">TANH(A1:A3)</f>"), "{xml}");
|
||||
// Uncalculated, the dynamic array keeps the area the file says it spilled over.
|
||||
assert!(xml.contains("<c r=\"C2\" cm=\"1\"><f t=\"array\" ref=\"C2:C4\">TANH(A1:A3)</f>"), "{xml}");
|
||||
assert!(xml.contains("<c r=\"D2\"><f t=\"array\" ref=\"D2:D4\">TANH(A1:A3)</f>"), "{xml}");
|
||||
let (back, _) = read_xlsx(&bytes).unwrap();
|
||||
for a in ["B2", "B3", "C2", "D2"] {
|
||||
for (a, dynamic) in [("B2", false), ("B3", false), ("C2", true), ("D2", false)] {
|
||||
assert_eq!(text(&back, a), text(&wb, a), "{a}");
|
||||
let formula = back.sheet(0).unwrap().cell(at(a)).unwrap().formula.as_ref().unwrap();
|
||||
assert_eq!(formula.dynamic, dynamic, "{a}: dynamic-array metadata survives saving");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -106,10 +106,8 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
|
||||
|
||||
| Format | Excel | GridCraft read | GridCraft write | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection; per-column day/month date-order detection for `/` and `-` dates) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Excel writes the **displayed** values, and so do we; `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). |
|
||||
| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`; likely Windows-1256 Arabic detection for invalid UTF-8; per-column day/month date-order detection for `/` and `-` dates) | yes | Text Import Wizard options partly via Text to Columns |
|
||||
| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection; per-column day/month date-order detection for `/` and `-` dates) | yes (UTF-8 without BOM, CRLF) | Writes the **displayed** values like Excel (number formats applied, formula results, never column-width `#####`); `file.exportCsv {values: true}` writes raw values instead. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). |
|
||||
| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`; likely Windows-1256 Arabic detection for invalid UTF-8; per-column day/month date-order detection for `/` and `-` dates) | yes (displayed values) | Text Import Wizard options partly via Text to Columns |
|
||||
| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, likely Windows-1256 Arabic detection, otherwise Windows-1252 fallback; delimiter detection; per-column day/month date-order detection for `/` and `-` dates) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`); `file.exportCsv {values: true}` writes raw values (full precision, ISO 8601 dates) for automation. **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV GridCraft wrote, opened and saved again, is unchanged. A CSV from elsewhere can change on its first save: a decimal with 16 or 17 significant digits is cut to 15, as in Excel (`3.141592653589793` → `3.14159265358979`), and a number typed in scientific notation gets the `0.00E+00` format on open and is saved rounded to it (`1.23456789012346E-10` → `1.23E-10`, unchanged from before). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). |
|
||||
| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`; likely Windows-1256 Arabic detection for invalid UTF-8; per-column day/month date-order detection for `/` and `-` dates) | yes (displayed values, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns |
|
||||
| `.prn` formatted text (space-delimited) | R/W | no | no | |
|
||||
| `.slk` SYLK | R/W | **yes, partial** (#1481) | no (Save As `.xlsx`) | Values (numbers, text, booleans, errors), formulas converted from R1C1 to A1 as Excel does (relative and absolute references, ranges, whole rows and columns, shared formulas) with their cached results, number formats (`P`/`F;P`), column widths (`F;W`); the sheet is named after the file. Not read: fonts and cell styles, row heights, names, comments. Non-UTF-8 files are read as Latin-1 | engine `io/tests.rs` (`sylk_*`) |
|
||||
| `.dif` Data Interchange Format | R/W | no | no | Small, legacy |
|
||||
@@ -203,9 +201,9 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
| 2026-10-19 | minor | .xls import skips dialog sheets (WsBool `fDialog`), which share the worksheet BOF type and were read as empty worksheets |
|
||||
| 2026-10-19 | minor | `.xls` import reads WINDOW2: right-to-left sheets (common in older Arabic and Hebrew files) open right-to-left, and hidden gridlines, headings and zero values and Show Formulas carry over |
|
||||
| 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged |
|
||||
| 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` |
|
||||
| 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) |
|
||||
| 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other |
|
||||
| 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` |
|
||||
| 2026-10-16 | trivial | XLSX charts: `[0]!Name` (a workbook-scoped defined name) in series references is read as the name, so the series resolve instead of showing `#NAME?`. Names in chart references are written qualified (`[0]!Name`, or `Sheet!Name` for a sheet-scoped name): Excel draws a chart with a bare name blank (#1686) |
|
||||
| 2026-10-16 | trivial | XLSX reads and writes the workbook's show-objects setting (`workbookPr showObjects`: all, placeholders, none), which Ctrl+6 switches; a file without it is saved without it |
|
||||
| 2026-10-16 | trivial | XLSX: pictures in headers and footers (`&G`, the VML drawing `<legacyDrawingHF>` names and its images) are kept on save; they are still not shown (#1257) |
|
||||
@@ -217,6 +215,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
| 2026-10-15 | minor | XLSX text preserves CR and CRLF across save/reopen; shared strings use `_x000D_` and other XML text uses ` ` (#1488) |
|
||||
| 2026-10-15 | minor | XLSX save keeps legacy `INDEX`/`MATCH` formulas scalar instead of marking them as dynamic arrays (#1505) |
|
||||
| 2026-10-14 | minor | `.xls` import reads cell formatting from the Font, XF, Palette and Style records: fonts, fills, borders, alignment, protection, the custom palette, the Normal font and user cell styles |
|
||||
| 2026-10-14 | minor | CSV/text export writes General numbers with the 15 significant digits `&` gives (`0.3`, not `0.30000000000000004`) but never an exponent (integers below 1e16 keep every digit; 1E+15 and up as the shortest round-trip digits; small numbers written out), also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display. The underlying `&` conversion changed too (see [function-parity.md](function-parity.md)) |
|
||||
| 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped |
|
||||
| 2026-10-14 | minor | XLSX formulas read with dynamic-array metadata (`cm`) keep it on save, so Excel does not recalculate them with implicit intersection |
|
||||
| 2026-10-14 | minor | PDF export writes clickable annotations for safe cell URLs and destinations on printed pages; CLI `convert` accepts `.pdf` output (#954) |
|
||||
|
||||
@@ -176,6 +176,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere
|
||||
| 2026-10-14 | minor | Analysis ToolPak value arguments (EOMONTH, WORKDAY, YEARFRAC, COUPDAYS, DISC, BIN2DEC, IM* and the rest, observed in Excel 365) give `#VALUE!` for a multi-cell reference instead of lifting it |
|
||||
| 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) |
|
||||
| 2026-10-14 | minor | Set precision as displayed: results, spills and typed or reformatted numbers are stored as their format shows them when the option is on (#1343) |
|
||||
| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred |
|
||||
| 2026-10-14 | minor | Bounded references up to 1,048,576 cells (`D3:AZ400`) keep their full shape instead of stopping at the used range, so `SUMPRODUCT(D3:AZ400*B3:B400,(A3:A400=x)*(D1:AZ1=y))` broadcasts like Excel and `ROWS`, `COUNTBLANK` and `--(r="")` count the blanks; references that run to the edge of the sheet (`A:A`) still stop at the used range (#1010) |
|
||||
| 2026-10-13 | minor | Legacy formulas from files (no dynamic-array metadata) evaluate with implicit intersection: cells differing from Excel's cached values 68,964 → 49,866 across 4,224 test-corpus workbooks (none gets more) |
|
||||
| 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Localization parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (RaTeX equation parser messages follow the interface language); previously minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Brazilian Portuguese function help); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Per-language status against Excel, which ships its UI in dozens of languages (Windows language
|
||||
packs cover 100+), with localized function names, argument separators, number and date formats,
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **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
|
||||
@@ -105,6 +105,9 @@ Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and
|
||||
`keymap.rs` (everything added in #110, with a `lookup` table that tests cover) and
|
||||
`formula_bar.rs` (keys while editing). "Ctrl" means Cmd on a Mac unless the Mac column says
|
||||
otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, wherever `$` is).
|
||||
Punctuation keys go by the character the keyboard layout types, as in Excel: on a Croatian or German
|
||||
keyboard Ctrl+Shift+, types `;` and inserts the date, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert.
|
||||
A character egui has no key for (`č`, `ö`, `<`) falls back to the key's position.
|
||||
|
||||
| Shortcut (Windows) | Mac | Action | Status |
|
||||
|---|---|---|---|
|
||||
@@ -332,6 +335,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format |
|
||||
| 2026-10-19 | trivial | While a mouse button is held (a click or a drag selecting cells) the selection outline is drawn on its cells at once instead of gliding after the pointer, which read as lag; keyboard moves still glide |
|
||||
| 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) |
|
||||
| 2026-10-14 | minor | Punctuation shortcuts follow the character the keyboard layout types, digits keep their position: on a Croatian or German keyboard Ctrl+Shift+, (`;`) inserts the date instead of decreasing the font size, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert, Ctrl+' copies the formula above, and Ctrl+Shift+0 (`=`) unhides columns instead of opening Insert |
|
||||
| 2026-10-17 | minor | A Ctrl+Alt+letter key that types a character (a user-defined Windows hotkey such as Ctrl+Alt+A for `ä`) types it instead of running the Ctrl+letter shortcut, e.g. Select All (#1530) |
|
||||
| 2026-10-16 | minor | Right-drag on the fill handle opens the fill menu on release: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…; Esc cancels the drag or closes the menu without filling |
|
||||
| 2026-10-16 | minor | With the active cell in a Table whose header row is scrolled out of view, the column headings show the header names and their filter buttons in place of the letters (#1423) |
|
||||
|
||||
+17
-1
@@ -70,6 +70,12 @@ pub fn render(entries: &[Entry]) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Whether the checked-in checklist matches the generated text. A Windows checkout with
|
||||
/// `core.autocrlf=true` (Git for Windows' default) has CRLF line ends, which aren't a change.
|
||||
pub fn up_to_date(current: &str, generated: &str) -> bool {
|
||||
current == generated || current.replace("\r\n", "\n") == generated
|
||||
}
|
||||
|
||||
#[cfg(feature = "engine")]
|
||||
fn entries() -> Vec<Entry> {
|
||||
use gridcraft_engine::catalog::CATALOG;
|
||||
@@ -106,7 +112,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
|
||||
let text = render(&entries());
|
||||
if check {
|
||||
let current = std::fs::read_to_string(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
if current != text {
|
||||
if !up_to_date(¤t, &text) {
|
||||
return Err(format!("{} is out of date; run `cargo xtask parity`", out.display()));
|
||||
}
|
||||
println!("{} ({} up to date)", summary_line(), out.display());
|
||||
@@ -149,4 +155,14 @@ mod tests {
|
||||
fn empty_catalog_renders() {
|
||||
assert!(render(&[]).contains("0 / 0 commands implemented (0.0%)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_checkout_of_the_current_checklist_is_up_to_date() {
|
||||
let text = render(&[e("file.new", "File", true), e("home.bold", "Home", false)]);
|
||||
assert!(up_to_date(&text, &text));
|
||||
assert!(up_to_date(&text.replace('\n', "\r\n"), &text));
|
||||
let stale = render(&[e("file.new", "File", false), e("home.bold", "Home", false)]);
|
||||
assert!(!up_to_date(&stale, &text));
|
||||
assert!(!up_to_date(&stale.replace('\n', "\r\n"), &text));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user