diff --git a/ROADMAP.md b/ROADMAP.md index 864f53cbb7..5ac06ac15d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,7 @@ > **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (IRR's Newton solver checks its scaled residual before accepting a small step; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) > **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365) + GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. This page is the summary. The detail is in: @@ -151,6 +152,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) | | 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used | | 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged | +| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 | | 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) | | 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently | | 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export | @@ -304,6 +306,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories | | 2026-10-31 | minor | Progress log: Function Library | | 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles | +| 2026-10-26 | minor | Progress log: Excel open check | | 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets | | 2026-10-26 | minor | Progress log: Arabic PDF text | | 2026-10-26 | minor | Progress log: Arabic bidi display and editing | diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 2c786bf0a8..b4e0772ac0 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -23,9 +23,9 @@ mod sort; mod tools; mod validation; -pub use filter::filter_values; pub(crate) use filter::{apply_filter, grow_autofilter}; use filter::{clear_filter, filter_by, reapply, toggle_filter}; +pub use filter::{filter_selection, filter_values}; use grouping::{detail, group, outline_settings, show_levels, subtotal}; pub use sort::sort_context; use sort::{quick_sort, sort}; diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 274c0879bc..e4570acc44 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -3,6 +3,7 @@ use super::{ AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, current_region, data_target, edit, json, }; +use std::collections::{HashMap, HashSet}; // ---------------------------------------------------------------- filter @@ -181,19 +182,18 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } } -/// Hides rows of the autofilter range that fail any criterion. -pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { - let Some(sh) = wb.sheet(sheet) else { return }; - let Some(af) = sh.autofilter.clone() else { return }; - // An imported range can name rows past the grid; none of those exist to hide. - let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col)); - let mut hide = Vec::new(); +/// Statistics use the original range within the grid, regardless of the other active criteria. +fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap, f64)> { + let r = af.range; // Precompute per-criterion top10 threshold and average once, not per row. - let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); + let mut col_stats = HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { - let col = r.start.col + off; - let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); + let Some(col) = r.start.col.checked_add(*off) else { continue }; + // Keep main's imported-range bound after extracting statistics from apply_filter. + let mut nums: Vec = (r.start.row.saturating_add(1)..=r.end.row.min(gridcraft_core::MAX_ROWS - 1)) + .filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()) + .collect(); let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::() / nums.len() as f64 }; let thr = match c { FilterCriterion::Top10 { bottom, percent, count } => { @@ -207,59 +207,97 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { col_stats.insert(i, (thr, avg)); } } - for row in r.start.row + 1..=r.end.row { - let mut visible = true; - for (i, (off, crit)) in af.criteria.iter().enumerate() { - let c = CellRef::new(row, r.start.col + off); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { - if filter_blank(&v) { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) - } - } - FilterCriterion::Custom { a, b, and } => { - let x = custom_ok(&v, &text, &a.0, &a.1); - match b { - Some(b) => { - let y = custom_ok(&v, &text, &b.0, &b.1); - if *and { x && y } else { x || y } - } - None => x, - } - } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((thr, _))) => { - let thr = thr.unwrap_or(n); - if *bottom { n <= thr } else { n >= thr } - } - _ => false, - }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((_, avg))) => { - if *above { - n > *avg - } else { - n < *avg - } - } - _ => false, - }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, - // Icons are not evaluated here: the row keeps its current visibility. - FilterCriterion::Icon { .. } => !sh.is_row_hidden(row), - }; - if !ok { - visible = false; - break; - } - } - hide.push((row, !visible)); + col_stats +} + +/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query. +struct FilterMatcher<'a> { + wb: &'a Workbook, + sh: &'a Sheet, + af: &'a AutoFilter, + stats: HashMap, f64)>, + values: HashMap>, +} + +impl<'a> FilterMatcher<'a> { + fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self { + let values = af + .criteria + .iter() + .enumerate() + .filter_map(|(i, (_, crit))| match crit { + FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())), + _ => None, + }) + .collect(); + Self { wb, sh, af, stats: filter_stats(sh, af), values } } + + fn row_matches(&self, row: u32, excluded_offset: Option) -> bool { + self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit)) + } + + fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool { + let Some(col) = self.af.range.start.col.checked_add(off) else { return true }; + let c = CellRef::new(row, col); + let v = self.sh.value(c); + let text = crate::display::cell_text(self.wb, self.sh, c); + match crit { + FilterCriterion::Values { blanks, .. } => { + if filter_blank(&v) { + *blanks + } else { + self.values + .get(&i) + .is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase())) + } + } + FilterCriterion::Custom { a, b, and } => { + let x = custom_ok(&v, &text, &a.0, &a.1); + match b { + Some(b) => { + let y = custom_ok(&v, &text, &b.0, &b.1); + if *and { x && y } else { x || y } + } + None => x, + } + } + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) { + (Some(n), Some((thr, _))) => { + let thr = thr.unwrap_or(n); + if *bottom { n <= thr } else { n >= thr } + } + _ => false, + }, + FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) { + (Some(n), Some((_, avg))) => { + if *above { + n > *avg + } else { + n < *avg + } + } + _ => false, + }, + FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col, + // Icon criteria are retained from files but cannot be evaluated yet. + FilterCriterion::Icon { .. } => true, + } + } +} + +/// Hides rows of the autofilter range that fail any criterion. +pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { + let Some(sh) = wb.sheet(sheet) else { return }; + let Some(af) = sh.autofilter.clone() else { return }; + // An imported range can name rows past the grid; none of those exist to hide. + let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col)); + let matcher = FilterMatcher::new(wb, sh, &af); + // Reapplying a retained icon filter preserves visibility until icons can be evaluated. + let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. })); + let hide: Vec<_> = + (r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect(); let Some(shm) = wb.sheet_mut(sheet) else { return }; for (row, h) in hide { if h { @@ -294,30 +332,52 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result { }) } -/// Distinct display values of a filter column (for the dropdown list). +/// Distinct display values from rows matching the other columns' criteria. +/// The current criterion only determines checkboxes, so its unchecked alternatives stay available. pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> { + column_filter_values(wb, sheet, col, true) +} + +/// Applies edited eligible choices to the whole column's checkbox state, retaining choices hidden by other filters. +pub fn filter_selection(wb: &Workbook, sheet: usize, col: u32, choices: &[(String, bool)]) -> Vec<(String, bool)> { + let mut edited = std::collections::BTreeMap::new(); + for (value, on) in choices { + *edited.entry(value.to_ascii_lowercase()).or_insert(false) |= *on; + } + let mut selection = column_filter_values(wb, sheet, col, false); + for (value, on) in &mut selection { + if let Some(checked) = edited.get(&value.to_ascii_lowercase()) { + *on = *checked; + } + } + selection +} + +fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bool) -> Vec<(String, bool)> { let Some(sh) = wb.sheet(sheet) else { return vec![] }; let Some(af) = &sh.autofilter else { return vec![] }; - let off = col.saturating_sub(af.range.start.col); - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); + if col < af.range.start.col || col > af.range.end.col { + return vec![]; + } + let off = col - af.range.start.col; + let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off); + let matcher = FilterMatcher::new(wb, sh, af); let mut seen = std::collections::BTreeMap::new(); - for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) { + // Imported end rows cannot add choices beyond the grid either. + for row in + af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)).min(gridcraft_core::MAX_ROWS - 1) + { + if eligible_only && !matcher.row_matches(row, Some(off)) { + continue; + } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; - let on = match selected { - Some(FilterCriterion::Values { values, blanks }) => { - if blank { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&t)) - } - } - _ => true, - }; + let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit)); let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; - seen.entry((key, t)).or_insert(on); + // One choice can represent rows with different colors; keep any matching row checked. + *seen.entry((key, t)).or_insert(false) |= on; } let mut values: Vec<_> = seen.into_iter().collect(); values.sort_by(|((a, ta), _), ((b, tb), _)| { diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index decd9d4ba6..01e6cb8f03 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -57,7 +57,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000; use layout::bands; pub(crate) use layout::split_bands; pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range}; -use layout::{known_paper, seg_size, segments}; +use layout::{seg_size, segments}; use objects::{PicCache, draw_objects}; #[cfg(test)] use text::{center_across_width, wrap_lines}; @@ -96,7 +96,7 @@ pub fn specs() -> Vec { "Page Setup…", ["Page Layout", "Page Setup"], None, - "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", + "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", has_doc, page_setup ), @@ -309,8 +309,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result { let paper = match str_param(p, "paper") { None => None, Some(name) => { - known_paper(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; - Some(name.trim().to_string()) + // Stored under its table name, which every file format knows. + let paper = gridcraft_model::paper::canonical(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; + Some(paper.to_string()) } }; let margin_src = p.get("margins").filter(|m| m.is_object()).unwrap_or(p); diff --git a/crates/engine/src/cmd/print/layout.rs b/crates/engine/src/cmd/print/layout.rs index 0d86de5158..1f2ec38ee7 100644 --- a/crates/engine/src/cmd/print/layout.rs +++ b/crates/engine/src/cmd/print/layout.rs @@ -9,43 +9,10 @@ pub(super) const DENSE_BLOCK: u64 = 60_000; // ---------------------------------------------------------------- paper -/// Paper size in points (portrait) for a paper name; unknown names fall back to Letter. +/// Paper size in points, as named (see `gridcraft_model::paper`); unknown names, and the empty +/// name of a file that stated no paper, fall back to Letter. pub fn paper_size(name: &str) -> (f32, f32) { - known_paper(name).unwrap_or((612.0, 792.0)) -} - -/// Paper sizes in points, portrait. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel and its -/// e-mail attachments use (257×364, 182×257 and 128×182 mm); the ISO B series stays reachable as -/// `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and envelopes are the JIS ones too. -pub(super) fn known_paper(name: &str) -> Option<(f32, f32)> { - // Spaces, hyphens, underscores and parentheses don't matter: `B5 (JIS)`, `b5-jis` and `b5` - // are one name. - let n = name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - Some(match n.as_str() { - "letter" | "usletter" => (612.0, 792.0), - "legal" | "uslegal" => (612.0, 1008.0), - "a4" => (595.28, 841.89), - "a3" => (841.89, 1190.55), - "a5" => (419.53, 595.28), - "a6" => (297.64, 419.53), - "tabloid" | "11x17" => (792.0, 1224.0), - "ledger" => (1224.0, 792.0), - "executive" => (522.0, 756.0), - "b4" | "b4jis" => (728.50, 1031.81), - "b5" | "b5jis" => (515.91, 728.50), - "b6" | "b6jis" => (362.83, 515.91), - "b4iso" => (708.66, 1000.63), - "b5iso" => (498.90, 708.66), - "b6iso" => (354.33, 498.90), - "japanesepostcard" | "postcard" => (283.46, 419.53), - "japanesedoublepostcard" | "doublepostcard" => (419.53, 566.93), - "japaneseenvelope#3" | "chou#3" => (340.16, 666.14), - // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. - "japaneseenvelope#4" | "chou#4" => (255.12, 581.10), - "japaneseenvelopekaku#2" | "kaku#2" => (680.31, 941.10), - "japaneseenvelopekaku#3" | "kaku#3" => (612.28, 785.20), - _ => return None, - }) + gridcraft_model::paper::size_pt(name).unwrap_or((612.0, 792.0)) } // ---------------------------------------------------------------- layout diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 853e59937d..b506f0d2bd 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -974,6 +974,48 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } +/// An empty paper name means no paper is stated; it prints on Letter. +#[test] +fn an_unstated_paper_prints_on_letter() { + let mut wb = gridcraft_model::Workbook::new(); + std::sync::Arc::make_mut(&mut wb.sheets[0]).set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + std::sync::Arc::make_mut(&mut wb.sheets[0]).print.paper = String::new(); + let layouts = super::layout::layouts(&wb, &super::layout::PrintOptions::default()); + let l = &layouts[0]; + assert_eq!((l.page_w, l.page_h), (612.0, 792.0)); + assert_eq!(paper_size(""), (612.0, 792.0)); +} + +/// Both commands that set the paper store a known one under its table name, so every file +/// format finds it. +#[test] +fn paper_size_commands_store_the_table_name() { + let mut s = s(); + s.execute("pageLayout.size", json!({"paper": "b5-jis"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5"); + s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid"); + // Statement and the envelopes XLSX names are accepted by both commands (Page Setup refused + // them before), stored under their table name and printed on their own size. + s.execute("range.setValues", json!({"range": "A1", "values": [["x"]]})).unwrap(); + let close = |v: &Json, want: f64| (v.as_f64().unwrap() - want).abs() < 0.01; + for (cmd, given, stored, w, h) in [ + ("pageLayout.pageSetup", "statement", "Statement", 396.0, 612.0), + ("pageLayout.pageSetup", "envelope #10", "Envelope #10", 297.0, 684.0), + ("pageLayout.pageSetup", "Envelope-DL", "Envelope DL", 311.81, 623.62), + ("pageLayout.size", "Statement", "Statement", 396.0, 612.0), + ("pageLayout.size", "envelope dl", "Envelope DL", 311.81, 623.62), + ] { + s.execute(cmd, json!({"paper": given})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, stored, "{cmd} {given}"); + let pv = s.execute("file.printPreview", json!({})).unwrap(); + let page = &pv["pageList"][0]; + assert!(close(&page["width"], w) && close(&page["height"], h), "{cmd} {given}: {page}"); + } + // A new workbook still prints on Letter. + assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter"); +} + #[test] fn hostile_settings_never_panic_and_cap_pages() { let mut s = s(); @@ -1344,3 +1386,39 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() { assert!(pics.chart((0, 1), || vec![line(1000)]).is_none()); assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1))); } + +/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name. +#[test] +fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() { + use std::io::{Cursor, Read, Write}; + let mut wb = gridcraft_model::Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + wb.sheet_mut(0).unwrap().print.paper = "Legal".into(); + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let mut input = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let mut output = zip::ZipWriter::new(Cursor::new(Vec::new())); + for i in 0..input.len() { + let mut part = input.by_index(i).unwrap(); + let mut data = Vec::new(); + part.read_to_end(&mut data).unwrap(); + let name = part.name().unwrap().to_string(); + if name == "xl/worksheets/sheet1.xml" { + let xml = String::from_utf8(data).unwrap(); + assert!(xml.contains(r#"paperSize="5""#)); + // Set the input id independently of the shared paper-name mapping under test. + data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes(); + } + output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + let bytes = output.finish().unwrap().into_inner(); + let mut s = Session::new(); + s.execute("file.open", json!({"name": "iso-b5.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + let preview = s.execute("file.printPreview", json!({})).unwrap(); + let page = &preview["pageList"][0]; + assert!((page["width"].as_f64().unwrap() - 498.90).abs() < 0.01, "{page}"); + assert!((page["height"].as_f64().unwrap() - 708.66).abs() < 0.01, "{page}"); + let (pdf, pages) = pdf_of(&mut s, json!({})); + assert_eq!(pages, 1); + assert!(contains(&pdf, "/MediaBox [0 0 498.9 708.66]")); +} diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 954ec95ad9..9df96f1c1e 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Size", ["Page Layout", "Page Setup"], None, - "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes)}", + "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}", has_doc, paper ), @@ -324,7 +324,9 @@ fn orientation(s: &mut Session, p: &Json) -> Result { } fn paper(s: &mut Session, p: &Json) -> Result { - let paper = str_param(p, "paper").unwrap_or("Letter").to_string(); + // A known paper is stored under its table name; any other name is kept (it prints on Letter). + let name = str_param(p, "paper").unwrap_or("Letter"); + let paper = gridcraft_model::paper::canonical(name).unwrap_or(name).to_string(); edit(s, |cx| { let si = cx.sheet_index(); cx.sheet_mut(si)?.print.paper = paper.clone(); diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs new file mode 100644 index 0000000000..0eb731522d --- /dev/null +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -0,0 +1,427 @@ +use std::sync::Arc; + +use gridcraft_engine::{ + Session, + cmd::data::{filter_selection, filter_values}, + core::{CellRef, Value}, + model::{Cell, Color, FilterCriterion, PyCode}, +}; +use serde_json::json; + +#[test] +fn python_cells_offer_cached_results_without_exposing_or_changing_code() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Company", "Result"], ["East", 7], ["East", null], ["West", 99]]})).unwrap(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + for (at, value) in [("B2", Value::Number(7.0)), ("B3", Value::Empty), ("B4", Value::Number(99.0))] { + // A loaded workbook can keep Python code alongside a cached or empty result. + sh.set_cell(CellRef::parse(at).unwrap(), Cell { value, py: Some(Arc::new(PyCode::new("secret_input * 2"))), ..Default::default() }); + } + s.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let doc = s.doc().unwrap(); + let (before, revision, undo) = (doc.wb.clone(), doc.revision, doc.undo.len()); + assert_eq!(filter_values(&doc.wb, 0, 1), vec![("7".into(), true), ("(Blanks)".into(), true)]); + assert_eq!( + filter_selection(&doc.wb, 0, 1, &[("7".into(), false), ("(Blanks)".into(), false)]), + vec![("7".into(), false), ("99".into(), true), ("(Blanks)".into(), false)], + "eligible edits overlay the cached results; a hidden result keeps its checkbox" + ); + let doc = s.doc().unwrap(); + assert!(Arc::ptr_eq(&before, &doc.wb), "neither query mutates or evaluates the workbook"); + assert_eq!((doc.revision, doc.undo.len()), (revision, undo)); + assert_eq!(doc.wb.active().unwrap().cell(CellRef::parse("B3").unwrap()).unwrap().py.as_ref().unwrap().code, "secret_input * 2"); +} + +#[test] +fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name"], ["one"], ["two"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "F1", "values": [["Region"], ["East"], ["West"]]})).unwrap(); + s.execute("insert.table", json!({"range": "F1:F3", "name": "Other", "header": true})).unwrap(); + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:A3"})).unwrap(); + let id = s.execute("insert.slicer", json!({"table": "Other", "column": "Region"})).unwrap()["slicer"].as_u64().unwrap(); + + s.execute("slicer.toggle", json!({"slicer": id, "value": "East"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "A1:A3"); + assert!(!sh.is_row_hidden(1)); + assert!(sh.is_row_hidden(2)); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true)]); + + s.execute("data.reapply", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2)); + s.execute("slicer.clear", json!({"slicer": id})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(1)); + assert!(!sh.is_row_hidden(2)); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true), ("two".into(), true)]); +} + +#[test] +fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { + for (criterion, expected, mid_checked) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false), + (json!({"top": {"count": 2}}), vec!["high", "upper"], false), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true), + (json!({"aboveAverage": true}), vec!["high"], false), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount"], ["low", 10], ["mid", 20], ["upper", 30], ["high", 100], ["blank", null], ["text", "n/a"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:B7"})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + // The current column's own criterion must not narrow its alternatives. + s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}, with the current column filtered"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("20".into(), mid_checked)], + "the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}" + ); + } +} + +#[test] +fn statistical_thresholds_use_the_original_range_not_other_columns_subset() { + for (criterion, names, expected) in [ + (json!({"top": {"count": 2}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 50, "percent": true}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 2, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"aboveAverage": true}), vec!["low", "mid", "upper"], vec![]), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], vec!["low", "mid", "upper"]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount", "Job"], ["low", 10, "low"], ["mid", 20, "mid"], ["upper", 30, "upper"], ["high", 100, "high"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:C5"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": names})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + // A and B both remain active when enumerating C. Subset statistics produce different jobs. + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 2).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + } +} + +#[test] +fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "B3", "values": [ + ["Company", "Job", "Status"], + ["East", "Alpha", "Open"], + ["East", "Beta", "Open"], + ["East", "Closed job", "Closed"], + ["West", "Other company", "Open"], + ["East", null, "Open"], + ["East", "=\"\"", "Open"], + ["East", "Outside range", "Open"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "B3:D9"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "D", "values": ["Open"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "C", "values": ["Alpha"]})).unwrap(); + + let choices = |s: &Session| filter_values(&s.doc().unwrap().wb, 0, 2); + let expected = + |beta: bool, blanks: bool| -> Vec<(String, bool)> { vec![("Alpha".into(), !beta), ("Beta".into(), beta), ("(Blanks)".into(), blanks)] }; + assert_eq!(choices(&s), expected(false, false)); + s.execute("data.filterBy", json!({"column": "C", "values": ["Beta"], "blanks": true})).unwrap(); + assert_eq!(choices(&s), expected(true, true)); + s.execute("data.filterBy", json!({"column": "C", "clear": true})).unwrap(); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); + // Manual visibility is not a filter criterion, even when every eligible row is hidden. + s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap(); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty()); +} + +#[test] +fn a_header_only_table_has_no_data_values_or_blank_choice() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + s.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C3"})).unwrap(); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(sh.tables[0].header_row); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + for col in [1, 2] { + assert!(filter_values(&d.wb, 0, col).is_empty(), "headers are not values or blank data rows"); + } +} + +#[test] +fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Value"], ["empty", null], ["formula", "=\"\""], ["spaces", " "], ["number", 12], ["other", 30] + ]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true)]); + for value in ["12", "12.00"] { + s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]); + } + s.execute("data.filterBy", json!({"column": "B", "values": ["absent"]})).unwrap(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); +} + +#[test] +fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Color"], ["red", 1], ["plain", 2]]})).unwrap(); + s.execute("home.fillColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("home.fontColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B3"})).unwrap(); + for criterion in [FilterCriterion::FillColor(Color::Rgb(0xFF0000)), FilterCriterion::FontColor(Color::Rgb(0xFF0000))] { + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]); + assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]); + } + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })]; + s.execute("data.reapply", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2), "reapply preserves imported icon visibility"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 0), + vec![("plain".into(), true), ("red".into(), true)], + "unsupported icon criteria cannot distinguish manual and current-column hiding" + ); +} + +#[test] +fn duplicate_color_choices_keep_any_eligible_match() { + for font in [false, true] { + for matching_cell in ["B2", "B3"] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Company", "Color"], ["East", "Same"], ["East", "Same"], ["West", "Same"]]}), + ) + .unwrap(); + let command = if font { "home.fontColor" } else { "home.fillColor" }; + s.execute(command, json!({"range": "B4", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) }; + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }), (1, color)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("Same".into(), false)], + "an excluded red row cannot check an eligible choice" + ); + + s.execute(command, json!({"range": matching_cell, "color": "#FF0000"})).unwrap(); + s.execute("data.reapply", json!({})).unwrap(); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + assert_eq!(choices, vec![("Same".into(), true)], "either eligible duplicate can supply the color match"); + let selected = filter_selection(&s.doc().unwrap().wb, 0, 1, &choices); + assert_eq!(selected, vec![("Same".into(), true)]); + let values: Vec<_> = selected.into_iter().filter_map(|(value, on)| on.then_some(value)).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(CellRef::parse(matching_cell).unwrap().row), "unchanged Apply keeps the previously matching row"); + assert!(sh.is_row_hidden(3), "the other column still excludes West"); + } + } +} + +#[test] +fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() { + for table in [false, true] { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + if table { + s.execute("insert.table", json!({"range": "B3:C6", "header": true})).unwrap(); + } + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + let before = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); + assert_eq!(before, gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap()); + let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap(); + let sh = reopened.active().unwrap(); + let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria }; + assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })]); + assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5)); + } +} + +#[test] +fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap(); + s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false })]; + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); +} + +#[test] +fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { + let mut s = Session::new(); + s.new_workbook(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty()); + s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["West", "Before last"], ["East", "Last East"]]})) + .unwrap(); + s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); +} + +#[test] +fn imported_filters_keep_choices_and_statistics_inside_the_grid() { + use gridcraft_engine::core::{MAX_ROWS, RangeRef}; + use gridcraft_engine::model::AutoFilter; + + for criterion in [FilterCriterion::Top10 { bottom: false, percent: false, count: 1 }, FilterCriterion::AboveAverage(true)] { + let mut s = Session::new(); + s.new_workbook(); + let range = RangeRef::new(CellRef::new(MAX_ROWS - 3, 0), CellRef::new(MAX_ROWS + 1, 0)); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + // Model data loaded from a malformed workbook can extend beyond the grid. + for (row, value) in [(MAX_ROWS - 2, 1.0), (MAX_ROWS - 1, 9.0), (MAX_ROWS, 100.0)] { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Number(value), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { range, criteria: vec![(0, criterion)] }); + let doc = s.doc().unwrap(); + let before = doc.wb.clone(); + let expected = vec![("1".into(), false), ("9".into(), true)]; + assert_eq!(filter_values(&doc.wb, 0, 0), expected, "out-of-grid data must not affect the choices or thresholds"); + assert_eq!(filter_selection(&doc.wb, 0, 0, &[]), expected); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().wb), "queries must not trim the stored workbook"); + + s.execute("data.reapply", json!({})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(sh.is_row_hidden(MAX_ROWS - 2)); + assert!(!sh.is_row_hidden(MAX_ROWS - 1), "the valid maximum still matches Top 1 and Above Average"); + assert!(sh.rows.keys().all(|row| *row < MAX_ROWS), "no hidden-row entries may be created beyond the grid"); + assert_eq!(sh.autofilter.as_ref().unwrap().range, range, "the scan bound does not rewrite imported metadata"); + assert_eq!(sh.value(CellRef::new(MAX_ROWS, 0)), Value::Number(100.0)); + } +} + +#[test] +fn merging_hidden_choices_preserves_the_active_criterion() { + for (criterion, checked) in [ + (json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]), + (json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]), + (json!({"top": {"count": 2}}), [false, false, true, true, false]), + (json!({"aboveAverage": true}), [false, false, false, true, false]), + (json!({"aboveAverage": false}), [true, true, true, false, false]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let doc = s.doc().unwrap(); + let choices = filter_values(&doc.wb, 0, 1); + let selection = filter_selection(&doc.wb, 0, 1, &choices); + let expected: Vec<_> = + ["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect(); + assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}"); + let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() { + assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}"); + } + } +} + +#[test] +fn large_values_criteria_preserve_ascii_case_and_blank_matching() { + use gridcraft_engine::core::RangeRef; + use gridcraft_engine::model::AutoFilter; + let mut s = Session::new(); + s.new_workbook(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + let mut selected = Vec::new(); + for row in 1..=5_000 { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() }); + selected.push(format!("ITEM-{row}")); + } + selected.extend(["ITEM-1".into(), "Ä".into()]); + for (row, value, label) in [ + (5_001, Value::Text("Ä".into()), "unicode selected"), + (5_002, Value::Text("ä".into()), "unicode excluded"), + (5_003, Value::Empty, "blank row"), + ] { + sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { + range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)), + criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], + }); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect(); + expected.extend([("blank row".into(), true), ("unicode selected".into(), true)]); + assert_eq!(choices, expected); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c099fa85c1..7dd0bb388d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,6 +1,7 @@ //! The crate's integration tests, one module per file, built as one test binary. mod autofit_filter_buttons; +mod cascading_filter_values; mod cf_formula_validate; mod chart_area_stacked100; mod chart_workbook_names; diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 755df94e96..e8758df131 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -11,7 +11,10 @@ pub enum Orientation { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrintSettings { pub orientation: Orientation, - /// Paper size name (`Letter`, `A4`, `Legal`…). + /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]). Empty means no paper is + /// stated, so the printer's or locale's paper applies: a reader may leave it so for a file + /// that states none (none does yet). Print layout falls back to Letter and XLSX writes no + /// `paperSize`. New sheets default to Letter. pub paper: String, /// Margins in inches: left, right, top, bottom, header, footer. pub margins: [f32; 6], diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 9c3377665b..08adff8fd0 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -9,6 +9,7 @@ pub mod cell; mod cellmap; pub mod features; pub mod macros; +pub mod paper; pub mod password; pub mod preserved; pub mod python; diff --git a/crates/model/src/paper.rs b/crates/model/src/paper.rs new file mode 100644 index 0000000000..2db5c28e84 --- /dev/null +++ b/crates/model/src/paper.rs @@ -0,0 +1,137 @@ +//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats +//! (paper ids or page sizes) and print layout all read this one table. + +/// Paper names and sizes in points, width then height, as the paper is named: Ledger is +/// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was +/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and +/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and +/// envelopes are the JIS ones too. +pub const PAPERS: [(&str, f32, f32); 24] = [ + ("Letter", 612.0, 792.0), + ("Legal", 612.0, 1008.0), + ("A4", 595.28, 841.89), + ("A3", 841.89, 1190.55), + ("A5", 419.53, 595.28), + ("A6", 297.64, 419.53), + ("Tabloid", 792.0, 1224.0), + ("Ledger", 1224.0, 792.0), + ("Executive", 522.0, 756.0), + ("Statement", 396.0, 612.0), + ("B4", 728.50, 1031.81), + ("B5", 515.91, 728.50), + ("B6", 362.83, 515.91), + ("B4 (ISO)", 708.66, 1000.63), + ("B5 (ISO)", 498.90, 708.66), + ("B6 (ISO)", 354.33, 498.90), + ("Envelope #10", 297.0, 684.0), + ("Envelope DL", 311.81, 623.62), + ("Japanese Postcard", 283.46, 419.53), + ("Japanese Double Postcard", 419.53, 566.93), + ("Japanese Envelope #3", 340.16, 666.14), + // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. + ("Japanese Envelope #4", 255.12, 581.10), + ("Japanese Envelope Kaku #2", 680.31, 941.10), + ("Japanese Envelope Kaku #3", 612.28, 785.20), +]; + +/// Other spellings of the names above, in [`key`] form. +const ALIASES: [(&str, &str); 13] = [ + // The B5 envelope is ISO B5 itself (176×250 mm): one size, one name. + ("envelopeb5", "B5 (ISO)"), + ("usletter", "Letter"), + ("uslegal", "Legal"), + ("11x17", "Tabloid"), + ("b4jis", "B4"), + ("b5jis", "B5"), + ("b6jis", "B6"), + ("postcard", "Japanese Postcard"), + ("doublepostcard", "Japanese Double Postcard"), + ("chou#3", "Japanese Envelope #3"), + ("chou#4", "Japanese Envelope #4"), + ("kaku#2", "Japanese Envelope Kaku #2"), + ("kaku#3", "Japanese Envelope Kaku #3"), +]; + +/// A name as compared: spaces, hyphens, underscores and parentheses don't matter, nor does case +/// (`B5 (JIS)`, `b5-jis` and `b5jis` are one name). +fn key(name: &str) -> String { + name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "") +} + +/// The paper `name` stands for, under its table name. +pub fn canonical(name: &str) -> Option<&'static str> { + // No paper name is long; a huge one (from a file or a command) is not worth folding. + if name.len() > 64 { + return None; + } + let k = key(name); + PAPERS.iter().map(|(n, _, _)| *n).find(|n| key(n) == k).or_else(|| ALIASES.iter().find(|(a, _)| *a == k).map(|(_, n)| *n)) +} + +/// The size of paper `name` in points (width, height). +pub fn size_pt(name: &str) -> Option<(f32, f32)> { + let n = canonical(name)?; + PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h)) +} + +/// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it +/// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese +/// Envelope Kaku #3), so the nearest wins, not the first in the table. +/// +/// The name is the paper as the page stands: a 17×11 in page is `Ledger`. A caller that also +/// records a landscape orientation should pass the size upright (narrow side first), since +/// print layout turns the named paper once more for landscape. +pub fn for_size(width: f32, height: f32) -> Option<&'static str> { + const TOLERANCE: f32 = 5.67; // 2 mm + let nearest = |w: f32, h: f32| { + PAPERS + .iter() + .filter_map(|(n, pw, ph)| { + let (dw, dh) = ((pw - w).abs(), (ph - h).abs()); + (dw < TOLERANCE && dh < TOLERANCE).then_some((dw + dh, *n)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, n)| n) + }; + nearest(width, height).or_else(|| nearest(height, width)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_sizes() { + assert_eq!(size_pt("b5-jis"), Some((515.91, 728.50))); + assert_eq!(size_pt("US Letter"), Some((612.0, 792.0))); + assert_eq!(size_pt("nonsense"), None); + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(792.0, 1224.0), Some("Tabloid")); + assert_eq!(for_size(842.0, 595.0), Some("A4")); + assert_eq!(canonical("ledger"), Some("Ledger")); + assert_eq!(canonical(""), None); + assert_eq!(canonical(&"A4".repeat(1000)), None); + } + + #[test] + fn every_size_reads_back_as_its_name() { + for (name, w, h) in PAPERS { + assert_eq!(for_size(w, h), Some(name), "{name}"); + } + assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)")); + } + + /// Letter (612×792) and Japanese Envelope Kaku #3 (612.28×785.2) are within 2 mm of some + /// of the same sizes: the nearer paper wins, whichever comes first in the table. + #[test] + fn for_size_picks_the_nearest_paper() { + assert_eq!(for_size(612.2, 788.0), Some("Japanese Envelope Kaku #3")); + assert_eq!(for_size(612.0, 790.0), Some("Letter")); + assert_eq!(for_size(788.0, 612.2), Some("Japanese Envelope Kaku #3")); + // A wide page that is a paper as it stands is not read as another paper turned. + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(1000.0, 10.0), None); + assert_eq!(for_size(f32::NAN, 792.0), None); + assert_eq!(for_size(f32::INFINITY, f32::INFINITY), None); + } +} diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index da7dd57ece..9c083bccfc 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -345,7 +345,10 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face let mut bound: Vec = Vec::new(); for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] { let Some(primary) = pick_face(faces, bold, italic) else { continue }; + let role = role_key(family, bold, italic); let mut chain: Vec = Vec::new(); + // The face the role's text is actually drawn in: the first one whose file could be read. + let mut drawn: Option<&Face> = None; for face in [Some(primary), pick_face(faces, false, false)] { let Some(face) = face else { continue }; let key = face_key(face); @@ -359,12 +362,15 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face fonts.font_data.insert(key.clone(), std::sync::Arc::new(fd)); } chain.push(key); + drawn.get_or_insert(face); } - if chain.is_empty() { - continue; - } + let Some(drawn) = drawn else { continue }; + // Imitate what the drawn face lacks: italic when it is upright; bold when it is the family's + // plain face (the family has no bold of its own, or the bold file couldn't be read). + let own_bold = pick_face(faces, false, italic).is_none_or(|plain| face_key(plain) != face_key(primary)); + set_synthetic(&role, SLANT, italic && !drawn.italic); + set_synthetic(&role, BOLD, bold && (face_key(drawn) != face_key(primary) || !own_bold)); chain.extend(base.iter().cloned()); - let role = role_key(family, bold, italic); fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain); bound.push(role); } @@ -389,6 +395,41 @@ pub fn is_bound(role: &str) -> bool { bound().read().unwrap_or_else(std::sync::PoisonError::into_inner).contains(role) } +/// Roles drawn with a face that lacks their slant or weight (Arial Black has one face only), as +/// `{role}|slant` and `{role}|bold`. Excel imitates the missing style (observed in its PDF: a cell in +/// Arial Black, bold italic, is slanted by 1/3 and outlined about 1/36 of its size thick). +static SYNTHETIC: OnceLock>> = OnceLock::new(); +const SLANT: &str = "slant"; +const BOLD: &str = "bold"; + +fn synthetic() -> &'static std::sync::RwLock> { + SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new())) +} + +fn set_synthetic(role: &str, style: &str, on: bool) { + let mut set = synthetic().write().unwrap_or_else(|e| e.into_inner()); + let key = format!("{role}|{style}"); + if on { + set.insert(key); + } else { + set.remove(&key); + } +} + +fn is_synthetic(role: &str, style: &str) -> bool { + is_bound(role) && synthetic().read().unwrap_or_else(|e| e.into_inner()).contains(&format!("{role}|{style}")) +} + +/// Does italic text in this installed family have to be slanted when drawn (no italic face)? +pub fn is_slanted(family: &str, bold: bool) -> bool { + is_synthetic(&role_key(family, bold, true), SLANT) +} + +/// Does bold text in this installed family have to be thickened when drawn (no face of its own)? +pub fn is_emboldened(family: &str, italic: bool) -> bool { + is_synthetic(&role_key(family, true, italic), BOLD) +} + /// Serializes tests that mutate the process-wide bound-family registry. #[cfg(test)] pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -490,6 +531,44 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn styles_a_family_has_no_face_for_are_imitated() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("gridcraft-fonts-synthetic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + // One font file stands in for every face; each face is its own (path, index) by its name. + let face = |family: &str, file: &str, weight: f32, italic: bool| { + let path = dir.join(file); + std::fs::write(&path, epaint_default_fonts::UBUNTU_LIGHT).expect("write"); + Face { family: family.into(), names: vec![family.into()], path, index: 0, weight, italic } + }; + let mut fonts = egui::FontDefinitions::default(); + // Like Arial Black: one face, whatever its weight. + let mut bound = bind_faces(&mut fonts, "One Face", &[face("One Face", "one.ttf", 900.0, false)]); + let full = [ + face("Full", "full.ttf", 400.0, false), + face("Full", "full-b.ttf", 700.0, false), + face("Full", "full-i.ttf", 400.0, true), + face("Full", "full-bi.ttf", 700.0, true), + ]; + bound.extend(bind_faces(&mut fonts, "Full", &full)); + // Bold and italic faces whose files can't be read: the regular face draws them, imitated. + let gone = |file: &str, weight: f32, italic: bool| Face { path: dir.join(file), ..face("Gone", "gone.ttf", weight, italic) }; + let broken = [face("Gone", "gone.ttf", 400.0, false), gone("missing-b.ttf", 700.0, false), gone("missing-i.ttf", 400.0, true)]; + bound.extend(bind_faces(&mut fonts, "Gone", &broken)); + set_bound(bound); + assert!(is_slanted("One Face", false) && is_slanted("One Face", true)); + assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true)); + assert!(is_slanted("Gone", false) && is_emboldened("Gone", false), "the regular face stands in, imitated"); + assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are"); + assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are"); + assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false)); + set_bound([]); + assert!(!is_slanted("One Face", false) && !is_emboldened("One Face", false), "nothing is imitated once unbound"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A font that is just a table directory and a `name` table holding `records` as /// `(Windows language id, name id, text)`: all [`file_faces`] reads. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index ac10c049e1..26bd8cf92e 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -327,6 +327,10 @@ pub struct GridState { pub cells_rect: Option, /// Column and row of the clicked header cell, and where to open the menu. pub filter_menu: Option<(u32, u32, Pos2)>, + /// Pending popup edits travel with this window and are dropped when its menu or window closes. + pub filter_checks: Option>, + pub filter_search: String, + pub filter_buttons: Vec, pub context_menu: Option, /// The frame a right-click opened `context_menu` in: that click's own press doesn't close it. pub context_menu_frame: u64, diff --git a/crates/ui-egui/src/grid/cell_paint.rs b/crates/ui-egui/src/grid/cell_paint.rs index 73a3a1405d..2fc283df9a 100644 --- a/crates/ui-egui/src/grid/cell_paint.rs +++ b/crates/ui-egui/src/grid/cell_paint.rs @@ -230,6 +230,25 @@ pub(super) fn merged_edges(wb: &Workbook, si: usize, sh: &Sheet, geo: &Geo, area out } +/// One cell's text as a layout job, wrapped at `wrap` (`f32::INFINITY`: one line). `slant` draws it +/// oblique, for an italic cell whose font has no italic face (see [`crate::fonts::is_slanted`]). +pub(super) fn cell_job(text: String, font: FontId, color: Color32, wrap: f32, slant: bool) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::simple(text, font, color, wrap); + for section in &mut job.sections { + section.format.italics = slant; + } + job +} + +/// Paints one cell's text; `bold_dx` > 0 paints it again that far right, to thicken a bold cell +/// whose font has no bold face (see [`crate::fonts::is_emboldened`]). +pub(super) fn paint_cell_galley(p: &Painter, pos: Pos2, galley: std::sync::Arc, color: Color32, bold_dx: f32) { + if bold_dx > 0.0 { + p.galley(pos + egui::vec2(bold_dx, 0.0), galley.clone(), color); + } + p.galley(pos, galley, color); +} + /// The smaller font that makes `text` fit in `room` points of width (Shrink to fit), or `None` /// when it already fits at its own size. pub(super) fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option { diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index b6546dacfa..c81a39ff6b 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -31,14 +31,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ } } let wb = app.session.active().map(|d| d.wb.clone()).unwrap_or(wb); - let values = gridcraft_engine::cmd::data::filter_values(&wb, si, col); - let key = egui::Id::unique(("filter_sel", col)); - let search_key = egui::Id::unique(("filter_search", col)); - let buttons_key = egui::Id::unique(("filter_buttons", col)); // Enter is the menu's OK, as in Excel: taken before the search box (which would only drop its // focus) and the value checkboxes (which would toggle) see it. A focused button keeps it as its click. - let buttons: Vec = ui.ctx().data_mut(|d| d.get_temp(buttons_key)).unwrap_or_default(); - let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| buttons.contains(&f)); + let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| app.grid.filter_buttons.contains(&f)); let enter = !on_button && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); let mut close = false; let area = egui::Area::new(egui::Id::unique("filter_menu")).fixed_pos(at + vec2(-180.0, 10.0)).order(egui::Order::Foreground); @@ -57,9 +52,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ } ui.separator(); ui.label(egui::RichText::new("Filter").strong()); - let mut checks: Vec<(String, bool)> = ui.ctx().data_mut(|d| d.get_temp::>(key)).unwrap_or(values.clone()); + let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col)); // A search narrows the list; Select All and Apply then only cover the matches. - let mut search: String = ui.ctx().data_mut(|d| d.get_temp(search_key)).unwrap_or_default(); + let mut search = app.grid.filter_search.clone(); let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY)); if !was_open { field.request_focus(); @@ -81,10 +76,8 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ ui.checkbox(on, v.as_str()); } }); - ui.ctx().data_mut(|d| { - d.insert_temp(key, checks.clone()); - d.insert_temp(search_key, search.clone()); - }); + app.grid.filter_checks = Some(checks.clone()); + app.grid.filter_search.clone_from(&search); let checks: Vec<(String, bool)> = checks.iter().map(|(v, on)| (v.clone(), *on && matches(v))).collect(); ui.separator(); ui.horizontal(|ui| { @@ -96,8 +89,12 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ // Nothing checked would hide every row, so Enter (unlike a click on Apply) does nothing then. let any = checks.iter().any(|(_, on)| *on); let apply = ui.button("Apply"); - ui.ctx().data_mut(|d| d.insert_temp(buttons_key, vec![ascending.id, descending.id, clear.id, apply.id])); + app.grid.filter_buttons = vec![ascending.id, descending.id, clear.id, apply.id]; if apply.clicked() || (enter && any) { + let mut checks = gridcraft_engine::cmd::data::filter_selection(&wb, si, col, &checks); + for (value, on) in &mut checks { + *on &= matches(value); + } let blanks = checks.iter().any(|(v, on)| v == "(Blanks)" && *on); let vals: Vec = checks.iter().filter(|(v, on)| *on && v != "(Blanks)").map(|(v, _)| v.clone()).collect(); let p = if checks.iter().all(|(_, b)| *b) { @@ -112,11 +109,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ }); }); if close || popup_dismissed(&response.response, was_open) { - ui.ctx().data_mut(|d| { - d.remove::>(key); - d.remove::(search_key); - d.remove::>(buttons_key); - }); + app.grid.filter_checks = None; + app.grid.filter_search.clear(); + app.grid.filter_buttons.clear(); app.grid.filter_menu = None; } } diff --git a/crates/ui-egui/src/grid/quadrant.rs b/crates/ui-egui/src/grid/quadrant.rs index dedead69e8..a222222654 100644 --- a/crates/ui-egui/src/grid/quadrant.rs +++ b/crates/ui-egui/src/grid/quadrant.rs @@ -1,7 +1,7 @@ use super::active_row::paint_active_row; use super::cell_paint::{ - Look, MergedArea, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, paint_cf_icon, - painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y, + Look, MergedArea, cell_job, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, + paint_cell_galley, paint_cf_icon, painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y, }; use super::geo::Geo; use super::tables::{filter_button_rect, paint_filter_button}; @@ -352,6 +352,11 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option 0 first paints it that far along the text's own +/// direction, the second impression of imitated bold. +fn paint_rotated_galley(cp: &Painter, pos: Pos2, galley: std::sync::Arc, color: Color32, angle: f32, bold_dx: f32) { + if bold_dx > 0.0 { + let mut thick = egui::epaint::TextShape::new(pos + bold_dx * egui::vec2(angle.cos(), angle.sin()), galley.clone(), color); + thick.angle = angle; + cp.add(thick); + } + let mut shape = egui::epaint::TextShape::new(pos, galley, color); + shape.angle = angle; + cp.add(shape); +} + struct TextDecoration { x: f32, y: f32, diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 8fe69acaa5..562e1d92ac 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -360,6 +360,7 @@ impl Geo> ActiveCellVisibility<'_, F> { } fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) { + let window = app.session.active_window(); let previous_popups = (app.grid.filter_menu, app.grid.list_picker, app.grid.header_menu, app.grid.fill_menu); // A pan the grid never saw end (it was hidden mid-drag) must not swallow the next press. if app.grid.touch_pan && !resp.dragged() && !resp.drag_stopped() { @@ -374,6 +375,15 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re crate::paper_view::interact(app, ui, resp, geo, sh, wb); interact(app, ui, resp, geo, sh, wb); } + // A form button can switch windows and swap GridState; the old popup and geometry belong to the outgoing window. + if app.session.active_window() != window { + return; + } + if previous_popups.0 != app.grid.filter_menu && previous_popups.0.is_some() { + app.grid.filter_checks = None; + app.grid.filter_search.clear(); + app.grid.filter_buttons.clear(); + } update_cursor(app, ui, resp, geo, sh); crate::text_box::show(app, ui, geo, sh); if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) { diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs new file mode 100644 index 0000000000..da6cc24d35 --- /dev/null +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -0,0 +1,346 @@ +use crate::common; + +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::kittest::{NodeT, Queryable}; +use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_engine::model::{ObjKind, ObjRef}; +use gridcraft_ui_egui::grid; +use serde_json::json; + +fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }); + } + h.run_steps(3); +} + +fn click_filter(h: &mut common::Harness, cell: &str) { + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = grid::filter_button_rect(&geo, sh, CellRef::parse(cell).unwrap()).center(); + h.input_mut().events.push(Event::PointerMoved(at)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.run_steps(3); +} + +#[test] +fn a_header_only_tables_popup_has_no_value_choices() { + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + session.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + session.execute("selection.set", json!({"cell": "B3"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + click_filter(&mut h, "B3"); + assert_eq!(h.state().grid.filter_menu.map(|(col, row, _)| (col, row)), Some((1, 2))); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + assert_eq!(h.state().grid.filter_checks, Some(vec![])); + assert!(h.query_by_label("(Blanks)").is_none()); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().grid.filter_menu.is_none()); +} + +#[test] +fn switching_filter_columns_discards_old_edits_and_recomputes_eligible_choices() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"] + ]}), + ) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Other").click(); + h.run_steps(2); + assert!(h.state().grid.filter_search.is_empty()); + + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + assert!(h.state().grid.filter_search.is_empty(), "the new column starts without the old search"); + assert!(h.query_by_label("East").is_some(), "the new column's choices must remain available"); + click_filter(&mut h, "B1"); + assert_eq!(h.get_by_label("Other").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "old checkbox edits are discarded"); + click_filter(&mut h, "A1"); + h.get_by_label("West").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + click_filter(&mut h, "B1"); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "eligible alternatives must remain available"); + assert!(h.query_by_label("Other").is_none(), "the other column's new criterion must narrow the reopened list"); +} + +#[test] +fn switching_filter_columns_keeps_another_windows_pending_choices() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"] + ]}), + ) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let image = std::env::var("GRIDCRAFT_FILTER_WINDOW_SNAPSHOT").ok(); + let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)); + let builder = if image.is_some() { builder.wgpu() } else { builder }; + let mut h = common::harness_with(builder, common::app(session), 4); + let first = h.state().session.active_window().unwrap(); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active_window().unwrap(); + assert_ne!(first, second); + assert_eq!(h.state().session.documents().len(), 1, "two windows on the same workbook"); + click_filter(&mut h, "B1"); + h.input_mut().events.push(Event::Text("Bet".into())); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + assert!(h.query_by_label("Alpha").is_none()); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = &image { + h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap(); + } + + h.state_mut().enter_window(first); + h.run_steps(2); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + h.state_mut().enter_window(second); + h.run_steps(3); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + assert!(h.query_by_label("Alpha").is_none(), "switching the other window's column must keep this search"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False), "its unsaved checkbox stays unchecked"); + if let Some(path) = image { + h.render().unwrap().save(path).unwrap(); + } + assert!(h.state().session.active().unwrap().wb.active().unwrap().autofilter.as_ref().unwrap().criteria.is_empty(), "no filter was applied"); +} + +#[test] +fn a_form_button_window_switch_keeps_the_incoming_filter_edits() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute("range.setValues", json!({"range": "A1", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let button = session.execute("insert.button", json!({"at": "E12", "text": "Other window"})).unwrap()["control"].as_u64().unwrap() as u32; + let image = std::env::var("GRIDCRAFT_FILTER_BUTTON_WINDOW_SNAPSHOT").ok(); + let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)); + let builder = if image.is_some() { builder.wgpu() } else { builder }; + let mut h = common::harness_with(builder, common::app(session), 4); + let first = h.state().session.active_window().unwrap(); + click_filter(&mut h, "A1"); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active_window().unwrap(); + h.state_mut().run("control.assign", json!({"id": button, "command": "view.switchWindows", "params": {"window": second}})).unwrap(); + click_filter(&mut h, "B1"); + h.input_mut().events.push(Event::Text("Bet".into())); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + let checks = h.state().grid.filter_checks.clone(); + assert_eq!(h.state().grid.filter_search, "Bet"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = &image { + h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap(); + } + + h.state_mut().enter_window(first); + h.run_steps(2); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = gridcraft_ui_egui::chartview::object_rect(&geo, sh, ObjRef::new(ObjKind::Control, button)).unwrap().center(); + for pressed in [true, false] { + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.input_mut().events.push(Event::PointerMoved(at)); + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + assert_eq!(h.state().session.active_window(), Some(second), "the real button action switches windows during grid interaction"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + assert_eq!(h.state().grid.filter_search, "Bet", "the outgoing popup must not clear the incoming search"); + assert_eq!(h.state().grid.filter_checks, checks, "the incoming window keeps its unsaved checkbox edits"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = image { + h.render().unwrap().save(path).unwrap(); + } +} + +#[test] +fn applying_eligible_choices_preserves_values_and_blanks_hidden_by_another_filter() { + for table in [false, true] { + for click in [false, true] { + for edit in [false, true] { + for (values, blanks, other_hidden, blank_hidden) in + [(vec!["Alpha", "Other"], false, false, true), (vec!["Alpha", "Beta"], false, true, true), (vec!["Alpha"], true, true, false)] + { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["West", null] + ]}), + ) + .unwrap(); + if table { + session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap(); + } else { + session.execute("data.filter", json!({"range": "A1:B5"})).unwrap(); + } + session.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": blanks})).unwrap(); + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Other").is_none()); + assert!(h.query_by_label("(Blanks)").is_none()); + if edit { + h.get_by_label("Beta").click(); + h.run_steps(2); + } + if click { + h.get_by_label("Apply").click(); + h.run_steps(3); + } else { + key(&mut h, Key::Enter, Modifiers::NONE); + } + assert!(h.state().grid.filter_menu.is_none()); + h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + let beta_hidden = values.contains(&"Beta") == edit; + assert_eq!( + (1..=4).map(|row| sh.is_row_hidden(row)).collect::>(), + [false, beta_hidden, other_hidden, blank_hidden], + "table={table}, click={click}, edit={edit}, values={values:?}" + ); + } + } + } + } +} + +#[test] +fn search_apply_excludes_hidden_nonmatches_and_keeps_hidden_matches() { + for click in [false, true] { + for beta in [false, true] { + let mut session = Session::new(); + session.new_workbook(); + let mut values = vec![json!(["Company", "Job"]), json!(["East", "Alpha"])]; + if beta { + values.push(json!(["East", "Beta"])); + } + values.extend([json!(["West", "Alphonse"]), json!(["West", "Other"]), json!(["West", null])]); + let last = values.len() - 1; + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("data.filter", json!({"range": format!("A1:B{}", last + 1)})).unwrap(); + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Other").is_none()); + assert!(h.query_by_label("Alphonse").is_none()); + h.input_mut().events.push(Event::Text("Alph".into())); + h.run_steps(2); + assert_eq!(h.state().grid.filter_search, "Alph"); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_none()); + if click { + h.get_by_label("Apply").click(); + h.run_steps(3); + } else { + key(&mut h, Key::Enter, Modifiers::NONE); + } + assert!(h.state().grid.filter_menu.is_none()); + h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(1), "Alpha must remain selected"); + assert!(!sh.is_row_hidden((last - 2) as u32), "hidden Alphonse must still match the search"); + assert!(sh.is_row_hidden((last - 1) as u32), "hidden Other must be excluded: click={click}, beta={beta}"); + assert!(sh.is_row_hidden(last as u32), "hidden blanks do not match the search"); + if beta { + assert!(sh.is_row_hidden(2), "eligible Beta does not match the search"); + } + } + } +} + +#[test] +fn dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() { + for table in [false, true] { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["East", null] + ]}), + ) + .unwrap(); + if table { + session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap(); + } + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("data.filterBy", json!({"column": "B", "values": ["Alpha"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let screenshot = std::env::var("GRIDCRAFT_CASCADING_SNAPSHOT").ok().filter(|_| !table); + let mut h = if screenshot.is_some() { + common::harness_with( + common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)).wgpu(), + common::app(session), + 4, + ) + } else { + common::os_harness(session, egui::os::OperatingSystem::Windows) + }; + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "current-column filtering must not remove alternatives"); + assert!(h.query_by_label("(Blanks)").is_some()); + assert!(h.query_by_label("Other").is_none(), "the other company's job must not be listed"); + if let Some(path) = screenshot { + h.render().unwrap().save(path).unwrap(); + } + h.get_by_label("Alpha").click(); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + let hidden = |h: &common::Harness| { + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + (1..=4).map(|row| sh.is_row_hidden(row)).collect::>() + }; + assert_eq!(hidden(&h), [true, false, true, true]); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Clear Filter").click(); + h.run_steps(3); + assert_eq!(hidden(&h), [false, false, true, false], "clearing Job keeps Company filtered"); + } +} diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index 7c508ce6bf..87b8ab7108 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -375,7 +375,7 @@ fn alt_down_opens_autofilter_headers_without_changing_the_workbook() { // Opening focuses the existing search box; typing must not edit the header. h.input_mut().events.push(Event::Text("1".into())); h.run_steps(2); - assert_eq!(h.ctx.data(|data| data.get_temp::(egui::Id::unique(("filter_search", column)))).as_deref(), Some("1")); + assert_eq!(h.state().grid.filter_search, "1"); assert!(h.state().editor.is_none()); assert_eq!(h.state().session.active().unwrap().wb, before); key(&mut h, Key::Escape, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d014cbfdb7..b3d966b14b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -13,6 +13,7 @@ mod argument_names; mod autosave_persist; mod autosum_edit; mod borders; +mod cascading_filter_values; mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index cf89dbcf12..a1d4eb82d6 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -57,7 +57,8 @@ pub use gridcraft_core::color::INDEXED; /// Paper sizes (`pageSetup paperSize`) we name. ID 12/13 are the JIS B4/B5 that /// `pageLayout.pageSetup` calls `B4`/`B5`; 42 is ISO B4, and 43–88 are the Japanese postcards, -/// envelopes and B6. The engine's `known_paper` uses the same names and sizes. +/// envelopes and B6. Their sizes are in `gridcraft_model::paper`, under the same names. 34 is +/// ECMA-376's "B5 envelope (176 mm by 250 mm)": the ISO B5 size, so it reads as `B5 (ISO)`. const PAPERS: [(u32, &str); 23] = [ (1, "Letter"), (3, "Tabloid"), @@ -72,7 +73,7 @@ const PAPERS: [(u32, &str); 23] = [ (13, "B5"), (20, "Envelope #10"), (27, "Envelope DL"), - (34, "Envelope B5"), + (34, "B5 (ISO)"), (42, "B4 (ISO)"), (43, "Japanese Postcard"), (69, "Japanese Double Postcard"), @@ -88,25 +89,10 @@ pub fn paper_name(id: u32) -> Option<&'static str> { PAPERS.iter().find(|(i, _)| *i == id).map(|(_, n)| *n) } -/// The file ID for a paper name. Spelling is loose like `known_paper`'s — spaces, hyphens, -/// underscores and parentheses don't matter, and the JIS/ISO and Japanese-envelope spellings the -/// page-setup commands take are folded onto the name in [`PAPERS`]. +/// The file ID for a paper name, spelled any way [`gridcraft_model::paper::canonical`] takes. pub fn paper_id(name: &str) -> Option { - let norm = |s: &str| s.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - let normalized = norm(name); - let alias = match normalized.as_str() { - "b4jis" => "b4", - "b5jis" => "b5", - "b6jis" => "b6", - "postcard" => "japanesepostcard", - "doublepostcard" => "japanesedoublepostcard", - "chou#3" => "japaneseenvelope#3", - "chou#4" => "japaneseenvelope#4", - "kaku#2" => "japaneseenvelopekaku#2", - "kaku#3" => "japaneseenvelopekaku#3", - other => other, - }; - PAPERS.iter().find(|(_, n)| norm(n) == alias).map(|(i, _)| *i) + let name = gridcraft_model::paper::canonical(name)?; + PAPERS.iter().find(|(_, n)| *n == name).map(|(i, _)| *i) } /// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with @@ -336,6 +322,20 @@ pub const EMU_PER_PX: f64 = 9525.0; mod tests { use super::*; + /// Every paper in the shared table saves with an XLSX id, so it reopens as itself. ECMA-376 + /// has no upright ISO B6 id (35 is the B6 envelope stated wide), so `B6 (ISO)` alone has none. + #[test] + fn every_shared_paper_has_an_xlsx_id() { + for (name, _, _) in gridcraft_model::paper::PAPERS { + let id = paper_id(name); + if name == "B6 (ISO)" { + assert_eq!(id, None); + } else { + assert_eq!(id.and_then(paper_name), Some(name), "{name}"); + } + } + } + #[test] fn widths() { assert_eq!(col_width_to_px(9.140625), 64.0); diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index ca6b7093e1..dcac0267b1 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1922,6 +1922,25 @@ fn japanese_paper_sizes_round_trip() { assert_eq!(back.sheet(0).unwrap().print.paper, "B5"); } +/// The paper names every spelling folds onto keep their file id: `11x17` is Tabloid (3), and +/// ISO B5 is id 34 (ECMA-376's 176×250 mm "B5 envelope"), read back as `B5 (ISO)`. An empty +/// paper (none stated) writes no `paperSize`, so the reader's own paper applies. +#[test] +fn paper_names_keep_their_xlsx_id_and_an_unstated_paper_writes_none() { + for (paper, id, back_as) in [("11x17", 3, "Tabloid"), ("US Legal", 5, "Legal"), ("B5 (ISO)", 34, "B5 (ISO)"), ("Envelope B5", 34, "B5 (ISO)")] { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = paper.into(); + let bytes = write_xlsx(&wb).unwrap(); + assert!(sheet1_xml(&bytes).0.contains(&format!("paperSize=\"{id}\"")), "{paper}"); + let (back, _) = read_xlsx(&bytes).unwrap(); + assert_eq!(back.sheet(0).unwrap().print.paper, back_as); + } + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = String::new(); + let (xml, _) = sheet1_xml(&write_xlsx(&wb).unwrap()); + assert!(!xml.contains("paperSize"), "{xml}"); +} + /// A table's dropdown filter lives in `sheet.autofilter` (the engine's only live filter state), /// not in `Table::filter`. Writing used to suppress the sheet `` because a table /// intersects it and write the table part from `Table::filter`, which was empty: the criteria diff --git a/docs/architecture.md b/docs/architecture.md index 051f15f21f..4fc0e31397 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md). @@ -17,7 +17,7 @@ including tests, 2026-10-10. | L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits | | L1 | `functions` | ~13.4k | The function library: `FnSpec` registry (name, arity, category, scalar args, signature, description) and pure implementations; automatic array lifting | | L1 | `math` | ~1.1k | Equations: LaTeX laid out by RaTeX (MIT, pinned) into plain glyph, rule and path data, and LaTeX to Office Math; every entry point capped and panic-guarded | -| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings, protection | +| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings (paper names and sizes in `paper`, the one table file formats and print layout read), protection | | L2 | `calc` | ~2.9k | Evaluator (references, names, tables, LET/LAMBDA, special forms like OFFSET/INDIRECT/SUBTOTAL) and dependency-graph recalculation with dynamic arrays, spills and cycle detection; single-threaded | | L2 | `xlsx` | ~10.7k | XLSX read/write (transitional and strict read), CSV/TSV, XLSB and ODS data import, PivotTable caches, DrawingML charts and drawings; byte slices only (WASM-safe); lenient reader that reports warnings | | L2 | `pdf` | ~1k | Small PDF 1.7 writer (14 standard fonts, vectors, images) for print and export | @@ -272,6 +272,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means no paper is stated (no reader sets it yet); `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | | 2026-11-13 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 253fe1d739..d96dc665b6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -161,9 +161,11 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-23 | minor | Clarify that imported XLSX paper id 34 changes printed output from the old Letter fallback to ISO B5 (176×250 mm); add import-to-preview/PDF regression coverage | | 2026-11-14 | minor | A sheet or workbook protection password set in GridCraft is kept both as Excel's salted SHA-512 hash and as a SHA-256 digest (the form OpenDocument stores); XLSX writes the SHA-512 form, and a digest-only password keeps its protection without the password; one shared base64 implementation. GridCraft JSON (`.json`) workbooks keep such a password in the shape earlier GridCraft versions read (the SHA-512 hash, with the digest in an extra `odf` field they ignore), so they still open there | | 2026-11-14 | minor | Style model: `Alignment::padding` (left, right, top, bottom, hundredths of a point; none where a file states none) keeps an OpenDocument cell's padding; styles differing only by padding stay apart. XLSX and XLS read none and the XLSX writer leaves it out; GridCraft does not draw it yet | | 2026-11-14 | minor | XLSX fonts' outlined (hollow) letters, ``, are read and written back after `` as Excel writes them, in cell fonts and differential formats (a differential format that turns it off, ``, keeps that too); they were dropped before. Two fonts differing only in it are different styles. Set by `home.formatCells {style: {font: {outline: true}}}`; GridCraft does not draw outlined text yet (it shows solid) | +| 2026-11-13 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize`; Page Setup and Size now take Statement, Envelope #10 and Envelope DL (Page Setup refused them before) and print them on their own size | | 2026-11-13 | minor | PDF of a right-to-left sheet keeps explicit Left and Right alignment on the side the grid shows them | | 2026-11-12 | minor | `.xls` files open with their data validation (drop-down lists, input messages, error alerts and the rules), read by craft-xls and mapped as the `.xlsx` reader maps the same rules. A rule Excel would refuse, or one past 65,536 in a workbook, is skipped with a warning (#3634, from #3636) | | 2026-11-12 | minor | .xls import reads the file with craft-xls (storytold/craft-libs), the reader that moved there from this repository; GridCraft keeps the mapping onto its model. The workbook now opens on the sheet it was saved on (WINDOW1 `itabCur`), falling back to the first visible sheet as before (from #3551), and cells saved as RString records (text with formatting runs) are read as text instead of skipped | diff --git a/docs/gaps.md b/docs/gaps.md index c1bbc46885..27a7d7b6c2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,6 +2,7 @@ > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (§5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365) + Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open PRs first (50 open on 2026-10-10; several already address entries here), and update the entry @@ -22,6 +23,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- - **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTable round-trip noted as "unverified in real Excel" since 10-07; #64 (dynamic-array flag) shows the class of bug. +- **Check:** `packaging/windows/excel-open-check/check.ps1` saves workbooks with `gridcraft-cli` and opens each result in real Excel through COM with `CorruptLoad` = normal load, so a repair is a failure. The 0.12.1 run (18 public synthetic fixtures + 7 feature scenarios: charts, pivots with pivot chart and slicer, CF, validation, tables and names, shapes and pictures, sheets and protection) gave 24 of 25 saved files opening cleanly; the 25th (`gc_legacy_to_array`) is not a repair but Excel taking over 200 s on legacy formulas saved as whole-column array formulas (#410, open PRs #417, #1367, #1660). Still open: a run over a large real-world corpus. - **Impact:** the main format; a repair prompt or silent loss destroys trust. - **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md) @@ -203,6 +205,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | 2026-11-01 | minor | §4: chart data tables implemented for column, bar, line, area and compatible combo charts, with legend keys and border settings, live source values, XLSX round-trip and print/PDF; other chart gaps remain. | | 2026-10-31 | minor | §13: Solver Options (Max Evaluations, Integer Optimality and the Evolutionary options), saved with the model | | 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog | +| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly | | 2026-10-26 | minor | §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry. Other script and UI gaps remain. | | 2026-10-26 | minor | Arabic shared bidi display/editing and persisted cell reading direction; other script and PDF work remain separate | | 2026-10-26 | minor | §5: Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 33f7122bf7..a05bbaea3b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -65,6 +65,7 @@ this logic, with one undo step. | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Searchable data validation dropdown (typing filters the in-cell list) | done (10-21): entries with a word starting with the typed text, ignoring case and the accents of Latin letters (é, ç, ß, ł, ș, ǎ, Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), in list order; Up/Down highlight, Enter/Tab/Ctrl+Enter/click commit the highlighted entry as the list spells it (other commits, such as clicking another cell, keep the typed text), Escape hides the list then cancels; `data.validationList {cell, search?}` gives agents the same search. The search reads at most 200,000 cells of the list's source and keeps at most 10,000 matches; past either, `truncated` is set and the popup says more entries aren't shown (validation itself still checks the whole list). Fuzzy matching isn't offered (Excel doesn't either); behaviour follows the documented Excel 365 feature, not yet measured against the app | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | +| AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Without a search, Apply preserves selected and excluded values and blanks absent from the narrowed list. With a search, Apply excludes nonmatches throughout the column, including values hidden by another filter. Clear Filter clears the whole column. Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. | | Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog | | Reorder selected whole columns by dragging their headers | done (10-11) | @@ -79,6 +80,30 @@ this logic, with one undo step. | Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar in the tab bar (60/40 split, drag, track click pages) 10-13 (#176, #840); dragging the handle at the scrollbar's left edge gives the tabs more or less of the bar; each workbook keeps its share while it is open (not saved in the file) | | Text overflow into empty neighbours, wrap, rotation, shrink to fit | done | +## AutoFilter population and pending integrations + +[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel) +describes additive column filters and restricting other dropdowns to the filtered range. The +current column is excluded from enumeration so its unchecked alternatives remain available. +The existing one-million-data-row enumeration limit and value sorting remain unchanged. +Imported end rows stop at the last worksheet row in choices, statistics and visibility scans. +Checkbox state uses the row matcher for the active criterion, including raw and formatted +Values matches, custom comparisons, numeric thresholds and colors. A duplicate choice is +checked when any eligible row matches, including when those rows have different colors. +Hidden choices retain that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +lookup sets once per query rather than scanning every selected value for each row. + +This changes the population behind the pending row-count work (#1737, and its stacked Only +button #1741): a future count beside a choice should count eligible rows satisfying the other +columns, including rows rejected by the current column. It must not count the whole original +range or just currently visible rows. Search narrows the displayed choices, not that population; +Apply with a search excludes nonmatching values even when another filter hides them. +These PRs are not incorporated here. Date grouping (#1509) should group this same eligible +population. Table filter activation / roundtrip ownership changes remain in #2506. Enumeration +reads the active sheet AutoFilter without changing criteria, row visibility or the XLSX +representation. A separate table dropdown outside that AutoFilter's columns remains empty; +it does not receive choices from its own eligible-row population. + ## Keyboard | Area | Excel | GridCraft | @@ -277,10 +302,13 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-11-14 | minor | The searched validation list measures its rows at their real height, like the dropdown arrow's list: it shows eight rows instead of six, the highlighted row stays in view and the last entries of a long list can be reached. It opens above the cell when it would run past the bottom of the window, measures its width once per search instead of every frame, and its "More entries not shown" note goes through the interface translations. Typing over the open dropdown drops the entries the dropdown had read | | 2026-11-13 | minor | The full list the dropdown arrow (or Alt+Down) opens reads its source once while it stays open, within the same 200,000-cell budget, and draws only the rows in view, so a list over a huge column no longer rereads and redraws every entry each frame; it says when entries aren't shown, and its rows are measured at their real height so eight show, as intended | | 2026-11-13 | minor | A searched validation list reads at most 200,000 cells of its source (`LIST_SOURCE_BUDGET`), walking a range source within the used range instead of evaluating it whole, so a list over a huge or whole column can't stall the edit; `data.validationList` reports `truncated` and the popup says when entries aren't shown | +| 2026-11-11 | minor | Carry the imported AutoFilter end-row bound through shared statistics and dropdown choices as well as row visibility; retain duplicate-color and per-window pending-choice fixes (#2641) | +| 2026-11-10 | minor | Keep duplicate choices checked when any eligible row matches a color filter; a form-button window switch preserves the incoming window's pending filter search and checkbox edits (#2641) | | 2026-11-05 | minor | Reconcile upstream form-control coverage with the CJK baseline and cell-alignment updates | | 2026-11-04 | minor | Keep centered emoji and symbol fallback placement when a row starts with a fallback or contains only fallbacks; use primary or baseline-aligned glyphs to anchor cell alignment | | 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines | | 2026-11-04 | minor | Align wrapped and unwrapped cells with the same vertical margins; regressions compare numbers with mixed CJK/Latin text, including explicit line breaks | +| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 | | 2026-11-03 | minor | Find and Replace: workbook Undo/Redo works with a keyboard-focused button; focused text fields keep text-editing Undo, and a modal message blocks workbook shortcuts. Regression covers Replace All, both Redo shortcuts, actual text undo, and an error message | | 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default | @@ -295,12 +323,14 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-11-03 | minor | Draw tab: the stroke drawn under the pointer while dragging a pen is the ink that will be committed, in the pen's colour and thickness (translucent for a highlighter), instead of always blue at 2 pt (#1786) | | 2026-11-03 | minor | Copy puts a cell that holds a quote on the clipboard as it is (`say "hi"`), quoting only text with a tab or line break, as Excel does; pasting text reads a field as quoted only when its closing quote ends it, so `"hi" there` pastes with its quotes (#2225) | | 2026-11-03 | minor | Ctrl+. (Control+. on a Mac): Next Corner of Selection, `selection.nextCorner`: the active cell moves clockwise to the next corner of the selected area, which stays selected, and becomes the anchor, as in Excel (#1442) | +| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 | | 2026-11-02 | minor | Dragging the selection's border onto cells that hold data asks "There's already data here. Do you want to replace it?" (OK replaces, Cancel leaves the sheet and clipboard as they were) through the new `range.move` command (#3136); the row no longer claims Ctrl/Option copy and Shift insert for the border drag, which are not wired yet | | 2026-11-02 | minor | RefEdit reference boxes in dialogs: pick a range on the grid, collapse the dialog while selecting; Goal Seek, Solver (with the Model Range of Load/Save) and Data Analysis use them; while collapsed the arrow keys move the selection and Shift+arrow extends it, F4 cycles a reference's anchors, a click elsewhere keeps the box picking, a dialog opened over a picking one puts the selection back, OK stays on the sheet its command showed, and scripted cancel and confirm end a pick like the buttons; the dialog's sheet is followed through the recorded undo steps, so a sheet deleted and recreated under its name is not taken for it and an undo of the deletion brings it back; a box the dialog stops showing is no longer picked into; the dialog's sheet is recorded when it opens, not at its first pick | | 2026-11-02 | minor | Python mode edits a cell's code in the formula bar's code editor (Ctrl+Alt+Shift+P, `=PY` then Tab, editing a Python cell), with the PY badge beside fx; its keys apply in input order, also several in one frame, and Ctrl+Enter commits through `python.set` (empty code clears the cell), keeping the code and showing the command's message when the code is refused | | 2026-11-02 | minor | Insert › Symbols: Equation split button (access keys N E), a gallery of examples, and an equation editor with quick-insert buttons, the error underlined at its position and a live preview; double-clicking an equation edits it | | 2026-11-02 | minor | Floating objects: one selection for charts, pictures, shapes and slicers, eight resize handles with matching cursors (right-to-left sheets included), Escape drops the selection | | 2026-11-02 | minor | Record macOS mixed CJK/Latin rendering validation, the actual fallback fonts and the unverified Calibri 10 case | +| 2026-11-01 | minor | Filter popup checkbox edits, search and button state belong to their document window; switching columns in another window no longer discards an open popup's pending choices (#2641); the separate AutoFilter section documents the empty dropdown outside the active sheet filter columns (#2506) | | 2026-11-01 | minor | Chart Design › Add Chart Element offers Data Table with/no legend keys and None; Format Chart Area has a Data Table section with visibility, legend keys, horizontal/vertical borders and outline. Both use engine commands. | | 2026-11-01 | minor | Page Setup has a Page order choice (Down, then over, the default, or Over, then down) with a small picture of the order, also when Print Titles opens it on its Sheet tab; OK sets it with the margins in one undo step. Printing, PDF export, the print preview, Page Break Preview's page numbers and Page Layout view's headers and footers follow the order. The dialog is in German now too | | 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows | @@ -310,6 +340,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown | | 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used | | 2026-10-31 | minor | CJK fallback text shares the Latin baseline in cells, editors and window titles; fixed row heights and clipping remain workbook-controlled | +| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; documents pending counts, date grouping and table roundtrip integration; retains slicer row filtering when its criterion is outside the sheet filter columns | +| 2026-10-30 | minor | Italic and bold in an installed font that has no face for them (Arial Black has a single face) are imitated on the grid, as Excel does: the text is slanted and drawn a second time a little to the right (about 1/36 of the size, at least one pixel). Observed in Excel's PDF of a cell in Arial Black, bold italic: oblique by 1/3 and outlined 0.23 pt thick at 9 pt. egui's slant is fixed at about 1/4. Print and PDF still use the standard PDF fonts (`fonts.rs` test) | | 2026-10-30 | minor | Checkbox cells print and export to PDF as boxes, as on screen: unchecked white with a grey outline, checked green with a white tick (#2972). They printed their value as TRUE or FALSE; other values in a checkbox cell still print as text | | 2026-10-29 | minor | Formula pointing from the keyboard: Ctrl+arrow (⌘arrow) moves the pointed cell to the edge of its data and Ctrl+Shift+arrow (⌘⇧arrow) extends the pointed range there, as the same keys move and extend the selection, so typing `=COUNTIF(`, clicking the top of a column and pressing ⌘⇧↓ points at the whole column of data; the keys used to move or extend by one cell. A range reaching the sheet edge is written as whole columns or rows (`A:B`). The editor reads the modifiers of the arrow's own key event, so a keystroke pressed and released within one frame (a control client's `ui.key`, an automation tool) keeps its Shift and Ctrl | | 2026-10-29 | minor | Insert Hyperlink opens with an existing link's address, display text and ScreenTip (#2876). An address-only edit preserves the cell's content and formula; Cancel leaves the link unchanged, and Undo restores the edit | diff --git a/packaging/windows/excel-open-check/README.md b/packaging/windows/excel-open-check/README.md new file mode 100644 index 0000000000..a927997bb1 --- /dev/null +++ b/packaging/windows/excel-open-check/README.md @@ -0,0 +1,13 @@ +# Excel open check + +Saves workbooks with `gridcraft-cli` and opens each result in real Excel (COM), recording per file `PASS` or the +exact failure. Windows with Excel only. See `check.ps1` for the options. + +```powershell +.\check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe -Inputs C:\workbooks -Csv result.csv +``` + +Inputs are any `.xlsx`/`.xlsm` (the synthetic `gridcraft/` fixtures in a public fixtures repo are a good start); each +`*.jsonl` here is a feature scenario run on the Sales sample. Add a scenario by dropping in another `.jsonl` +(`gridcraft-cli run --script` format). Results: `Original` is the input opened in Excel (so a file Excel itself +rejects or loads slowly isn't blamed on GridCraft), `Saved` is the GridCraft-saved copy. diff --git a/packaging/windows/excel-open-check/charts.jsonl b/packaging/windows/excel-open-check/charts.jsonl new file mode 100644 index 0000000000..3746a83e9c --- /dev/null +++ b/packaging/windows/excel-open-check/charts.jsonl @@ -0,0 +1,12 @@ +# One chart of each common kind over the sales table +insert.chart={"range":"B4:F8","type":"bar","at":"K36"} +insert.chart={"range":"B4:F8","type":"line","subtype":"markers","at":"S3"} +insert.chart={"range":"B4:F8","type":"area","subtype":"stacked","at":"S19"} +insert.chart={"range":"C5:D8","type":"scatter","at":"S36"} +insert.chart={"range":"B4:F8","type":"radar","at":"AA3"} +insert.chart={"range":"B4:C8","type":"doughnut","at":"AA19"} +insert.chart={"range":"B4:C8","type":"waterfall","at":"AA36"} +insert.chart={"range":"B4:C8","type":"treemap","at":"AI3"} +insert.chart={"range":"B4:C8","type":"histogram","at":"AI19"} +insert.sparkline={"range":"C5:F5","location":"J5","type":"line"} +insert.sparkline={"range":"C6:F6","location":"J6","type":"column"} diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 new file mode 100644 index 0000000000..1e82a48633 --- /dev/null +++ b/packaging/windows/excel-open-check/check.ps1 @@ -0,0 +1,125 @@ +<# +Excel open check: saves workbooks with GridCraft, opens each result in real Excel (COM) and records per +file whether Excel loads it as it is or has to repair it (docs/file-format-parity.md, "Excel open check"). + + check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe [-Inputs C:\workbooks] [-Out C:\out] [-Csv result.csv] + [-TimeoutSec 120] + +Files saved: + - every .xlsx / .xlsm in -Inputs, opened and saved with `gridcraft-cli run --in --out` (the original + is opened in Excel too, so a file Excel itself dislikes or loads slowly is told apart from a + GridCraft regression); + - every *.jsonl scenario next to this script (one feature each), run on the Sales sample. + +Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a +failure instead of a silent fix, with DisplayAlerts off and VBA macros disabled so nothing waits on a prompt. +AutomationSecurity does not cover Excel 4.0 (XLM) macros, which would still prompt, so a workbook that +holds XLM macro sheets is never opened: it is reported as SKIP-XLM and the run does not pass. +Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and +that instance (found by its window's process id) is stopped. Nothing is written next to the inputs; any other +Excel, such as one the person starts meanwhile, is never touched. Exit code 1 when any saved file is not PASS. +#> +param( + [Parameter(Mandatory = $true)][string]$Cli, + [string]$Inputs, + [string]$Out = (Join-Path ([IO.Path]::GetTempPath()) 'gridcraft-excel-open-check'), + [string]$Csv, + [int]$TimeoutSec = 120 +) +$ErrorActionPreference = 'Stop' + +# Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it. +$probe = { + param($path) + $x = $null + try { + # Compiled before Excel starts, so nothing between the start and the PID line can fail or stall on it. + Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);' + $x = New-Object -ComObject Excel.Application + # Report this instance's process id so the caller can stop exactly it and nothing else. + $xlPid = [uint32]0 + [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) + "PID`t$xlPid" + $x.Visible = $false + $x.DisplayAlerts = $false + $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: no VBA macros (XLM is screened by Test-HasXlm) + # Named arguments: PowerShell can't skip the optional ones in between positionally. + $wb = [System.__ComObject].InvokeMember('Open', [Reflection.BindingFlags]::InvokeMethod, $null, $x.Workbooks, + @($path, 0, $true, 0), $null, $null, @('Filename', 'UpdateLinks', 'ReadOnly', 'CorruptLoad')) + $sheets = $wb.Worksheets.Count + $wb.Chartsheets.Count + $wb.Close($false) + "PASS`t$sheets sheets" + } catch { + "FAIL`t" + ($_.Exception.Message -replace '\s+', ' ') + } finally { + # Also covers a failure before the PID line: this process's own instance is quit, no other is touched. + if ($x) { try { $x.Quit() } catch {} } + } +} + +# True when the package holds Excel 4.0 macro sheets, which ForceDisable does not stop and Excel would prompt for. +function Test-HasXlm([string]$path) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + # Not a zip at all: nothing to screen, Excel gets to report it. + try { $zip = [IO.Compression.ZipFile]::OpenRead($path) } catch { return $false } + try { return [bool]($zip.Entries | Where-Object { $_.FullName -like 'xl/macrosheets/*' }) } finally { $zip.Dispose() } +} + +function Test-InExcel([string]$path) { + if (Test-HasXlm $path) { return [pscustomobject]@{ State = 'SKIP-XLM'; Seconds = 0; Detail = 'Excel 4.0 macro sheets; not opened' } } + $clock = [Diagnostics.Stopwatch]::StartNew() + $job = Start-Job -ScriptBlock $probe -ArgumentList $path + $done = Wait-Job $job -Timeout $TimeoutSec + $lines = @(Receive-Job $job -Keep -ErrorAction SilentlyContinue) + $failed = $job.State -eq 'Failed' + if (-not $done) { Stop-Job $job } + Remove-Job $job -Force + $xlPid = ($lines | Where-Object { $_ -like "PID`t*" } | Select-Object -First 1) -replace '^PID\t', '' + $out = $lines | Where-Object { $_ -notlike "PID`t*" } | Select-Object -Last 1 + if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif ($failed -or -not $out) { $out = "CRASH`tno result (Excel died)" } + if ($xlPid) { + # A clean Quit lets Excel exit by itself; give it a moment, then stop only this instance. + Wait-Process -Id ([int]$xlPid) -Timeout 15 -ErrorAction SilentlyContinue + Stop-Process -Id ([int]$xlPid) -Force -ErrorAction SilentlyContinue + } + $state, $detail = $out -split "`t", 2 + [pscustomobject]@{ State = $state; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); Detail = $detail } +} + +$saved = Join-Path $Out 'saved' +Remove-Item -LiteralPath $saved -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Path $saved -Force | Out-Null + +# (name, original or $null, saved) per file +$work = @() +if ($Inputs) { + foreach ($f in Get-ChildItem -LiteralPath $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { + $work += , @($f.Name, $f.FullName, (Join-Path $saved $f.Name), @('run', '--in', $f.FullName, '--quiet')) + } +} +foreach ($s in Get-ChildItem -Path $PSScriptRoot -Filter *.jsonl | Sort-Object Name) { + $work += , @("scenario:$($s.BaseName)", $null, (Join-Path $saved "$($s.BaseName).xlsx"), @('run', '--sample', 'sales', '--script', $s.FullName, '--quiet')) +} + +$rows = @() +foreach ($w in $work) { + $name, $orig, $dest, $cliArgs = $w + # The CLI reports on stderr, which Stop would turn into an exception. + Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue + $ErrorActionPreference = 'Continue' + & $Cli @cliArgs --out $dest *> $null + $code = $LASTEXITCODE + $ErrorActionPreference = 'Stop' + $base = if ($orig) { (Test-InExcel $orig) } else { $null } + $r = if ($code -eq 0 -and (Test-Path -LiteralPath $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } + $rows += [pscustomobject]@{ + File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State + Seconds = $r.Seconds; Detail = $r.Detail + } +} +$rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output +if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv } +$bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count +$savedBad = @($rows | Where-Object Saved -ne 'PASS').Count +"{0} of {1} saved files pass" -f ($rows.Count - $savedBad), $rows.Count +if ($bad) { exit 1 } diff --git a/packaging/windows/excel-open-check/conditional-formats.jsonl b/packaging/windows/excel-open-check/conditional-formats.jsonl new file mode 100644 index 0000000000..ebfb544fa9 --- /dev/null +++ b/packaging/windows/excel-open-check/conditional-formats.jsonl @@ -0,0 +1,8 @@ +# Colour scale, data bar, icon set, top 10, formula and text rules +home.conditionalFormat={"range":"C5:F8","rule":{"type":"colorScale"}} +home.conditionalFormat={"range":"C5:C8","rule":{"type":"dataBar"}} +home.conditionalFormat={"range":"D5:D8","rule":{"type":"iconSet"}} +home.conditionalFormat={"range":"E5:E8","rule":{"type":"top10","rank":2}} +home.conditionalFormat={"range":"F5:F8","rule":{"type":"cellIs","operator":"greaterThan","value":"60000","preset":"lightRedFill"}} +home.conditionalFormat={"range":"B5:B8","rule":{"type":"containsText","text":"th","preset":"yellowFill"}} +home.conditionalFormat={"range":"C5:F8","rule":{"type":"expression","formula":"=C5>AVERAGE($C$5:$F$8)","preset":"greenFill"}} diff --git a/packaging/windows/excel-open-check/pivots.jsonl b/packaging/windows/excel-open-check/pivots.jsonl new file mode 100644 index 0000000000..23315f9e8b --- /dev/null +++ b/packaging/windows/excel-open-check/pivots.jsonl @@ -0,0 +1,4 @@ +# PivotTable on the sales table, a pivot chart, a table slicer +insert.pivotTable={"source":"Sales","destination":"Sales!K40","rows":["Region"],"values":[{"field":"Q1","func":"sum"}]} +insert.pivotChart={"pivot":"Sales!K42","type":"column","at":"S50"} +insert.slicer={"table":"Sales","column":"Region","at":"AA50"} diff --git a/packaging/windows/excel-open-check/protection-sheets.jsonl b/packaging/windows/excel-open-check/protection-sheets.jsonl new file mode 100644 index 0000000000..f05bd57ce4 --- /dev/null +++ b/packaging/windows/excel-open-check/protection-sheets.jsonl @@ -0,0 +1,9 @@ +# Extra sheets (renamed, coloured, hidden), grouping and a protected sheet +home.insertSheet={} +sheet.rename={"name":"Second"} +sheet.tabColor={"color":"#FF0000"} +cell.set={"cell":"A1","input":"=Sales!B5&\" \"&Sales!C5"} +home.insertSheet={} +sheet.hide={} +sheet.activate={"sheet":"Sales"} +review.protectSheet={"formatCells":true} diff --git a/packaging/windows/excel-open-check/shapes-pictures.jsonl b/packaging/windows/excel-open-check/shapes-pictures.jsonl new file mode 100644 index 0000000000..ecfcfbbaef --- /dev/null +++ b/packaging/windows/excel-open-check/shapes-pictures.jsonl @@ -0,0 +1,5 @@ +# Shapes with text and a picture from base64 (a 1x1 PNG) +insert.shape={"kind":"rectangle","at":"K30","width":120,"height":40,"text":"Box","fill":"#FFC000"} +insert.shape={"kind":"ellipse","at":"O30","width":80,"height":40} +insert.shape={"kind":"arrow","at":"K33","width":80,"height":30} +insert.picture={"base64":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==","mime":"image/png","at":"B20","width":60,"height":60,"alt":"dot"} diff --git a/packaging/windows/excel-open-check/tables-names.jsonl b/packaging/windows/excel-open-check/tables-names.jsonl new file mode 100644 index 0000000000..98f07d0949 --- /dev/null +++ b/packaging/windows/excel-open-check/tables-names.jsonl @@ -0,0 +1,13 @@ +# Table style and total row, defined names, merged cells, frozen panes, hyperlink-free cell notes +selection.set={"cell":"C5"} +table.totalRow={} +table.style={"style":"TableStyleLight9"} +formulas.defineName={"name":"NorthQ1","refersTo":"=Sales!$C$5"} +formulas.defineName={"name":"AllRegions","refersTo":"=Sales!$B$5:$B$8"} +formulas.defineName={"name":"Rate","refersTo":"=0.2","comment":"tax rate"} +cell.set={"cell":"K14","input":"=SUM(AllRegions)"} +cell.set={"cell":"K15","input":"=NorthQ1*Rate"} +home.mergeCells={"range":"K16:M16"} +view.freezePanes={"cell":"C5"} +review.newNote={"cell":"C5","text":"checked"} +review.newComment={"cell":"D5","text":"threaded"} diff --git a/packaging/windows/excel-open-check/validation.jsonl b/packaging/windows/excel-open-check/validation.jsonl new file mode 100644 index 0000000000..cd7e2efa09 --- /dev/null +++ b/packaging/windows/excel-open-check/validation.jsonl @@ -0,0 +1,8 @@ +# One rule of each kind +data.validation={"range":"K2:K5","type":"list","formula1":"North,South,East,West"} +data.validation={"range":"K6:K8","type":"whole","operator":"between","formula1":"1","formula2":"100","inputTitle":"Count","inputMessage":"1 to 100","errorStyle":"warning"} +data.validation={"range":"L2:L5","type":"decimal","operator":"greaterThan","formula1":"0"} +data.validation={"range":"L6:L8","type":"date","operator":"greaterOrEqual","formula1":"2026-01-01"} +data.validation={"range":"M2:M5","type":"textLength","operator":"lessOrEqual","formula1":"10"} +data.validation={"range":"M6:M8","type":"custom","formula1":"=ISNUMBER(M6)"} +data.validation={"range":"N2:N5","type":"list","formula1":"=$B$5:$B$8"}