From 17aae2da04d3cf94c113182711753afa5a7581f2 Mon Sep 17 00:00:00 2001 From: DerKarussellbremser <67138735+DerKarussellbremser@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:41:23 +0200 Subject: [PATCH 01/23] Grid: italic and bold in a one-face font are slanted and thickened, as in Excel Arial Black has a single face. A cell in Arial Black, bold italic, drew it upright and at its own weight; Excel slants it and thickens it (observed in its PDF: oblique by 1/3, outlined 0.23 pt at 9 pt). fonts.rs notes, while it binds a family's roles, which italic roles got an upright face and which bold roles got the plain face; the grid then lays such text out with egui's italics and paints it a second time about 1/36 of its size to the right. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9 --- crates/ui-egui/src/fonts.rs | 70 ++++++++++++++++++++++++++++++++++++- crates/ui-egui/src/grid.rs | 37 +++++++++++++++----- docs/ui-parity.md | 3 +- 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 1a381b9d46..11125a9b04 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -325,6 +325,13 @@ 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); + if italic && !primary.italic { + mark_synthetic(&role, SLANT); + } + if bold && pick_face(faces, false, italic).is_some_and(|plain| face_key(plain) == face_key(primary)) { + mark_synthetic(&role, BOLD); + } let mut chain: Vec = Vec::new(); for face in [Some(primary), pick_face(faces, false, false)] { let Some(face) = face else { continue }; @@ -344,7 +351,6 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face continue; } 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); } @@ -374,6 +380,35 @@ pub fn is_bound(role: &str) -> bool { bound().read().unwrap_or_else(|e| e.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 mark_synthetic(role: &str, style: &str) { + synthetic().write().unwrap_or_else(|e| e.into_inner()).insert(format!("{role}|{style}")); +} + +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(()); @@ -473,6 +508,39 @@ 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)); + 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("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 b485104b1d..ce5545b8c6 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -1242,6 +1242,9 @@ pub(crate) fn paint_quadrant( let size = st.font.size * 96.0 / 72.0 * z; let fam = theme::cell_family(&st.font.name, st.font.bold, st.font.italic); let font = FontId::new(size, fam); + let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold); + let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic); + let bold_dx = if embolden { (size / 36.0).max(1.0 / p.ctx().pixels_per_point()) } else { 0.0 }; // Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns). let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0); let avail_w = rect.right() - text_left; @@ -1268,7 +1271,7 @@ pub(crate) fn paint_quadrant( // Rotated text wraps along its own direction (below), not across the column width. if !rotated && (st.align.wrap || st.align.h == HAlign::Justify) { let wrap_w = (rect.width() - 2.0 * pad - indent).max(4.0); - let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, wrap_w); + let mut job = cell_job(text.clone(), font.clone(), color, wrap_w, slant); job.halign = match halign { HAlign::Center | HAlign::CenterAcross => egui::Align::Center, HAlign::Right => egui::Align::RIGHT, @@ -1281,7 +1284,7 @@ pub(crate) fn paint_quadrant( _ => text_left + pad + indent, }; let y = wrapped_cell_text_y(st.align.v, *rect, galley.size().y, z); - p.with_clip_rect(rect.intersect(p.clip_rect())).galley(pos2(x, y), galley, color); + paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx); continue; } // Wrap Text off: Excel ignores the line breaks and draws the whole string on one line. @@ -1295,7 +1298,7 @@ pub(crate) fn paint_quadrant( .flatten(); let shrunk = small.is_some(); let font = small.unwrap_or(font); - let mut galley = p.layout_no_wrap(first_line.clone(), font.clone(), color); + let mut galley = p.layout_job(cell_job(first_line.clone(), font.clone(), color, f32::INFINITY, slant)); let mut w = galley.size().x; // Numbers and dates never overflow: they show #### when too narrow. let hashed = !shrunk && (numeric || matches!(v, Value::Number(_))) && w > avail_w - 2.0 * pad && st.align.h != HAlign::Fill; @@ -1303,7 +1306,7 @@ pub(crate) fn paint_quadrant( // Measured on `#` itself: it is wider than `0` in some fonts, and #### must fit its cell. let hash_w = p.layout_no_wrap("#".to_string(), font.clone(), color).size().x.max(1.0); let n = ((avail_w - 2.0 * pad) / hash_w).floor().max(1.0) as usize; - galley = p.layout_no_wrap("#".repeat(n), font.clone(), color); + galley = p.layout_job(cell_job("#".repeat(n), font.clone(), color, f32::INFINITY, slant)); w = galley.size().x; } // Repeat fill (`*` in number formats) / Fill alignment. A number already shown as #### keeps @@ -1319,7 +1322,7 @@ pub(crate) fn paint_quadrant( if first_line.is_char_boundary(pos) { s.insert_str(pos, &ch.to_string().repeat(n)); } - galley = p.layout_no_wrap(s, font.clone(), color); + galley = p.layout_job(cell_job(s, font.clone(), color, f32::INFINITY, slant)); w = galley.size().x; } // Center Across Selection: the text is centred over this cell and the empty cells to its right that also use it. @@ -1381,8 +1384,7 @@ pub(crate) fn paint_quadrant( let angle = -(st.align.rotation as f32).to_radians(); // Upright (±90°) wrapped text wraps to the row height: lines then stack across the column. let galley = if st.align.wrap && st.align.rotation.abs() == 90 { - let job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0)); - p.layout_job(job) + p.layout_job(cell_job(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0), slant)) } else { galley.clone() }; @@ -1391,7 +1393,7 @@ pub(crate) fn paint_quadrant( shape.angle = angle; cp.add(shape); } else { - cp.galley(pos2(x, y), galley.clone(), color); + paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx); } let baseline = y + gh * 0.82; match st.font.underline { @@ -1604,6 +1606,25 @@ fn merged_edges( 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`]). +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`]). +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. fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efeee..49c18d66bc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -178,6 +178,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | 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-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) | | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From c4ef580a22a5c276a76e94401085bef5b7a932db Mon Sep 17 00:00:00 2001 From: DerKarussellbremser <67138735+DerKarussellbremser@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:41:41 +0200 Subject: [PATCH 02/23] Grid: imitate the styles of the face actually drawn; bold for shrunk and rotated text Review fixes. The slant and bold markers are now set from the face the role is drawn in (the first whose file could be read), so a family whose bold or italic file is missing gets them imitated too, and a later binding that no longer needs a marker removes it. The bold offset follows the size that is painted after Shrink to Fit, and rotated text gets its second impression along its own direction. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9 --- crates/ui-egui/src/fonts.rs | 33 ++++++++++++++++++++++----------- crates/ui-egui/src/grid.rs | 15 ++++++++++++--- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 11125a9b04..a785c65b2e 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -326,13 +326,9 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face 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); - if italic && !primary.italic { - mark_synthetic(&role, SLANT); - } - if bold && pick_face(faces, false, italic).is_some_and(|plain| face_key(plain) == face_key(primary)) { - mark_synthetic(&role, BOLD); - } 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); @@ -346,10 +342,14 @@ 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()); fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain); bound.push(role); @@ -391,8 +391,14 @@ fn synthetic() -> &'static std::sync::RwLock> { SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new())) } -fn mark_synthetic(role: &str, style: &str) { - synthetic().write().unwrap_or_else(|e| e.into_inner()).insert(format!("{role}|{style}")); +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 { @@ -530,9 +536,14 @@ mod tests { 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)); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index ce5545b8c6..7bf2b15b4b 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -1244,7 +1244,9 @@ pub(crate) fn paint_quadrant( let font = FontId::new(size, fam); let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold); let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic); - let bold_dx = if embolden { (size / 36.0).max(1.0 / p.ctx().pixels_per_point()) } else { 0.0 }; + // How far the second impression of imitated bold sits from the first, by the size painted. + let ppp = p.ctx().pixels_per_point(); + let bold_dx = |size: f32| if embolden { (size / 36.0).max(1.0 / ppp) } else { 0.0 }; // Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns). let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0); let avail_w = rect.right() - text_left; @@ -1284,7 +1286,7 @@ pub(crate) fn paint_quadrant( _ => text_left + pad + indent, }; let y = wrapped_cell_text_y(st.align.v, *rect, galley.size().y, z); - paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx); + paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx(size)); continue; } // Wrap Text off: Excel ignores the line breaks and draws the whole string on one line. @@ -1389,11 +1391,18 @@ pub(crate) fn paint_quadrant( galley.clone() }; let pos = rotated_text_pos(*rect, galley.size(), angle, painted_halign(st.align.h, geo.rtl), st.align.v, pad, indent); + // Imitated bold: the second impression along the text's own direction. + let d = bold_dx(font.size); + if d > 0.0 { + let mut thick = egui::epaint::TextShape::new(pos + d * 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); } else { - paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx); + paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx(font.size)); } let baseline = y + gh * 0.82; match st.font.underline { From 1fe4f79db6cfaf718375fc5c923451f3fb13b45c Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:22:28 -0500 Subject: [PATCH 03/23] Excel open check: save workbooks with the CLI and open them in real Excel, a repair counts as a failure --- ROADMAP.md | 4 +- docs/gaps.md | 4 +- packaging/windows/excel-open-check/README.md | 13 +++ .../windows/excel-open-check/charts.jsonl | 12 ++ packaging/windows/excel-open-check/check.ps1 | 109 ++++++++++++++++++ .../conditional-formats.jsonl | 8 ++ .../windows/excel-open-check/pivots.jsonl | 4 + .../excel-open-check/protection-sheets.jsonl | 9 ++ .../excel-open-check/shapes-pictures.jsonl | 5 + .../excel-open-check/tables-names.jsonl | 13 +++ .../windows/excel-open-check/validation.jsonl | 8 ++ 11 files changed, 187 insertions(+), 2 deletions(-) create mode 100644 packaging/windows/excel-open-check/README.md create mode 100644 packaging/windows/excel-open-check/charts.jsonl create mode 100644 packaging/windows/excel-open-check/check.ps1 create mode 100644 packaging/windows/excel-open-check/conditional-formats.jsonl create mode 100644 packaging/windows/excel-open-check/pivots.jsonl create mode 100644 packaging/windows/excel-open-check/protection-sheets.jsonl create mode 100644 packaging/windows/excel-open-check/shapes-pictures.jsonl create mode 100644 packaging/windows/excel-open-check/tables-names.jsonl create mode 100644 packaging/windows/excel-open-check/validation.jsonl diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce78..817ef74dfe 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (Excel open check script; AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **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. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-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-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | @@ -242,6 +243,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Progress log: Excel open check | | 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column | | 2026-10-23 | minor | Progress log: accounting negatives in number text | | 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! | diff --git a/docs/gaps.md b/docs/gaps.md index 97299acda0..cd026b845f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (§8: PivotTable Enable show details; earlier: PivotTable Show Details) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (§1: repeatable Excel open check; §8: PivotTable Enable show details; earlier: PivotTable Show Details) · **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 @@ -22,6 +22,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) @@ -183,6 +184,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 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-24 | minor | §8: PivotTable Enable show details: `pivot.options` `enableShowDetails` turns Show Details off for a PivotTable, read and written in XLSX as `enableDrill` | | 2026-10-23 | minor | §8: PivotTable Show Details: double-clicking a value cell lists its source records on a new sheet (#2364) | | 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) | 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..08dff4f162 --- /dev/null +++ b/packaging/windows/excel-open-check/check.ps1 @@ -0,0 +1,109 @@ +<# +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 macros disabled so nothing waits on a prompt. +Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and +Excel started by this script is stopped. Nothing is written next to the inputs; Excel processes that were +already running are 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' + +# Excel processes already running are the person's own work: only ones started after this point are ever killed. +$before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | ForEach-Object Id) +function Stop-Excel { + Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id } | Stop-Process -Force -ErrorAction SilentlyContinue +} + +# 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 { + $x = New-Object -ComObject Excel.Application + $x.Visible = $false + $x.DisplayAlerts = $false + $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros + # 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 { + if ($x) { try { $x.Quit() } catch {} } + } +} + +function Test-InExcel([string]$path) { + $clock = [Diagnostics.Stopwatch]::StartNew() + $job = Start-Job -ScriptBlock $probe -ArgumentList $path + if (Wait-Job $job -Timeout $TimeoutSec) { + $out = (Receive-Job $job) -join ' ' + if (-not $out) { $out = "CRASH`tno result (Excel died)" } + } else { + Stop-Job $job + $out = "TIMEOUT`tno answer in $TimeoutSec s" + } + Remove-Job $job -Force + # Next file only once this Excel has exited, else its first call can get RPC_E_SERVERCALL_RETRYLATER. + $deadline = (Get-Date).AddSeconds(15) + while ((Get-Date) -lt $deadline -and @(Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id }).Count) { Start-Sleep -Milliseconds 200 } + Stop-Excel + $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 $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 -Path $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. + $ErrorActionPreference = 'Continue' + & $Cli @cliArgs --out $dest *> $null + $ErrorActionPreference = 'Stop' + $base = if ($orig) { (Test-InExcel $orig) } else { $null } + $r = if (Test-Path $dest) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $LASTEXITCODE" } } + $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').Count +"{0} of {1} saved files pass" -f ($rows.Count - $bad), $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"} From cfcde5bfbd665ea22bf36c51e4130ef26a9a7409 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:35:56 -0500 Subject: [PATCH 04/23] Excel open check: stop only the Excel instance a probe started, found by its window's process id --- packaging/windows/excel-open-check/check.ps1 | 37 ++++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 08dff4f162..68c9b1afcd 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -14,8 +14,8 @@ Files saved: 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 macros disabled so nothing waits on a prompt. Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and -Excel started by this script is stopped. Nothing is written next to the inputs; Excel processes that were -already running are never touched. Exit code 1 when any saved file is not PASS. +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, @@ -26,12 +26,6 @@ param( ) $ErrorActionPreference = 'Stop' -# Excel processes already running are the person's own work: only ones started after this point are ever killed. -$before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | ForEach-Object Id) -function Stop-Excel { - Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id } | Stop-Process -Force -ErrorAction SilentlyContinue -} - # Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it. $probe = { param($path) @@ -39,6 +33,11 @@ $probe = { try { $x = New-Object -ComObject Excel.Application $x.Visible = $false + # Report this instance's process id so the caller can stop exactly it and nothing else. + Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);' + $xlPid = [uint32]0 + [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) + "PID`t$xlPid" $x.DisplayAlerts = $false $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros # Named arguments: PowerShell can't skip the optional ones in between positionally. @@ -57,18 +56,18 @@ $probe = { function Test-InExcel([string]$path) { $clock = [Diagnostics.Stopwatch]::StartNew() $job = Start-Job -ScriptBlock $probe -ArgumentList $path - if (Wait-Job $job -Timeout $TimeoutSec) { - $out = (Receive-Job $job) -join ' ' - if (-not $out) { $out = "CRASH`tno result (Excel died)" } - } else { - Stop-Job $job - $out = "TIMEOUT`tno answer in $TimeoutSec s" - } + $done = Wait-Job $job -Timeout $TimeoutSec + $lines = @(Receive-Job $job -Keep) + if (-not $done) { Stop-Job $job } Remove-Job $job -Force - # Next file only once this Excel has exited, else its first call can get RPC_E_SERVERCALL_RETRYLATER. - $deadline = (Get-Date).AddSeconds(15) - while ((Get-Date) -lt $deadline -and @(Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id }).Count) { Start-Sleep -Milliseconds 200 } - Stop-Excel + $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 (-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 } } From 260b84d09352287812930ebae6906ebd78c5ee76 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:47:06 -0500 Subject: [PATCH 05/23] Excel open check: a failed probe job is a CRASH, not an error that ends the run --- packaging/windows/excel-open-check/check.ps1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 68c9b1afcd..c58a02fb5f 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -57,12 +57,13 @@ function Test-InExcel([string]$path) { $clock = [Diagnostics.Stopwatch]::StartNew() $job = Start-Job -ScriptBlock $probe -ArgumentList $path $done = Wait-Job $job -Timeout $TimeoutSec - $lines = @(Receive-Job $job -Keep) + $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 (-not $out) { $out = "CRASH`tno result (Excel died)" } + 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 From b023410ca4435e8a45db638b9a686418829af549 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:55:56 -0500 Subject: [PATCH 06/23] Excel open check: skip workbooks with Excel 4.0 macro sheets, require a zero CLI exit before opening the saved file --- packaging/windows/excel-open-check/check.ps1 | 21 ++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index c58a02fb5f..1faabf5bcb 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -12,7 +12,9 @@ Files saved: - 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 macros disabled so nothing waits on a prompt. +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. @@ -39,7 +41,7 @@ $probe = { [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) "PID`t$xlPid" $x.DisplayAlerts = $false - $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros + $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')) @@ -53,7 +55,16 @@ $probe = { } } +# 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 @@ -92,11 +103,13 @@ $rows = @() foreach ($w in $work) { $name, $orig, $dest, $cliArgs = $w # The CLI reports on stderr, which Stop would turn into an exception. + Remove-Item $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 (Test-Path $dest) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $LASTEXITCODE" } } + $r = if ($code -eq 0 -and (Test-Path $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 @@ -104,6 +117,6 @@ foreach ($w in $work) { } $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').Count +$bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count "{0} of {1} saved files pass" -f ($rows.Count - $bad), $rows.Count if ($bad) { exit 1 } From 1053b66a0e8905b82a7ee04fca73c0358a9d6c5f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:12:32 -0500 Subject: [PATCH 07/23] Excel open check: literal paths for saved workbooks and the input folder --- packaging/windows/excel-open-check/check.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 1faabf5bcb..77cb82ecd1 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -85,13 +85,13 @@ function Test-InExcel([string]$path) { } $saved = Join-Path $Out 'saved' -Remove-Item $saved -Recurse -Force -ErrorAction SilentlyContinue +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 -Path $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { + 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')) } } @@ -103,13 +103,13 @@ $rows = @() foreach ($w in $work) { $name, $orig, $dest, $cliArgs = $w # The CLI reports on stderr, which Stop would turn into an exception. - Remove-Item $dest -Force -ErrorAction SilentlyContinue + 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 $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } + $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 From c4920c463b33217b01fcce13811d5220d3f4e5df Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:30:56 -0500 Subject: [PATCH 08/23] Excel open check: count saved passes apart from the XLM gate --- packaging/windows/excel-open-check/check.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 77cb82ecd1..c5687e778b 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -118,5 +118,6 @@ foreach ($w in $work) { $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 -"{0} of {1} saved files pass" -f ($rows.Count - $bad), $rows.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 } From 9bbcb7ce908b3b734749b3160d3a4037e6d9ea6f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:44:00 -0500 Subject: [PATCH 09/23] Excel open check: compile the helper before Excel starts so the PID line is not held up --- packaging/windows/excel-open-check/check.ps1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index c5687e778b..1e82a48633 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -33,13 +33,14 @@ $probe = { param($path) $x = $null try { - $x = New-Object -ComObject Excel.Application - $x.Visible = $false - # Report this instance's process id so the caller can stop exactly it and nothing else. + # 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. @@ -51,6 +52,7 @@ $probe = { } 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 {} } } } From a7a708d0f64ad20a76dcba4e00de8f2219411eb2 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Mon, 26 Oct 2026 13:22:28 -0500 Subject: [PATCH 10/23] #2641: cascade AutoFilter dropdown values --- crates/engine/src/cmd/data.rs | 145 ++++++++------ .../engine/tests/cascading_filter_values.rs | 183 ++++++++++++++++++ .../ui-egui/tests/cascading_filter_values.rs | 69 +++++++ docs/ui-parity.md | 20 +- 4 files changed, 360 insertions(+), 57 deletions(-) create mode 100644 crates/engine/tests/cascading_filter_values.rs create mode 100644 crates/ui-egui/tests/cascading_filter_values.rs diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index fcab9db713..de17bc54c8 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -679,17 +679,17 @@ 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 }; +/// Statistics use the original range, regardless of the other active criteria (as in Excel). +fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> std::collections::HashMap, f64)> { let r = af.range; - let mut hide = Vec::new(); // Precompute per-criterion top10 threshold and average once, not per row. let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { + if Some(*off) == excluded_offset { + continue; + } if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { - let col = r.start.col + off; + let Some(col) = r.start.col.checked_add(*off).filter(|col| *col <= r.end.col) else { continue }; let mut nums: Vec = (r.start.row + 1..=r.end.row).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 { @@ -704,59 +704,84 @@ 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())) + col_stats +} + +/// Evaluate criteria directly, without conflating manual visibility with filter results. +fn filter_row_matches( + wb: &Workbook, + sh: &Sheet, + af: &AutoFilter, + row: u32, + col_stats: &std::collections::HashMap, f64)>, + excluded_offset: Option, +) -> bool { + for (i, (off, crit)) in af.criteria.iter().enumerate() { + if Some(*off) == excluded_offset { + continue; + } + let Some(col) = af.range.start.col.checked_add(*off).filter(|col| *col <= af.range.end.col) else { continue }; + let c = CellRef::new(row, col); + 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 } } - 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, + _ => false, + }, + FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { + (Some(n), Some((_, avg))) => { + if *above { + n > *avg + } else { + n < *avg } } - 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; - } + _ => 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, + // Icon criteria are retained from files but cannot be evaluated yet. + FilterCriterion::Icon { .. } => true, + }; + if !ok { + return false; } - hide.push((row, !visible)); } + 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 }; + let r = af.range; + let col_stats = filter_stats(sh, &af, None); + // 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, !filter_row_matches(wb, sh, &af, row, &col_stats, 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 { @@ -789,14 +814,22 @@ 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)> { 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); + if col < af.range.start.col || col > af.range.end.col { + return vec![]; + } + let off = col - af.range.start.col; let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); + let col_stats = filter_stats(sh, af, Some(off)); 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) { + for row in af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)) { + if !filter_row_matches(wb, sh, af, row, &col_stats, Some(off)) { + continue; + } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); diff --git a/crates/engine/tests/cascading_filter_values.rs b/crates/engine/tests/cascading_filter_values.rs new file mode 100644 index 0000000000..afaf720282 --- /dev/null +++ b/crates/engine/tests/cascading_filter_values.rs @@ -0,0 +1,183 @@ +use std::sync::Arc; + +use gridcraft_engine::{ + Session, + cmd::data::filter_values, + model::{Color, FilterCriterion}, +}; +use serde_json::json; + +#[test] +fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { + for (criterion, expected) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"]), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"]), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"]), + (json!({"top": {"count": 2}}), vec!["high", "upper"]), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"]), + (json!({"aboveAverage": true}), vec!["high"]), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"]), + ] { + 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}"); + // Statistics still come from the whole range even with another column filtered. + 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(), true)], + "the numeric column's own criterion must be excluded: {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).len(), 3); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty()); +} + +#[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)]); + } + 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 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"], ["East", "Last East"], ["West", "Last West"]]})).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)]); +} diff --git a/crates/ui-egui/tests/cascading_filter_values.rs b/crates/ui-egui/tests/cascading_filter_values.rs new file mode 100644 index 0000000000..c217d35fc4 --- /dev/null +++ b/crates/ui-egui/tests/cascading_filter_values.rs @@ -0,0 +1,69 @@ +#[path = "common/mod.rs"] +mod common; + +use egui::{Event, Key, Modifiers}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +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); +} + +#[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/docs/ui-parity.md b/docs/ui-parity.md index f35899236b..dca4ea508e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cascading AutoFilter choices) · **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 @@ -60,6 +60,7 @@ this logic, with one undo step. | Point mode (click/drag/arrow references), reference colouring, F4 | done | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | 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). 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) | @@ -91,6 +92,22 @@ this logic, with one undo step. | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | +### 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. + +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. +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 used by the current table dropdown without changing criteria, +row visibility or the XLSX representation. + ### Shortcut audit (#110) Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and Mac tables, @@ -187,6 +204,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); document pending counts, date grouping and table roundtrip integration | | 2026-10-25 | minor | AutoSum (Alt+=, Home › AutoSum) over a selected row puts its total to the right of the row, or in its last cell when that is empty, as in Excel; it wrote a one-cell total under each cell. A selection's empty last column takes each row's total and its empty last row each column's, with the block's total in the corner when both are empty | | 2026-10-25 | minor | Paste Name lays out only the names in view, so a workbook with thousands of names opens it at once; the arrow keys still scroll the chosen name into view. Go To matches a `Sheet2!Name` reference and hides a workbook name behind the active sheet's own name in any case and script (`Größe` = `GRÖSSE`), as formulas do. The two Page Layout view rows are one; the 0.7 in side margin used when Align with Page Margins is off is marked unverified | | 2026-10-24 | minor | Go To lists the named ranges on every sheet, as Excel's does ("The Go to popup window shows named ranges on every worksheet in your workbook"): a name scoped to another sheet appears as `Sheet2!Name`, and hidden names, constants and formulas are left out. It keeps the references entered (newest first, ten at most), and a double-click on an entry goes there. The Reference box and `edit.goTo` take several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30,H21:H29`) and select them all; `edit.goTo {list: true}` returns the list | From 1fcaffe7b7fdefe5885c819c8bc64d2e0bc3ef0e Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Mon, 26 Oct 2026 13:40:03 -0500 Subject: [PATCH 11/23] #2641: address review coverage and menu scan cost --- .../tests/{ => it}/cascading_filter_values.rs | 35 +++++++++++++++++-- crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/grid.rs | 6 ++-- .../tests/{ => it}/cascading_filter_values.rs | 3 +- crates/ui-egui/tests/it/main.rs | 1 + 5 files changed, 40 insertions(+), 6 deletions(-) rename crates/engine/tests/{ => it}/cascading_filter_values.rs (84%) rename crates/ui-egui/tests/{ => it}/cascading_filter_values.rs (98%) diff --git a/crates/engine/tests/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs similarity index 84% rename from crates/engine/tests/cascading_filter_values.rs rename to crates/engine/tests/it/cascading_filter_values.rs index afaf720282..5c39131d21 100644 --- a/crates/engine/tests/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -33,7 +33,7 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { 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}"); - // Statistics still come from the whole range even with another column filtered. + // 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"); @@ -45,6 +45,36 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { } } +#[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(); @@ -176,7 +206,8 @@ fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { 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"], ["East", "Last East"], ["West", "Last West"]]})).unwrap(); + 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)]); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4c91e58ac4..23f03a14f0 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/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 2f9a1ba6eb..1cdf58390c 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -3326,7 +3326,6 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) } } 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)); @@ -3352,7 +3351,10 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) } 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: Vec<(String, bool)> = ui + .ctx() + .data_mut(|d| d.get_temp::>(key)) + .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 field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY)); diff --git a/crates/ui-egui/tests/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs similarity index 98% rename from crates/ui-egui/tests/cascading_filter_values.rs rename to crates/ui-egui/tests/it/cascading_filter_values.rs index c217d35fc4..0b4e2259bc 100644 --- a/crates/ui-egui/tests/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -1,5 +1,4 @@ -#[path = "common/mod.rs"] -mod common; +use crate::common; use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 53625015ed..b8fa0baa11 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -11,6 +11,7 @@ mod advanced_filter; mod argument_names; mod autosave_persist; mod borders; +mod cascading_filter_values; mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; From 91e6a41a63be4e67a12bfd22a8bbeff7b9ce1446 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 28 Oct 2026 23:50:52 -0500 Subject: [PATCH 12/23] #2641: Discard old filter-menu state when switching columns Clear the previous column checkbox, search and button caches after the grid interaction changes the open menu. Keep the new menu state intact. The real UI regression fails on the prior production code and passes with the fix. Validation: filter15, popup6, strict UI all-target Clippy, fmt and WASM pass. Aggregate CI rerun retains only the two unchanged Windows baseline diagnostics. Small CodeRabbit finding validated and fixed directly after the three medium merge-resolution reviews. --- crates/ui-egui/src/grid/show.rs | 9 ++++ .../tests/it/cascading_filter_values.rs | 54 ++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 193d8dc734..ba9b99881d 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -337,6 +337,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); } + if previous_popups.0 != app.grid.filter_menu + && let Some((col, _, _)) = previous_popups.0 + { + ui.ctx().data_mut(|d| { + d.remove::>(egui::Id::unique(("filter_sel", col))); + d.remove::(egui::Id::unique(("filter_search", col))); + d.remove::>(egui::Id::unique(("filter_buttons", col))); + }); + } 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 index 0b4e2259bc..8b6a50341b 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -1,8 +1,10 @@ use crate::common; -use egui::{Event, Key, Modifiers}; +use egui::{Event, Key, Modifiers, PointerButton}; use egui_kittest::kittest::Queryable; use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_ui_egui::grid; use serde_json::json; fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { @@ -12,6 +14,56 @@ fn key(h: &mut common::Harness, key: Key, modifiers: 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 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_eq!(h.ctx.data(|d| d.get_temp::(egui::Id::unique(("filter_search", 1u32)))).as_deref(), Some("")); + + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + h.ctx.data(|d| { + assert!(d.get_temp::>(egui::Id::unique(("filter_sel", 1u32))).is_none(), "old checkbox edits must be discarded"); + assert!(d.get_temp::(egui::Id::unique(("filter_search", 1u32))).is_none(), "old search must be discarded"); + assert!(d.get_temp::>(egui::Id::unique(("filter_buttons", 1u32))).is_none(), "old button focus IDs must be discarded"); + }); + assert!(h.query_by_label("East").is_some(), "the new column's choices must remain available"); + 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 dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() { for table in [false, true] { From 0de56624d5dd4445d037c5816d25855a53bfd733 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Sun, 1 Nov 2026 01:05:32 -0500 Subject: [PATCH 13/23] 2641: cover header-only filter tables and manual visibility Exercise the real engine and header-button popup with a genuine header-only table. Verify that its installed AutoFilter offers neither header values nor a phantom blank row, and that the popup dismisses normally. Strengthen the existing manual-hide case to check exact values and selection state. Production filter matching, selection merging and popup caching are unchanged. Ten focused engine, eighteen filter UI and six popup tests, formatting and strict changed-target Clippy pass. Required aggregate CI retains the unchanged baseline Windows CLI lint failure; exact-new-head hosted CI remains pending. --- .../tests/it/cascading_filter_values.rs | 19 ++++++++++++++++++- .../tests/it/cascading_filter_values.rs | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 928f3eb0e2..c6d7f4d1e4 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -135,11 +135,28 @@ fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { 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).len(), 3); + 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(); diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs index 6357cfb7b0..ed33019848 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -26,6 +26,25 @@ fn click_filter(h: &mut common::Harness, cell: &str) { 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.ctx.data(|d| d.get_temp::>(egui::Id::unique(("filter_sel", 1u32)))), 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(); From 6c447a808215d0a040206848fe8bfe34d34c0146 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Sun, 1 Nov 2026 22:58:40 -0600 Subject: [PATCH 14/23] #2641: Clarify AutoFilter documentation scope Move the AutoFilter population discussion into its own section before Keyboard while leaving Shortcut audit under Keyboard. State explicitly that separate table dropdowns outside the active sheet AutoFilter columns remain empty, retaining the separate #2506 activation/roundtrip scope. Update the existing feature history entry. Addresses both outside-diff comments in CodeRabbit5732175733. Documentation only; implementation, tests, dependencies, credits and workflows unchanged. Formatting/parity checks pass. Required local CI hits only the unchanged Windows CLI lint; actual preceding c9 Ubuntu run passed all10 gates and lock verification. New-head hosted CI remains required. Small review findings fixed directly without new agents or tests. --- docs/ui-parity.md | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bed023d49c..f3216bb4dd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -75,6 +75,24 @@ 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. + +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 | @@ -93,23 +111,6 @@ this logic, with one undo step. | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | -### 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. - -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 used by the current table dropdown without changing criteria, -row visibility or the XLSX representation. - ### Shortcut audit (#110) Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and Mac tables, @@ -214,7 +215,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 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) | +| 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 | From c01eb6cd2a0a4fb9af0652a6d284f74e903ae237 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 22:24:34 -0600 Subject: [PATCH 15/23] #2641: Preserve active filter choices and index Values matching Root verified both findings, red/green regression, matcher semantics and all five quality axes; see review-4476435045-decisions.md. No additional delegate for small confirmed fixes. Fourteen scoped steps pass on the recorded tree, including engine/UI suites, strict Clippy and standalone gates. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted validation pending. --- crates/engine/src/cmd/data/filter.rs | 99 ++++++++++--------- .../tests/it/cascading_filter_values.rs | 92 +++++++++++++++-- docs/ui-parity.md | 9 +- 3 files changed, 139 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index c76701ad1d..18688e7412 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,14 +182,11 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } /// Statistics use the original range, regardless of the other active criteria. -fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> std::collections::HashMap, f64)> { +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 Some(*off) == excluded_offset { - continue; - } if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { let Some(col) = r.start.col.checked_add(*off) else { continue }; let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); @@ -208,29 +206,46 @@ fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> st col_stats } -/// Evaluate criteria directly, without conflating manual visibility with filter results. -fn filter_row_matches( - wb: &Workbook, - sh: &Sheet, - af: &AutoFilter, - row: u32, - col_stats: &std::collections::HashMap, f64)>, - excluded_offset: Option, -) -> bool { - for (i, (off, crit)) in af.criteria.iter().enumerate() { - if Some(*off) == excluded_offset { - continue; - } - let Some(col) = af.range.start.col.checked_add(*off) else { continue }; +/// 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 = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { + 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 { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + 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 } => { @@ -243,14 +258,14 @@ fn filter_row_matches( None => x, } } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { + 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(), col_stats.get(&i)) { + FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) { (Some(n), Some((_, avg))) => { if *above { n > *avg @@ -260,16 +275,12 @@ fn filter_row_matches( } _ => 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, + 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, - }; - if !ok { - return false; } } - true } /// Hides rows of the autofilter range that fail any criterion. @@ -277,12 +288,11 @@ 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 }; let r = af.range; - let col_stats = filter_stats(sh, &af, None); + 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, !filter_row_matches(wb, sh, &af, row, &col_stats, None) || (has_icon && sh.is_row_hidden(row)))) - .collect(); + 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 { @@ -345,27 +355,18 @@ fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bo return vec![]; } let off = col - af.range.start.col; - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); - let col_stats = if eligible_only { filter_stats(sh, af, Some(off)) } else { Default::default() }; + 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.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)) { - if eligible_only && !filter_row_matches(wb, sh, af, row, &col_stats, Some(off)) { + 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); } diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 45346b39a1..345c4f4da5 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -63,14 +63,14 @@ fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() { #[test] fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { - for (criterion, expected) in [ - (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"]), - (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"]), - (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"]), - (json!({"top": {"count": 2}}), vec!["high", "upper"]), - (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"]), - (json!({"aboveAverage": true}), vec!["high"]), - (json!({"aboveAverage": false}), vec!["low", "mid", "upper"]), + 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(); @@ -93,8 +93,8 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { assert_eq!(actual, expected, "{criterion}, with the current column filtered"); assert_eq!( filter_values(&s.doc().unwrap().wb, 0, 1), - vec![("20".into(), true)], - "the numeric column's own criterion must be excluded: {criterion}" + vec![("20".into(), mid_checked)], + "the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}" ); } } @@ -220,6 +220,7 @@ fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() 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) })]; @@ -283,3 +284,74 @@ fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { 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 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); + assert_eq!(choices.len(), 5_002); + assert!(choices.contains(&("unicode selected".into(), true))); + assert!(choices.contains(&("blank row".into(), true))); + assert!(!choices.iter().any(|(label, _)| label == "unicode excluded")); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c94ccb7550..eb86b356e7 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-03 · **Change:** minor (cascading AutoFilter choices and pending popup selections per document window; form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -14,6 +14,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Element | Excel | GridCraft | Status | |---|---|---|---| +| 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-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | @@ -86,6 +87,10 @@ this logic, with one undo step. 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. +Checkbox state uses the row matcher for the active criterion, including raw and formatted +Values matches, custom comparisons, numeric thresholds and 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 @@ -287,7 +292,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-31 | minor | Esc in a File-page text field leaves the field and cancels editing; the next Esc returns to the sheet (#3035) | | 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-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; document pending counts, date grouping and table roundtrip integration; retain slicer row filtering when its criterion is outside the sheet filter columns | +| 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 | 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 | From 1baac9125c76b349ef9316f6e8b43d6c13171a02 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 22:54:44 -0600 Subject: [PATCH 16/23] #2641: Put the parity revision entry in its history table Move the existing Nov4 row intact out of Window and chrome. All other lines and all production/test/dependency trees are identical to the preceding head. Structural and fmt checks pass; required aggregate CI still stops only at the unchanged Windows CLI lint. Runtime suites are not repeated for this documentation-only move. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index eb86b356e7..568fd86479 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -14,7 +14,6 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Element | Excel | GridCraft | Status | |---|---|---|---| -| 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-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | @@ -266,6 +265,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 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 | Highlight the active cell's row: a global preference that tints the whole row, off by default | | 2026-11-03 | minor | The formula bar's bottom edge is a resize handle: dragging it sets the bar's height in whole lines, up to half the window, and dragging it to one line collapses it; expanding (the chevron, Ctrl+Shift+U) returns to the dragged height, which is kept with the UI preferences. `view.expandFormulaBar {lines}` sets it (#1246) | From f0de6913d1acbd9e4f8c96f7a5e918a282fe1013 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 23:01:12 -0600 Subject: [PATCH 17/23] #2641: Assert every large Values filter choice Strengthen the existing fixture to check the complete sorted list and checkbox states. Production, docs, manifests and lock unchanged. Engine integration113, strict engine Clippy, fmt and diff checks pass. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later aggregate stages skipped. --- crates/engine/tests/it/cascading_filter_values.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 345c4f4da5..125df8b5c6 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -350,8 +350,7 @@ fn large_values_criteria_preserve_ascii_case_and_blank_matching() { criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], }); let choices = filter_values(&s.doc().unwrap().wb, 0, 1); - assert_eq!(choices.len(), 5_002); - assert!(choices.contains(&("unicode selected".into(), true))); - assert!(choices.contains(&("blank row".into(), true))); - assert!(!choices.iter().any(|(label, _)| label == "unicode excluded")); + 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); } From 19b8009d2a45b1b96d00537f1ccea928d144f0f0 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Tue, 10 Nov 2026 08:04:37 -0600 Subject: [PATCH 18/23] 2641: preserve filter choices across colors and window actions Keep a duplicate value checked when any eligible row matches the current criterion. Stop processing outgoing popup state when a form button switches the active window during grid interaction. Add regressions for fill/font color duplicates, other-column exclusion, unchanged Apply, and a real button press preserving another window's search and checkbox edits. --- crates/engine/src/cmd/data/filter.rs | 3 +- .../tests/it/cascading_filter_values.rs | 39 +++++++++++++ crates/ui-egui/src/grid/show.rs | 5 ++ .../tests/it/cascading_filter_values.rs | 56 +++++++++++++++++++ docs/ui-parity.md | 8 ++- 5 files changed, 107 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index a94c0efcae..b9d794b56d 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -368,7 +368,8 @@ fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bo let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; 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/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 125df8b5c6..afd72ef00b 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -233,6 +233,45 @@ fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() ); } +#[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] { diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 178039abe7..13aed13989 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,10 @@ 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(); diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs index ba7bc0abff..da6cc24d35 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -4,6 +4,7 @@ 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; @@ -134,6 +135,61 @@ fn switching_filter_columns_keeps_another_windows_pending_choices() { 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] { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1aeb561b42..e40d721fff 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-05 · **Change:** minor (preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (retain duplicate color-filter matches and pending popup edits across form-button window switches; 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: AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -87,8 +87,9 @@ describes additive column filters and restricting other dropdowns to the filtere 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. Checkbox state uses the row matcher for the active criterion, including raw and formatted -Values matches, custom comparisons, numeric thresholds and colors. Hidden choices retain -that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +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 @@ -290,6 +291,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 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 | From 2a506bfc851c6f0821e84be7c7d5acdab5ce722a Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 09:04:00 +0000 Subject: [PATCH 19/23] model::paper: one paper-size table for print layout and XLSX Paper names and sizes now live in one table, `gridcraft_model::paper` (`canonical`, `size_pt`, `for_size`). The engine's `known_paper` and the XLSX writer's alias list read it instead of keeping their own copies. - Page Setup and `pageLayout.size` store a known paper under its table name (`11x17` -> `Tabloid`, `b5-jis` -> `B5`), so every file format finds it. - XLSX paper id 34 (ECMA-376 "B5 envelope, 176 x 250 mm", the ISO B5 size) reads as `B5 (ISO)`; `B5 (ISO)` now saves with paperSize 34 instead of none. `Envelope B5` is still accepted as an alias. - Statement, Envelope #10 and Envelope DL print on their own size. - `PrintSettings::paper` documents an empty name as "the file stated no paper": layout falls back to Letter and XLSX writes no paperSize. New sheets still default to Letter. --- crates/engine/src/cmd/print.rs | 7 +- crates/engine/src/cmd/print/layout.rs | 39 +--------- crates/engine/src/cmd/print/tests.rs | 28 +++++++ crates/engine/src/cmd/view.rs | 4 +- crates/model/src/features/print.rs | 5 +- crates/model/src/lib.rs | 1 + crates/model/src/paper.rs | 108 ++++++++++++++++++++++++++ crates/xlsx/src/tables.rs | 26 ++----- crates/xlsx/src/tests/roundtrip.rs | 19 +++++ docs/architecture.md | 5 +- docs/file-format-parity.md | 3 +- 11 files changed, 181 insertions(+), 64 deletions(-) create mode 100644 crates/model/src/paper.rs diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index b3ce40d583..a76f45c5e8 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -39,7 +39,7 @@ type PicCache = std::collections::HashMap<(usize, usize), Option<(Vec, u32, 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::draw_objects; #[cfg(test)] use text::{center_across_width, wrap_lines}; @@ -258,8 +258,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 0f484f8755..3c21ed1154 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 3230604702..ee22e14e20 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -631,6 +631,34 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } +/// An empty paper name means the file stated none; 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 Excel names now print on their own size. + s.execute("pageLayout.pageSetup", json!({"paper": "Envelope DL"})).unwrap(); + assert_eq!(paper_size("Statement"), (396.0, 612.0)); + // 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(); diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 3631d0e561..d6d56b0509 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -296,7 +296,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/model/src/features/print.rs b/crates/model/src/features/print.rs index 694c2ac6da..049ac454d0 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`]), or empty when the file + /// stated none: the printer's or locale's paper then, which an ODF file leaves to the + /// application. 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 35cfa315f8..65f2e819c7 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..b3068e6aab --- /dev/null +++ b/crates/model/src/paper.rs @@ -0,0 +1,108 @@ +//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats +//! (XLSX paper ids, ODF 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: as it stands, else turned. +pub fn for_size(width: f32, height: f32) -> Option<&'static str> { + let near = |a: f32, b: f32| (a - b).abs() < 5.67; + let find = |w: f32, h: f32| PAPERS.iter().find(|(_, pw, ph)| near(*pw, w) && near(*ph, h)).map(|(n, _, _)| *n); + find(width, height).or_else(|| find(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)")); + } +} diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index 3cfd84c2dc..2ad41e9d4f 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 diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 4eb6c3cfe2..4bcb39a041 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1421,6 +1421,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 (the file stated none) 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 68639541ea..df3e2ac134 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (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-11 · **Change:** minor (paper names and sizes in one table, `model::paper`; 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 | @@ -236,6 +236,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| +| 2026-11-11 | 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 the file stated none | | 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 | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2660dde02..981ddd3fa5 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-03 · **Change:** minor (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-11 · **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 an empty paper name, a file that stated none, writes no `paperSize`; 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** @@ -158,6 +158,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | 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` | | 2026-11-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) | | 2026-11-03 | minor | XLSX `` (Remove personal information from file properties on save) is read and written back, and while it is on GridCraft saves no author (`dc:creator`) and no company, as Excel leaves them empty (#3089, file part) | From f21dc313dbe38bbf5b6530563501f98362c5de67 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 10:28:45 +0000 Subject: [PATCH 20/23] model::paper: nearest-size match, new papers documented and tested - for_size picks the nearest paper within 2 mm (as it stands, else turned) instead of the first in table order: Letter and Japanese Envelope Kaku #3 are less than 4 mm apart. - Page Setup and Size list Statement, Envelope #10 and Envelope DL in their params docs; a test checks both commands store and print them. - Paper docs are format-neutral. --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/cmd/print/tests.rs | 20 +++++++++++++--- crates/engine/src/cmd/view.rs | 2 +- crates/model/src/features/print.rs | 5 ++-- crates/model/src/paper.rs | 35 ++++++++++++++++++++++++---- docs/architecture.md | 2 +- docs/file-format-parity.md | 4 ++-- 7 files changed, 54 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index a76f45c5e8..6e3d888e45 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -78,7 +78,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 ), diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index ee22e14e20..6457002d1b 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -652,9 +652,23 @@ fn paper_size_commands_store_the_table_name() { 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 Excel names now print on their own size. - s.execute("pageLayout.pageSetup", json!({"paper": "Envelope DL"})).unwrap(); - assert_eq!(paper_size("Statement"), (396.0, 612.0)); + // 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"); } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index d6d56b0509..b01c8b71a8 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 ), diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 049ac454d0..833588c734 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -12,9 +12,8 @@ pub enum Orientation { pub struct PrintSettings { pub orientation: Orientation, /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]), or empty when the file - /// stated none: the printer's or locale's paper then, which an ODF file leaves to the - /// application. Print layout falls back to Letter and XLSX writes no `paperSize`. New sheets - /// default to Letter. + /// stated none: the printer's or locale's paper then. 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/paper.rs b/crates/model/src/paper.rs index b3068e6aab..546c1d2577 100644 --- a/crates/model/src/paper.rs +++ b/crates/model/src/paper.rs @@ -1,5 +1,5 @@ //! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats -//! (XLSX paper ids, ODF page sizes) and print layout all read this one table. +//! (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 @@ -74,11 +74,22 @@ pub fn size_pt(name: &str) -> Option<(f32, f32)> { PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h)) } -/// The paper of a page `width` × `height` points, within 2 mm: as it stands, else turned. +/// 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. pub fn for_size(width: f32, height: f32) -> Option<&'static str> { - let near = |a: f32, b: f32| (a - b).abs() < 5.67; - let find = |w: f32, h: f32| PAPERS.iter().find(|(_, pw, ph)| near(*pw, w) && near(*ph, h)).map(|(n, _, _)| *n); - find(width, height).or_else(|| find(height, width)) + 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)] @@ -105,4 +116,18 @@ mod tests { } 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/docs/architecture.md b/docs/architecture.md index df3e2ac134..236b72238d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -236,7 +236,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| -| 2026-11-11 | 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 the file stated none | +| 2026-11-11 | 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 the file stated none; `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | | 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 | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 981ddd3fa5..c3d87732fc 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-11 · **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 an empty paper name, a file that stated none, writes no `paperSize`; 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-11 · **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 an empty paper name, a file that stated none, writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; 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** @@ -158,7 +158,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-11-11 | 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` | +| 2026-11-11 | 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-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) | | 2026-11-03 | minor | XLSX `` (Remove personal information from file properties on save) is read and written back, and while it is on GridCraft saves no author (`dc:creator`) and no company, as Excel leaves them empty (#3089, file part) | From 8cb34cd3120c2e98e47f7ebdea9fe0acfe0507c1 Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 08:52:38 +0100 Subject: [PATCH 21/23] model::paper: say what an empty paper means today; every table paper keeps an XLSX id Review round 1. - PrintSettings::paper and the docs said an empty paper is "a file that stated none", but no reader produces it yet. They now say empty means no paper is stated, which a reader may set. - for_size documents that it names the page as it stands (17x11 in is Ledger), so a caller that also records landscape passes the size upright. - xlsx: a test that every paper in model::paper::PAPERS saves with an id and reads back as itself, so the two tables cannot drift. B6 (ISO) is the one exception (ECMA-376 has no upright ISO B6 id). --- crates/engine/src/cmd/print/tests.rs | 2 +- crates/model/src/features/print.rs | 7 ++++--- crates/model/src/paper.rs | 4 ++++ crates/xlsx/src/tables.rs | 14 ++++++++++++++ crates/xlsx/src/tests/roundtrip.rs | 2 +- docs/architecture.md | 2 +- docs/file-format-parity.md | 2 +- 7 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index c056a23f9e..2e198bd25f 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -631,7 +631,7 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } -/// An empty paper name means the file stated none; it prints on Letter. +/// 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(); diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 833588c734..241b4b40e4 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -11,9 +11,10 @@ pub enum Orientation { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrintSettings { pub orientation: Orientation, - /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]), or empty when the file - /// stated none: the printer's or locale's paper then. Print layout falls back to Letter and - /// XLSX writes no `paperSize`. New sheets default to Letter. + /// 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/paper.rs b/crates/model/src/paper.rs index 546c1d2577..2db5c28e84 100644 --- a/crates/model/src/paper.rs +++ b/crates/model/src/paper.rs @@ -77,6 +77,10 @@ pub fn size_pt(name: &str) -> Option<(f32, f32)> { /// 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| { diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index 363ab9cedf..5427f31e01 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -323,6 +323,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 928ba0a597..668d154479 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1681,7 +1681,7 @@ fn japanese_paper_sizes_round_trip() { /// 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 (the file stated none) writes no `paperSize`, so the reader's own paper applies. +/// 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)")] { diff --git a/docs/architecture.md b/docs/architecture.md index 341333718c..bbc7a05cae 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -242,7 +242,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 the file stated none; `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | +| 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-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 | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 34b114bff7..15e10fb98b 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-13 · **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 an empty paper name, a file that stated none, writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; 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-13 · **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 an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; 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** From a1b96711b6ba6328d037bc71b2d5b2739725ce50 Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 23 Nov 2026 10:36:04 +0100 Subject: [PATCH 22/23] PR4139: verify imported ISO B5 print dimensions --- crates/engine/src/cmd/print/tests.rs | 35 ++++++++++++++++++++++++++++ docs/file-format-parity.md | 3 ++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 6ef29e6c05..af06027c62 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -1264,3 +1264,38 @@ 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(); + if part.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(part.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/docs/file-format-parity.md b/docs/file-format-parity.md index 719b55abca..df5ad00e0f 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-13 · **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 an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; 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: 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** @@ -163,6 +163,7 @@ 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-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) | From 0f36a7aee31703dc70f32ea129055cc3ee13dfdb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:34:27 +0700 Subject: [PATCH 23/23] print tests: read the zip entry name through main's fallible ZipFile::name() --- crates/engine/src/cmd/print/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 71f0a29fc9..918a94c2c5 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -1307,13 +1307,14 @@ fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() { let mut part = input.by_index(i).unwrap(); let mut data = Vec::new(); part.read_to_end(&mut data).unwrap(); - if part.name() == "xl/worksheets/sheet1.xml" { + 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(part.name(), zip::write::SimpleFileOptions::default()).unwrap(); + output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); output.write_all(&data).unwrap(); } let bytes = output.finish().unwrap().into_inner();