diff --git a/ROADMAP.md b/ROADMAP.md index 5ff15b422..fd27ee9eb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -180,6 +180,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 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) | +| 2026-10-14 | XLSX import warns when a pivot cache is missing, malformed or too large, naming the cache and saying its PivotTable was kept as plain cells, instead of dropping the PivotTable silently (#1039) | | 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) | | 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison | | 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift | @@ -305,6 +306,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook | | 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) | | 2026-10-16 | minor | Progress log: interface fonts held once instead of twice | +| 2026-10-14 | trivial | Progress log: pivot cache import warnings (#1039) | | 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) | | 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting | | 2026-10-14 | minor | Progress log: lookups compare numbers exactly | diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index f05b421df..f5232b17c 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -340,12 +340,16 @@ fn main() -> eframe::Result<()> { for f in &files { app.open_path(f); } + // Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the + // window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame. + app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none(); let mut viewport = egui::ViewportBuilder::default() .with_title("GridCraft") .with_inner_size([1440.0, 900.0]) .with_min_inner_size([640.0, 420.0]) .with_app_id("ai.storyteller.gridcraft") - .with_drag_and_drop(true); + .with_drag_and_drop(true) + .with_decorations(!app.window_controls); if cfg!(target_os = "macos") { viewport = viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false); } diff --git a/crates/calc/src/eval/special.rs b/crates/calc/src/eval/special.rs index 0151ea2f9..2e7083457 100644 --- a/crates/calc/src/eval/special.rs +++ b/crates/calc/src/eval/special.rs @@ -27,62 +27,153 @@ pub fn resized_sum_range(sum: RangeRef, height: u32, width: u32) -> RangeRef { RangeRef::new(sum.start, CellRef::new(row, col)) } +/// Most expression nodes [`precedents`] visits before giving up and marking the formula dynamic. +const MAX_PRECEDENT_NODES: usize = 1_000_000; + /// Collects the static references of an expression with their sheets resolved; `dynamic` is /// set when the formula uses INDIRECT/OFFSET/names/tables whose targets can change. +/// +/// Every node is visited once (#2183: range-operator chains used to re-walk shared operands, +/// costing 2^k for k operands), with an explicit stack, so a flat chain as long as Excel allows +/// (`1+1+…`, about 4,000 levels deep) never recurses. Past [`MAX_PRECEDENT_NODES`] the result +/// is conservative: `dynamic` is set so the formula recalculates every time. pub fn precedents(wb: &Workbook, sheet: usize, e: &Expr) -> (Vec, bool) { - let mut out = Vec::new(); - let mut dynamic = false; - let push = |out: &mut Vec, r: &Reference, range: RangeRef| match &r.sheet { - SheetSel::Current => out.push(Area { sheet, range }), - SheetSel::Named(n) => { - if let Some(i) = wb.sheet_index(n) { - out.push(Area { sheet: i, range }); - } + let mut c = Precedents { wb, sheet, out: Vec::new(), dynamic: false, boxes: Vec::new() }; + c.collect(e); + (c.out, c.dynamic) +} + +/// Grows the per-sheet bounding box in `boxes` to cover `area`. +fn union_box(boxes: &mut Vec, area: Area) { + match boxes.iter_mut().find(|x| x.sheet == area.sheet) { + Some(x) => x.range = x.range.union(&area.range), + None => boxes.push(area), + } +} + +/// One entry of [`Precedents::collect`]'s explicit stack. `boxes` indexes +/// [`Precedents::boxes`]: the bounding boxes of the innermost enclosing range operator, if any. +enum PrecedentStep<'e> { + /// Visit an expression and queue its children. + Visit(&'e Expr, Option), + /// Both operands of a range operator have been visited: record the bounding boxes they + /// collected in `inner`, growing the `outer` operator's boxes too. + Close { inner: usize, outer: Option }, +} + +struct Precedents<'w> { + wb: &'w Workbook, + sheet: usize, + out: Vec, + dynamic: bool, + /// Per-sheet bounding boxes, one list per range operator (`A1:INDEX(…)`) met so far. + boxes: Vec>, +} + +impl Precedents<'_> { + /// Records `area`, also growing the bounding boxes of the enclosing range operator, if any. + fn add(&mut self, area: Area, boxes: Option) { + if let Some(b) = boxes.and_then(|i| self.boxes.get_mut(i)) { + union_box(b, area); } - SheetSel::Span(a, b) => { - if let (Some(i), Some(j)) = (wb.sheet_index(a), wb.sheet_index(b)) { - for s in i.min(j)..=i.max(j) { - out.push(Area { sheet: s, range }); + self.out.push(area); + } + + fn push(&mut self, r: &Reference, range: RangeRef, boxes: Option) { + match &r.sheet { + SheetSel::Current => self.add(Area { sheet: self.sheet, range }, boxes), + SheetSel::Named(n) => { + if let Some(i) = self.wb.sheet_index(n) { + self.add(Area { sheet: i, range }, boxes); + } + } + SheetSel::Span(a, b) => { + if let (Some(i), Some(j)) = (self.wb.sheet_index(a), self.wb.sheet_index(b)) { + for s in i.min(j)..=i.max(j) { + self.add(Area { sheet: s, range }, boxes); + } } } } - }; - e.walk(&mut |x| match x { - Expr::Ref(r) => push(&mut out, r, r.range()), - // The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when - // the criteria range's size isn't known statically, recalculate the formula every time. - Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) { - (Some(Expr::Ref(c)), Some(Expr::Ref(s))) => { - let (crit, sum) = (c.range(), s.range()); - push(&mut out, s, resized_sum_range(sum, crit.height(), crit.width())); - } - (_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {} - _ => dynamic = true, - }, - Expr::Call(n, _) - if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") => - { - dynamic = true - } - Expr::Name(_) | Expr::Struct(_) => dynamic = true, - Expr::Call(n, _) if gridcraft_functions::lookup(n).is_none() && !is_special(n) => dynamic = true, - // A range ending in a function's result (`A1:INDEX(B1:B9,n)`) covers the cells between - // the references inside it, not only those references. - Expr::Binary(BinOp::Range, a, b) if !matches!((&**a, &**b), (Expr::Ref(_), Expr::Ref(_))) => { - let mut inner = precedents(wb, sheet, a).0; - inner.extend(precedents(wb, sheet, b).0); - let mut boxes: Vec = Vec::new(); - for area in inner { - match boxes.iter_mut().find(|x| x.sheet == area.sheet) { - Some(x) => x.range = x.range.union(&area.range), - None => boxes.push(area), + } + + /// Visits every node of `root` once, parents before children, left to right. Areas found + /// inside a range operator (`A1:INDEX(…)`) also grow that operator's per-sheet bounding boxes. + fn collect(&mut self, root: &Expr) { + let mut pending = vec![PrecedentStep::Visit(root, None)]; + let mut nodes = 0usize; + while let Some(step) = pending.pop() { + let (x, boxes) = match step { + PrecedentStep::Visit(x, boxes) => (x, boxes), + PrecedentStep::Close { inner, outer } => { + let areas = self.boxes.get_mut(inner).map(std::mem::take).unwrap_or_default(); + for area in areas { + self.add(area, outer); + } + continue; } + }; + nodes = nodes.saturating_add(1); + if nodes > MAX_PRECEDENT_NODES { + self.dynamic = true; + return; } - out.extend(boxes); + self.visit(x, boxes, &mut pending); } - _ => {} - }); - (out, dynamic) + } + + /// Handles one node for [`Precedents::collect`], queueing the children still to visit. + fn visit<'e>(&mut self, x: &'e Expr, boxes: Option, pending: &mut Vec>) { + match x { + Expr::Ref(r) => self.push(r, r.range(), boxes), + // The cells SUMIF/AVERAGEIF really read from the sum range (see `resized_sum_range`); when + // the criteria range's size isn't known statically, recalculate the formula every time. + Expr::Call(n, args) if resizes_sum_range(n, args.len()) => match (args.first(), args.get(2)) { + (Some(Expr::Ref(c)), Some(Expr::Ref(s))) => { + let (crit, sum) = (c.range(), s.range()); + self.push(s, resized_sum_range(sum, crit.height(), crit.width()), boxes); + } + (_, Some(Expr::Number(_) | Expr::Text(_) | Expr::Bool(_) | Expr::Error(_) | Expr::Array(_) | Expr::Missing)) => {} + _ => self.dynamic = true, + }, + Expr::Call(n, _) + if matches!(n.as_str(), "INDIRECT" | "OFFSET" | "NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" | "CELL" | "INFO") => + { + self.dynamic = true + } + Expr::Name(_) | Expr::Struct(_) => self.dynamic = true, + Expr::Call(n, _) if gridcraft_functions::lookup(n).is_none() && !is_special(n) => self.dynamic = true, + // A range ending in a function's result (`A1:INDEX(B1:B9,n)`), or a chain of plain + // references the parser can't fold into one (`A1:B2:C3`), covers the cells between the + // references inside it, not only those references. Both operands are visited once, + // collecting their bounding boxes on the way, which `Close` then records. + Expr::Binary(BinOp::Range, a, b) => { + let inner = self.boxes.len(); + self.boxes.push(Vec::new()); + pending.push(PrecedentStep::Close { inner, outer: boxes }); + pending.push(PrecedentStep::Visit(b, Some(inner))); + pending.push(PrecedentStep::Visit(a, Some(inner))); + return; + } + _ => {} + } + // Children are pushed in reverse so they pop left to right. + let visit = |e: &'e Expr| PrecedentStep::Visit(e, boxes); + match x { + Expr::Array(rows) => pending.extend(rows.iter().flatten().rev().map(visit)), + Expr::Unary(_, e) | Expr::Paren(e) => pending.push(visit(e)), + Expr::Binary(_, a, b) => { + pending.push(visit(b)); + pending.push(visit(a)); + } + Expr::Call(_, args) => pending.extend(args.iter().rev().map(visit)), + Expr::Invoke(c, args) => { + pending.extend(args.iter().rev().map(visit)); + pending.push(visit(c)); + } + _ => {} + } + } } fn is_special(n: &str) -> bool { diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 7f6e753de..5ab61a8b8 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2331,6 +2331,85 @@ fn median_large_values_recalculate_dependents() { } } +/// #2183: `INDEX(…):INDEX(…):…` used to re-walk each operand of the left-associative range chain, +/// costing 2^k for k operands (28 took 40 s; 60 would take millennia), on open and on every edit. +#[test] +fn range_operator_chain_precedents_are_linear() { + let operands: Vec = (1..=60).map(|i| format!("INDEX(A{i},1)")).collect(); + let src = format!("=SUM({})", operands.join(":")); + let e = gridcraft_formula::parse(&src).unwrap(); + let wb = Workbook::new(); + // With the old 2^k walk this call would never return; #2183 asks for under 100 ms. + #[allow(clippy::disallowed_methods)] // a native test: the clock is there + let t0 = std::time::Instant::now(); + let (areas, dynamic) = crate::eval::precedents(&wb, 0, &e); + let took = t0.elapsed(); + assert!(took < std::time::Duration::from_millis(100), "precedents took {took:?}"); + assert!(!dynamic); + // The chain covers A1:A60, not only the 60 cells named in it. + let whole = gridcraft_core::RangeRef::new(c("A1"), c("A60")); + assert!(areas.iter().any(|a| a.sheet == 0 && a.range == whole), "{areas:?}"); + // Each node is visited once: 60 references plus one box per range operator. + assert!(areas.len() < 200, "{} areas", areas.len()); + + // Through the recalculation engine: setting it finishes and editing a cell in the box recalculates. + let mut t = T::new(); + for i in 1..=60 { + t.set(&format!("A{i}"), "1"); + } + t.set("B1", &src); + assert_eq!(t.num("B1"), 60.0); + t.set("A30", "5"); + assert_eq!(t.num("B1"), 64.0); +} + +/// A chained range of plain references (`A1:B2:C3`, which the parser can't fold into one +/// reference) covers their bounding box, as the evaluator expands it: an edit inside the box but +/// outside each operand still recalculates. +#[test] +fn chained_plain_range_precedents_cover_the_bounding_box() { + let e = gridcraft_formula::parse("=SUM(A1:B2:C3)").unwrap(); + let (areas, dynamic) = crate::eval::precedents(&Workbook::new(), 0, &e); + assert!(!dynamic); + let whole = gridcraft_core::RangeRef::new(c("A1"), c("C3")); + assert!(areas.iter().any(|a| a.sheet == 0 && a.range == whole), "{areas:?}"); + + let mut t = T::new(); + t.set("A1", "1"); + t.set("E1", "=SUM(A1:B2:C3)"); + assert_eq!(t.num("E1"), 1.0); + t.set("C1", "4"); + assert_eq!(t.num("E1"), 5.0); +} + +/// `precedents` walks with an explicit stack: an expression nested deeper than any formula +/// within the length limit can build still finds its references, on a small stack. +#[test] +fn precedents_of_deep_nesting_do_not_recurse() { + let (areas, dynamic) = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(|| { + let mut e = gridcraft_formula::parse("=A1").unwrap(); + for _ in 0..10_000 { + e = gridcraft_formula::Expr::Paren(Box::new(e)); + } + let found = crate::eval::precedents(&Workbook::new(), 0, &e); + // Dropping the deep tree recurses; leak it so only `precedents` is under test. + std::mem::forget(e); + found + }) + .unwrap() + .join() + .unwrap(); + assert!(!dynamic); + assert_eq!(areas.len(), 1); + // Shallow nesting stays static. + let e = gridcraft_formula::parse("=((((A1))))").unwrap(); + let (areas, dynamic) = crate::eval::precedents(&Workbook::new(), 0, &e); + assert!(!dynamic); + assert_eq!(areas.len(), 1); +} + #[test] fn cell_filename_names_the_workbook_file() { // Excel returns `/[]`, and the classic sheet-name formula splits it on diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index a0b4fcad6..4d76ef70e 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -454,8 +454,9 @@ pub fn number_to_text(n: f64) -> String { if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 { return sci_text(n, 15); } - // A value just below 1e15 can round up to 1e15 at 15 significant digits. - if format!("{:.14e}", a).parse::().is_ok_and(|r| r >= 1e15) { + // A value just below 1e15 can round up to 1e15 at 15 significant digits. Only that narrow + // band pays for the exact formatting: it runs for every number literal a formula prints. + if a >= 9.999_999_999_999_9e14 && format!("{:.14e}", a).parse::().is_ok_and(|r| r >= 1e15) { return sci_text(n, 15); } // 15 significant digits, trailing zeros trimmed. @@ -506,6 +507,9 @@ mod tests { assert_eq!(number_to_text(999999999999999.9), "1E+15"); assert_eq!(number_to_text(-999999999999999.9), "-1E+15"); assert_eq!(number_to_text(999999999999999.0), "999999999999999"); + assert_eq!(number_to_text(999999999999999.5), "1E+15"); + assert_eq!(number_to_text(999999999999999.4), "999999999999999"); + assert_eq!(number_to_text(999999999999989.9), "999999999999990"); } #[test] diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 179dc04a1..274c0879b 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -166,14 +166,15 @@ fn filter_blank(v: &Value) -> bool { /// A table's own filter is left to the table, and a row typed after a blank row does not count. /// A formula counts before it is calculated: this runs inside the edit, ahead of the recalc. pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { - if !sh.cells.get(at).is_some_and(|c| !filter_blank(&c.value) || c.formula.is_some()) { - return; - } + // The AutoFilter checks come first: they are cheap, and most sheets have none. let Some(af) = sh.autofilter.as_ref() else { return }; let r = af.range; if r.end.row.checked_add(1) != Some(at.row) || at.col < r.start.col || at.col > r.end.col || sh.tables.iter().any(|t| t.range == r) { return; } + if !sh.cells.get(at).is_some_and(|c| !filter_blank(&c.value) || c.formula.is_some()) { + return; + } let grown = RangeRef::new(r.start, CellRef::new(at.row, r.end.col)); if let Some(af) = sh.autofilter.as_mut() { af.range = grown; diff --git a/crates/engine/src/cmd/data/tools.rs b/crates/engine/src/cmd/data/tools.rs index e4b9f028f..2d0ffc3f9 100644 --- a/crates/engine/src/cmd/data/tools.rs +++ b/crates/engine/src/cmd/data/tools.rs @@ -183,8 +183,11 @@ pub(super) fn split_delimited(text: &str, delims: &[char], consecutive: bool, qu let mut in_q = false; let mut last_delim = false; let mut chars = text.chars().peekable(); + let mut at_start = true; while let Some(c) = chars.next() { - if c == quote { + if c == quote && (in_q || at_start) { + at_start = false; + last_delim = false; if in_q && chars.peek() == Some("e) { cur.push(quote); chars.next(); @@ -199,9 +202,11 @@ pub(super) fn split_delimited(text: &str, delims: &[char], consecutive: bool, qu } out.push(std::mem::take(&mut cur)); last_delim = true; + at_start = true; continue; } last_delim = false; + at_start = false; cur.push(c); } out.push(cur); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 58979526c..e068f7a1e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -305,6 +305,19 @@ fn trim_to_budget(history: &mut Vec, byte_budget: usize) { } } +/// A writer that only counts the bytes written to it. +struct ByteCounter(usize); + +impl std::io::Write for ByteCounter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(buf.len()); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + impl DocState { /// A document for `wb`, which came from where `trust` says: [`Trust::FromFile`] for anything /// read from bytes (a file, a download, a recovery copy), [`Trust::Local`] only for a workbook @@ -638,7 +651,11 @@ impl Session { /// Journals a command, then trims the oldest entries past either cap. A recording in progress /// keeps pointing at the same entry (the steps the trim dropped are lost). fn push_journal(&mut self, id: &str, params: Json) { - let size = |e: &(String, Json)| serde_json::to_vec(e).map_or(0, |v| v.len()); + // Counted as it is written, without building the text: a paste's params can be MBs. + let size = |e: &(String, Json)| { + let mut counter = ByteCounter(0); + serde_json::to_writer(&mut counter, e).map_or(0, |()| counter.0) + }; // `journal` is public: if it was changed from outside, measure it again. if self.journal_sizes.len() != self.journal.len() { self.journal_sizes = self.journal.iter().map(size).collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c9953e485..f29cb59fb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6416,6 +6416,16 @@ mod objects; mod python_cells; mod python_commands; mod python_files; + +#[test] +fn text_to_columns_keeps_a_mid_field_quote() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "'5\" pipe,abc"})).unwrap(); + s.execute("data.textToColumns", json!({"range": "A1", "delimiters": [","]})).unwrap(); + assert_eq!(v(&s, "A1"), Value::text("5\" pipe")); + assert_eq!(v(&s, "B1"), Value::text("abc")); +} + mod seams; #[test] diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs index 63cf1d92b..8c7805dc4 100644 --- a/crates/engine/src/tests/python_cells.rs +++ b/crates/engine/src/tests/python_cells.rs @@ -175,8 +175,8 @@ fn text_to_columns_keeps_a_py_piece_as_text() { s.execute("cell.set", json!({"cell": "A1", "input": "'=PY(\"x\");7"})).unwrap(); assert_eq!(super::v(&s, "A1"), Value::text("=PY(\"x\");7")); s.execute("data.textToColumns", json!({"range": "A1", "delimiters": [";"]})).unwrap(); - // The default text qualifier takes the quotes away, as in Excel. - assert_eq!(super::v(&s, "A1"), Value::text("=PY(x)"), "the piece is kept, not cleared"); + // A quote in the middle of a field is kept, as in Excel. + assert_eq!(super::v(&s, "A1"), Value::text("=PY(\"x\")"), "the piece is kept, not cleared"); assert_eq!(code(&s, 0, "A1"), None, "and it is not a Python cell"); assert_eq!(super::v(&s, "B1"), Value::Number(7.0)); } diff --git a/crates/formula/src/ast.rs b/crates/formula/src/ast.rs index 94756c09f..3c784d2f4 100644 --- a/crates/formula/src/ast.rs +++ b/crates/formula/src/ast.rs @@ -215,7 +215,9 @@ impl Expr { /// Visits every node depth-first, parents before children, left to right. pub fn walk<'a>(&'a self, f: &mut dyn FnMut(&'a Expr)) { // An explicit stack: a long operator chain must not recurse once per operand. - let mut pending = vec![self]; + // Room for a typical formula up front, so walking one costs one allocation, not several. + let mut pending = Vec::with_capacity(8); + pending.push(self); while let Some(e) = pending.pop() { f(e); match e { @@ -236,6 +238,19 @@ impl Expr { } /// Rewrites every node bottom-up, children left to right before their parent. pub fn map(self, f: &mut dyn FnMut(Expr) -> Expr) -> Expr { + // One operator on a non-chain operand (`A1*2`), the common case, needs no spine: rewrite + // the operands in their boxes. + if let Expr::Binary(op, mut a, mut b) = self { + if !matches!(*a, Expr::Binary(..)) { + *a = std::mem::replace(&mut *a, Expr::Missing).map(f); + *b = std::mem::replace(&mut *b, Expr::Missing).map(f); + return f(Expr::Binary(op, a, b)); + } + return Expr::Binary(op, a, b).map_chain(f); + } + self.map_chain(f) + } + fn map_chain(self, f: &mut dyn FnMut(Expr) -> Expr) -> Expr { // Unwind the left spine of a long operator chain into a list, then rebuild it from the // innermost operand outwards, in the order a recursive rewrite would visit the nodes. let mut spine = Vec::new(); @@ -283,6 +298,12 @@ impl Expr { impl Clone for Expr { fn clone(&self) -> Self { + // One operator on a non-chain operand needs no spine. + if let Expr::Binary(op, a, b) = self + && !matches!(**a, Expr::Binary(..)) + { + return Expr::Binary(*op, a.clone(), b.clone()); + } // Copy the left spine of an operator chain in a loop (see [`Expr`]). let mut spine = Vec::new(); let mut node = self; diff --git a/crates/functions/src/math.rs b/crates/functions/src/math.rs index 7c84d553b..37c617fc0 100644 --- a/crates/functions/src/math.rs +++ b/crates/functions/src/math.rs @@ -520,7 +520,7 @@ fn integer_args(a: &[Arg]) -> R> { v.iter() .map(|x| { let t = x.trunc(); - if !(0.0..9.007_199_254_740_992e15).contains(&t) { Err(CellError::Num) } else { Ok(t as u64) } + if !(0.0..9.007_199_254_740_992e15).contains(x) { Err(CellError::Num) } else { Ok(t as u64) } }) .collect() } diff --git a/crates/functions/src/math/tests.rs b/crates/functions/src/math/tests.rs index 92449eb26..b6143b4f6 100644 --- a/crates/functions/src/math/tests.rs +++ b/crates/functions/src/math/tests.rs @@ -229,6 +229,20 @@ fn combinatorics() { is_err(ev("MULTINOMIAL", vec![n(-1.0), n(2.0)]), Num); } +#[test] +fn gcd_and_lcm_reject_negative_fractions_before_truncation() { + for name in ["GCD", "LCM"] { + for x in [-0.1, -0.5, -0.999] { + is_err(ev2(name, x, 2.0), Num); + is_err(ev(name, vec![rf(row(&[2.0, x]))]), Num); + // A zero elsewhere must not hide an invalid negative argument. + is_err(ev2(name, 0.0, x), Num); + } + close(ev2(name, -0.0, 2.0), if name == "GCD" { 2.0 } else { 0.0 }); + close(ev2(name, 12.9, 18.9), if name == "GCD" { 6.0 } else { 36.0 }); + } +} + #[test] fn trig() { close(ev1("SIN", PI / 2.0), 1.0); diff --git a/crates/model/src/store.rs b/crates/model/src/store.rs index e2da31e43..21406efa7 100644 --- a/crates/model/src/store.rs +++ b/crates/model/src/store.rs @@ -235,11 +235,12 @@ impl CellStore { bytes = bytes.saturating_add(size_of::()); for (row, cols) in &band.rows { bytes = bytes.saturating_add(size_of::() + 3 * size_of::()); + let next_row = next.and_then(|b| b.rows.get(row)); for (col, cell) in cols { // Cells and BTreeMap nodes are duplicated with a cloned band even when // their formula/value Arcs are still shared with the next snapshot. bytes = bytes.saturating_add(size_of::() + size_of::() + 3 * size_of::()); - let next_cell = next.and_then(|b| b.rows.get(row)).and_then(|r| r.get(col)); + let next_cell = next_row.and_then(|r| r.get(col)); if let Some(formula) = &cell.formula && !next_cell.and_then(|c| c.formula.as_ref()).is_some_and(|f| Arc::ptr_eq(f, formula)) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 535c91a5c..471905fbd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -78,6 +78,8 @@ impl SheetApp { macros: macro_ui::MacroUi::default(), started: now_ms(), allow_close: false, + window_controls: false, + viewport_commands: Vec::new(), bring_forward: false, open_switch_windows: false, ui_window: None, @@ -252,6 +254,9 @@ impl SheetApp { macro_ui::question_box(self, &ctx); widgets::message_box(self, &ctx); widgets::toast(self, &ctx); + // Last, so its resize cursors win over the widgets under the window edges. + ribbon::window_frame(self, &ctx); + self.flush_viewport_commands(&ctx); // Requests are admitted in `logic`, for the root viewport, so only its pass issues them. if ctx.viewport_id() == egui::ViewportId::ROOT { control::issue_screenshots(self, &ctx); @@ -304,6 +309,12 @@ impl SheetApp { } sel.active.a1() } + + pub(crate) fn flush_viewport_commands(&mut self, ctx: &egui::Context) { + for command in self.viewport_commands.drain(..) { + ctx.send_viewport_cmd(command); + } + } } #[cfg(test)] diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 4825318bc..1963e7054 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -163,6 +163,26 @@ impl SheetApp { /// UI-only commands (dialogs, view toggles that aren't saved in the file). fn run_ui_command(&mut self, id: &str, p: &Json) -> Option> { let r = match id { + "ui.window.minimize" => { + self.viewport_commands.push(egui::ViewportCommand::Minimized(true)); + Ok(Json::Null) + } + "ui.window.maximize" => { + let on = p.get("on").and_then(Json::as_bool).unwrap_or(true); + self.viewport_commands.push(egui::ViewportCommand::Maximized(on)); + Ok(Json::Null) + } + "ui.window.close" => { + self.viewport_commands.push(egui::ViewportCommand::Close); + Ok(Json::Null) + } + "ui.window.beginResize" => { + let Some(direction) = p.get("direction").and_then(Json::as_str).and_then(crate::parse_resize_direction) else { + return Some(Err("direction must be north, south, east, west, northeast, northwest, southeast, or southwest".into())); + }; + self.viewport_commands.push(egui::ViewportCommand::BeginResize(direction)); + Ok(Json::Null) + } "app.checkForUpdates" | "help.checkForUpdates" => { self.check_for_updates(); Ok(Json::Null) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 602d5ccdf..7d7daf006 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -275,6 +275,10 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - ("options.autoComplete", "Enable AutoComplete for cell values", "{on?: bool} (toggles without it) → {on}"), ("options.highlightActiveRow", "Highlight the active cell's row", "{on?: bool} (toggles without it) → {on}"), ("view.interfaceScale", "Interface Size", "{percent: 75–200 | \"auto\"} (100 = auto; clamped)"), + ("ui.window.minimize", "Minimize Window", ""), + ("ui.window.maximize", "Maximize Window", "{on: bool}"), + ("ui.window.close", "Close Window", ""), + ("ui.window.beginResize", "Resize Window", "{direction: north|south|east|west|northeast|northwest|southeast|southwest}"), ("ui.dialog", "Open Dialog", ""), ("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|account|close}"), ( diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index eaee085cf..a2d1312be 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -278,6 +278,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Uložit", "Save As" => "Uložit jako", "Export" => "Exportovat", + "Minimize" => "Minimalizovat", + "Maximize" => "Maximalizovat", + "Restore Down" => "Obnovit dolů", "Close" => "Zavřít", "Options" => "Možnosti", "Account" => "Účet", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 07fdb6710..fa4303851 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -294,6 +294,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Speichern", "Save As" => "Speichern unter", "Export" => "Exportieren", + "Minimize" => "Minimieren", + "Maximize" => "Maximieren", + "Restore Down" => "Nach unten wiederherstellen", "Close" => "Schließen", "Options" => "Optionen", "Account" => "Konto", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index ec42b3473..2a7449fd6 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -271,6 +271,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Αποθήκευση", "Save As" => "Αποθήκευση ως", "Export" => "Εξαγωγή", + "Minimize" => "Ελαχιστοποίηση", + "Maximize" => "Μεγιστοποίηση", + "Restore Down" => "Επαναφορά", "Close" => "Κλείσιμο", "Options" => "Επιλογές", "Blank workbook" => "Κενό βιβλίο εργασίας", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index db78d8105..df0fb4384 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -283,6 +283,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Guardar", "Save As" => "Guardar como", "Export" => "Exportar", + "Minimize" => "Minimizar", + "Maximize" => "Maximizar", + "Restore Down" => "Restaurar", "Close" => "Cerrar", "Options" => "Opciones", "Account" => "Cuenta", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fd5e23b5b..31e42afe5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -370,6 +370,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Enregistrer", "Save As" => "Enregistrer sous", "Export" => "Exporter", + "Minimize" => "Réduire", + "Maximize" => "Agrandir", + "Restore Down" => "Restaurer", "Close" => "Fermer", "Options" => "Options", "Account" => "Compte", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index dcede52cc..24fa45c95 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -365,6 +365,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Salva", "Save As" => "Salva con nome", "Export" => "Esporta", + "Minimize" => "Riduci a icona", + "Maximize" => "Ingrandisci", + "Restore Down" => "Ripristina", "Close" => "Chiudi", "Options" => "Opzioni", "Blank workbook" => "Cartella di lavoro vuota", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index d558be6ec..a659da744 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -364,6 +364,9 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Save", "上書き保存"), ("Save As", "名前を付けて保存"), ("Export", "エクスポート"), + ("Minimize", "最小化"), + ("Maximize", "最大化"), + ("Restore Down", "元のサイズに戻す"), ("Close", "閉じる"), ("Options", "オプション"), ("Blank workbook", "空白のブック"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index ca2710272..9d6d3644a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -370,6 +370,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "저장", "Save As" => "다른 이름으로 저장", "Export" => "내보내기", + "Minimize" => "최소화", + "Maximize" => "최대화", + "Restore Down" => "이전 크기로 복원", "Close" => "닫기", "Options" => "옵션", "Account" => "계정", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index 64c24b1f2..44a1b3815 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -364,6 +364,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Opslaan", "Save As" => "Opslaan als", "Export" => "Exporteren", + "Minimize" => "Minimaliseren", + "Maximize" => "Maximaliseren", + "Restore Down" => "Vorig formaat", "Close" => "Sluiten", "Options" => "Opties", "Blank workbook" => "Lege werkmap", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 29264ce91..d232a6e0d 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -357,6 +357,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Zapisz", "Save As" => "Zapisz jako", "Export" => "Eksportuj", + "Minimize" => "Minimalizuj", + "Maximize" => "Maksymalizuj", + "Restore Down" => "Przywróć w dół", "Close" => "Zamknij", "Options" => "Opcje", "Blank workbook" => "Pusty skoroszyt", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 3cc4faf76..d93054309 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -367,6 +367,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Salvar", "Save As" => "Salvar como", "Export" => "Exportar", + "Minimize" => "Minimizar", + "Maximize" => "Maximizar", + "Restore Down" => "Restaurar", "Close" => "Fechar", "Options" => "Opções", "Account" => "Conta", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 3d5a193d1..0876ac50f 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -364,6 +364,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Salvare", "Save As" => "Salvare ca", "Export" => "Exportare", + "Minimize" => "Minimizare", + "Maximize" => "Maximizare", + "Restore Down" => "Restaurare", "Close" => "Închidere", "Options" => "Opțiuni", "Blank workbook" => "Registru gol", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 2d4d3fe1f..f422bcb93 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -372,6 +372,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Сохранить", "Save As" => "Сохранить как", "Export" => "Экспорт", + "Minimize" => "Свернуть", + "Maximize" => "Развернуть", + "Restore Down" => "Восстановить", "Close" => "Закрыть", "Options" => "Параметры", "Account" => "Учетная запись", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index a0eac0a4f..fa9d1285a 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -363,6 +363,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Sačuvaj", "Save As" => "Sačuvaj kao", "Export" => "Izvezi", + "Minimize" => "Minimizuj", + "Maximize" => "Maksimizuj", + "Restore Down" => "Vrati", "Close" => "Zatvori", "Options" => "Opcije", "Account" => "Nalog", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index ed3d0bf01..35143bf9a 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -277,6 +277,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Kaydet", "Save As" => "Farklı Kaydet", "Export" => "Dışarı Aktar", + "Minimize" => "Simge durumuna küçült", + "Maximize" => "Ekranı kapla", + "Restore Down" => "Önceki boyuta getir", "Close" => "Kapat", "Options" => "Seçenekler", "Blank workbook" => "Boş çalışma kitabı", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 7059a0ff4..4374cc135 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -361,6 +361,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Зберегти", "Save As" => "Зберегти як", "Export" => "Експорт", + "Minimize" => "Згорнути", + "Maximize" => "Розгорнути", + "Restore Down" => "Відновити", "Close" => "Закрити", "Options" => "Параметри", "Blank workbook" => "Порожня книга", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 260f9572d..62462cc4b 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -367,6 +367,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "Lưu", "Save As" => "Lưu thành", "Export" => "Xuất", + "Minimize" => "Thu nhỏ", + "Maximize" => "Phóng to", + "Restore Down" => "Khôi phục", "Close" => "Đóng", "Options" => "Tùy chọn", "Blank workbook" => "Sổ làm việc trống", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index ff671a7c9..e7ff3fc75 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -368,6 +368,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save" => "保存", "Save As" => "另存为", "Export" => "导出", + "Minimize" => "最小化", + "Maximize" => "最大化", + "Restore Down" => "向下还原", "Close" => "关闭", "Options" => "选项", "Account" => "账户", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ce7ce347b..3086d1fc9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -83,6 +83,20 @@ pub use services::{Chrome, Inbox, Services}; pub use state::{NoticeKind, OpenWindow, SaveAnswer, SheetView}; pub mod desktop_theme; +fn parse_resize_direction(value: &str) -> Option { + match value { + "north" => Some(egui::ResizeDirection::North), + "south" => Some(egui::ResizeDirection::South), + "east" => Some(egui::ResizeDirection::East), + "west" => Some(egui::ResizeDirection::West), + "northeast" => Some(egui::ResizeDirection::NorthEast), + "northwest" => Some(egui::ResizeDirection::NorthWest), + "southeast" => Some(egui::ResizeDirection::SouthEast), + "southwest" => Some(egui::ResizeDirection::SouthWest), + _ => None, + } +} + /// Persisted UI preferences. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -308,6 +322,10 @@ pub struct SheetApp { /// Every unsaved workbook has been answered for quitting (or `app.quit` asked): the next /// window close goes through. pub allow_close: bool, + /// Linux/BSD: the window has no system frame; the title bar draws minimize, maximize and + /// close, and the window resizes from its edges (`ribbon::window_frame`). + pub window_controls: bool, + viewport_commands: Vec, /// A quit question is waiting in the active window: [`doc_windows`] brings its native window /// to the front, also when the app is hidden or the window minimized (a Dock quit). pub bring_forward: bool, @@ -341,3 +359,32 @@ pub fn clean_error(e: &str) -> String { pub fn cell(r: u32, c: u32) -> CellRef { CellRef::new(r, c) } + +#[cfg(test)] +mod viewport_command_tests { + use super::parse_resize_direction; + + #[test] + fn resize_direction_parser_accepts_all_edges_and_rejects_unknown_values() { + for name in ["north", "south", "east", "west", "northeast", "northwest", "southeast", "southwest"] { + assert!(parse_resize_direction(name).is_some(), "{name}"); + } + assert!(parse_resize_direction("middle").is_none()); + } + + #[test] + fn window_commands_queue_viewport_commands_without_a_workbook() { + use egui::ViewportCommand; + let mut a = crate::SheetApp::new(gridcraft_engine::Session::new(), crate::Services::default()); + for (id, params, expected) in [ + ("ui.window.minimize", serde_json::json!({}), ViewportCommand::Minimized(true)), + ("ui.window.maximize", serde_json::json!({"on": true}), ViewportCommand::Maximized(true)), + ("ui.window.close", serde_json::json!({}), ViewportCommand::Close), + ("ui.window.beginResize", serde_json::json!({"direction": "east"}), ViewportCommand::BeginResize(egui::ResizeDirection::East)), + ] { + assert!(a.run(id, params).is_ok(), "{id} should route without a workbook"); + assert!(a.viewport_commands.contains(&expected), "{id} queues {expected:?}"); + } + assert!(a.run("ui.window.beginResize", serde_json::json!({"direction": "diagonal"})).is_err()); + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 47f1eabd7..d14724f1b 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -38,7 +38,7 @@ use insert::{draw, insert}; use page_layout::page_layout; use review::review; pub use shortcuts::shortcut; -pub use title_bar::{MAC_CONTENT_LEFT, MAC_TITLE_BAR, TITLE_LEFT_PAD, title_bar}; +pub use title_bar::{MAC_CONTENT_LEFT, MAC_TITLE_BAR, TITLE_LEFT_PAD, title_bar, window_frame}; use title_bar::{TITLE_BAR_H, TITLE_CONTROL_H}; use view::view; diff --git a/crates/ui-egui/src/ribbon/title_bar.rs b/crates/ui-egui/src/ribbon/title_bar.rs index 29bd4f270..e6de96f20 100644 --- a/crates/ui-egui/src/ribbon/title_bar.rs +++ b/crates/ui-egui/src/ribbon/title_bar.rs @@ -120,6 +120,9 @@ pub fn title_bar(app: &mut SheetApp, ui: &mut Ui) { }); let left_end = ui.min_rect().right(); let right = ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if app.window_controls { + ui.add_space(3.0 * CONTROL_W); + } ui.add_space(8.0); let __k = icon_button(ui, Icon::Search, t.text_dim, "Search commands", vec2(28.0, ch)); control_keytip(app, ui, &__k, "commandSearch"); @@ -206,6 +209,120 @@ fn paint_title(ui: &Ui, center: egui::Pos2, title: &str, dirty: bool, max_w: f32 } } +/// Width of one window-control button on the title bar. +pub const CONTROL_W: f32 = 46.0; +const CONTROL_TITLE_H: f32 = 38.0; +const RESIZE_BAND: f32 = 5.0; + +/// Draw application controls and edge resizing for frameless windows. +pub fn window_frame(app: &mut SheetApp, ctx: &egui::Context) { + if !app.window_controls { + return; + } + let (maximized, fullscreen) = ctx.input(|i| (i.viewport().maximized.unwrap_or(false), i.viewport().fullscreen.unwrap_or(false))); + if fullscreen { + return; + } + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let controls = egui::Rect::from_min_size(egui::pos2(screen.max.x - 3.0 * CONTROL_W, screen.min.y), egui::vec2(3.0 * CONTROL_W, CONTROL_TITLE_H)); + egui::Area::new(egui::Id::unique("gc_window_controls")).order(egui::Order::Foreground).fixed_pos(controls.min).show(ctx, |ui| { + ui.spacing_mut().item_spacing = egui::vec2(0.0, 0.0); + ui.horizontal(|ui| { + for kind in ["minimize", "maximize", "close"] { + let (r, resp) = ui.allocate_exact_size(egui::vec2(CONTROL_W, CONTROL_TITLE_H), egui::Sense::click()); + let label = app.ui.language.tr(match kind { + "minimize" => "Minimize", + "maximize" if maximized => "Restore Down", + "maximize" => "Maximize", + _ => "Close", + }); + let hot = resp.hovered() || resp.is_pointer_button_down_on(); + if hot { + ui.painter().rect_filled( + r, + 0.0, + if kind == "close" { + egui::Color32::from_rgb(0xC4, 0x2B, 0x1C) + } else if resp.is_pointer_button_down_on() { + t.pressed + } else { + t.hover + }, + ); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let m = r.center(); + let stroke = egui::Stroke::new(1.0, if kind == "close" && hot { egui::Color32::WHITE } else { t.text }); + match kind { + "minimize" => { + ui.painter().line_segment([egui::pos2(m.x - 5.0, m.y), egui::pos2(m.x + 5.0, m.y)], stroke); + } + "maximize" if maximized => { + let front = egui::Rect::from_min_size(egui::pos2(m.x - 5.0, m.y - 3.0), egui::vec2(8.0, 8.0)); + ui.painter().rect_stroke(front, 0.0, stroke, egui::StrokeKind::Inside); + ui.painter().line_segment([egui::pos2(m.x - 3.0, m.y - 5.0), egui::pos2(m.x + 5.0, m.y - 5.0)], stroke); + ui.painter().line_segment([egui::pos2(m.x + 5.0, m.y - 5.0), egui::pos2(m.x + 5.0, m.y + 3.0)], stroke); + } + "maximize" => { + ui.painter().rect_stroke(r.shrink(15.0), 0.0, stroke, egui::StrokeKind::Inside); + } + _ => { + ui.painter().line_segment([m - egui::vec2(5.0, 5.0), m + egui::vec2(5.0, 5.0)], stroke); + ui.painter().line_segment([m + egui::vec2(5.0, -5.0), m - egui::vec2(5.0, -5.0)], stroke); + } + } + if resp.on_hover_text(label).clicked() { + match kind { + "minimize" => app.run_or_alert("ui.window.minimize", json!({})), + "maximize" => app.run_or_alert("ui.window.maximize", json!({"on": !maximized})), + "close" => app.run_or_alert("ui.window.close", json!({})), + _ => {} + } + } + } + }); + }); + if maximized { + return; + } + let Some(pos) = ctx.input(|i| i.pointer.hover_pos()) else { + return; + }; + let l = pos.x <= screen.min.x + RESIZE_BAND; + let r = pos.x >= screen.max.x - RESIZE_BAND; + let top = pos.y <= screen.min.y + RESIZE_BAND; + let b = pos.y >= screen.max.y - RESIZE_BAND; + let dir = match (l, r, top, b) { + (true, false, true, false) => Some(egui::viewport::ResizeDirection::NorthWest), + (false, true, true, false) => Some(egui::viewport::ResizeDirection::NorthEast), + (true, false, false, true) => Some(egui::viewport::ResizeDirection::SouthWest), + (false, true, false, true) => Some(egui::viewport::ResizeDirection::SouthEast), + (true, false, _, _) => Some(egui::viewport::ResizeDirection::West), + (false, true, _, _) => Some(egui::viewport::ResizeDirection::East), + (_, _, true, false) => Some(egui::viewport::ResizeDirection::North), + (_, _, false, true) => Some(egui::viewport::ResizeDirection::South), + _ => None, + }; + if let Some(dir) = dir + && ctx.input(|i| i.pointer.primary_pressed()) + && !controls.contains(pos) + { + let direction = match dir { + egui::ResizeDirection::North => "north", + egui::ResizeDirection::South => "south", + egui::ResizeDirection::East => "east", + egui::ResizeDirection::West => "west", + egui::ResizeDirection::NorthEast => "northeast", + egui::ResizeDirection::NorthWest => "northwest", + egui::ResizeDirection::SouthEast => "southeast", + egui::ResizeDirection::SouthWest => "southwest", + }; + app.run_or_alert("ui.window.beginResize", json!({"direction": direction})); + } + app.flush_viewport_commands(ctx); +} + #[cfg(test)] mod title_bar_tests { use super::*; diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index a03206702..c201f90ae 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -47,6 +47,7 @@ fn prefix_params(e: Expr, scope: &[String]) -> Expr { Expr::Name(n) if scope.iter().any(|s| s.eq_ignore_ascii_case(&n)) => Expr::Name(format!("{PARAM_PREFIX}{n}")), Expr::Unary(op, x) => Expr::Unary(op, sub(x, scope)), Expr::Paren(x) => Expr::Paren(sub(x, scope)), + Expr::Binary(op, a, b) if !matches!(*a, Expr::Binary(..)) => Expr::Binary(op, sub(a, scope), sub(b, scope)), Expr::Binary(op, a, b) => { // A long chain such as A1+A2+… nests on its left: follow it in a loop, not one // level of recursion per operand. diff --git a/crates/xlsx/src/pivot/read.rs b/crates/xlsx/src/pivot/read.rs index 134a8ab22..bce6457a9 100644 --- a/crates/xlsx/src/pivot/read.rs +++ b/crates/xlsx/src/pivot/read.rs @@ -69,7 +69,23 @@ fn item_label_el(e: &El, sys: DateSystem) -> String { } fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option { - let x = cx.optional_xml(part).ok().flatten()?; + // A cache that can't be read loses its PivotTable: say so instead of dropping it silently. + // An oversized cache is refused before it inflates, so warning and opening the rest is safe. + let x = match cx.optional_xml(part) { + Ok(Some(x)) => x, + Ok(None) => { + cx.warn(format!("a PivotTable's cache {part} is missing or could not be read; kept as plain cells")); + return None; + } + Err(IoError::TooLarge(m)) => { + cx.warn(format!("a PivotTable's cache is too large to read ({m}); kept as plain cells")); + return None; + } + Err(e) => { + cx.warn(format!("a PivotTable's cache could not be read ({e}); kept as plain cells")); + return None; + } + }; if x.name != "pivotCacheDefinition" { cx.warn(format!("{part} is not a pivot cache definition; its PivotTable was kept as plain cells")); return None; diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 569003fd4..d0a8e0bfc 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -711,6 +711,51 @@ fn data_on_rows_with_one_value_field_reads_without_warning() { assert!(back.sheet(0).unwrap().pivots[0].values_on_rows); } +const SIMPLE_TABLE: &str = r#""#; +const CACHE_PART: &str = "xl/pivotCache/pivotCacheDefinition1.xml"; + +/// Rewrites the uncompressed size a zip's central directory declares for `name`. +fn declare_size(mut zip: Vec, name: &str, size: u32) -> Vec { + let at = (0..zip.len().saturating_sub(46)) + .find(|&i| { + zip[i..i + 4] == [0x50, 0x4b, 0x01, 0x02] && { + let len = u16::from_le_bytes([zip[i + 28], zip[i + 29]]) as usize; + zip.get(i + 46..i + 46 + len) == Some(name.as_bytes()) + } + }) + .unwrap(); + zip[at + 24..at + 28].copy_from_slice(&size.to_le_bytes()); + zip +} + +#[test] +fn unreadable_pivot_cache_warns() { + // Control: a readable cache gives a PivotTable and no cache warning. + let (wb, report) = read_xlsx(&with_pivot(SIMPLE_TABLE, Some(GOOD_CACHE))).unwrap(); + assert_eq!(wb.sheet(0).unwrap().pivots.len(), 1, "{:?}", report.warnings); + assert!(!report.warnings.iter().any(|w| w.contains("PivotTable's cache")), "{:?}", report.warnings); + // Malformed and missing caches: the workbook opens and the lost PivotTable is reported. + let lost = format!("a PivotTable's cache {CACHE_PART} is missing or could not be read; kept as plain cells"); + for cache in [Some("garbage <<<"), None] { + let (wb, report) = read_xlsx(&with_pivot(SIMPLE_TABLE, cache)).unwrap(); + assert!(wb.sheet(0).unwrap().pivots.is_empty()); + assert!(report.warnings.contains(&lost), "{cache:?}: {:?}", report.warnings); + } +} + +#[test] +fn oversized_pivot_cache_warns() { + // The cache declares more than the per-part limit, so it is refused before it inflates. + let declared = u32::try_from(crate::package::MAX_PART + 1).unwrap(); + let bytes = declare_size(with_pivot(SIMPLE_TABLE, Some(GOOD_CACHE)), CACHE_PART, declared); + let (wb, report) = read_xlsx(&bytes).unwrap(); + assert_eq!(wb.sheet(0).unwrap().name, "Data"); + assert!(wb.sheet(0).unwrap().pivots.is_empty()); + let limit = crate::package::MAX_PART; + let lost = format!("a PivotTable's cache is too large to read ({CACHE_PART} expands to more than {limit} bytes); kept as plain cells"); + assert!(report.warnings.contains(&lost), "{:?}", report.warnings); +} + /// A one-sheet-of-data workbook with a pivot on "Report": `columns` are the source columns /// (header, values), `pt` the pivot built on `Data!A1:`. fn small_pivot(columns: &[(&str, Vec)], pt: impl FnOnce(&mut PivotTable)) -> HashMap { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0847714a3..6e5b1a23f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -209,6 +209,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-15 | minor | XLSX: formulas and PivotTable sources quote sheet names like Excel (a leading `.`, R1C1-like and cell-like names), so `'.x'!A1` no longer saves as `.x!A1`, which Excel could not open (#1458) | | 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 | trivial | XLSX import warns when a pivot cache is missing, malformed or too large instead of dropping its PivotTable silently (#1039) | | 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 | 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 | diff --git a/docs/function-parity.md b/docs/function-parity.md index 7dec2c03c..272056909 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-11-03 · **Change:** minor (GROUPBY total depth 2 or more adds subtotals; earlier: Python cells are edited in the formula bar; earlier: the Python errors `#PYTHON!`, `#BUSY!`, `#TIMEOUT!` and `#BLOCKED!`, and a Python in cells row; earlier: YEARFRAC basis 0 February-end rule, MOD quotient limit, PERCENTRANK significance; earlier: edge cases matched to Excel: base conversions, BITLSHIFT/BITRSHIFT, UNICHAR noncharacters, UPPER/LOWER/PROPER casing, FIXED/DOLLAR output, F/T/GAMMA/WEIBULL/BETA distributions, BINOM trial cap, HARMEAN; earlier: ECMA.CEILING listed with USDOLLAR as not on Microsoft's list; earlier: IMSQRT reproduces the stray real part Excel gives for negative reals) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-11-04 · **Change:** minor (GCD and LCM reject negative fractional arguments before truncation; earlier: GROUPBY total depth 2 or more adds subtotals; earlier: Python cells are edited in the formula bar; earlier: the Python errors `#PYTHON!`, `#BUSY!`, `#TIMEOUT!` and `#BLOCKED!`, and a Python in cells row; earlier: YEARFRAC basis 0 February-end rule, MOD quotient limit, PERCENTRANK significance; earlier: edge cases matched to Excel: base conversions, BITLSHIFT/BITRSHIFT, UNICHAR noncharacters, UPPER/LOWER/PROPER casing, FIXED/DOLLAR output, F/T/GAMMA/WEIBULL/BETA distributions, BINOM trial cap, HARMEAN; earlier: ECMA.CEILING listed with USDOLLAR as not on Microsoft's list; earlier: IMSQRT reproduces the stray real part Excel gives for negative reals) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -132,10 +132,16 @@ Work to close (16–26 h in total): the in-scope missing functions (10–16 h wi an oracle corpus of Excel-computed results per function (owner runs Excel on generated workbooks; results checked in as data, not Excel files) and fixing what it finds (6–10 h). +GCD and LCM validate the sign of the original argument before truncating it. Negative +fractions such as `-0.5` return `#NUM!`, including inside ranges and beside a zero argument. +Positive fractional inputs still truncate, and signed zero remains valid. Covered by +`gcd_and_lcm_reject_negative_fractions_before_truncation`; function counts and estimates are unchanged. + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | GCD and LCM reject negative fractional arguments before truncation; scalar and range regressions in the extracted math tests preserve positive truncation and signed-zero behavior; estimates unchanged | | 2026-11-03 | minor | GROUPBY: a total depth of 2 or more adds a subtotal line for each group of the leading key columns (after the group, or before it for a negative depth) and labels the last line Grand Total; a depth past the key columns, or above 1 with `field_relationship` 1, is `#VALUE!`, as in Excel (#1456 item 1) | | 2026-11-01 | minor | Python in cells row: Python mode in the formula bar | | 2026-11-01 | minor | Python in cells (stored, not run): `#PYTHON!`, `#BUSY!`, `#TIMEOUT!` and `#BLOCKED!` done, with their `ERROR.TYPE` numbers; `PY` still counted as missing |