Merge branch 'main' into gc-subtotal-filtered-rows-roundtrip

This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 19:41:41 +01:00
commit 5fbc21b2b3
97 files changed
+5688 -441

No files matched your search

+11 -1
View File
@@ -2,9 +2,10 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
This page is the summary. The detail is in:
@@ -151,6 +152,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
@@ -189,6 +191,9 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
@@ -301,6 +306,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
| 2026-10-31 | minor | Progress log: Function Library |
| 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles |
| 2026-10-26 | minor | Progress log: Excel open check |
| 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets |
| 2026-10-26 | minor | Progress log: Arabic PDF text |
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
@@ -320,13 +326,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save |
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
+8 -1
View File
@@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect()
}
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
/// in another workbook, a data connection or the Data Model).
fn pivot_count(s: &Sheet) -> usize {
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
s.pivots.len() + kept
}
fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) {
if a != b {
d.push(|| format!("{sheet}: {a} → {b}"));
@@ -154,7 +161,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec<Categor
}
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+3
View File
@@ -121,3 +121,6 @@ sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.alosslessdev]
real_name = "Francisco Herrera"
+1 -1
View File
@@ -23,9 +23,9 @@ mod sort;
mod tools;
mod validation;
pub use filter::filter_values;
pub(crate) use filter::{apply_filter, grow_autofilter};
use filter::{clear_filter, filter_by, reapply, toggle_filter};
pub use filter::{filter_selection, filter_values};
use grouping::{detail, group, outline_settings, show_levels, subtotal};
pub use sort::sort_context;
use sort::{quick_sort, sort};
+137 -77
View File
@@ -3,6 +3,7 @@ use super::{
AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param,
data_target, edit, json,
};
use std::collections::{HashMap, HashSet};
// ---------------------------------------------------------------- filter
@@ -269,19 +270,18 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) {
}
}
/// Hides rows of the autofilter range that fail any criterion.
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
let Some(sh) = wb.sheet(sheet) else { return };
let Some(af) = sh.autofilter.clone() else { return };
// An imported range can name rows past the grid; none of those exist to hide.
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
let mut hide = Vec::new();
/// Statistics use the original range within the grid, regardless of the other active criteria.
fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap<usize, (Option<f64>, f64)> {
let r = af.range;
// Precompute per-criterion top10 threshold and average once, not per row.
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
let mut col_stats = HashMap::new();
for (i, (off, c)) in af.criteria.iter().enumerate() {
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
let col = r.start.col + off;
let mut nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
let Some(col) = r.start.col.checked_add(*off) else { continue };
// Keep main's imported-range bound after extracting statistics from apply_filter.
let mut nums: Vec<f64> = (r.start.row.saturating_add(1)..=r.end.row.min(gridcraft_core::MAX_ROWS - 1))
.filter_map(|row| sh.value(CellRef::new(row, col)).as_f64())
.collect();
let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::<f64>() / nums.len() as f64 };
let thr = match c {
FilterCriterion::Top10 { bottom, percent, count } => {
@@ -295,59 +295,97 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
col_stats.insert(i, (thr, avg));
}
}
for row in r.start.row + 1..=r.end.row {
let mut visible = true;
for (i, (off, crit)) in af.criteria.iter().enumerate() {
let c = CellRef::new(row, r.start.col + off);
let v = sh.value(c);
let text = crate::display::cell_text(wb, sh, c);
let ok = match crit {
FilterCriterion::Values { values, blanks } => {
if filter_blank(&v) {
*blanks
} else {
values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display()))
}
}
FilterCriterion::Custom { a, b, and } => {
let x = custom_ok(&v, &text, &a.0, &a.1);
match b {
Some(b) => {
let y = custom_ok(&v, &text, &b.0, &b.1);
if *and { x && y } else { x || y }
}
None => x,
}
}
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) {
(Some(n), Some((thr, _))) => {
let thr = thr.unwrap_or(n);
if *bottom { n <= thr } else { n >= thr }
}
_ => false,
},
FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) {
(Some(n), Some((_, avg))) => {
if *above {
n > *avg
} else {
n < *avg
}
}
_ => false,
},
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
// Icons are not evaluated here: the row keeps its current visibility.
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
};
if !ok {
visible = false;
break;
}
}
hide.push((row, !visible));
col_stats
}
/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query.
struct FilterMatcher<'a> {
wb: &'a Workbook,
sh: &'a Sheet,
af: &'a AutoFilter,
stats: HashMap<usize, (Option<f64>, f64)>,
values: HashMap<usize, HashSet<String>>,
}
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<u32>) -> bool {
self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit))
}
fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool {
let Some(col) = self.af.range.start.col.checked_add(off) else { return true };
let c = CellRef::new(row, col);
let v = self.sh.value(c);
let text = crate::display::cell_text(self.wb, self.sh, c);
match crit {
FilterCriterion::Values { blanks, .. } => {
if filter_blank(&v) {
*blanks
} else {
self.values
.get(&i)
.is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase()))
}
}
FilterCriterion::Custom { a, b, and } => {
let x = custom_ok(&v, &text, &a.0, &a.1);
match b {
Some(b) => {
let y = custom_ok(&v, &text, &b.0, &b.1);
if *and { x && y } else { x || y }
}
None => x,
}
}
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) {
(Some(n), Some((thr, _))) => {
let thr = thr.unwrap_or(n);
if *bottom { n <= thr } else { n >= thr }
}
_ => false,
},
FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) {
(Some(n), Some((_, avg))) => {
if *above {
n > *avg
} else {
n < *avg
}
}
_ => false,
},
FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col,
FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col,
// Icon criteria are retained from files but cannot be evaluated yet.
FilterCriterion::Icon { .. } => true,
}
}
}
/// Hides rows of the autofilter range that fail any criterion.
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
let Some(sh) = wb.sheet(sheet) else { return };
let Some(af) = sh.autofilter.clone() else { return };
// An imported range can name rows past the grid; none of those exist to hide.
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
let matcher = FilterMatcher::new(wb, sh, &af);
// Reapplying a retained icon filter preserves visibility until icons can be evaluated.
let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. }));
let hide: Vec<_> =
(r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect();
let Some(shm) = wb.sheet_mut(sheet) else { return };
for (row, h) in hide {
if h {
@@ -382,30 +420,52 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
})
}
/// Distinct display values of a filter column (for the dropdown list).
/// Distinct display values from rows matching the other columns' criteria.
/// The current criterion only determines checkboxes, so its unchecked alternatives stay available.
pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> {
column_filter_values(wb, sheet, col, true)
}
/// Applies edited eligible choices to the whole column's checkbox state, retaining choices hidden by other filters.
pub fn filter_selection(wb: &Workbook, sheet: usize, col: u32, choices: &[(String, bool)]) -> Vec<(String, bool)> {
let mut edited = std::collections::BTreeMap::new();
for (value, on) in choices {
*edited.entry(value.to_ascii_lowercase()).or_insert(false) |= *on;
}
let mut selection = column_filter_values(wb, sheet, col, false);
for (value, on) in &mut selection {
if let Some(checked) = edited.get(&value.to_ascii_lowercase()) {
*on = *checked;
}
}
selection
}
fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bool) -> Vec<(String, bool)> {
let Some(sh) = wb.sheet(sheet) else { return vec![] };
let Some(af) = &sh.autofilter else { return vec![] };
let off = col.saturating_sub(af.range.start.col);
let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c);
if col < af.range.start.col || col > af.range.end.col {
return vec![];
}
let off = col - af.range.start.col;
let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off);
let matcher = FilterMatcher::new(wb, sh, af);
let mut seen = std::collections::BTreeMap::new();
for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) {
// Imported end rows cannot add choices beyond the grid either.
for row in
af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)).min(gridcraft_core::MAX_ROWS - 1)
{
if eligible_only && !matcher.row_matches(row, Some(off)) {
continue;
}
let c = CellRef::new(row, col);
let v = sh.value(c);
let blank = filter_blank(&v);
let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) };
let on = match selected {
Some(FilterCriterion::Values { values, blanks }) => {
if blank {
*blanks
} else {
values.iter().any(|x| x.eq_ignore_ascii_case(&t))
}
}
_ => true,
};
let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit));
let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) };
seen.entry((key, t)).or_insert(on);
// One choice can represent rows with different colors; keep any matching row checked.
*seen.entry((key, t)).or_insert(false) |= on;
}
let mut values: Vec<_> = seen.into_iter().collect();
values.sort_by(|((a, ta), _), ((b, tb), _)| {
+124 -18
View File
@@ -1,4 +1,5 @@
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
use gridcraft_model::Cell;
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
@@ -11,30 +12,85 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
}
.ok_or_else(|| bad("table.resize", "select a cell in a table"))?;
edit(s, |cx| {
let sheet = cx.sheet_mut(si)?;
let headers: Vec<String> = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect();
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
let wb = &cx.wb;
let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?;
let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?;
if r.start.row != t.range.start.row || !r.intersects(&t.range) {
return Err(EngineError::Other(
"The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(),
));
}
let mut cols = Vec::new();
for (i, h) in headers.iter().enumerate() {
let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() };
let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned();
cols.push(existing.unwrap_or(TableColumn {
name,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
xml: None,
}));
// Like Excel, the new range can't take in another table, a merged area, a PivotTable or a
// multi-cell array formula (a spill is fine: it shows #SPILL! inside the table).
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
}
if sheet.merges.iter().any(|m| m.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap merged cells.".into()));
}
if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) {
return Err(EngineError::Other("A table can't overlap a PivotTable report.".into()));
}
if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
// Header text per new column (`None`: empty). Without a header row, a column that stays
// keeps its name.
let texts: Vec<Option<String>> = (r.start.col..=r.end.col)
.map(|c| {
if !t.header_row {
return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone());
}
let at = CellRef::new(r.start.row, c);
let v = sheet.value(at);
let text = match v.as_text() {
Some(x) => x.to_string(),
None => crate::display::value_text(wb, sheet, at),
};
(!text.trim().is_empty()).then_some(text)
})
.collect();
let names = resized_column_names(&texts);
let old = t.range;
let old_cols = t.columns.clone();
let header_row = t.header_row;
let mut cols = Vec::with_capacity(names.len());
for (c, name) in (r.start.col..=r.end.col).zip(&names) {
// A column that stays keeps its settings (totals, calculated formula): with a header
// row it's found by name, without one by position.
let existing = if header_row {
// A header that was normalized into a generated name keeps the settings of the
// column at its address, not of whichever column already has that name.
let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref());
if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) {
old_cols.get((c - old.start.col) as usize)
} else {
old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name))
}
} else if c >= old.start.col && c <= old.end.col {
old_cols.get((c - old.start.col) as usize)
} else {
None
};
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
});
}
let sheet = cx.sheet_mut(si)?;
if header_row {
// Headers hold constant text: a generated or de-duplicated name is written into its
// cell, so the header row and the column names never disagree.
for (c, col) in (r.start.col..=r.end.col).zip(&cols) {
let at = CellRef::new(r.start.row, c);
let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none());
if !constant_text {
let style = sheet.style_id(at);
sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() });
}
}
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
t.columns = cols;
t.range = r;
cx.structural = true;
@@ -42,6 +98,56 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Unique column names for a resized table, from each column's header text (`None` = empty), the
/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`,
/// compared without case), and an empty header continues a `ColumnN` neighbour on its left
/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free
/// `ColumnN`.
fn resized_column_names(texts: &[Option<String>]) -> Vec<String> {
use std::collections::{HashMap, HashSet};
let mut taken: HashSet<String> = HashSet::new();
let mut next_suffix: HashMap<String, u64> = HashMap::new();
// The lowest `ColumnN` not yet tried, so many empty headers stay linear.
let mut lowest = 1u64;
let mut names: Vec<String> = Vec::with_capacity(texts.len());
let dedupe = |base: &str, taken: &HashSet<String>, next_suffix: &mut HashMap<String, u64>| {
let k = next_suffix.entry(base.to_lowercase()).or_insert(2);
let mut n = base.to_string();
while taken.contains(&n.to_lowercase()) {
n = format!("{base}{k}");
*k = k.saturating_add(1);
}
n
};
for text in texts {
let name = match text {
Some(t) => dedupe(t, &taken, &mut next_suffix),
None => {
let left = names.last().and_then(|l| {
l.strip_prefix("Column")
.filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
.and_then(|d| d.parse::<u64>().ok())
});
match left {
Some(n) => {
let cand = format!("Column{}", n.saturating_add(1));
if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand }
}
None => {
while taken.contains(&format!("column{lowest}")) {
lowest = lowest.saturating_add(1);
}
format!("Column{lowest}")
}
}
}
};
taken.insert(name.to_lowercase());
names.push(name);
}
names
}
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
/// into a rectangle of billions of slots.
+214 -3
View File
@@ -553,7 +553,12 @@ fn format_cells(s: &mut Session, p: &Json) -> Result<Json> {
{
*st = new;
}
})
})?;
// A number format set here widens columns as the ribbon's do (observed: Excel 16.0).
if patch.get("num_fmt").is_some() {
widen_for_numbers(s, p)?;
}
ok()
}
/// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the
@@ -732,9 +737,95 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
set_fmt(s, p, &code)
}
/// How many stored cells [`widen_for_numbers`] looks at in one command.
const MAX_WIDEN_CELLS: usize = 1_000_000;
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
let nf = NumFmt::new(code);
apply_style(s, p, |st| st.num_fmt = nf.clone())
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
widen_for_numbers(s, p)
}
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or
/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit,
/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
/// and columns never narrow.
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
if sh.show_formulas {
return Ok(Json::Null);
}
let targets: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&used)).collect();
// Merged areas over the targets as sorted row intervals per column, so each cell is checked
// with a binary search rather than a scan of every merge.
let mut merged: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
for m in sh.merges.iter().filter(|m| !m.is_single()) {
for x in targets.iter().filter_map(|r| m.intersection(r)) {
for col in x.start.col..=x.end.col {
merged.entry(col).or_default().push((m.start.row, m.end.row));
}
}
}
for v in merged.values_mut() {
v.sort_unstable();
v.dedup();
}
let in_merge = |c: CellRef| {
merged.get(&c.col).is_some_and(|v| {
let i = v.partition_point(|&(r0, _)| r0 <= c.row);
i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1)
})
};
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
// The stored cells looked at are capped, not the area: a sparse target as tall as the sheet
// still widens for the numbers it holds. Spilled values count as the grid shows them.
let mut budget = MAX_WIDEN_CELLS;
for r in &targets {
let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c));
for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) {
if budget == 0 {
break;
}
budget -= 1;
if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_)))
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|| in_merge(c)
{
continue;
}
let id = sh.style_id(c);
let st = cx.wb.styles.get(id);
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
continue;
}
let text = crate::display::cell_text(&cx.wb, sh, c);
let exact = measured.len() < EXACT_TEXT_WIDTHS;
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
Some(m) => m(t, &st.font, exact),
None => approx_text_width(t, st.font.size, st.font.bold),
});
let w = w + 6.0 + st.align.indent as f32 * 9.0;
let e = need.entry(c.col).or_insert(0.0);
*e = e.max(w);
}
}
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
let sh = cx.sheet_mut(sheet)?;
for (c, w) in widen {
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
}
Ok(Json::Null)
})
}
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
@@ -819,8 +910,8 @@ mod sizes;
use cell_styles::cell_style;
pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style};
use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
pub use sizes::{approx_text_width, chars_to_points};
use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
#[cfg(test)]
mod tests {
@@ -856,6 +947,112 @@ mod tests {
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
}
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
let sh = s.active().unwrap().wb.active().unwrap();
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
}
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
#[test]
fn increase_decimal_widens_a_column_nobody_sized() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
let (w, custom) = col(&s, 0);
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
assert_eq!(text, "3.141592650");
assert!(w > default, "the column widens for {text}: {w} vs {default}");
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
assert!(!custom, "it isn't a width set by hand, so it can widen again");
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
let wide = col(&s, 0).0;
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
}
#[test]
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
for a in ["A1", "B1", "D1"] {
s.execute("home.comma", json!({"range": a})).unwrap();
}
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
let (default, _) = col(&s, 4);
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
assert!(!col(&s, 0).1);
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
let fitted = col(&s, 0).0;
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
}
fn book() -> (crate::Session, f32) {
let mut s = crate::Session::new();
s.new_workbook();
let (default, _) = col(&s, 0);
(s, default)
}
/// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area.
#[test]
fn a_sparse_target_widens_for_the_numbers_it_holds() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap();
s.execute("home.comma", json!({"range": "A:E"})).unwrap();
assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down");
}
/// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1.
#[test]
fn a_spilled_number_widens_its_column() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap();
s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap();
assert!(col(&s, 7).0 > default, "H widens for the value it shows");
}
/// A merged area keeps its columns; the cell beside it widens.
#[test]
fn a_merged_area_keeps_its_columns() {
let (mut s, default) = book();
s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap();
s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap();
s.execute("home.comma", json!({"range": "J1:L1"})).unwrap();
assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K");
assert!(col(&s, 11).0 > default, "L does");
}
#[test]
fn format_cells_widens_for_a_number_format_only() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap();
assert_eq!(col(&s, 1).0, default, "no number format, no widening");
s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap();
assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does");
assert!(!col(&s, 0).1);
}
#[test]
fn format_cells_takes_the_documented_keys() {
let mut s = crate::Session::new();
@@ -870,6 +1067,20 @@ mod tests {
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
}
/// A table draws its header row bold; AutoFit measures that, not the cell's own plain font.
#[test]
fn autofit_measures_a_table_header_in_the_table_style_font() {
let mut s = crate::Session::new();
s.new_workbook();
let heading = "Quarterly Revenue by Region";
s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap();
s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap();
s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap();
let sh = s.active().unwrap().wb.active().unwrap();
let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1));
assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}");
}
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
#[test]
fn format_cells_sets_outlined_letters() {
+12 -5
View File
@@ -107,6 +107,7 @@ pub(super) fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w as f32);
e.hidden = w == 0.0;
e.custom = true;
}
}
Ok(Json::Null)
@@ -187,14 +188,15 @@ fn arabic_em(c: char) -> Option<f32> {
/// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a
/// quick measure so a huge column doesn't lay out every value.
const EXACT_TEXT_WIDTHS: usize = 2_000;
pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000;
pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let (si, lines) = line_targets(s, p, false)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
let mut measured: std::collections::HashMap<StyleId, std::collections::HashMap<String, f32>> = Default::default();
// Keyed by style and boldness: a table's style can make a cell bold (its header row).
let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap<String, f32>> = Default::default();
let mut distinct = 0usize;
// Selected columns, then one pass over the populated cells (the store is row-oriented, so a
// scan per column would revisit every row for each selected column, empty or not).
@@ -228,22 +230,26 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
}
let id = sh.style_id(cell);
let st = cx.wb.styles.get(id);
// The font as the grid draws the cell: in a table, the table style's (a bold
// header row), not only the cell's own.
let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font);
let font = table_font.as_ref().unwrap_or(&st.font);
let text = crate::display::cell_text(&cx.wb, sh, cell);
for line in text.lines() {
let w = match &measure {
Some(m) => {
let known = measured.entry(id).or_default();
let known = measured.entry((id, font.bold)).or_default();
match known.get(line) {
Some(w) => *w,
None => {
let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS);
let w = m(line, font, distinct < EXACT_TEXT_WIDTHS);
known.insert(line.to_owned(), w);
distinct += 1;
w
}
}
}
None => approx_text_width(line, st.font.size, st.font.bold),
None => approx_text_width(line, font.size, font.bold),
};
let w = w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell);
let max = maxes.entry(cell.col).or_insert(0.0);
@@ -258,6 +264,7 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w.ceil());
e.hidden = false;
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
}
Ok(Json::Null)
})
+300 -2
View File
@@ -217,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Conditional Formatting",
["Home", "Styles"],
None,
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
has_doc,
add_cf
),
@@ -227,7 +227,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Manage Rules…",
["Home", "Styles", "Conditional Formatting"],
None,
"{delete?: index, moveUp?: index, moveDown?: index}",
"{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}",
has_doc,
manage_cf
),
@@ -496,4 +496,302 @@ mod tests {
s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap();
s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap();
}
#[test]
fn colour_scale_thresholds_are_clamped_to_the_percent_range() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "percent", "value": -5, "color": "#112233"},
{"type": "percentile", "value": 150, "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Percent(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percentile(100.0), Color::Rgb(0x445566)),
(CfValueKind::Max, Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_reject_empty_formulas_and_unknown_types() {
let mut s = Session::new();
s.new_workbook();
let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}});
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "formula", "value": " ", "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("formula"), "{err}");
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "median", "value": 50, "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown stop type `median`"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn colour_scale_rejects_a_stops_value_that_is_not_an_array() {
let mut s = Session::new();
s.new_workbook();
// `stops` present but misshapen used to fall back to the default scale instead of erroring.
for stops in [json!({}), json!(null), json!("min")] {
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("`stops` must be an array"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule");
}
#[test]
fn colour_scale_formulas_are_stored_verbatim() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "formula", "value": "=$Z$1", "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into()));
}
#[test]
fn manage_rules_rejects_a_non_index_edit() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] {
let err = s
.execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("`edit` must be a rule index"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1));
}
#[test]
fn manage_rules_rejects_an_edit_past_the_last_rule() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
let err = s
.execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 1"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
// On a 32-bit target this used to cast to zero and replace the rule at index 0.
let err =
s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 4294967296"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_names_itself_in_a_style_error() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
// A style shared by both commands must name the one that was called.
let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}});
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(!err.contains("home.conditionalFormat"), "{err}");
let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
}
#[test]
fn manage_rules_names_itself_in_a_stop_count_error() {
let mut s = Session::new();
s.new_workbook();
let err = s
.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
}
#[test]
fn a_formula_rule_needs_a_formula_that_parses() {
let mut s = Session::new();
s.new_workbook();
// An empty box used to create a rule that never applies.
let err =
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string();
assert!(err.contains("formula is empty"), "{err}");
// `=C1>` used to be written as `<formula>C1&gt;</formula>`, which Excel refuses to open.
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}}))
.unwrap_err()
.to_string();
assert!(err.contains("invalid"), "{err}");
assert!(err.contains("does not parse"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored");
}
#[test]
fn an_invalid_formula_on_edit_leaves_the_rule_alone() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2");
}
#[test]
fn a_given_stop_value_must_be_a_number() {
let mut s = Session::new();
s.new_workbook();
for ty in ["num", "percent", "percentile"] {
let err = s
.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": ty, "value": "5", "color": "#112233"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{ty}: {err}");
assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}");
}
// A refused scale stores nothing.
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn an_omitted_stop_value_is_zero() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "num", "color": "#112233"},
{"type": "percent", "color": "#445566"},
{"type": "percentile", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Number(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percent(0.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(0.0), Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "num", "value": 5, "color": "#445566"},
{"type": "percentile", "value": 90, "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(
stops,
vec![
(CfValueKind::Min, Color::Rgb(0x112233)),
(CfValueKind::Number(5.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(90.0), Color::Rgb(0x778899)),
]
);
s.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
{"type": "max", "color": "#DEFDEF"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
}
}
+146 -84
View File
@@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool {
/// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a
/// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than
/// dropped: dropped, it left a rule with an empty format that matches and shows nothing.
fn cf_style_json(st: &Json) -> Result<Json> {
fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"];
let err = |m: String| bad("home.conditionalFormat", m);
let err = |m: String| bad(cmd, m);
let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) };
let mut st = obj.clone();
if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) {
@@ -103,36 +103,40 @@ fn cf_style_json(st: &Json) -> Result<Json> {
fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> {
// Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1'
// only parses after several strips and would still be saved unparseable. (#1999 review)
if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() {
let parsed = formula.strip_prefix('=').unwrap_or(formula);
// A rule with no formula never applies; the dialog also keeps OK disabled for it.
if parsed.trim().is_empty() {
return Err(bad(cmd, format!("the {what} formula is empty")));
}
if gridcraft_formula::parse(parsed).is_err() {
return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file")));
}
Ok(())
}
fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
if let gridcraft_model::features::CfValueKind::Formula(f) = v {
check_cf_formula("home.conditionalFormat", what, f)?;
check_cf_formula(cmd, what, f)?;
}
Ok(())
}
fn check_cf_rule(rule: &CfRule) -> Result<()> {
const CMD: &str = "home.conditionalFormat";
fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
match rule {
CfRule::CellIs { a, b, .. } => {
check_cf_formula(CMD, "comparison value", a)?;
check_cf_formula(cmd, "comparison value", a)?;
if let Some(b) = b {
check_cf_formula(CMD, "second comparison value", b)?;
check_cf_formula(cmd, "second comparison value", b)?;
}
}
CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?,
CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?,
CfRule::DataBar { min, max, .. } => {
check_cf_value("data bar minimum", min)?;
check_cf_value("data bar maximum", max)?;
check_cf_value(cmd, "data bar minimum", min)?;
check_cf_value(cmd, "data bar maximum", max)?;
}
CfRule::ColorScale { stops } => {
for (kind, _) in stops {
check_cf_value("color scale threshold", kind)?;
check_cf_value(cmd, "color scale threshold", kind)?;
}
}
_ => {}
@@ -140,41 +144,53 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> {
Ok(())
}
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
};
fn cf_style(rule: &Json, cmd: &str) -> Result<Style> {
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
let style = Box::new(match rule.get("style") {
match rule.get("style") {
Some(st) if !st.is_null() => {
let st = cf_style_json(st)?;
let st = cf_style_json(st, cmd)?;
let base = serde_json::to_value(Style::default()).map_err(|e| EngineError::Other(e.to_string()))?;
serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad("home.conditionalFormat", e.to_string()))?
Ok(serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad(cmd, e.to_string()))?)
}
_ => preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText")),
});
let kind = g("type").unwrap_or_else(|| "cellIs".into());
let value_kind = |v: Option<&Json>, default: CfValueKind| -> CfValueKind {
match v {
Some(Json::Object(o)) => {
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
let val = o.get("value").and_then(Json::as_f64).unwrap_or(0.0);
match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
"percent" => CfValueKind::Percent(val),
"percentile" => CfValueKind::Percentile(val),
"formula" => CfValueKind::Formula(o.get("value").and_then(Json::as_str).unwrap_or("").into()),
_ => CfValueKind::Number(val),
}
}
_ => default,
_ => Ok(preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText"))),
}
}
fn cf_value_kind(v: Option<&Json>, default: CfValueKind, cmd: &str) -> Result<CfValueKind> {
let Some(Json::Object(o)) = v else { return Ok(default) };
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
// A value that is given must be a number: a string used to be read as 0 without a word.
// Only an omitted `value` defaults to zero.
let number = || -> Result<f64> {
match o.get("value") {
None => Ok(0.0),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("the `{t}` stop's `value` must be a number, not {v}"))),
}
};
let rule = match kind.as_str() {
Ok(match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
// The dialog clamps these to 0-100; engine callers get the same range.
"percent" => CfValueKind::Percent(number()?.clamp(0.0, 100.0)),
"percentile" => CfValueKind::Percentile(number()?.clamp(0.0, 100.0)),
"formula" => {
let f = o.get("value").and_then(Json::as_str).unwrap_or("");
if f.trim().is_empty() {
return Err(bad(cmd, "a formula stop needs a formula"));
}
// Stored exactly: the evaluator takes the formula as written.
CfValueKind::Formula(f.into())
}
"num" => CfValueKind::Number(number()?),
other => return Err(bad(cmd, format!("unknown stop type `{other}`"))),
})
}
fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
let style = Box::new(cf_style(rule, cmd)?);
let kind = g("type").unwrap_or_else(|| "cellIs".into());
match kind.as_str() {
"cellIs" => {
// Excel's file and VBA names (`lessThan`, …) are accepted too.
let op = match g("operator").as_deref().unwrap_or("greater") {
@@ -186,7 +202,7 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
"greater" | "greaterThan" => CfOperator::Greater,
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
other => return Err(bad(cmd, format!("unknown operator `{other}`"))),
};
let a = rule.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default();
let b = rule.get("value2").map(crate::cmd::edit::json_to_input);
@@ -201,59 +217,85 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
format!("\"{}\"", v.replace('"', "\"\""))
}
};
CfRule::CellIs { op, a: quote(a), b: b.map(quote), style }
Ok(CfRule::CellIs { op, a: quote(a), b: b.map(quote), style })
}
"expression" => CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style },
"containsText" => CfRule::ContainsText { text: g("text").unwrap_or_default(), style },
"notContainsText" => CfRule::NotContainsText { text: g("text").unwrap_or_default(), style },
"beginsWith" => CfRule::BeginsWith { text: g("text").unwrap_or_default(), style },
"endsWith" => CfRule::EndsWith { text: g("text").unwrap_or_default(), style },
"blanks" => CfRule::Blanks { style },
"noBlanks" => CfRule::NoBlanks { style },
"errors" => CfRule::Errors { style },
"noErrors" => CfRule::NoErrors { style },
"duplicate" => CfRule::Duplicate { style },
"unique" => CfRule::Unique { style },
"top10" => CfRule::Top10 {
"expression" => Ok(CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style }),
"containsText" => Ok(CfRule::ContainsText { text: g("text").unwrap_or_default(), style }),
"notContainsText" => Ok(CfRule::NotContainsText { text: g("text").unwrap_or_default(), style }),
"beginsWith" => Ok(CfRule::BeginsWith { text: g("text").unwrap_or_default(), style }),
"endsWith" => Ok(CfRule::EndsWith { text: g("text").unwrap_or_default(), style }),
"blanks" => Ok(CfRule::Blanks { style }),
"noBlanks" => Ok(CfRule::NoBlanks { style }),
"errors" => Ok(CfRule::Errors { style }),
"noErrors" => Ok(CfRule::NoErrors { style }),
"duplicate" => Ok(CfRule::Duplicate { style }),
"unique" => Ok(CfRule::Unique { style }),
"top10" => Ok(CfRule::Top10 {
bottom: rule.get("bottom").and_then(Json::as_bool).unwrap_or(false),
percent: rule.get("percent").and_then(Json::as_bool).unwrap_or(false),
rank: rule.get("rank").and_then(Json::as_u64).unwrap_or(10) as u32,
style,
},
"aboveAverage" => CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style },
"timePeriod" => CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style },
"colorScale" => {
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
let stops = match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
};
CfRule::ColorScale { stops }
}),
"aboveAverage" => {
Ok(CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style })
}
"dataBar" => CfRule::DataBar {
min: value_kind(rule.get("min"), CfValueKind::Min),
max: value_kind(rule.get("max"), CfValueKind::Max),
"timePeriod" => Ok(CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style }),
"colorScale" => {
let stops = if let Some(stops) = rule.get("stops") {
// A present but misshapen `stops` is a mistake, not a request for `colors`.
let list = stops.as_array().ok_or_else(|| bad(cmd, "`stops` must be an array"))?;
let mut out = Vec::with_capacity(list.len().min(3));
for stop in list {
let color = crate::cmd::format::color_param(stop.get("color")).ok_or_else(|| bad(cmd, "a colour-scale stop needs a colour"))?;
out.push((cf_value_kind(Some(stop), CfValueKind::Min, cmd)?, color));
}
if !(2..=3).contains(&out.len()) {
return Err(bad(cmd, "a colour scale needs two or three stops"));
}
out
} else {
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
}
};
Ok(CfRule::ColorScale { stops })
}
"dataBar" => Ok(CfRule::DataBar {
min: cf_value_kind(rule.get("min"), CfValueKind::Min, cmd)?,
max: cf_value_kind(rule.get("max"), CfValueKind::Max, cmd)?,
color: crate::cmd::format::color_param(rule.get("color")).unwrap_or(Color::rgb(0x63, 0x8E, 0xC6)),
gradient: rule.get("gradient").and_then(Json::as_bool).unwrap_or(true),
show_value: true,
},
"iconSet" => CfRule::IconSet {
}),
"iconSet" => Ok(CfRule::IconSet {
set: g("set").unwrap_or_else(|| "3TrafficLights1".into()),
thresholds: vec![],
reverse: rule.get("reverse").and_then(Json::as_bool).unwrap_or(false),
show_value: true,
},
other => return Err(bad("home.conditionalFormat", format!("unknown rule type `{other}`"))),
}),
other => Err(bad(cmd, format!("unknown rule type `{other}`"))),
}
}
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
};
check_cf_rule(&rule)?;
let rule = cf_rule(rule, "home.conditionalFormat")?;
check_cf_rule("home.conditionalFormat", &rule)?;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let priority = sh.cond_formats.iter().map(|c| c.priority).max().unwrap_or(0) + 1;
@@ -295,17 +337,33 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() && p.get("edit").is_none() {
let list: Vec<Json> = s
.doc()?
.wb
.sheet(sheet)
.map(|sh| {
sh.cond_formats.iter().map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule})).collect()
sh.cond_formats
.iter()
.map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule, "priority": c.priority}))
.collect()
})
.unwrap_or_default();
return Ok(json!({"rules": list}));
}
let edited = match (p.get("edit"), p.get("rule")) {
(None, _) => None,
(Some(_), None) => return Err(bad("home.manageRules", "missing `rule` for an edit")),
(Some(e), Some(rule)) => {
let i = e.as_u64().ok_or_else(|| bad("home.manageRules", "`edit` must be a rule index"))?;
// A number too large for `usize` on this target names no rule: casting it would
// wrap to a real index and replace that rule instead of reporting out of range.
let i = usize::try_from(i).map_err(|_| bad("home.manageRules", format!("no conditional format at index {i}")))?;
let rule = cf_rule(rule, "home.manageRules")?;
check_cf_rule("home.manageRules", &rule)?;
Some((i, rule))
}
};
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
// The count is taken again after each step: a delete shortens the list.
@@ -314,6 +372,10 @@ pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
{
sh.cond_formats.remove(i);
}
if let Some((i, rule)) = edited {
let cf = sh.cond_formats.get_mut(i).ok_or_else(|| bad("home.manageRules", format!("no conditional format at index {i}")))?;
cf.rule = rule;
}
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
&& i > 0
&& i < sh.cond_formats.len()
+5 -4
View File
@@ -57,7 +57,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
use layout::bands;
pub(crate) use layout::split_bands;
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
use layout::{known_paper, seg_size, segments};
use layout::{seg_size, segments};
use objects::{PicCache, draw_objects};
#[cfg(test)]
use text::{center_across_width, wrap_lines};
@@ -96,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Page Setup…",
["Page Layout", "Page Setup"],
None,
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings",
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings",
has_doc,
page_setup
),
@@ -309,8 +309,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
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);
+3 -36
View File
@@ -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
+78
View File
@@ -974,6 +974,48 @@ fn page_setup_paper_sizes_reach_the_pdf_page() {
assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err());
}
/// An empty paper name means no paper is stated; it prints on Letter.
#[test]
fn an_unstated_paper_prints_on_letter() {
let mut wb = gridcraft_model::Workbook::new();
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into()));
std::sync::Arc::make_mut(&mut wb.sheets[0]).print.paper = String::new();
let layouts = super::layout::layouts(&wb, &super::layout::PrintOptions::default());
let l = &layouts[0];
assert_eq!((l.page_w, l.page_h), (612.0, 792.0));
assert_eq!(paper_size(""), (612.0, 792.0));
}
/// Both commands that set the paper store a known one under its table name, so every file
/// format finds it.
#[test]
fn paper_size_commands_store_the_table_name() {
let mut s = s();
s.execute("pageLayout.size", json!({"paper": "b5-jis"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5");
s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid");
// Statement and the envelopes XLSX names are accepted by both commands (Page Setup refused
// them before), stored under their table name and printed on their own size.
s.execute("range.setValues", json!({"range": "A1", "values": [["x"]]})).unwrap();
let close = |v: &Json, want: f64| (v.as_f64().unwrap() - want).abs() < 0.01;
for (cmd, given, stored, w, h) in [
("pageLayout.pageSetup", "statement", "Statement", 396.0, 612.0),
("pageLayout.pageSetup", "envelope #10", "Envelope #10", 297.0, 684.0),
("pageLayout.pageSetup", "Envelope-DL", "Envelope DL", 311.81, 623.62),
("pageLayout.size", "Statement", "Statement", 396.0, 612.0),
("pageLayout.size", "envelope dl", "Envelope DL", 311.81, 623.62),
] {
s.execute(cmd, json!({"paper": given})).unwrap();
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, stored, "{cmd} {given}");
let pv = s.execute("file.printPreview", json!({})).unwrap();
let page = &pv["pageList"][0];
assert!(close(&page["width"], w) && close(&page["height"], h), "{cmd} {given}: {page}");
}
// A new workbook still prints on Letter.
assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter");
}
#[test]
fn hostile_settings_never_panic_and_cap_pages() {
let mut s = s();
@@ -1344,3 +1386,39 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
assert!(pics.chart((0, 1), || vec![line(1000)]).is_none());
assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1)));
}
/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name.
#[test]
fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() {
use std::io::{Cursor, Read, Write};
let mut wb = gridcraft_model::Workbook::new();
wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into()));
wb.sheet_mut(0).unwrap().print.paper = "Legal".into();
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
let mut input = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap();
let mut output = zip::ZipWriter::new(Cursor::new(Vec::new()));
for i in 0..input.len() {
let mut part = input.by_index(i).unwrap();
let mut data = Vec::new();
part.read_to_end(&mut data).unwrap();
let name = part.name().unwrap().to_string();
if name == "xl/worksheets/sheet1.xml" {
let xml = String::from_utf8(data).unwrap();
assert!(xml.contains(r#"paperSize="5""#));
// Set the input id independently of the shared paper-name mapping under test.
data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes();
}
output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
output.write_all(&data).unwrap();
}
let bytes = output.finish().unwrap().into_inner();
let mut s = Session::new();
s.execute("file.open", json!({"name": "iso-b5.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
let preview = s.execute("file.printPreview", json!({})).unwrap();
let page = &preview["pageList"][0];
assert!((page["width"].as_f64().unwrap() - 498.90).abs() < 0.01, "{page}");
assert!((page["height"].as_f64().unwrap() - 708.66).abs() < 0.01, "{page}");
let (pdf, pages) = pdf_of(&mut s, json!({}));
assert_eq!(pages, 1);
assert!(contains(&pdf, "/MediaBox [0 0 498.9 708.66]"));
}
+4 -2
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Size",
["Page Layout", "Page Setup"],
None,
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes)}",
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
has_doc,
paper
),
@@ -324,7 +324,9 @@ fn orientation(s: &mut Session, p: &Json) -> Result<Json> {
}
fn paper(s: &mut Session, p: &Json) -> Result<Json> {
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();
@@ -7,6 +7,9 @@ fn table() -> Session {
s.new_workbook();
s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap();
s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap();
// Bold in its own style too, so the table style's bold header row changes nothing here and
// these tests compare only the filter button's room, with or without the table.
s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap();
s
}
@@ -0,0 +1,427 @@
use std::sync::Arc;
use gridcraft_engine::{
Session,
cmd::data::{filter_selection, filter_values},
core::{CellRef, Value},
model::{Cell, Color, FilterCriterion, PyCode},
};
use serde_json::json;
#[test]
fn python_cells_offer_cached_results_without_exposing_or_changing_code() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Company", "Result"], ["East", 7], ["East", null], ["West", 99]]})).unwrap();
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
for (at, value) in [("B2", Value::Number(7.0)), ("B3", Value::Empty), ("B4", Value::Number(99.0))] {
// A loaded workbook can keep Python code alongside a cached or empty result.
sh.set_cell(CellRef::parse(at).unwrap(), Cell { value, py: Some(Arc::new(PyCode::new("secret_input * 2"))), ..Default::default() });
}
s.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
let doc = s.doc().unwrap();
let (before, revision, undo) = (doc.wb.clone(), doc.revision, doc.undo.len());
assert_eq!(filter_values(&doc.wb, 0, 1), vec![("7".into(), true), ("(Blanks)".into(), true)]);
assert_eq!(
filter_selection(&doc.wb, 0, 1, &[("7".into(), false), ("(Blanks)".into(), false)]),
vec![("7".into(), false), ("99".into(), true), ("(Blanks)".into(), false)],
"eligible edits overlay the cached results; a hidden result keeps its checkbox"
);
let doc = s.doc().unwrap();
assert!(Arc::ptr_eq(&before, &doc.wb), "neither query mutates or evaluates the workbook");
assert_eq!((doc.revision, doc.undo.len()), (revision, undo));
assert_eq!(doc.wb.active().unwrap().cell(CellRef::parse("B3").unwrap()).unwrap().py.as_ref().unwrap().code, "secret_input * 2");
}
#[test]
fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Name"], ["one"], ["two"]]})).unwrap();
s.execute("range.setValues", json!({"range": "F1", "values": [["Region"], ["East"], ["West"]]})).unwrap();
s.execute("insert.table", json!({"range": "F1:F3", "name": "Other", "header": true})).unwrap();
s.execute("selection.set", json!({"cell": "A1"})).unwrap();
s.execute("data.filter", json!({"range": "A1:A3"})).unwrap();
let id = s.execute("insert.slicer", json!({"table": "Other", "column": "Region"})).unwrap()["slicer"].as_u64().unwrap();
s.execute("slicer.toggle", json!({"slicer": id, "value": "East"})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "A1:A3");
assert!(!sh.is_row_hidden(1));
assert!(sh.is_row_hidden(2));
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true)]);
s.execute("data.reapply", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2));
s.execute("slicer.clear", json!({"slicer": id})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1));
assert!(!sh.is_row_hidden(2));
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true), ("two".into(), true)]);
}
#[test]
fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() {
for (criterion, expected, mid_checked) in [
(json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true),
(json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false),
(json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false),
(json!({"top": {"count": 2}}), vec!["high", "upper"], false),
(json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true),
(json!({"aboveAverage": true}), vec!["high"], false),
(json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true),
] {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Name", "Amount"], ["low", 10], ["mid", 20], ["upper", 30], ["high", 100], ["blank", null], ["text", "n/a"]
]}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:B7"})).unwrap();
let mut params = criterion.clone();
params["column"] = json!("B");
s.execute("data.filterBy", params).unwrap();
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect();
assert_eq!(actual, expected, "{criterion}");
// The current column's own criterion must not narrow its alternatives.
s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap();
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect();
assert_eq!(actual, expected, "{criterion}, with the current column filtered");
assert_eq!(
filter_values(&s.doc().unwrap().wb, 0, 1),
vec![("20".into(), mid_checked)],
"the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}"
);
}
}
#[test]
fn statistical_thresholds_use_the_original_range_not_other_columns_subset() {
for (criterion, names, expected) in [
(json!({"top": {"count": 2}}), vec!["low", "mid", "upper"], vec!["upper"]),
(json!({"top": {"count": 50, "percent": true}}), vec!["low", "mid", "upper"], vec!["upper"]),
(json!({"top": {"count": 2, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]),
(json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]),
(json!({"aboveAverage": true}), vec!["low", "mid", "upper"], vec![]),
(json!({"aboveAverage": false}), vec!["low", "mid", "upper"], vec!["low", "mid", "upper"]),
] {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Name", "Amount", "Job"], ["low", 10, "low"], ["mid", 20, "mid"], ["upper", 30, "upper"], ["high", 100, "high"]
]}),
)
.unwrap();
s.execute("data.filter", json!({"range": "A1:C5"})).unwrap();
s.execute("data.filterBy", json!({"column": "A", "values": names})).unwrap();
let mut params = criterion.clone();
params["column"] = json!("B");
s.execute("data.filterBy", params).unwrap();
// A and B both remain active when enumerating C. Subset statistics produce different jobs.
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 2).into_iter().map(|(v, _)| v).collect();
assert_eq!(actual, expected, "{criterion}");
}
}
#[test]
fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "B3", "values": [
["Company", "Job", "Status"],
["East", "Alpha", "Open"],
["East", "Beta", "Open"],
["East", "Closed job", "Closed"],
["West", "Other company", "Open"],
["East", null, "Open"],
["East", "=\"\"", "Open"],
["East", "Outside range", "Open"]
]}),
)
.unwrap();
s.execute("data.filter", json!({"range": "B3:D9"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
s.execute("data.filterBy", json!({"column": "D", "values": ["Open"]})).unwrap();
s.execute("data.filterBy", json!({"column": "C", "values": ["Alpha"]})).unwrap();
let choices = |s: &Session| filter_values(&s.doc().unwrap().wb, 0, 2);
let expected =
|beta: bool, blanks: bool| -> Vec<(String, bool)> { vec![("Alpha".into(), !beta), ("Beta".into(), beta), ("(Blanks)".into(), blanks)] };
assert_eq!(choices(&s), expected(false, false));
s.execute("data.filterBy", json!({"column": "C", "values": ["Beta"], "blanks": true})).unwrap();
assert_eq!(choices(&s), expected(true, true));
s.execute("data.filterBy", json!({"column": "C", "clear": true})).unwrap();
assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]);
// Manual visibility is not a filter criterion, even when every eligible row is hidden.
s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap();
assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]);
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty());
}
#[test]
fn a_header_only_table_has_no_data_values_or_blank_choice() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap();
s.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap();
s.execute("data.filter", json!({"range": "B3:C3"})).unwrap();
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
assert!(sh.tables[0].header_row);
assert_eq!(sh.tables[0].range.height(), 1);
assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3");
for col in [1, 2] {
assert!(filter_values(&d.wb, 0, col).is_empty(), "headers are not values or blank data rows");
}
}
#[test]
fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Name", "Value"], ["empty", null], ["formula", "=\"\""], ["spaces", " "], ["number", 12], ["other", 30]
]}),
)
.unwrap();
s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap();
s.execute("data.filter", json!({"range": "A1:B6"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true)]);
for value in ["12", "12.00"] {
s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]);
}
s.execute("data.filterBy", json!({"column": "B", "values": ["absent"]})).unwrap();
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
}
#[test]
fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Color"], ["red", 1], ["plain", 2]]})).unwrap();
s.execute("home.fillColor", json!({"range": "B2", "color": "#FF0000"})).unwrap();
s.execute("home.fontColor", json!({"range": "B2", "color": "#FF0000"})).unwrap();
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
for criterion in [FilterCriterion::FillColor(Color::Rgb(0xFF0000)), FilterCriterion::FontColor(Color::Rgb(0xFF0000))] {
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)];
s.execute("data.reapply", json!({})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]);
assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]);
}
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })];
s.execute("data.reapply", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2), "reapply preserves imported icon visibility");
assert_eq!(
filter_values(&s.doc().unwrap().wb, 0, 0),
vec![("plain".into(), true), ("red".into(), true)],
"unsupported icon criteria cannot distinguish manual and current-column hiding"
);
}
#[test]
fn duplicate_color_choices_keep_any_eligible_match() {
for font in [false, true] {
for matching_cell in ["B2", "B3"] {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [["Company", "Color"], ["East", "Same"], ["East", "Same"], ["West", "Same"]]}),
)
.unwrap();
let command = if font { "home.fontColor" } else { "home.fillColor" };
s.execute(command, json!({"range": "B4", "color": "#FF0000"})).unwrap();
s.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) };
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.autofilter.as_mut().unwrap().criteria = vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }), (1, color)];
s.execute("data.reapply", json!({})).unwrap();
assert_eq!(
filter_values(&s.doc().unwrap().wb, 0, 1),
vec![("Same".into(), false)],
"an excluded red row cannot check an eligible choice"
);
s.execute(command, json!({"range": matching_cell, "color": "#FF0000"})).unwrap();
s.execute("data.reapply", json!({})).unwrap();
let choices = filter_values(&s.doc().unwrap().wb, 0, 1);
assert_eq!(choices, vec![("Same".into(), true)], "either eligible duplicate can supply the color match");
let selected = filter_selection(&s.doc().unwrap().wb, 0, 1, &choices);
assert_eq!(selected, vec![("Same".into(), true)]);
let values: Vec<_> = selected.into_iter().filter_map(|(value, on)| on.then_some(value)).collect();
s.execute("data.filterBy", json!({"column": "B", "values": values})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(CellRef::parse(matching_cell).unwrap().row), "unchanged Apply keeps the previously matching row");
assert!(sh.is_row_hidden(3), "the other column still excludes West");
}
}
}
#[test]
fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() {
for table in [false, true] {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]}))
.unwrap();
if table {
s.execute("insert.table", json!({"range": "B3:C6", "header": true})).unwrap();
}
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
let before = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]);
assert_eq!(before, gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap());
let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap();
let sh = reopened.active().unwrap();
let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria };
assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })]);
assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5));
}
}
#[test]
fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]}))
.unwrap();
s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap();
s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap();
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false })];
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
s.execute("data.filter", json!({"range": "B3:C6"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]);
}
#[test]
fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() {
let mut s = Session::new();
s.new_workbook();
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty());
s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["West", "Before last"], ["East", "Last East"]]}))
.unwrap();
s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]);
}
#[test]
fn imported_filters_keep_choices_and_statistics_inside_the_grid() {
use gridcraft_engine::core::{MAX_ROWS, RangeRef};
use gridcraft_engine::model::AutoFilter;
for criterion in [FilterCriterion::Top10 { bottom: false, percent: false, count: 1 }, FilterCriterion::AboveAverage(true)] {
let mut s = Session::new();
s.new_workbook();
let range = RangeRef::new(CellRef::new(MAX_ROWS - 3, 0), CellRef::new(MAX_ROWS + 1, 0));
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
// Model data loaded from a malformed workbook can extend beyond the grid.
for (row, value) in [(MAX_ROWS - 2, 1.0), (MAX_ROWS - 1, 9.0), (MAX_ROWS, 100.0)] {
sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Number(value), ..Default::default() });
}
sh.autofilter = Some(AutoFilter { range, criteria: vec![(0, criterion)] });
let doc = s.doc().unwrap();
let before = doc.wb.clone();
let expected = vec![("1".into(), false), ("9".into(), true)];
assert_eq!(filter_values(&doc.wb, 0, 0), expected, "out-of-grid data must not affect the choices or thresholds");
assert_eq!(filter_selection(&doc.wb, 0, 0, &[]), expected);
assert!(Arc::ptr_eq(&before, &s.doc().unwrap().wb), "queries must not trim the stored workbook");
s.execute("data.reapply", json!({})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert!(sh.is_row_hidden(MAX_ROWS - 2));
assert!(!sh.is_row_hidden(MAX_ROWS - 1), "the valid maximum still matches Top 1 and Above Average");
assert!(sh.rows.keys().all(|row| *row < MAX_ROWS), "no hidden-row entries may be created beyond the grid");
assert_eq!(sh.autofilter.as_ref().unwrap().range, range, "the scan bound does not rewrite imported metadata");
assert_eq!(sh.value(CellRef::new(MAX_ROWS, 0)), Value::Number(100.0));
}
}
#[test]
fn merging_hidden_choices_preserves_the_active_criterion() {
for (criterion, checked) in [
(json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]),
(json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]),
(json!({"top": {"count": 2}}), [false, false, true, true, false]),
(json!({"aboveAverage": true}), [false, false, false, true, false]),
(json!({"aboveAverage": false}), [true, true, true, false, false]),
] {
let mut s = Session::new();
s.new_workbook();
s.execute(
"range.setValues",
json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}),
)
.unwrap();
s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap();
s.execute("data.filter", json!({"range": "A1:B6"})).unwrap();
s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
let mut params = criterion.clone();
params["column"] = json!("B");
s.execute("data.filterBy", params).unwrap();
let doc = s.doc().unwrap();
let choices = filter_values(&doc.wb, 0, 1);
let selection = filter_selection(&doc.wb, 0, 1, &choices);
let expected: Vec<_> =
["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect();
assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}");
let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect();
s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap();
s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() {
assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}");
}
}
}
#[test]
fn large_values_criteria_preserve_ascii_case_and_blank_matching() {
use gridcraft_engine::core::RangeRef;
use gridcraft_engine::model::AutoFilter;
let mut s = Session::new();
s.new_workbook();
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
let mut selected = Vec::new();
for row in 1..=5_000 {
sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() });
sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() });
selected.push(format!("ITEM-{row}"));
}
selected.extend(["ITEM-1".into(), "Ä".into()]);
for (row, value, label) in [
(5_001, Value::Text("Ä".into()), "unicode selected"),
(5_002, Value::Text("ä".into()), "unicode excluded"),
(5_003, Value::Empty, "blank row"),
] {
sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() });
sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() });
}
sh.autofilter = Some(AutoFilter {
range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)),
criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })],
});
let choices = filter_values(&s.doc().unwrap().wb, 0, 1);
let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect();
expected.extend([("blank row".into(), true), ("unicode selected".into(), true)]);
assert_eq!(choices, expected);
}
+1
View File
@@ -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;
@@ -54,3 +54,168 @@ fn resize_next_to_another_table_still_works() {
s.execute("table.resize", json!({"table":"T", "range":"A1:C3"})).unwrap();
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
}
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
s.doc().unwrap().wb.active().unwrap()
}
fn names(s: &Session, table: usize) -> Vec<String> {
sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect()
}
fn headers(s: &Session, table: usize) -> Vec<String> {
let sh = sheet(s);
let r = sh.tables[table].range;
(r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect()
}
fn with_headers(range: &str, row: &[&str]) -> Session {
let mut s = Session::new();
s.new_workbook();
let rows = vec![row.iter().map(|h| json!(h)).collect::<Vec<_>>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()];
s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap();
s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap();
s
}
#[test]
fn resize_onto_another_table_is_rejected() {
// From the sales sample, growing Table2 over Table1 used to leave two overlapping tables.
let mut s = Session::new();
s.execute("file.new", json!({"sample": "sales"})).unwrap();
s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap();
s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap();
let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string();
assert!(e.contains("overlap another table"), "{e}");
let ranges: Vec<String> = sheet(&s).tables.iter().map(|t| t.range.a1()).collect();
assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}");
// Down over a table below, or around a whole table, is refused too; next to it is fine.
let mut s = table();
s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap();
s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap();
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err());
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err());
s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap();
assert_eq!(table_range(&s), "A1:B4");
}
#[test]
fn resize_onto_merged_cells_pivot_or_array_is_rejected() {
let mut s = table();
s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
assert!(e.contains("merged"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
let mut s = table();
s.execute("selection.set", json!({"range": "D1:D2"})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
assert!(e.contains("array"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
let mut s = table();
s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap();
s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap();
assert!(!sheet(&s).pivots.is_empty());
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string();
assert!(e.contains("PivotTable"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
}
#[test]
fn resize_onto_a_spill_is_allowed() {
// Excel lets a table take in a spilled formula (the spill then shows #SPILL!).
let mut s = table();
s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap();
assert_eq!(table_range(&s), "A1:D2");
}
#[test]
fn resized_in_columns_get_excel_names_written_into_the_header_row() {
// A resize whose new columns repeated a name left the header row and the column
// names out of step ("Column3" in memory, "Column32" after reopening).
let mut s = Session::new();
s.execute("file.new", json!({"sample": "grades"})).unwrap();
s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap();
s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap();
let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap();
assert_eq!(names(&s, ti), headers(&s, ti));
let mut seen = std::collections::HashSet::new();
assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti));
let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap();
let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap();
assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>(), names(&s, ti));
// Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes
// the lowest free ColumnN; a repeated header gets the next free suffix.
let cases: [(&str, &[&str], &str, &[&str]); 5] = [
("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]),
("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]),
("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]),
("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]),
("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]),
];
for (range, row, to, want) in cases {
let mut s = with_headers(range, row);
s.execute("table.resize", json!({"table": "T", "range": to})).unwrap();
assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::<Vec<_>>(), "{row:?} -> {to}");
assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}");
}
// Headers already in the new columns are kept, made unique and turned into text.
let mut s = with_headers("A1:B3", &["x", "y"]);
s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap();
assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]);
assert_eq!(headers(&s, 0), names(&s, 0));
assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none()));
}
#[test]
fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() {
let mut s = with_headers("A1:B3", &["a", "b"]);
// As a file can have it: the table starts at its first data row (A2:B3), with no header row.
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0];
t.header_row = false;
t.range.start.row = 1;
}
let r = sheet(&s).tables[0].range;
assert!(!sheet(&s).tables[0].header_row);
let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1));
let first = sheet(&s).value(r.start).display();
s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap();
assert_eq!(names(&s, 0), ["a", "b", "Column1"]);
assert_eq!(sheet(&s).value(r.start).display(), first);
}
#[test]
fn resized_formula_header_is_named_by_its_value_when_formulas_show() {
let mut s = with_headers("A1:B3", &["x", "y"]);
s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap();
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true;
}
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
assert_eq!(names(&s, 0), ["x", "y", "2"]);
assert_eq!(headers(&s, 0), names(&s, 0));
}
#[test]
fn resized_picture_header_is_replaced_and_its_picture_removed() {
let mut s = with_headers("A1:B3", &["x", "y"]);
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() };
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture));
}
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2)));
assert_eq!(headers(&s, 0), names(&s, 0));
}
+6 -2
View File
@@ -11,7 +11,10 @@ pub enum Orientation {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrintSettings {
pub orientation: Orientation,
/// Paper size name (`Letter`, `A4`, `Legal`…).
/// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]). Empty means no paper is
/// stated, so the printer's or locale's paper applies: a reader may leave it so for a file
/// that states none (none does yet). Print layout falls back to Letter and XLSX writes no
/// `paperSize`. New sheets default to Letter.
pub paper: String,
/// Margins in inches: left, right, top, bottom, header, footer.
pub margins: [f32; 6],
@@ -258,7 +261,8 @@ pub struct LineInfo {
pub outline: u8,
pub collapsed: bool,
pub style: Option<crate::style::StyleId>,
/// The size was set by the user (rows): automatic heights follow the content.
/// The size was set by the user. Rows without it follow their content's height; columns
/// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…).
#[serde(default)]
pub custom: bool,
}
+1
View File
@@ -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;
+137
View File
@@ -0,0 +1,137 @@
//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats
//! (paper ids or page sizes) and print layout all read this one table.
/// Paper names and sizes in points, width then height, as the paper is named: Ledger is
/// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was
/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and
/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and
/// envelopes are the JIS ones too.
pub const PAPERS: [(&str, f32, f32); 24] = [
("Letter", 612.0, 792.0),
("Legal", 612.0, 1008.0),
("A4", 595.28, 841.89),
("A3", 841.89, 1190.55),
("A5", 419.53, 595.28),
("A6", 297.64, 419.53),
("Tabloid", 792.0, 1224.0),
("Ledger", 1224.0, 792.0),
("Executive", 522.0, 756.0),
("Statement", 396.0, 612.0),
("B4", 728.50, 1031.81),
("B5", 515.91, 728.50),
("B6", 362.83, 515.91),
("B4 (ISO)", 708.66, 1000.63),
("B5 (ISO)", 498.90, 708.66),
("B6 (ISO)", 354.33, 498.90),
("Envelope #10", 297.0, 684.0),
("Envelope DL", 311.81, 623.62),
("Japanese Postcard", 283.46, 419.53),
("Japanese Double Postcard", 419.53, 566.93),
("Japanese Envelope #3", 340.16, 666.14),
// 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out.
("Japanese Envelope #4", 255.12, 581.10),
("Japanese Envelope Kaku #2", 680.31, 941.10),
("Japanese Envelope Kaku #3", 612.28, 785.20),
];
/// Other spellings of the names above, in [`key`] form.
const ALIASES: [(&str, &str); 13] = [
// The B5 envelope is ISO B5 itself (176×250 mm): one size, one name.
("envelopeb5", "B5 (ISO)"),
("usletter", "Letter"),
("uslegal", "Legal"),
("11x17", "Tabloid"),
("b4jis", "B4"),
("b5jis", "B5"),
("b6jis", "B6"),
("postcard", "Japanese Postcard"),
("doublepostcard", "Japanese Double Postcard"),
("chou#3", "Japanese Envelope #3"),
("chou#4", "Japanese Envelope #4"),
("kaku#2", "Japanese Envelope Kaku #2"),
("kaku#3", "Japanese Envelope Kaku #3"),
];
/// A name as compared: spaces, hyphens, underscores and parentheses don't matter, nor does case
/// (`B5 (JIS)`, `b5-jis` and `b5jis` are one name).
fn key(name: &str) -> String {
name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "")
}
/// The paper `name` stands for, under its table name.
pub fn canonical(name: &str) -> Option<&'static str> {
// No paper name is long; a huge one (from a file or a command) is not worth folding.
if name.len() > 64 {
return None;
}
let k = key(name);
PAPERS.iter().map(|(n, _, _)| *n).find(|n| key(n) == k).or_else(|| ALIASES.iter().find(|(a, _)| *a == k).map(|(_, n)| *n))
}
/// The size of paper `name` in points (width, height).
pub fn size_pt(name: &str) -> Option<(f32, f32)> {
let n = canonical(name)?;
PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h))
}
/// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it
/// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese
/// Envelope Kaku #3), so the nearest wins, not the first in the table.
///
/// The name is the paper as the page stands: a 17×11 in page is `Ledger`. A caller that also
/// records a landscape orientation should pass the size upright (narrow side first), since
/// print layout turns the named paper once more for landscape.
pub fn for_size(width: f32, height: f32) -> Option<&'static str> {
const TOLERANCE: f32 = 5.67; // 2 mm
let nearest = |w: f32, h: f32| {
PAPERS
.iter()
.filter_map(|(n, pw, ph)| {
let (dw, dh) = ((pw - w).abs(), (ph - h).abs());
(dw < TOLERANCE && dh < TOLERANCE).then_some((dw + dh, *n))
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, n)| n)
};
nearest(width, height).or_else(|| nearest(height, width))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_and_sizes() {
assert_eq!(size_pt("b5-jis"), Some((515.91, 728.50)));
assert_eq!(size_pt("US Letter"), Some((612.0, 792.0)));
assert_eq!(size_pt("nonsense"), None);
assert_eq!(for_size(1224.0, 792.0), Some("Ledger"));
assert_eq!(for_size(792.0, 1224.0), Some("Tabloid"));
assert_eq!(for_size(842.0, 595.0), Some("A4"));
assert_eq!(canonical("ledger"), Some("Ledger"));
assert_eq!(canonical(""), None);
assert_eq!(canonical(&"A4".repeat(1000)), None);
}
#[test]
fn every_size_reads_back_as_its_name() {
for (name, w, h) in PAPERS {
assert_eq!(for_size(w, h), Some(name), "{name}");
}
assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)"));
}
/// Letter (612×792) and Japanese Envelope Kaku #3 (612.28×785.2) are within 2 mm of some
/// of the same sizes: the nearer paper wins, whichever comes first in the table.
#[test]
fn for_size_picks_the_nearest_paper() {
assert_eq!(for_size(612.2, 788.0), Some("Japanese Envelope Kaku #3"));
assert_eq!(for_size(612.0, 790.0), Some("Letter"));
assert_eq!(for_size(788.0, 612.2), Some("Japanese Envelope Kaku #3"));
// A wide page that is a paper as it stands is not read as another paper turned.
assert_eq!(for_size(1224.0, 792.0), Some("Ledger"));
assert_eq!(for_size(1000.0, 10.0), None);
assert_eq!(for_size(f32::NAN, 792.0), None);
assert_eq!(for_size(f32::INFINITY, f32::INFINITY), None);
}
}
+8
View File
@@ -8,6 +8,7 @@
use std::sync::Arc;
use crate::sheet::Visibility;
use crate::style::Style;
/// A relationship from an owning part (the package root, the workbook or a sheet, or a kept part)
/// to a kept part or to an external target.
@@ -32,6 +33,13 @@ pub struct PreservedPart {
pub data: Arc<[u8]>,
/// The part's own relationships, ids unchanged (the part's bytes refer to them).
pub rels: Vec<PreservedRel>,
/// Differential formats its XML refers to by `dxfId`, by their id in the source file's styles
/// part. GridCraft rewrites the styles part, so the ids are renumbered on save (kept
/// PivotTables).
pub dxfs: Vec<(u32, Style)>,
/// Custom number formats its XML refers to by `numFmtId` (code by id in the source file),
/// renumbered on save like [`Self::dxfs`] (kept PivotTables and pivot caches).
pub num_fmts: Vec<(u32, String)>,
}
/// A raw XML element of an owning part that refers to kept parts, re-emitted on save with its
+12
View File
@@ -327,6 +327,18 @@ impl SheetApp {
self.open_dialog(name, p.clone());
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
match p.get("mode").and_then(Json::as_str) {
Some(id) => match crate::grid::SelectionMode::parse(id) {
Some(mode) => self.grid.set_selection_mode(mode),
None => return Some(Err(format!("unknown selection mode {id:?} (use \"extend\", \"add\" or \"off\")"))),
},
None if p.get("mode").is_some_and(|v| !v.is_null()) => return Some(Err("`mode` must be \"extend\", \"add\" or \"off\"".into())),
None => {}
}
Ok(json!({"mode": self.grid.selection_mode.id()}))
}
"ui.pythonMode" => {
// `{"on": true}` starts Python mode on the active cell (or switches the edit in
// progress to it), `{"on": false}` leaves it; without `on` it switches. A start
+2
View File
@@ -18,6 +18,8 @@ impl SheetApp {
self.message = Some(("Text Box".into(), clean_error(&e)));
return;
}
// Editing a cell ends Extend and Add mode, as in Excel.
self.grid.set_selection_mode(crate::grid::SelectionMode::Off);
let Some(d) = self.session.active() else { return };
let Some(sh) = d.wb.active() else { return };
let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active);
+5
View File
@@ -280,6 +280,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
("ui.window.close", "Close Window", ""),
("ui.window.beginResize", "Resize Window", "{direction: north|south|east|west|northeast|northwest|southeast|southwest}"),
("ui.dialog", "Open Dialog", ""),
(
"ui.selectionMode",
"Extend or Add to Selection",
"{mode?: \"extend\" (F8) | \"add\" (Shift+F8) | \"off\"} → {mode}; {} reports the mode",
),
("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|account|close}"),
(
"ui.printSettings",
+1
View File
@@ -1011,6 +1011,7 @@ impl Dialog {
dialog
}
"manageRules" => Dialog::custom("manageRules", "Conditional Formatting Rules Manager", json!({})),
"newFormattingRule" => cond_format_rules::new_rule_dialog(app, &params),
"commandSearch" => Dialog::custom("commandSearch", "Search Commands", json!({})),
"agents" => Dialog::custom("agents", "Agent Control", json!({})),
"about" => {
+451 -2
View File
@@ -1,10 +1,18 @@
use super::{Json, SheetApp, json};
//! Conditional formatting dialogs: the rules manager, and the New / Edit Formatting Rule editor
//! with its 2- and 3-colour scale stops.
use super::show::{ok_cancel_enabled, track_pick};
use super::{Dialog, Json, RefPick, SheetApp, json};
use egui::{Color32, Sense, Stroke, StrokeKind, vec2};
use gridcraft_engine::core::{CellRef, RangeRef};
use gridcraft_engine::model::{CfRule, CfValueKind, Color as CellColor, Theme};
/// The list scrolls inside the dialog: a sheet read from a file can carry thousands of rules, and
/// a list laid out in full made the window as tall as all of them (issue #3321).
const LIST_HEIGHT: f32 = 360.0;
pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
let lang = app.ui.language;
// Read the rules in place: running `home.manageRules` for them each frame copied and
// serialised every rule and journaled a step 60 times a second.
let count = app.session.active().and_then(|d| d.wb.active()).map_or(0, |sh| sh.cond_formats.len());
@@ -13,15 +21,20 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
return;
}
let mut action: Option<Json> = None;
let mut edit: Option<(usize, Json)> = None;
let row_height = ui.spacing().interact_size.y;
egui::ScrollArea::both().max_height(LIST_HEIGHT).auto_shrink([false, true]).show_rows(ui, row_height, count, |ui, rows| {
let Some(sh) = app.session.active().and_then(|d| d.wb.active()) else { return };
for i in rows {
let Some(cf) = sh.cond_formats.get(i) else { break };
let kind = serde_json::to_value(&cf.rule).ok().and_then(|r| r.as_object().and_then(|o| o.keys().next().cloned())).unwrap_or_default();
let rule = serde_json::to_value(&cf.rule).unwrap_or(Json::Null);
let kind = rule.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
let ranges = cf.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
ui.horizontal(|ui| {
ui.label(format!("{}. {kind} applies to {ranges}", i + 1));
if kind.contains("ColorScale") && ui.small_button(lang.tr("Edit")).clicked() {
edit = Some((i, rule.clone()));
}
if ui.small_button("▲").clicked() {
action = Some(json!({"moveUp": i}));
}
@@ -34,7 +47,443 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
});
}
});
if let Some((i, rule)) = edit {
app.open_dialog("newFormattingRule", json!({"edit": i, "rule": rule}));
}
if let Some(params) = action {
app.run_or_alert("home.manageRules", params);
}
}
/// The New Formatting Rule dialog, or the rule editor Manage Rules opens on an existing colour
/// scale (`edit` and `rule` in the params).
pub(super) fn new_rule_dialog(app: &mut SheetApp, params: &Json) -> Dialog {
let theme = app.session.active().map(|d| d.wb.theme.clone()).unwrap_or_default();
// Excel titles the Manage Rules path "Edit Formatting Rule": OK replaces the rule rather than
// adding one, and the window should say so.
let editing = params.get("edit").is_some();
let title = if editing { "Edit Formatting Rule" } else { "New Formatting Rule" };
let mut d = Dialog::custom("newFormattingRule", title, new_rule_defaults(params, &theme));
d.command = Some(if editing { "home.manageRules" } else { "home.conditionalFormat" });
// The sheet and selection the rule was opened on: Excel's "Applies to" stays put
// even if the selection moves or another sheet is shown before OK.
let (sheet, applies_to) = app
.session
.active()
.map(|doc| {
(
doc.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(),
doc.selection.ranges.iter().map(RangeRef::a1).collect::<Vec<_>>().join(","),
)
})
.unwrap_or_default();
d.values.insert("sheet".into(), json!(sheet));
d.values.insert("applies_to".into(), json!(applies_to));
sync_rule_pick(&mut d);
d
}
/// The command params OK sends: the rule the editor describes, on the scope it opened with.
pub(super) fn rule_params(d: &Dialog) -> Json {
let mut out = match d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells") {
"formula" => {
let formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
let preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText");
json!({"rule": {"type": "expression", "formula": formula, "preset": preset}})
}
_ => {
let stops: Vec<Json> = d.values.get("stops").and_then(Json::as_array).map(|a| a.iter().map(cf_stop_params).collect()).unwrap_or_default();
json!({"rule": {"type": "colorScale", "stops": stops}})
}
};
// The rule covers the sheet and range the dialog opened on, not whatever the
// selection shows now: a formula rule's pick box holds the same opening scope, and
// colour scales have no pick box but need it just as much to edit in place.
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default();
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default();
if !sheet.is_empty() && !applies_to.is_empty() {
out["sheet"] = json!(sheet);
out["range"] = json!(applies_to);
}
if let Some(edit) = d.values.get("edit").and_then(Json::as_u64) {
out["edit"] = json!(edit);
}
out
}
/// Draws the rule-type list and the editor for the chosen type, then OK/Cancel. OK stays disabled
/// while the rule description is incomplete (a formula stop or rule with no formula, or a rule
/// type this PR does not implement yet).
pub(super) fn new_formatting_rule(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
let lang = crate::i18n::current(ui.ctx());
ui.label(lang.tr("Select a Rule Type"));
let mut rule_type = d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
for (v, label) in RULE_TYPES {
ui.selectable_value(&mut rule_type, (*v).to_string(), lang.tr(label));
}
d.values.insert("ruleType".into(), json!(rule_type));
// Only a formula rule's box takes grid references, and it keeps the sheet and "Applies to"
// range the dialog opened on.
sync_rule_pick(d);
ui.separator();
ui.label(lang.tr("Edit the Rule Description"));
let supported = match rule_type.as_str() {
"allCells" => {
colour_scale_editor(ui, d, lang);
// A formula stop needs a formula: one whose value is missing, not a string, or
// blank would create a rule that never applies. Other stops confirm as they are.
d.values.get("stops").and_then(Json::as_array).is_none_or(|stops| {
stops.iter().all(|s| {
s.get("type").and_then(Json::as_str) != Some("formula")
|| s.get("value").and_then(Json::as_str).is_some_and(|f| !f.trim().is_empty())
})
})
}
"formula" => {
ui.label(lang.tr("Format values where this formula is true:"));
let mut formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
let r = ui.add(egui::TextEdit::singleline(&mut formula).desired_width(360.0));
if r.changed() {
d.values.insert("formula".into(), json!(formula.clone()));
}
if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == "formula") {
track_pick(pick, &r, r.changed());
}
ui.horizontal(|ui| {
ui.label(lang.tr("with"));
preset_combo(ui, d, lang);
});
// A formula rule with no formula never applies; OK waits for one.
!formula.trim().is_empty()
}
_ => {
ui.label(lang.tr("This rule type isn't available yet."));
false
}
};
ok_cancel_enabled(ui, confirm, open, supported);
}
fn cf_stop_json(kind: CfValueKind, color: &CellColor, theme: &Theme) -> Json {
let (ty, value) = match kind {
CfValueKind::Min => ("min", Json::Null),
CfValueKind::Max => ("max", Json::Null),
CfValueKind::Number(n) => ("num", json!(n)),
CfValueKind::Percent(n) => ("percent", json!(n)),
CfValueKind::Percentile(n) => ("percentile", json!(n)),
CfValueKind::Formula(f) => ("formula", json!(f)),
};
let hex = color.hex(theme).unwrap_or_else(|| "#000000".into());
// `source` keeps a theme colour by reference: OK without touching the picker sends it back
// unchanged, instead of freezing the theme's current RGB into the rule.
json!({"type": ty, "value": value, "color": hex.clone(), "source": color, "sourceHex": hex})
}
/// The stop as the engine takes it, dropping the dialog's bookkeeping. A colour the user did not
/// change keeps its original theme reference; a changed one is sent as the picked RGB.
fn cf_stop_params(stop: &Json) -> Json {
let mut obj = stop.as_object().cloned().unwrap_or_default();
let source = obj.remove("source").and_then(|v| serde_json::from_value::<CellColor>(v).ok());
let source_hex = obj.remove("sourceHex").and_then(|v| v.as_str().map(str::to_string));
if let (Some(source), Some(source_hex)) = (source, source_hex)
&& obj.get("color").and_then(Json::as_str).is_some_and(|c| c.eq_ignore_ascii_case(&source_hex))
{
obj.insert(
"color".into(),
match source {
CellColor::Auto => json!("auto"),
CellColor::Rgb(v) => json!(format!("#{v:06X}")),
CellColor::Theme(i, tint) => json!({"theme": i, "tint": tint as f64 / 1000.0}),
},
);
}
Json::Object(obj)
}
fn default_scale_stops(style: &str) -> Vec<Json> {
if style == "2color" {
vec![json!({"type": "min", "value": null, "color": "#F8696B"}), json!({"type": "max", "value": null, "color": "#63BE7B"})]
} else {
vec![
json!({"type": "min", "value": null, "color": "#F8696B"}),
json!({"type": "percentile", "value": 50, "color": "#FFEB84"}),
json!({"type": "max", "value": null, "color": "#63BE7B"}),
]
}
}
fn new_rule_defaults(params: &Json, theme: &Theme) -> Json {
// Excel's New Formatting Rule opens on the first type. Manage Rules edits a colour scale,
// so an edit always stays on that branch.
let mut rule_type = params.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
if params.get("edit").is_some() || !matches!(rule_type.as_str(), "allCells" | "formula") {
rule_type = "allCells".into();
}
let mut style = params.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
if !matches!(style.as_str(), "2color" | "3color") {
style = "3color".into();
}
let existing = params.get("rule").and_then(|rule| serde_json::from_value::<CfRule>(rule.clone()).ok()).and_then(|rule| match rule {
CfRule::ColorScale { stops } if (2..=3).contains(&stops.len()) => {
Some(stops.into_iter().map(|(kind, color)| cf_stop_json(kind, &color, theme)).collect::<Vec<_>>())
}
_ => None,
});
let stops = match existing {
Some(stops) => {
style = if stops.len() == 2 { "2color".into() } else { "3color".into() };
stops
}
None => default_scale_stops(&style),
};
json!({
"ruleType": rule_type,
"style": style,
"stops": stops,
"formula": "",
"preset": "lightRedFillDarkRedText",
"edit": params.get("edit").cloned(),
})
}
fn parse_hex_color(s: &str) -> Color32 {
let h = s.trim_start_matches('#');
u32::from_str_radix(h.get(..6).unwrap_or("000000"), 16)
.map(|v| Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
.unwrap_or(Color32::WHITE)
}
fn hex_color(c: Color32) -> String {
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
}
fn scale_preview(ui: &mut egui::Ui, stops: &[Json]) {
let (rect, _) = ui.allocate_exact_size(vec2(280.0, 26.0), Sense::hover());
let colors: Vec<Color32> = stops.iter().map(|s| parse_hex_color(s.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"))).collect();
if colors.is_empty() {
return;
}
let n = 64;
for i in 0..n {
let t = i as f32 / (n - 1) as f32;
let pos = t * (colors.len() - 1) as f32;
let lo = pos.floor() as usize;
let hi = (lo + 1).min(colors.len() - 1);
let f = pos - lo as f32;
let a = colors[lo];
let b = colors[hi];
let c = Color32::from_rgb(
(a.r() as f32 + (b.r() as f32 - a.r() as f32) * f) as u8,
(a.g() as f32 + (b.g() as f32 - a.g() as f32) * f) as u8,
(a.b() as f32 + (b.b() as f32 - a.b() as f32) * f) as u8,
);
let x = rect.left() + rect.width() * i as f32 / n as f32;
ui.painter().rect_filled(egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(rect.width() / n as f32 + 0.5, rect.height())), 0.0, c);
}
ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::from_gray(190)), StrokeKind::Inside);
}
fn stop_combo(ui: &mut egui::Ui, id: (&'static str, usize), current: &mut String, options: &[(&str, &str)], lang: crate::i18n::Language) {
let shown = options.iter().find(|(v, _)| *v == current).map(|(_, l)| lang.tr(l)).unwrap_or(current.as_str());
egui::ComboBox::from_id_salt(id).selected_text(shown).width(120.0).show_ui(ui, |ui| {
for (v, l) in options {
if ui.selectable_label(current == v, lang.tr(l)).clicked() {
*current = (*v).to_string();
}
}
});
}
fn colour_scale_editor(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
ui.label(lang.tr("Format all cells based on their values"));
ui.horizontal(|ui| {
ui.label(lang.tr("Format Style:"));
let mut style = d.values.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
egui::ComboBox::from_id_salt("newFormattingRule.style")
.selected_text(lang.tr(if style == "2color" { "2-Color Scale" } else { "3-Color Scale" }))
.width(150.0)
.show_ui(ui, |ui| {
for (v, l) in [("2color", "2-Color Scale"), ("3color", "3-Color Scale")] {
if ui.selectable_label(style == v, lang.tr(l)).clicked() {
style = v.to_string();
}
}
});
d.values.insert("style".into(), json!(style));
// The midpoint comes back as the default #FFEB84 rather than a copy of the minimum's
// colour, so 3 → 2 → 3 restores Excel's scale.
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
if style == "2color" && stops.len() == 3 {
stops.remove(1);
} else if style == "3color" && stops.len() == 2 {
stops.insert(1, json!({"type": "percentile", "value": 50, "color": "#FFEB84"}));
}
d.values.insert("stops".into(), Json::Array(stops));
});
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
let count = stops.len();
for i in 0..count {
let mut obj = stops.get(i).and_then(Json::as_object).cloned().unwrap_or_default();
let mut ty = obj.get("type").and_then(Json::as_str).unwrap_or("num").to_string();
let options: &[(&str, &str)] = if i == 0 {
&[("min", "Lowest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
} else if i + 1 == count {
&[("max", "Highest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
} else {
&[("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
};
ui.horizontal(|ui| {
ui.label(lang.tr(if i == 0 {
"Minimum"
} else if i + 1 == count {
"Maximum"
} else {
"Midpoint"
}));
stop_combo(ui, ("newFormattingRule.stopType", i), &mut ty, options, lang);
match ty.as_str() {
"min" | "max" => {
ui.label(lang.tr(if ty == "min" { "Lowest value" } else { "Highest value" }));
}
"formula" => {
let mut f = obj.get("value").and_then(Json::as_str).unwrap_or("").to_string();
ui.add(egui::TextEdit::singleline(&mut f).desired_width(120.0).hint_text(lang.tr("Formula")));
// Store what the field shows as a string even when it was not edited: a
// stop switched from Number still holds that number, which is no formula.
obj.insert("value".into(), json!(f));
}
_ => {
let mut n = obj.get("value").and_then(Json::as_f64).unwrap_or(0.0);
let speed = if ty == "num" { 1.0 } else { 0.1 };
if ui.add(egui::DragValue::new(&mut n).speed(speed).range(if ty == "num" { f64::MIN..=f64::MAX } else { 0.0..=100.0 })).changed()
{
obj.insert("value".into(), json!(n));
}
// A numeric stop must carry a number: a stop switched from Lowest or
// Highest value still holds `null`, which the engine refuses.
if obj.get("value").and_then(Json::as_f64).is_none() {
obj.insert("value".into(), json!(n));
}
}
}
let c = parse_hex_color(obj.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"));
let mut rgb = [c.r(), c.g(), c.b()];
if ui.color_edit_button_srgb(&mut rgb).changed() {
obj.insert("color".into(), json!(hex_color(Color32::from_rgb(rgb[0], rgb[1], rgb[2]))));
}
});
obj.insert("type".into(), json!(ty));
stops[i] = Json::Object(obj);
}
d.values.insert("stops".into(), Json::Array(stops.clone()));
scale_preview(ui, &stops);
}
fn preset_combo(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
const PRESETS: &[(&str, &str)] = &[
("lightRedFillDarkRedText", "Light Red Fill with Dark Red Text"),
("yellowFillDarkYellowText", "Yellow Fill with Dark Yellow Text"),
("greenFillDarkGreenText", "Green Fill with Dark Green Text"),
("lightRedFill", "Light Red Fill"),
("redText", "Red Text"),
("redBorder", "Red Border"),
];
let mut preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText").to_string();
let shown = PRESETS.iter().find(|(v, _)| *v == preset).map(|(_, l)| lang.tr(l)).unwrap_or(preset.as_str());
egui::ComboBox::from_id_salt("newFormattingRule.preset").selected_text(shown).width(260.0).show_ui(ui, |ui| {
for (v, l) in PRESETS {
if ui.selectable_label(preset == *v, lang.tr(l)).clicked() {
preset = (*v).to_string();
}
}
});
d.values.insert("preset".into(), json!(preset));
}
/// Excel's six rule types, in its order.
const RULE_TYPES: &[(&str, &str)] = &[
("allCells", "Format all cells based on their values"),
("cellsThatContain", "Format only cells that contain"),
("topBottom", "Format only top or bottom ranked values"),
("aboveBelow", "Format only values that are above or below average"),
("uniqueDuplicate", "Format only unique or duplicate values"),
("formula", "Use a formula to determine which cells to format"),
];
/// Gives a formula rule's box point mode, on the sheet and selection the dialog opened on;
/// other rule types take clicks on the grid as selection.
fn sync_rule_pick(d: &mut Dialog) {
if d.values.get("ruleType").and_then(Json::as_str) != Some("formula") {
d.pick = None;
return;
}
if d.pick.is_some() {
return;
}
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default().to_string();
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default().to_string();
d.pick = Some(RefPick { key: "formula", sheet, caret: 0, point: None, anchor: CellRef::new(0, 0), refocus: false, applies_to });
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formula_rule_picks_references_and_keeps_the_opening_range() {
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
let mut app = SheetApp::new(session, Default::default());
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({"ruleType": "formula"})).unwrap();
assert!(d.picks_references());
assert_eq!(d.pick.as_ref().unwrap().sheet, sheet);
// A grid click writes the reference into the formula box.
d.pick_reference(CellRef::new(0, 0), &sheet, false);
assert_eq!(d.values["formula"], "=$A$1");
// Moving the selection before OK must not move the rule.
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
let params = super::super::build_params(&d);
assert_eq!(params["sheet"], sheet.as_str());
assert_eq!(params["range"], "B2:C5");
}
#[test]
fn a_rule_switched_to_formula_picks_on_the_opening_scope() {
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
let mut app = SheetApp::new(session, Default::default());
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
// The dialog opens on the default (colour scale) type; choosing the formula type later
// turns point mode on, still on the sheet and range it opened with.
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
assert!(!d.picks_references());
d.values.insert("ruleType".into(), json!("formula"));
sync_rule_pick(&mut d);
assert!(d.picks_references());
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
let params = super::super::build_params(&d);
assert_eq!(params["sheet"], sheet.as_str());
assert_eq!(params["range"], "B2:C5");
}
#[test]
fn colour_scale_rule_keeps_the_opening_range_without_grid_references() {
let mut session = gridcraft_engine::Session::default();
session.new_workbook();
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
let mut app = SheetApp::new(session, Default::default());
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
let d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
assert!(!d.picks_references());
// No pick box, but the rule still covers the range and sheet the dialog opened on.
let params = super::super::build_params(&d);
assert_eq!(params["sheet"], sheet.as_str());
assert_eq!(params["range"], "B2:C5");
}
}
+13 -5
View File
@@ -91,6 +91,7 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
v["range"] = json!(pick.applies_to);
}
}
"newFormattingRule" => v = super::cond_format_rules::rule_params(d),
"series" => {
if let Some(s) = d.values.get("stop").and_then(Json::as_str).and_then(|s| s.parse::<f64>().ok()) {
v["stop"] = json!(s);
@@ -149,7 +150,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
let width = match d.name.as_str() {
"formatCells" => 560.0,
"about" => 820.0,
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "journal" | "agents" | "equation" => 520.0,
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "newFormattingRule" | "journal" | "agents" | "equation" => 520.0,
"macros" => 480.0,
"recommendedCharts" => 600.0,
"analysisToolPak" => 420.0,
@@ -195,6 +196,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
"nameManager" => name_manager(app, ui, &mut d, &mut open),
"pasteName" => paste_name(app, ui, &mut d, &mut confirm, &mut open),
"manageRules" => manage_rules(app, ui),
"newFormattingRule" => super::cond_format_rules::new_formatting_rule(ui, &mut d, &mut confirm, &mut open),
"recommendedCharts" => recommended_charts(app, ui, &mut d, &mut confirm, &mut open),
"selectData" => select_data(app, ui, &mut d, &mut confirm, &mut open),
"commandSearch" => command_search(app, ui, &mut d, &mut confirm),
@@ -524,6 +526,11 @@ pub(super) fn open_confirmed_link(app: &mut SheetApp, d: &Dialog) -> Result<(),
}
pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool) {
ok_cancel_enabled(ui, confirm, open, true);
}
/// Like [`ok_cancel`], but OK (and Enter) do nothing while `enabled` is false.
pub(super) fn ok_cancel_enabled(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool, enabled: bool) {
ui.add_space(8.0);
// A row as tall as the buttons: a right-to-left layout straight in the window takes all the
// height it is offered, which stretched every form dialog to the screen's height.
@@ -531,14 +538,15 @@ pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool)
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let lang = crate::i18n::current(ui.ctx());
let t = crate::theme::Tokens::get(ui.ctx());
let ok = ui.add(egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
if ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
let ok =
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
if enabled && (ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter))) {
*confirm = true;
}
if ui.button(format!(" {} ", lang.tr("Cancel"))).clicked() {
*open = false;
}
})
});
});
}
@@ -571,7 +579,7 @@ pub(super) fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
/// Keeps a picking formula box's caret, and gives it the keyboard back after a grid click put a
/// reference in it (the click took the focus), its caret after the reference.
fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
pub(super) fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
if typed {
pick.point = None;
}
+83 -4
View File
@@ -345,7 +345,10 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face
let mut bound: Vec<String> = Vec::new();
for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] {
let Some(primary) = pick_face(faces, bold, italic) else { continue };
let role = role_key(family, bold, italic);
let mut chain: Vec<String> = Vec::new();
// The face the role's text is actually drawn in: the first one whose file could be read.
let mut drawn: Option<&Face> = None;
for face in [Some(primary), pick_face(faces, false, false)] {
let Some(face) = face else { continue };
let key = face_key(face);
@@ -359,12 +362,15 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face
fonts.font_data.insert(key.clone(), std::sync::Arc::new(fd));
}
chain.push(key);
drawn.get_or_insert(face);
}
if chain.is_empty() {
continue;
}
let Some(drawn) = drawn else { continue };
// Imitate what the drawn face lacks: italic when it is upright; bold when it is the family's
// plain face (the family has no bold of its own, or the bold file couldn't be read).
let own_bold = pick_face(faces, false, italic).is_none_or(|plain| face_key(plain) != face_key(primary));
set_synthetic(&role, SLANT, italic && !drawn.italic);
set_synthetic(&role, BOLD, bold && (face_key(drawn) != face_key(primary) || !own_bold));
chain.extend(base.iter().cloned());
let role = role_key(family, bold, italic);
fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain);
bound.push(role);
}
@@ -389,6 +395,41 @@ pub fn is_bound(role: &str) -> bool {
bound().read().unwrap_or_else(std::sync::PoisonError::into_inner).contains(role)
}
/// Roles drawn with a face that lacks their slant or weight (Arial Black has one face only), as
/// `{role}|slant` and `{role}|bold`. Excel imitates the missing style (observed in its PDF: a cell in
/// Arial Black, bold italic, is slanted by 1/3 and outlined about 1/36 of its size thick).
static SYNTHETIC: OnceLock<std::sync::RwLock<HashSet<String>>> = OnceLock::new();
const SLANT: &str = "slant";
const BOLD: &str = "bold";
fn synthetic() -> &'static std::sync::RwLock<HashSet<String>> {
SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new()))
}
fn set_synthetic(role: &str, style: &str, on: bool) {
let mut set = synthetic().write().unwrap_or_else(|e| e.into_inner());
let key = format!("{role}|{style}");
if on {
set.insert(key);
} else {
set.remove(&key);
}
}
fn is_synthetic(role: &str, style: &str) -> bool {
is_bound(role) && synthetic().read().unwrap_or_else(|e| e.into_inner()).contains(&format!("{role}|{style}"))
}
/// Does italic text in this installed family have to be slanted when drawn (no italic face)?
pub fn is_slanted(family: &str, bold: bool) -> bool {
is_synthetic(&role_key(family, bold, true), SLANT)
}
/// Does bold text in this installed family have to be thickened when drawn (no face of its own)?
pub fn is_emboldened(family: &str, italic: bool) -> bool {
is_synthetic(&role_key(family, true, italic), BOLD)
}
/// Serializes tests that mutate the process-wide bound-family registry.
#[cfg(test)]
pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
@@ -490,6 +531,44 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn styles_a_family_has_no_face_for_are_imitated() {
let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = std::env::temp_dir().join(format!("gridcraft-fonts-synthetic-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
// One font file stands in for every face; each face is its own (path, index) by its name.
let face = |family: &str, file: &str, weight: f32, italic: bool| {
let path = dir.join(file);
std::fs::write(&path, epaint_default_fonts::UBUNTU_LIGHT).expect("write");
Face { family: family.into(), names: vec![family.into()], path, index: 0, weight, italic }
};
let mut fonts = egui::FontDefinitions::default();
// Like Arial Black: one face, whatever its weight.
let mut bound = bind_faces(&mut fonts, "One Face", &[face("One Face", "one.ttf", 900.0, false)]);
let full = [
face("Full", "full.ttf", 400.0, false),
face("Full", "full-b.ttf", 700.0, false),
face("Full", "full-i.ttf", 400.0, true),
face("Full", "full-bi.ttf", 700.0, true),
];
bound.extend(bind_faces(&mut fonts, "Full", &full));
// Bold and italic faces whose files can't be read: the regular face draws them, imitated.
let gone = |file: &str, weight: f32, italic: bool| Face { path: dir.join(file), ..face("Gone", "gone.ttf", weight, italic) };
let broken = [face("Gone", "gone.ttf", 400.0, false), gone("missing-b.ttf", 700.0, false), gone("missing-i.ttf", 400.0, true)];
bound.extend(bind_faces(&mut fonts, "Gone", &broken));
set_bound(bound);
assert!(is_slanted("One Face", false) && is_slanted("One Face", true));
assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true));
assert!(is_slanted("Gone", false) && is_emboldened("Gone", false), "the regular face stands in, imitated");
assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are");
assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are");
assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false));
set_bound([]);
assert!(!is_slanted("One Face", false) && !is_emboldened("One Face", false), "nothing is imitated once unbound");
let _ = std::fs::remove_dir_all(&dir);
}
/// A font that is just a table directory and a `name` table holding `records` as
/// `(Windows language id, name id, text)`: all [`file_faces`] reads.
#[cfg(not(target_arch = "wasm32"))]
+65
View File
@@ -327,6 +327,10 @@ pub struct GridState {
pub cells_rect: Option<Rect>,
/// Column and row of the clicked header cell, and where to open the menu.
pub filter_menu: Option<(u32, u32, Pos2)>,
/// Pending popup edits travel with this window and are dropped when its menu or window closes.
pub filter_checks: Option<Vec<(String, bool)>>,
pub filter_search: String,
pub filter_buttons: Vec<egui::Id>,
pub context_menu: Option<Pos2>,
/// The frame a right-click opened `context_menu` in: that click's own press doesn't close it.
pub context_menu_frame: u64,
@@ -401,10 +405,71 @@ pub struct GridState {
pub wheel_zoom: Option<WheelZoom>,
/// A one-finger touch drag in progress: it pans the sheet instead of selecting.
pub touch_pan: bool,
/// F8 Extend Selection or Shift+F8 Add or Remove Selection mode (see [`SelectionMode`]).
pub selection_mode: SelectionMode,
/// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next
/// arrow moves it again instead of keeping it.
pub add_pending: Option<RangeRef>,
/// Add mode header drag: the areas kept from before the drag, which the dragged range joins.
pub header_drag_base: Vec<String>,
/// What the macro step editor shows on the grid (Check, debugging).
pub macro_overlay: Option<crate::macro_editor::MacroOverlay>,
}
/// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and
/// clicks extend from the anchor as if Shift were held. In Add mode (Shift+F8) arrow keys move the
/// active cell without dropping the selected areas, Shift+arrows grow a new area from there, and a
/// click adds an area (or removes one already selected) as Ctrl+click does. Esc, the same key
/// again, or editing a cell turns the mode off.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SelectionMode {
#[default]
Off,
Extend,
Add,
}
impl SelectionMode {
/// The id the `ui.selectionMode` command takes and returns.
pub fn id(self) -> &'static str {
match self {
Self::Off => "off",
Self::Extend => "extend",
Self::Add => "add",
}
}
pub fn parse(id: &str) -> Option<Self> {
match id.trim().to_ascii_lowercase().as_str() {
"off" | "none" => Some(Self::Off),
"extend" => Some(Self::Extend),
"add" => Some(Self::Add),
_ => None,
}
}
/// The status bar text (an i18n catalog key), when the mode shows one.
pub fn status_text(self) -> Option<&'static str> {
match self {
Self::Off => None,
Self::Extend => Some("Extend Selection"),
Self::Add => Some("Add or Remove Selection"),
}
}
}
impl GridState {
/// Turns `mode` on, or off when it is already on (F8 / Shift+F8); the other mode ends.
pub fn toggle_selection_mode(&mut self, mode: SelectionMode) {
self.set_selection_mode(if self.selection_mode == mode { SelectionMode::Off } else { mode });
}
pub fn set_selection_mode(&mut self, mode: SelectionMode) {
self.selection_mode = mode;
self.add_pending = None;
}
}
/// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and
/// fine-grained wheels send parts of one, so the turning is counted in notches, and each whole
/// notch steps [`WHEEL_ZOOM_LADDER`]. With animations on the zoom then glides to that step.
+19
View File
@@ -230,6 +230,25 @@ pub(super) fn merged_edges(wb: &Workbook, si: usize, sh: &Sheet, geo: &Geo, area
out
}
/// One cell's text as a layout job, wrapped at `wrap` (`f32::INFINITY`: one line). `slant` draws it
/// oblique, for an italic cell whose font has no italic face (see [`crate::fonts::is_slanted`]).
pub(super) fn cell_job(text: String, font: FontId, color: Color32, wrap: f32, slant: bool) -> egui::text::LayoutJob {
let mut job = egui::text::LayoutJob::simple(text, font, color, wrap);
for section in &mut job.sections {
section.format.italics = slant;
}
job
}
/// Paints one cell's text; `bold_dx` > 0 paints it again that far right, to thicken a bold cell
/// whose font has no bold face (see [`crate::fonts::is_emboldened`]).
pub(super) fn paint_cell_galley(p: &Painter, pos: Pos2, galley: std::sync::Arc<egui::Galley>, color: Color32, bold_dx: f32) {
if bold_dx > 0.0 {
p.galley(pos + egui::vec2(bold_dx, 0.0), galley.clone(), color);
}
p.galley(pos, galley, color);
}
/// The smaller font that makes `text` fit in `room` points of width (Shrink to fit), or `None`
/// when it already fits at its own size.
pub(super) fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option<FontId> {
+38 -11
View File
@@ -4,11 +4,11 @@ use super::editor::validation_arrow;
use super::geo::Geo;
use super::keyboard::keyboard;
use super::menus::set_fill_tag;
use super::selection::select_ranges;
use super::selection::{add_mode_base, select_ranges};
use super::tables::{is_filter_button, table_headings};
use super::{
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, Sheet, SheetApp, Stroke, Tokens, Workbook,
json, pos2, vec2,
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, Tokens,
Workbook, json, pos2, vec2,
};
// ------------------------------------------------------------------ interaction
@@ -23,6 +23,7 @@ struct InteractionInput<'a> {
press_origin: Option<Pos2>,
any_pointer_down: bool,
modifiers: egui::Modifiers,
selection_modifiers: egui::Modifiers,
position: Option<Pos2>,
primary_clicked: bool,
in_cells: bool,
@@ -58,6 +59,12 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
let primary_clicked = resp.clicked_by(egui::PointerButton::Primary);
let pointer = ctx.input(|i| i.pointer.clone());
let mods = ctx.input(|i| i.modifiers);
let mut selection_modifiers = mods;
match app.grid.selection_mode {
SelectionMode::Extend => selection_modifiers.shift = true,
SelectionMode::Add => selection_modifiers.command = true,
SelectionMode::Off => {}
}
// Hit-testing works in logical coordinates (see `Geo::rtl`).
let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p));
let in_cells = pos.is_some_and(|p| geo.in_cells(p));
@@ -91,6 +98,7 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
press_origin: pointer.press_origin(),
any_pointer_down: pointer.any_down(),
modifiers: mods,
selection_modifiers,
position: pos,
primary_clicked,
in_cells,
@@ -341,7 +349,7 @@ fn handle_header_autofit(app: &mut SheetApp, input: &InteractionInput<'_>) -> bo
fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
let mods = input.modifiers;
let mods = input.selection_modifiers;
let resp = input.response;
let in_col_header = input.in_column_header;
if in_col_header {
@@ -372,6 +380,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
return;
}
let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) };
app.grid.header_drag_base = add_mode_base(app);
note_selecting_press(app);
select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c));
app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c });
@@ -380,7 +389,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
let mods = input.modifiers;
let mods = input.selection_modifiers;
let in_row_header = input.in_row_header;
if in_row_header {
if let Some((r, y)) = row_edge(geo, sh, p.y) {
@@ -394,6 +403,7 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
return;
}
let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) };
app.grid.header_drag_base = add_mode_base(app);
note_selecting_press(app);
select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0)));
app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r });
@@ -403,6 +413,7 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response);
let (pos, mods, sel) = (input.position, input.modifiers, &input.selection);
let sel_mods = input.selection_modifiers;
let (primary_clicked, in_cells, in_col_header, in_row_header, in_corner) =
(input.primary_clicked, input.in_cells, input.in_column_header, input.in_row_header, input.in_corner);
let (freeze_cols, freeze_rows) = (input.freeze_columns, input.freeze_rows);
@@ -520,13 +531,27 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
return;
}
app.grid.last_click = Some((c, now));
if mods.shift {
if sel_mods.shift {
note_selecting_press(app);
app.grid.header_drag_base = add_mode_base(app);
let mut ranges = app.grid.header_drag_base.clone();
if let Some(pending) = app.grid.add_pending.take()
&& ranges.last().is_some_and(|r| r == &pending.a1())
{
ranges.pop();
}
ranges.push(RangeRef::new(sel.anchor, c).a1());
let _ = app.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()}));
if let Some(d) = app.session.active_mut() {
d.selection.anchor = sel.anchor;
}
} else if mods.shift {
note_selecting_press(app);
let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()}));
if let Some(d) = app.session.active_mut() {
d.selection.anchor = sel.anchor;
}
} else if mods.command {
} else if mods.command || sel_mods.command {
// Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection.
if let Some(h) = sh.hyperlinks.get(&c).cloned()
&& acts
@@ -719,14 +744,16 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
}
Drag::Rows(anchor) => {
let r = geo.row_at(sh, p.y);
let _ =
app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()}));
let range = RangeRef::rows(anchor.min(r), anchor.max(r)).a1();
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
scroll_by(app, vec2(0.0, auto.y));
}
Drag::Cols(anchor) => {
let c = geo.col_at(sh, p.x);
let _ =
app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()}));
let range = RangeRef::cols(anchor.min(c), anchor.max(c)).a1();
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
scroll_by(app, vec2(auto.x, 0.0));
}
drag @ (Drag::PointRows(_) | Drag::PointCols(_)) => {
+78 -9
View File
@@ -1,7 +1,8 @@
use super::geo::Geo;
use super::interact::object_key;
use super::menus::is_checkbox;
use super::{CellRef, Drag, Sheet, SheetApp, json};
use super::selection::add_mode_move;
use super::{CellRef, Drag, SelectionMode, Sheet, SheetApp, json};
/// Whether something other than the grid owns the keyboard this frame: an editor, a dialog, a
/// message, a menu or another focused widget. Kept out of [`keyboard`] to hold its complexity
@@ -82,6 +83,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
use egui::Key;
let Some(m) = selection_mode_key(app, sh, key, m) else { continue };
let nudged = object_key(app, sh, key, m);
if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
shortcut_ran |= !nudged;
@@ -89,13 +91,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
let cmd = m.command;
let shift = m.shift;
let mv = |app: &mut SheetApp, dr: i64, dc: i64| {
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
app.grid.ensure_visible = true;
app.grid.reveal_moving_end = shift;
app.grid.reveal_from = from;
};
let mv = |app: &mut SheetApp, dr: i64, dc: i64| move_selection(app, dr, dc, shift, cmd);
match key {
Key::ArrowUp => mv(app, -1, 0),
Key::ArrowDown => mv(app, 1, 0),
@@ -106,6 +102,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
Key::PageUp if !cmd => mv(app, -page, 0),
Key::PageDown => app.run_or_alert("sheet.next", json!({})),
Key::PageUp => app.run_or_alert("sheet.previous", json!({})),
// Add mode: Home and End move the active cell as arrows do, keeping the selected areas.
Key::Home if cmd => {
let r = sh.freeze.map(|f| f.0).unwrap_or(0);
let c = sh.freeze.map(|f| f.1).unwrap_or(0);
@@ -149,11 +146,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
}
Key::Escape if app.selected_object.is_some() => app.selected_object = None,
Key::Escape => cancel_pending(app),
Key::Escape => cancel_pending_and_selection_mode(app),
Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})),
// F8 Extend Selection, Shift+F8 Add or Remove Selection: each toggles its mode.
Key::F8 if m.alt => {
app.open_dialog("macros", json!({}));
}
Key::F8 if !cmd => toggle_selection_mode(app, shift),
Key::F9 => app.run_or_alert("formulas.calculateNow", json!({})),
Key::F4 if !cmd => {}
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
@@ -243,6 +242,76 @@ fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response,
});
}
/// The F8 selection modes' part of a key press. Extend mode makes the navigation keys extend from
/// the anchor as if Shift were held; Add mode moves Shift+Home and Ctrl+Shift+End within the area
/// being added, and Home, Ctrl+Home and Ctrl+End move the active cell keeping the areas. The modifiers to handle the key with, or `None` when the key was handled here.
/// Kept out of [`keyboard`] to hold its complexity within the workspace limit.
fn selection_mode_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> Option<egui::Modifiers> {
use egui::Key;
let navigation =
matches!(key, Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::PageUp | Key::PageDown | Key::Home | Key::End);
let m = if navigation && app.grid.selection_mode == SelectionMode::Extend { egui::Modifiers { shift: true, ..m } } else { m };
if app.grid.selection_mode == SelectionMode::Add && m.shift && (key == Key::Home || (m.command && key == Key::End)) {
let from = app.session.active().map(|d| d.selection.moving_end()).unwrap_or_default();
let to = match (key, m.command) {
(Key::Home, true) => CellRef::new(0, 0),
(Key::Home, false) => CellRef::new(from.row, 0),
(Key::End, true) => sh.used_range().map(|u| u.end).unwrap_or_default(),
_ => from,
};
add_mode_move(app, i64::from(to.row) - i64::from(from.row), i64::from(to.col) - i64::from(from.col), true, false);
return None;
}
if add_mode_home_end(app, sh, key, m.command) {
return None;
}
Some(m)
}
/// An arrow or Page key's move: `selection.move` (extending with Shift, jumping with Ctrl), or in
/// Add mode a move of the active cell that keeps the selected areas.
fn move_selection(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, cmd: bool) {
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
if app.grid.selection_mode == SelectionMode::Add {
add_mode_move(app, dr, dc, shift, cmd);
app.grid.reveal_from = from;
return;
}
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
app.grid.ensure_visible = true;
app.grid.reveal_moving_end = shift;
app.grid.reveal_from = from;
}
/// Add mode: Home and Ctrl+Home/Ctrl+End move the active cell as the arrows do, keeping the
/// selected areas. Whether the key was one of those (and so was handled).
fn add_mode_home_end(app: &mut SheetApp, sh: &Sheet, key: egui::Key, cmd: bool) -> bool {
if app.grid.selection_mode != SelectionMode::Add || !(cmd || key == egui::Key::Home) {
return false;
}
let a = app.session.active().map(|d| d.selection.active).unwrap_or_default();
let to = match key {
egui::Key::Home if cmd => CellRef::new(sh.freeze.map(|f| f.0).unwrap_or(0), sh.freeze.map(|f| f.1).unwrap_or(0)),
egui::Key::End => sh.used_range().map(|u| u.end).unwrap_or_default(),
_ => CellRef::new(a.row, 0),
};
add_mode_move(app, i64::from(to.row) - i64::from(a.row), i64::from(to.col) - i64::from(a.col), false, false);
true
}
/// Esc: what [`cancel_pending`] cancels, and the F8 selection modes end.
fn cancel_pending_and_selection_mode(app: &mut SheetApp) {
cancel_pending(app);
let _ = app.run("ui.selectionMode", json!({"mode": "off"}));
}
/// F8 toggles Extend Selection, Shift+F8 Add or Remove Selection.
fn toggle_selection_mode(app: &mut SheetApp, shift: bool) {
let target = if shift { SelectionMode::Add } else { SelectionMode::Extend };
let mode = if app.grid.selection_mode == target { SelectionMode::Off } else { target };
let _ = app.run("ui.selectionMode", json!({"mode": mode.id()}));
}
/// This frame's input events, without those the focused form control took.
fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec<egui::Event> {
let events = ctx.input(|i| i.events.clone());
+13 -18
View File
@@ -31,14 +31,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
}
}
let wb = app.session.active().map(|d| d.wb.clone()).unwrap_or(wb);
let values = gridcraft_engine::cmd::data::filter_values(&wb, si, col);
let key = egui::Id::unique(("filter_sel", col));
let search_key = egui::Id::unique(("filter_search", col));
let buttons_key = egui::Id::unique(("filter_buttons", col));
// Enter is the menu's OK, as in Excel: taken before the search box (which would only drop its
// focus) and the value checkboxes (which would toggle) see it. A focused button keeps it as its click.
let buttons: Vec<egui::Id> = ui.ctx().data_mut(|d| d.get_temp(buttons_key)).unwrap_or_default();
let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| buttons.contains(&f));
let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| app.grid.filter_buttons.contains(&f));
let enter = !on_button && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
let mut close = false;
let area = egui::Area::new(egui::Id::unique("filter_menu")).fixed_pos(at + vec2(-180.0, 10.0)).order(egui::Order::Foreground);
@@ -57,9 +52,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
}
ui.separator();
ui.label(egui::RichText::new("Filter").strong());
let mut checks: Vec<(String, bool)> = ui.ctx().data_mut(|d| d.get_temp::<Vec<(String, bool)>>(key)).unwrap_or(values.clone());
let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col));
// A search narrows the list; Select All and Apply then only cover the matches.
let mut search: String = ui.ctx().data_mut(|d| d.get_temp(search_key)).unwrap_or_default();
let mut search = app.grid.filter_search.clone();
let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY));
if !was_open {
field.request_focus();
@@ -81,10 +76,8 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
ui.checkbox(on, v.as_str());
}
});
ui.ctx().data_mut(|d| {
d.insert_temp(key, checks.clone());
d.insert_temp(search_key, search.clone());
});
app.grid.filter_checks = Some(checks.clone());
app.grid.filter_search.clone_from(&search);
let checks: Vec<(String, bool)> = checks.iter().map(|(v, on)| (v.clone(), *on && matches(v))).collect();
ui.separator();
ui.horizontal(|ui| {
@@ -96,8 +89,12 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
// Nothing checked would hide every row, so Enter (unlike a click on Apply) does nothing then.
let any = checks.iter().any(|(_, on)| *on);
let apply = ui.button("Apply");
ui.ctx().data_mut(|d| d.insert_temp(buttons_key, vec![ascending.id, descending.id, clear.id, apply.id]));
app.grid.filter_buttons = vec![ascending.id, descending.id, clear.id, apply.id];
if apply.clicked() || (enter && any) {
let mut checks = gridcraft_engine::cmd::data::filter_selection(&wb, si, col, &checks);
for (value, on) in &mut checks {
*on &= matches(value);
}
let blanks = checks.iter().any(|(v, on)| v == "(Blanks)" && *on);
let vals: Vec<String> = checks.iter().filter(|(v, on)| *on && v != "(Blanks)").map(|(v, _)| v.clone()).collect();
let p = if checks.iter().all(|(_, b)| *b) {
@@ -112,11 +109,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
});
});
if close || popup_dismissed(&response.response, was_open) {
ui.ctx().data_mut(|d| {
d.remove::<Vec<(String, bool)>>(key);
d.remove::<String>(search_key);
d.remove::<Vec<egui::Id>>(buttons_key);
});
app.grid.filter_checks = None;
app.grid.filter_search.clear();
app.grid.filter_buttons.clear();
app.grid.filter_menu = None;
}
}
+26 -10
View File
@@ -1,7 +1,7 @@
use super::active_row::paint_active_row;
use super::cell_paint::{
Look, MergedArea, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, paint_cf_icon,
painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y,
Look, MergedArea, cell_job, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border,
paint_cell_galley, paint_cf_icon, painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y,
};
use super::geo::Geo;
use super::tables::{filter_button_rect, paint_filter_button};
@@ -352,6 +352,11 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
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);
// 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;
@@ -380,7 +385,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
// 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.direction = direction;
job.halign_min_is_start = false;
job.halign = match painted_halign(halign, geo.rtl) {
@@ -397,7 +402,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
let (text_top, text_bottom) = galley_baseline_bounds(&galley);
let y = wrapped_cell_text_y(st.align.v, *rect, text_bottom - text_top, z) - text_top;
let text_clip = wrapped_text_clip(p, *rect, &galley, y, st.align.v);
p.with_clip_rect(text_clip).galley(pos2(x, y), galley, color);
paint_cell_galley(&p.with_clip_rect(text_clip), pos2(x, y), galley, color, bold_dx(size));
return;
}
// Wrap Text off: Excel ignores the line breaks and draws the whole string on one line.
@@ -412,7 +417,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
let shrunk = small.is_some();
let font = small.unwrap_or(font);
let layout = |text: String| {
let mut job = egui::text::LayoutJob::simple(text, font.clone(), color, f32::INFINITY);
let mut job = cell_job(text, font.clone(), color, f32::INFINITY, slant);
job.direction = direction;
job.halign_min_is_start = false;
p.layout_job(job)
@@ -507,18 +512,16 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
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 mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0));
let mut job = cell_job(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0), slant);
job.direction = direction;
p.layout_job(job)
} else {
galley.clone()
};
let pos = rotated_text_pos(*rect, galley.size(), angle, halign, st.align.v, pad, indent);
let mut shape = egui::epaint::TextShape::new(pos, galley, color);
shape.angle = angle;
cp.add(shape);
paint_rotated_galley(&cp, pos, galley, color, angle, bold_dx(font.size));
} else {
cp.galley(pos2(x, y), galley.clone(), color);
paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx(font.size));
}
paint_text_decorations(
&cp,
@@ -526,6 +529,19 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
);
}
/// Paints rotated cell text; `bold_dx` > 0 first paints it that far along the text's own
/// direction, the second impression of imitated bold.
fn paint_rotated_galley(cp: &Painter, pos: Pos2, galley: std::sync::Arc<egui::Galley>, color: Color32, angle: f32, bold_dx: f32) {
if bold_dx > 0.0 {
let mut thick = egui::epaint::TextShape::new(pos + bold_dx * egui::vec2(angle.cos(), angle.sin()), galley.clone(), color);
thick.angle = angle;
cp.add(thick);
}
let mut shape = egui::epaint::TextShape::new(pos, galley, color);
shape.angle = angle;
cp.add(shape);
}
struct TextDecoration {
x: f32,
y: f32,
+57 -5
View File
@@ -3,7 +3,7 @@ use super::geo::Geo;
use super::interact::{hidden_col_edge, hidden_row_edge};
#[cfg(test)]
use super::show::hidden_around;
use super::{CellRef, Color32, Painter, RangeRef, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
use super::{CellRef, Color32, Painter, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
/// Where the active cell is on screen: the whole merged cell when it is part of one.
fn active_rect(geo: &Geo, sh: &Sheet, sel: &gridcraft_engine::Selection) -> Rect {
@@ -190,15 +190,67 @@ fn toggled_ranges(mut ranges: Vec<String>, clicked: String, add: bool) -> Vec<St
ranges
}
/// An arrow (or Page Up/Down, Ctrl+arrow) in Add mode. Without Shift the active cell moves and the
/// selected areas stay, the cell it lands on becoming a provisional last area that the next arrow
/// moves again; with Shift that area grows from its anchor and is kept, so the next arrow starts
/// another one.
pub(super) fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) {
app.grid.ensure_visible = true;
app.grid.reveal_moving_end = shift;
if shift {
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump}));
app.grid.add_pending = None;
return;
}
let Some(mut keep) = app.session.active().map(|d| d.selection.ranges.clone()) else { return };
// Only the provisional area this mode made is dropped, and only while it is still the last area.
if let Some(p) = app.grid.add_pending.take()
&& keep.last() == Some(&p)
{
keep.pop();
}
// The engine works out where the cell lands (hidden rows, merged cells, Ctrl+arrow jumps).
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump}));
let Some((area, active)) = app.session.active().map(|d| (d.selection.current(), d.selection.active)) else { return };
// Landing on an area already kept leaves it kept: the next arrow doesn't drop it.
let kept = keep.contains(&area);
keep.retain(|r| *r != area);
keep.push(area);
let range = keep.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
let _ = app.run("selection.set", json!({"range": range, "active": active.a1()}));
app.grid.add_pending = (!kept).then_some(area);
}
/// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes.
pub(super) fn add_mode_base(app: &SheetApp) -> Vec<String> {
if app.grid.selection_mode != SelectionMode::Add {
return Vec::new();
}
let mut ranges = app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect::<Vec<_>>()).unwrap_or_default();
if let Some(pending) = app.grid.add_pending
&& ranges.last().is_some_and(|range| range == &pending.a1())
{
ranges.pop();
}
ranges
}
pub(super) fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) {
let current: Vec<String> =
if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] };
// A clicked area is kept: the next Add mode arrow starts a new one.
app.grid.add_pending = None;
let current: Vec<RangeRef> = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] };
let clicked = r.a1();
let ranges = toggled_ranges(current, clicked.clone(), add);
// A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does.
let inside =
(add && current.len() > 1 && r.start == r.end).then(|| current.iter().position(|x| x.a1() != clicked && x.contains(r.start))).flatten();
let ranges: Vec<String> = match inside {
Some(i) => current.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, x)| x.a1()).collect(),
None => toggled_ranges(current.iter().map(|x| x.a1()).collect(), clicked.clone(), add),
};
// A removed area takes the active cell with it; `selection.set` then puts it at the start of the last area.
let params =
if ranges.contains(&clicked) { json!({"range": ranges.join(","), "active": active.a1()}) } else { json!({"range": ranges.join(",")}) };
let _ = app.session.run("selection.set", params);
let _ = app.run("selection.set", params);
}
#[cfg(test)]
+10
View File
@@ -360,6 +360,7 @@ impl<F: Fn(&mut SheetApp, egui::Vec2) -> Geo> ActiveCellVisibility<'_, F> {
}
fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) {
let window = app.session.active_window();
let previous_popups = (app.grid.filter_menu, app.grid.list_picker, app.grid.header_menu, app.grid.fill_menu);
// A pan the grid never saw end (it was hidden mid-drag) must not swallow the next press.
if app.grid.touch_pan && !resp.dragged() && !resp.drag_stopped() {
@@ -374,6 +375,15 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re
crate::paper_view::interact(app, ui, resp, geo, sh, wb);
interact(app, ui, resp, geo, sh, wb);
}
// A form button can switch windows and swap GridState; the old popup and geometry belong to the outgoing window.
if app.session.active_window() != window {
return;
}
if previous_popups.0 != app.grid.filter_menu && previous_popups.0.is_some() {
app.grid.filter_checks = None;
app.grid.filter_search.clear();
app.grid.filter_buttons.clear();
}
update_cursor(app, ui, resp, geo, sh);
crate::text_box::show(app, ui, geo, sh);
if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) {
+33
View File
@@ -435,6 +435,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Výběr odkazu",
"Calculate" => "Přepočítat",
"Select destination and press Enter or choose Paste" => "Vyberte cíl a stiskněte Enter nebo zvolte Vložit",
"Extend Selection" => "Rozšířit výběr",
"Add or Remove Selection" => "Přidat nebo odebrat výběr",
"General" => "Obecný",
"Number" => "Číslo",
"Currency" => "Měna",
@@ -580,6 +582,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Previous sheet" => "Předchozí list",
"Zoom In" => "Přiblížit",
"Zoom Out" => "Oddálit",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nové pravidlo formátování",
"Edit Formatting Rule" => "Upravit pravidlo formátování",
"Format all cells based on their values" => "Formátovat všechny buňky podle jejich hodnot",
"Format Style:" => "Styl formátu:",
"2-Color Scale" => "Dvoubarevná škála",
"3-Color Scale" => "Tříbarevná škála",
"Lowest value" => "Nejnižší hodnota",
"Highest value" => "Nejvyšší hodnota",
"Percent" => "Procento",
"Percentile" => "Percentil",
"Formula" => "Vzorec",
"Midpoint" => "Střední bod",
"More Rules…" => "Další pravidla…",
"Select a Rule Type" => "Vybrat typ pravidla",
"Edit the Rule Description" => "Upravit popis pravidla",
"Format only cells that contain" => "Formátovat pouze buňky, které obsahují",
"Format only top or bottom ranked values" => "Formátovat pouze hodnoty s nejvyšším nebo nejnižším pořadím",
"Format only values that are above or below average" => "Formátovat pouze hodnoty nad nebo pod průměrem",
"Format only unique or duplicate values" => "Formátovat pouze jedinečné nebo duplicitní hodnoty",
"Use a formula to determine which cells to format" => "Pomocí vzorce určit, které buňky se mají formátovat",
"Format values where this formula is true:" => "Formátovat hodnoty, pro které platí tento vzorec:",
"with" => "s",
"This rule type isn't available yet." => "Tento typ pravidla zatím není dostupný.",
// widgets.rs (alphabetical keys).
"Dismiss" => "Zavřít",
"Rename" => "Přejmenovat",
@@ -746,6 +772,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Vyplnit měsíce",
"Fill Years" => "Vyplnit roky",
"Auto Fill Options" => "Možnosti automatického vyplnění",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Světle červená výplň s tmavě červeným textem",
"Yellow Fill with Dark Yellow Text" => "Žlutá výplň s tmavě žlutým textem",
"Green Fill with Dark Green Text" => "Zelená výplň s tmavě zeleným textem",
"Light Red Fill" => "Světle červená výplň",
"Red Text" => "Červený text",
"Red Border" => "Červený rámeček",
_ => return None,
})
}
+33
View File
@@ -452,6 +452,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Zeigen",
"Calculate" => "Berechnen",
"Select destination and press Enter or choose Paste" => "Ziel auswählen und die Eingabetaste drücken oder „Einfügen“ wählen",
"Extend Selection" => "Markierung erweitern",
"Add or Remove Selection" => "Markierung hinzufügen oder entfernen",
"General" => "Standard",
"Number" => "Zahl",
"Currency" => "Währung",
@@ -671,6 +673,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Reihe…",
"Down" => "Nach unten",
"Up" => "Nach oben",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Neue Formatierungsregel",
"Edit Formatting Rule" => "Formatierungsregel bearbeiten",
"Select a Rule Type" => "Regeltyp auswählen",
"Edit the Rule Description" => "Regelbeschreibung bearbeiten",
"Format all cells based on their values" => "Alle Zellen basierend auf ihren Werten formatieren",
"Format only cells that contain" => "Nur Zellen formatieren, die enthalten",
"Format only top or bottom ranked values" => "Nur Werte formatieren, die oben oder unten eingestuft sind",
"Format only values that are above or below average" => "Nur Werte formatieren, die über oder unter dem Durchschnitt liegen",
"Format only unique or duplicate values" => "Nur eindeutige oder doppelte Werte formatieren",
"Use a formula to determine which cells to format" => "Formel zur Ermittlung der zu formatierenden Zellen verwenden",
"This rule type isn't available yet." => "Dieser Regeltyp ist noch nicht verfügbar.",
"Format Style:" => "Formatvorlage:",
"2-Color Scale" => "2-Farben-Skala",
"3-Color Scale" => "3-Farben-Skala",
"Midpoint" => "Mittelpunkt",
"Lowest value" => "Niedrigster Wert",
"Highest value" => "Höchster Wert",
"Percent" => "Prozent",
"Percentile" => "Perzentil",
"Formula" => "Formel",
"Format values where this formula is true:" => "Werte formatieren, für die diese Formel wahr ist:",
"with" => "mit",
"More Rules…" => "Weitere Regeln…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Helle rote Füllung mit dunkelrotem Text",
"Yellow Fill with Dark Yellow Text" => "Gelbe Füllung mit dunkelgelbem Text",
"Green Fill with Dark Green Text" => "Grüne Füllung mit dunkelgrünem Text",
"Light Red Fill" => "Helle rote Füllung",
"Red Text" => "Roter Text",
"Red Border" => "Roter Rahmen",
_ => return None,
})
}
+22
View File
@@ -1153,6 +1153,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Συμπλήρωση μηνών",
"Fill Years" => "Συμπλήρωση ετών",
"Auto Fill Options" => "Επιλογές αυτόματης συμπλήρωσης",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Νέος κανόνας μορφοποίησης",
"Edit Formatting Rule" => "Επεξεργασία κανόνα μορφοποίησης",
"Select a Rule Type" => "Επιλογή τύπου κανόνα",
"Edit the Rule Description" => "Επεξεργασία περιγραφής κανόνα",
"Format all cells based on their values" => "Μορφοποίηση όλων των κελιών με βάση τις τιμές τους",
"Format only cells that contain" => "Μορφοποίηση μόνο κελιών που περιέχουν",
"Format only top or bottom ranked values" => "Μορφοποίηση μόνο τιμών με την υψηλότερη ή χαμηλότερη κατάταξη",
"Format only values that are above or below average" => "Μορφοποίηση μόνο τιμών πάνω ή κάτω από τον μέσο όρο",
"Format only unique or duplicate values" => "Μορφοποίηση μόνο μοναδικών ή διπλότυπων τιμών",
"Use a formula to determine which cells to format" => "Χρήση τύπου για τον καθορισμό των κελιών που θα μορφοποιηθούν",
"This rule type isn't available yet." => "Αυτός ο τύπος κανόνα δεν είναι ακόμη διαθέσιμος.",
"Format Style:" => "Στυλ μορφής:",
"2-Color Scale" => "Κλίμακα 2 χρωμάτων",
"3-Color Scale" => "Κλίμακα 3 χρωμάτων",
"Midpoint" => "Μέσο σημείο",
"Lowest value" => "Χαμηλότερη τιμή",
"Highest value" => "Υψηλότερη τιμή",
"Percent" => "Ποσοστό",
"Percentile" => "Εκατοστημόριο",
"Formula" => "Τύπος",
"More Rules…" => "Περισσότεροι κανόνες…",
_ => return None,
})
}
+33
View File
@@ -439,6 +439,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Señalar",
"Calculate" => "Calcular",
"Select destination and press Enter or choose Paste" => "Seleccione el destino y presione Entrar o elija Pegar",
"Extend Selection" => "Extender selección",
"Add or Remove Selection" => "Agregar o quitar selección",
"General" => "General",
"Number" => "Número",
"Currency" => "Moneda",
@@ -677,6 +679,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Serie…",
"Down" => "Hacia abajo",
"Up" => "Hacia arriba",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nueva regla de formato",
"Edit Formatting Rule" => "Editar regla de formato",
"Select a Rule Type" => "Seleccionar un tipo de regla",
"Edit the Rule Description" => "Editar la descripción de la regla",
"Format all cells based on their values" => "Dar formato a todas las celdas según sus valores",
"Format only cells that contain" => "Dar formato solo a las celdas que contengan",
"Format only top or bottom ranked values" => "Dar formato solo a los valores con clasificación superior o inferior",
"Format only values that are above or below average" => "Dar formato solo a los valores que estén por encima o por debajo del promedio",
"Format only unique or duplicate values" => "Dar formato solo a los valores únicos o duplicados",
"Use a formula to determine which cells to format" => "Usar una fórmula para determinar qué celdas se van a aplicar formato",
"This rule type isn't available yet." => "Este tipo de regla aún no está disponible.",
"Format Style:" => "Estilo de formato:",
"2-Color Scale" => "Escala de 2 colores",
"3-Color Scale" => "Escala de 3 colores",
"Midpoint" => "Punto medio",
"Lowest value" => "Valor mínimo",
"Highest value" => "Valor máximo",
"Percent" => "Porcentaje",
"Percentile" => "Percentil",
"Formula" => "Fórmula",
"Format values where this formula is true:" => "Dar formato a los valores donde esta fórmula sea verdadera:",
"with" => "con",
"More Rules…" => "Más reglas…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Relleno rojo claro con texto rojo oscuro",
"Yellow Fill with Dark Yellow Text" => "Relleno amarillo con texto amarillo oscuro",
"Green Fill with Dark Green Text" => "Relleno verde con texto verde oscuro",
"Light Red Fill" => "Relleno rojo claro",
"Red Text" => "Texto rojo",
"Red Border" => "Borde rojo",
_ => return None,
})
}
+33
View File
@@ -314,6 +314,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Point",
"Calculate" => "Calculer",
"Select destination and press Enter or choose Paste" => "Sélectionnez la destination et appuyez sur Entrée ou choisissez Coller",
"Extend Selection" => "Étendre la sélection",
"Add or Remove Selection" => "Ajouter ou supprimer la sélection",
"General" => "Standard",
"Number" => "Nombre",
"Currency" => "Monétaire",
@@ -639,6 +641,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Série…",
"Down" => "Vers le bas",
"Up" => "Vers le haut",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nouvelle règle de mise en forme",
"Edit Formatting Rule" => "Modifier la règle de mise en forme",
"Select a Rule Type" => "Sélectionner un type de règle",
"Edit the Rule Description" => "Modifier la description de la règle",
"Format all cells based on their values" => "Mettre en forme toutes les cellules en fonction de leurs valeurs",
"Format only cells that contain" => "Mettre en forme uniquement les cellules qui contiennent",
"Format only top or bottom ranked values" => "Mettre en forme uniquement les valeurs classées en haut ou en bas",
"Format only values that are above or below average" => "Mettre en forme uniquement les valeurs supérieures ou inférieures à la moyenne",
"Format only unique or duplicate values" => "Mettre en forme uniquement les valeurs uniques ou en double",
"Use a formula to determine which cells to format" => "Utiliser une formule pour déterminer pour quelles cellules le format sera appliqué",
"This rule type isn't available yet." => "Ce type de règle n'est pas encore disponible.",
"Format Style:" => "Style de mise en forme :",
"2-Color Scale" => "Échelle à 2 couleurs",
"3-Color Scale" => "Échelle à 3 couleurs",
"Midpoint" => "Point milieu",
"Lowest value" => "Valeur la plus basse",
"Highest value" => "Valeur la plus haute",
"Percent" => "Pourcentage",
"Percentile" => "Centile",
"Formula" => "Formule",
"Format values where this formula is true:" => "Mettre en forme les valeurs pour lesquelles cette formule est vraie :",
"with" => "avec",
"More Rules…" => "Autres règles…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Remplissage rouge clair avec texte rouge foncé",
"Yellow Fill with Dark Yellow Text" => "Remplissage jaune avec texte jaune foncé",
"Green Fill with Dark Green Text" => "Remplissage vert avec texte vert foncé",
"Light Red Fill" => "Remplissage rouge clair",
"Red Text" => "Texte rouge",
"Red Border" => "Bordure rouge",
_ => return None,
})
}
+22
View File
@@ -1157,6 +1157,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Riempi mesi",
"Fill Years" => "Riempi anni",
"Auto Fill Options" => "Opzioni di riempimento automatico",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nuova regola di formattazione",
"Edit Formatting Rule" => "Modifica regola di formattazione",
"Select a Rule Type" => "Seleziona un tipo di regola",
"Edit the Rule Description" => "Modifica la descrizione della regola",
"Format all cells based on their values" => "Formatta tutte le celle in base ai loro valori",
"Format only cells that contain" => "Formatta solo le celle che contengono",
"Format only top or bottom ranked values" => "Formatta solo i valori con classificazione superiore o inferiore",
"Format only values that are above or below average" => "Formatta solo i valori superiori o inferiori alla media",
"Format only unique or duplicate values" => "Formatta solo valori univoci o duplicati",
"Use a formula to determine which cells to format" => "Usa una formula per determinare quali celle formattare",
"This rule type isn't available yet." => "Questo tipo di regola non è ancora disponibile.",
"Format Style:" => "Stile formato:",
"2-Color Scale" => "Scala a 2 colori",
"3-Color Scale" => "Scala a 3 colori",
"Midpoint" => "Punto medio",
"Lowest value" => "Valore minimo",
"Highest value" => "Valore massimo",
"Percent" => "Percentuale",
"Percentile" => "Percentile",
"Formula" => "Formula",
"More Rules…" => "Altre regole…",
_ => return None,
})
}
+22
View File
@@ -305,6 +305,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Point", "ポイント"),
("Calculate", "計算"),
("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"),
("Extend Selection", "選択範囲の拡張"),
("Add or Remove Selection", "選択範囲の追加または削除"),
("General", "標準"),
("Number", "数値"),
("Currency", "通貨"),
@@ -1143,6 +1145,26 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("\\@char has non-numeric argument {argument}", "\\@char の引数 {argument} が数値ではありません"),
("\\@char with invalid code point {code}", "\\@char のコード ポイント {code} が無効です"),
("Invalid environment name character: {character}", "環境名に無効な文字があります: {character}"),
("New Formatting Rule", "新しい書式ルール"),
("Edit Formatting Rule", "書式ルールの編集"),
("Select a Rule Type", "ルールの種類を選択"),
("Edit the Rule Description", "ルールの説明を編集"),
("Format all cells based on their values", "値に基づいてすべてのセルを書式設定"),
("Format only cells that contain", "含むセルのみを書式設定"),
("Format only top or bottom ranked values", "上位または下位に入る値のみを書式設定"),
("Format only values that are above or below average", "平均より上または下の値のみを書式設定"),
("Format only unique or duplicate values", "重複する値または一意の値のみを書式設定"),
("Use a formula to determine which cells to format", "数式を使用して、書式設定するセルを決定"),
("This rule type isn't available yet.", "このルールの種類はまだ使用できません。"),
("Format Style:", "書式スタイル:"),
("2-Color Scale", "2 色スケール"),
("3-Color Scale", "3 色スケール"),
("Midpoint", "中間"),
("Lowest value", "最小値"),
("Highest value", "最大値"),
("Percentile", "パーセンタイル"),
("Formula", "数式"),
("More Rules…", "その他のルール…"),
];
/// Labels of the ribbon menus, pop-ups and palettes that the reference catalog does not cover (the
+33
View File
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "가리키기",
"Calculate" => "계산",
"Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요",
"Extend Selection" => "선택 영역 확장",
"Add or Remove Selection" => "선택 영역 추가 또는 제거",
"General" => "일반",
"Number" => "숫자",
"Currency" => "통화",
@@ -637,6 +639,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "연속 데이터…",
"Down" => "아래쪽",
"Up" => "위쪽",
// Conditional formatting: colour scales.
"New Formatting Rule" => "새 서식 규칙",
"Edit Formatting Rule" => "서식 규칙 편집",
"Select a Rule Type" => "규칙 유형 선택",
"Edit the Rule Description" => "규칙 설명 편집",
"Format all cells based on their values" => "해당 값에 따라 모든 셀의 서식 지정",
"Format only cells that contain" => "다음을 포함하는 셀만 서식 지정",
"Format only top or bottom ranked values" => "순위가 위 또는 아래인 값만 서식 지정",
"Format only values that are above or below average" => "평균보다 높거나 낮은 값만 서식 지정",
"Format only unique or duplicate values" => "고유하거나 중복되는 값만 서식 지정",
"Use a formula to determine which cells to format" => "수식을 사용하여 서식을 지정할 셀 결정",
"This rule type isn't available yet." => "이 규칙 유형은 아직 사용할 수 없습니다.",
"Format Style:" => "서식 스타일:",
"2-Color Scale" => "2색조 눈금",
"3-Color Scale" => "3색조 눈금",
"Midpoint" => "중간점",
"Lowest value" => "최저값",
"Highest value" => "최고값",
"Percent" => "백분율",
"Percentile" => "백분위수",
"Formula" => "수식",
"Format values where this formula is true:" => "다음 수식을 만족하는 값에 서식 지정:",
"with" => "서식:",
"More Rules…" => "기타 규칙…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "연한 빨강 채우기 및 진한 빨강 텍스트",
"Yellow Fill with Dark Yellow Text" => "노랑 채우기 및 진한 노랑 텍스트",
"Green Fill with Dark Green Text" => "연한 초록 채우기 및 진한 초록 텍스트",
"Light Red Fill" => "연한 빨강 채우기",
"Red Text" => "빨강 텍스트",
"Red Border" => "빨강 테두리",
_ => return None,
})
}
+33
View File
@@ -305,6 +305,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Aanwijzen",
"Calculate" => "Berekenen",
"Select destination and press Enter or choose Paste" => "Selecteer de bestemming en druk op Enter of kies Plakken",
"Extend Selection" => "Selectie uitbreiden",
"Add or Remove Selection" => "Selectie toevoegen of verwijderen",
"General" => "Algemeen",
"Number" => "Getal",
"Currency" => "Valuta",
@@ -709,6 +711,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Maanden vullen",
"Fill Years" => "Jaren vullen",
"Auto Fill Options" => "Opties voor automatisch vullen",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nieuwe opmaakregel",
"Edit Formatting Rule" => "Opmaakregel bewerken",
"Select a Rule Type" => "Een regeltype selecteren",
"Edit the Rule Description" => "De beschrijving van de regel bewerken",
"Format all cells based on their values" => "Alle cellen opmaken op basis van hun waarden",
"Format only cells that contain" => "Alleen cellen opmaken die bevatten",
"Format only top or bottom ranked values" => "Alleen waarden met een hoge of lage rangorde opmaken",
"Format only values that are above or below average" => "Alleen waarden boven of onder het gemiddelde opmaken",
"Format only unique or duplicate values" => "Alleen unieke of dubbele waarden opmaken",
"Use a formula to determine which cells to format" => "Een formule gebruiken om te bepalen welke cellen worden opgemaakt",
"This rule type isn't available yet." => "Dit regeltype is nog niet beschikbaar.",
"Format Style:" => "Opmaakstijl:",
"2-Color Scale" => "Schaal met 2 kleuren",
"3-Color Scale" => "Schaal met 3 kleuren",
"Midpoint" => "Middelpunt",
"Lowest value" => "Laagste waarde",
"Highest value" => "Hoogste waarde",
"Percent" => "Percentage",
"Percentile" => "Percentiel",
"Formula" => "Formule",
"Format values where this formula is true:" => "Waarden opmaken waarop deze formule waar is:",
"with" => "met",
"More Rules…" => "Meer regels…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Lichte rode opvulling met donkerrode tekst",
"Yellow Fill with Dark Yellow Text" => "Gele opvulling met donkergele tekst",
"Green Fill with Dark Green Text" => "Groene opvulling met donkergroene tekst",
"Light Red Fill" => "Lichte rode opvulling",
"Red Text" => "Rode tekst",
"Red Border" => "Rode rand",
_ => return None,
})
}
+22
View File
@@ -1145,6 +1145,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Wypełnij miesiącami",
"Fill Years" => "Wypełnij latami",
"Auto Fill Options" => "Opcje autowypełniania",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nowa reguła formatowania",
"Edit Formatting Rule" => "Edytuj regułę formatowania",
"Select a Rule Type" => "Wybierz typ reguły",
"Edit the Rule Description" => "Edytuj opis reguły",
"Format all cells based on their values" => "Formatuj wszystkie komórki na podstawie ich wartości",
"Format only cells that contain" => "Formatuj tylko komórki zawierające",
"Format only top or bottom ranked values" => "Formatuj tylko wartości o najwyższej lub najniższej pozycji",
"Format only values that are above or below average" => "Formatuj tylko wartości powyżej lub poniżej średniej",
"Format only unique or duplicate values" => "Formatuj tylko wartości unikatowe lub zduplikowane",
"Use a formula to determine which cells to format" => "Użyj formuły do określenia, które komórki mają być formatowane",
"This rule type isn't available yet." => "Ten typ reguły nie jest jeszcze dostępny.",
"Format Style:" => "Styl formatu:",
"2-Color Scale" => "Skala dwukolorowa",
"3-Color Scale" => "Skala trójkolorowa",
"Midpoint" => "Punkt środkowy",
"Lowest value" => "Najniższa wartość",
"Highest value" => "Najwyższa wartość",
"Percent" => "Procent",
"Percentile" => "Percentyl",
"Formula" => "Formuła",
"More Rules…" => "Więcej reguł…",
_ => return None,
})
}
+24
View File
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Apontar",
"Calculate" => "Calcular",
"Select destination and press Enter or choose Paste" => "Selecione o destino e pressione Enter ou escolha Colar",
"Extend Selection" => "Estender Seleção",
"Add or Remove Selection" => "Adicionar ou Remover Seleção",
"General" => "Geral",
"Number" => "Número",
"Currency" => "Moeda",
@@ -1161,6 +1163,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Preencher Meses",
"Fill Years" => "Preencher Anos",
"Auto Fill Options" => "Opções de Autopreenchimento",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Nova Regra de Formatação",
"Edit Formatting Rule" => "Editar Regra de Formatação",
"Select a Rule Type" => "Selecionar um Tipo de Regra",
"Edit the Rule Description" => "Editar a Descrição da Regra",
"Format all cells based on their values" => "Formatar todas as células com base em seus valores",
"Format only cells that contain" => "Formatar apenas células que contenham",
"Format only top or bottom ranked values" => "Formatar apenas valores classificados acima ou abaixo",
"Format only values that are above or below average" => "Formatar apenas valores acima ou abaixo da média",
"Format only unique or duplicate values" => "Formatar apenas valores exclusivos ou duplicados",
"Use a formula to determine which cells to format" => "Usar uma fórmula para determinar quais células devem ser formatadas",
"This rule type isn't available yet." => "Este tipo de regra ainda não está disponível.",
"Format Style:" => "Estilo de Formatação:",
"2-Color Scale" => "Escala de 2 Cores",
"3-Color Scale" => "Escala de 3 Cores",
"Midpoint" => "Ponto Médio",
"Lowest value" => "Valor mais baixo",
"Highest value" => "Valor mais alto",
"Percent" => "Porcentagem",
"Percentile" => "Percentil",
"Formula" => "Fórmula",
"More Rules…" => "Mais Regras…",
_ => return None,
})
}
+22
View File
@@ -1207,6 +1207,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Umplere luni",
"Fill Years" => "Umplere ani",
"Auto Fill Options" => "Opțiuni de umplere automată",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Regulă de formatare nouă",
"Edit Formatting Rule" => "Editați regula de formatare",
"Select a Rule Type" => "Selectați un tip de regulă",
"Edit the Rule Description" => "Editați descrierea regulii",
"Format all cells based on their values" => "Formatați toate celulele în funcție de valorile lor",
"Format only cells that contain" => "Formatați numai celulele care conțin",
"Format only top or bottom ranked values" => "Formatați numai valorile clasate primele sau ultimele",
"Format only values that are above or below average" => "Formatați numai valorile peste sau sub medie",
"Format only unique or duplicate values" => "Formatați numai valorile unice sau duplicate",
"Use a formula to determine which cells to format" => "Utilizați o formulă pentru a stabili ce celule să fie formatate",
"This rule type isn't available yet." => "Acest tip de regulă nu este încă disponibil.",
"Format Style:" => "Stil de formatare:",
"2-Color Scale" => "Scară cu 2 culori",
"3-Color Scale" => "Scară cu 3 culori",
"Midpoint" => "Punct de mijloc",
"Lowest value" => "Valoarea cea mai mică",
"Highest value" => "Valoarea cea mai mare",
"Percent" => "Procent",
"Percentile" => "Percentilă",
"Formula" => "Formulă",
"More Rules…" => "Mai multe reguli…",
_ => return None,
})
}
+25
View File
@@ -301,6 +301,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Указание",
"Calculate" => "Вычисление",
"Select destination and press Enter or choose Paste" => "Выберите место вставки и нажмите Enter или выберите «Вставить»",
"Extend Selection" => "Расширить выделение",
"Add or Remove Selection" => "Добавить или удалить выделение",
"General" => "Общий",
"Number" => "Числовой",
"Currency" => "Денежный",
@@ -1211,6 +1213,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Заполнить по месяцам",
"Fill Years" => "Заполнить по годам",
"Auto Fill Options" => "Параметры автозаполнения",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Новое правило форматирования",
"Edit Formatting Rule" => "Изменение правила форматирования",
"Select a Rule Type" => "Выбор типа правила",
"Edit the Rule Description" => "Изменение описания правила",
"Format all cells based on their values" => "Форматировать все ячейки на основе их значений",
"Format only cells that contain" => "Форматировать только ячейки, которые содержат",
"Format only top or bottom ranked values" => "Форматировать только значения, имеющие верхний или нижний рейтинг",
"Format only values that are above or below average" => "Форматировать только значения выше или ниже среднего",
"Format only unique or duplicate values" => "Форматировать только уникальные или повторяющиеся значения",
"Use a formula to determine which cells to format" => "Использовать формулу для определения форматируемых ячеек",
"This rule type isn't available yet." => "Этот тип правила пока недоступен.",
"Format Style:" => "Стиль формата:",
"2-Color Scale" => "Двухцветная шкала",
"3-Color Scale" => "Трехцветная шкала",
"Midpoint" => "Средняя точка",
"Lowest value" => "Наименьшее значение",
"Highest value" => "Наибольшее значение",
"Percent" => "Процент",
"Percentile" => "Процентиль",
"Formula" => "Формула",
"More Rules…" => "Другие правила…",
// Conditional formatting: the formatting presets the rule editor offers.
_ => return None,
})
}
+33
View File
@@ -304,6 +304,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "Pokaži",
"Calculate" => "Izračunavanje",
"Select destination and press Enter or choose Paste" => "Izaberi odredište i pritisni Enter ili izaberi Nalepi",
"Extend Selection" => "Proširi izbor",
"Add or Remove Selection" => "Dodaj ili ukloni izbor",
"General" => "Opšte",
"Number" => "Broj",
"Currency" => "Valuta",
@@ -630,6 +632,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Niz…",
"Down" => "Nadole",
"Up" => "Nagore",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Novo pravilo oblikovanja",
"Edit Formatting Rule" => "Izmeni pravilo oblikovanja",
"Select a Rule Type" => "Izaberi tip pravila",
"Edit the Rule Description" => "Uredi opis pravila",
"Format all cells based on their values" => "Oblikuj sve ćelije na osnovu njihovih vrednosti",
"Format only cells that contain" => "Oblikuj samo ćelije koje sadrže",
"Format only top or bottom ranked values" => "Oblikuj samo vrednosti rangirane na vrhu ili dnu",
"Format only values that are above or below average" => "Oblikuj samo vrednosti iznad ili ispod proseka",
"Format only unique or duplicate values" => "Oblikuj samo jedinstvene ili duplikatne vrednosti",
"Use a formula to determine which cells to format" => "Koristi formulu za određivanje ćelija koje se oblikuju",
"This rule type isn't available yet." => "Ovaj tip pravila još nije dostupan.",
"Format Style:" => "Stil oblikovanja:",
"2-Color Scale" => "Dvobojna skala",
"3-Color Scale" => "Trobojna skala",
"Midpoint" => "Srednja tačka",
"Lowest value" => "Najniža vrednost",
"Highest value" => "Najviša vrednost",
"Percent" => "Procenat",
"Percentile" => "Percentil",
"Formula" => "Formula",
"Format values where this formula is true:" => "Oblikuj vrednosti za koje je ova formula tačna:",
"with" => "sa",
"More Rules…" => "Druga pravila…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Svetlo crvena ispuna sa tamno crvenim tekstom",
"Yellow Fill with Dark Yellow Text" => "Žuta ispuna sa tamno žutim tekstom",
"Green Fill with Dark Green Text" => "Zelena ispuna sa tamno zelenim tekstom",
"Light Red Fill" => "Svetlo crvena ispuna",
"Red Text" => "Crveni tekst",
"Red Border" => "Crveni okvir",
_ => return None,
})
}
+31
View File
@@ -602,6 +602,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Seri…",
"Down" => "Aşağı",
"Up" => "Yukarı",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Yeni Biçimlendirme Kuralı",
"Edit Formatting Rule" => "Biçimlendirme Kuralını Düzenle",
"Select a Rule Type" => "Kural Türü Seçin",
"Edit the Rule Description" => "Kural Açıklamasını Düzenle",
"Format all cells based on their values" => "Tüm hücreleri değerlerine göre biçimlendir",
"Format only cells that contain" => "Yalnızca şunu içeren hücreleri biçimlendir",
"Format only top or bottom ranked values" => "Yalnızca en yüksek veya en düşük sıralamadaki değerleri biçimlendir",
"Format only values that are above or below average" => "Yalnızca ortalamanın üstündeki veya altındaki değerleri biçimlendir",
"Format only unique or duplicate values" => "Yalnızca benzersiz veya yinelenen değerleri biçimlendir",
"Use a formula to determine which cells to format" => "Hangi hücrelerin biçimlendirileceğini belirlemek için formül kullan",
"This rule type isn't available yet." => "Bu kural türü henüz kullanılamıyor.",
"Format Style:" => "Biçim Stili:",
"2-Color Scale" => "2 Renkli Ölçek",
"3-Color Scale" => "3 Renkli Ölçek",
"Midpoint" => "Orta nokta",
"Lowest value" => "En düşük değer",
"Highest value" => "En yüksek değer",
"Percent" => "Yüzde",
"Percentile" => "Yüzdebirlik",
"Formula" => "Formül",
"Format values where this formula is true:" => "Bu formülün doğru olduğu değerleri biçimlendir:",
"with" => "ile",
"More Rules…" => "Diğer Kurallar…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Açık Kırmızı Dolgu ve Koyu Kırmızı Metin",
"Yellow Fill with Dark Yellow Text" => "Sarı Dolgu ve Koyu Sarı Metin",
"Green Fill with Dark Green Text" => "Yeşil Dolgu ve Koyu Yeşil Metin",
"Light Red Fill" => "Açık Kırmızı Dolgu",
"Red Text" => "Kırmızı Metin",
"Red Border" => "Kırmızı Kenarlık",
_ => return None,
})
}
+24 -2
View File
@@ -658,8 +658,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Last month" => "Last month",
"This month" => "This month",
"Next month" => "Next month",
"Format values where this formula is true:" => "Format values where this formula is true:",
"with" => "with",
"Format values where this formula is true:" => "Форматувати значення, для яких ця формула істинна:",
"with" => "з",
"Light Red Fill with Dark Red Text" => "Light Red Fill with Dark Red Text",
"Yellow Fill with Dark Yellow Text" => "Yellow Fill with Dark Yellow Text",
"Green Fill with Dark Green Text" => "Green Fill with Dark Green Text",
@@ -1149,6 +1149,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Fill Months" => "Заповнити місяці",
"Fill Years" => "Заповнити роки",
"Auto Fill Options" => "Параметри автозаповнення",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Нове правило форматування",
"Edit Formatting Rule" => "Змінити правило форматування",
"Select a Rule Type" => "Виберіть тип правила",
"Edit the Rule Description" => "Редагувати опис правила",
"Format all cells based on their values" => "Форматувати всі клітинки за їхніми значеннями",
"Format only cells that contain" => "Форматувати лише клітинки, що містять",
"Format only top or bottom ranked values" => "Форматувати лише значення з найвищим або найнижчим рейтингом",
"Format only values that are above or below average" => "Форматувати лише значення вище або нижче середнього",
"Format only unique or duplicate values" => "Форматувати лише унікальні або повторювані значення",
"Use a formula to determine which cells to format" => "Використати формулу, щоб визначити, які клітинки форматувати",
"This rule type isn't available yet." => "Цей тип правила ще недоступний.",
"Format Style:" => "Стиль формату:",
"2-Color Scale" => "Двоколірна шкала",
"3-Color Scale" => "Триколірна шкала",
"Midpoint" => "Середина",
"Lowest value" => "Найнижче значення",
"Highest value" => "Найвище значення",
"Percent" => "Відсоток",
"Percentile" => "Перцентиль",
"Formula" => "Формула",
"More Rules…" => "Більше правил…",
_ => return None,
})
}
+31
View File
@@ -598,6 +598,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "Chuỗi…",
"Down" => "Xuống",
"Up" => "Lên",
// Conditional formatting: colour scales.
"New Formatting Rule" => "Quy tắc định dạng mới",
"Edit Formatting Rule" => "Chỉnh sửa quy tắc định dạng",
"Select a Rule Type" => "Chọn loại quy tắc",
"Edit the Rule Description" => "Sửa mô tả quy tắc",
"Format all cells based on their values" => "Định dạng tất cả ô dựa trên giá trị của chúng",
"Format only cells that contain" => "Chỉ định dạng các ô chứa",
"Format only top or bottom ranked values" => "Chỉ định dạng các giá trị có thứ hạng cao nhất hoặc thấp nhất",
"Format only values that are above or below average" => "Chỉ định dạng các giá trị trên hoặc dưới mức trung bình",
"Format only unique or duplicate values" => "Chỉ định dạng các giá trị duy nhất hoặc trùng lặp",
"Use a formula to determine which cells to format" => "Dùng công thức để xác định ô nào cần định dạng",
"This rule type isn't available yet." => "Loại quy tắc này chưa khả dụng.",
"Format Style:" => "Kiểu định dạng:",
"2-Color Scale" => "Thang 2 màu",
"3-Color Scale" => "Thang 3 màu",
"Midpoint" => "Điểm giữa",
"Lowest value" => "Giá trị thấp nhất",
"Highest value" => "Giá trị cao nhất",
"Percent" => "Phần trăm",
"Percentile" => "Bách phân vị",
"Formula" => "Công thức",
"Format values where this formula is true:" => "Định dạng các giá trị mà công thức này đúng:",
"with" => "với",
"More Rules…" => "Thêm quy tắc…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "Tô đỏ nhạt với chữ đỏ đậm",
"Yellow Fill with Dark Yellow Text" => "Tô vàng với chữ vàng đậm",
"Green Fill with Dark Green Text" => "Tô xanh lá nhạt với chữ xanh lá đậm",
"Light Red Fill" => "Tô đỏ nhạt",
"Red Text" => "Chữ đỏ",
"Red Border" => "Viền đỏ",
_ => return None,
})
}
+33
View File
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Point" => "指向",
"Calculate" => "计算",
"Select destination and press Enter or choose Paste" => "选择目标位置并按 Enter,或选择“粘贴”",
"Extend Selection" => "扩展式选定",
"Add or Remove Selection" => "添加或删除所选内容",
"General" => "常规",
"Number" => "数值",
"Currency" => "货币",
@@ -621,6 +623,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Series…" => "序列…",
"Down" => "向下",
"Up" => "向上",
// Conditional formatting: colour scales.
"New Formatting Rule" => "新建格式规则",
"Edit Formatting Rule" => "编辑格式规则",
"Select a Rule Type" => "选择规则类型",
"Edit the Rule Description" => "编辑规则说明",
"Format all cells based on their values" => "基于各自值设置所有单元格的格式",
"Format only cells that contain" => "仅对包含以下内容的单元格设置格式",
"Format only top or bottom ranked values" => "仅对排名靠前或靠后的数值设置格式",
"Format only values that are above or below average" => "仅对高于或低于平均值的数值设置格式",
"Format only unique or duplicate values" => "仅对唯一值或重复值设置格式",
"Use a formula to determine which cells to format" => "使用公式确定要设置格式的单元格",
"This rule type isn't available yet." => "此规则类型尚不可用。",
"Format Style:" => "格式样式:",
"2-Color Scale" => "双色刻度",
"3-Color Scale" => "三色刻度",
"Midpoint" => "中点",
"Lowest value" => "最小值",
"Highest value" => "最大值",
"Percent" => "百分比",
"Percentile" => "百分位",
"Formula" => "公式",
"Format values where this formula is true:" => "为符合此公式的值设置格式:",
"with" => "格式:",
"More Rules…" => "其他规则…",
// Conditional formatting: the formatting presets the rule editor offers.
"Light Red Fill with Dark Red Text" => "浅红填充色深红色文本",
"Yellow Fill with Dark Yellow Text" => "黄填充色深黄色文本",
"Green Fill with Dark Green Text" => "绿填充色深绿色文本",
"Light Red Fill" => "浅红色填充",
"Red Text" => "红色文本",
"Red Border" => "红色边框",
_ => return None,
})
}
+49 -1
View File
@@ -702,6 +702,7 @@ fn number_combo(app: &mut SheetApp, ui: &mut Ui, st: &Style) {
}
fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
let lang = app.ui.language;
ui.menu_button("Highlight Cells Rules", |ui| {
for (label, op) in [("Greater Than…", "greater"), ("Less Than…", "less"), ("Between…", "between"), ("Equal To…", "equal")] {
if ui.button(label).clicked() {
@@ -754,6 +755,10 @@ fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
act(app, "home.conditionalFormat", json!({"rule": {"type": "colorScale", "colors": cols}}));
}
}
ui.separator();
if ui.button(lang.tr("More Rules…")).clicked() {
app.open_dialog("newFormattingRule", json!({"style": "3color"}));
}
});
ui.menu_button("Icon Sets", |ui| {
for (label, set) in [
@@ -771,7 +776,7 @@ fn cf_menu(app: &mut SheetApp, ui: &mut Ui) {
});
ui.separator();
if ui.button("New Rule…").clicked() {
app.open_dialog("cfQuick", json!({"type": "expression", "title": "New Formatting Rule"}));
app.open_dialog("newFormattingRule", json!({}));
}
ui.menu_button("Clear Rules", |ui| {
menu_items(
@@ -815,3 +820,46 @@ mod accounting_symbol_tests {
}
}
}
#[cfg(test)]
mod cf_menu_tests {
use super::*;
use egui_kittest::kittest::Queryable;
#[test]
fn new_rule_opens_the_rule_type_list_with_the_formula_entry() {
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let app = SheetApp::new(session, Default::default());
let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
cf_menu(app, ui);
crate::dialogs::show(app, ui.ctx());
},
app,
);
h.run_steps(2);
h.get_by_label("New Rule…").click();
h.run_steps(2);
let d = h.state().dialog.as_ref().expect("New Rule… opens a dialog");
assert_eq!(d.name(), "newFormattingRule");
assert_eq!(d.values.get("ruleType").and_then(serde_json::Value::as_str), Some("allCells"));
// Formula rules stay reachable: New Rule… shows Excel's rule-type list, formula entry included.
h.get_by_label("Use a formula to determine which cells to format");
}
#[test]
fn more_rules_follows_the_interface_language() {
let mut session = gridcraft_engine::Session::new();
session.new_workbook();
let mut app = SheetApp::new(session, Default::default());
app.run("app.language.set", serde_json::json!({"language": "es"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(|ui, app: &mut SheetApp| cf_menu(app, ui), app);
h.run_steps(2);
h.get_by_label("Color Scales").click();
h.run_steps(2);
let more = crate::i18n::Language::Es.tr("More Rules…");
assert_ne!(more, "More Rules…");
assert!(h.query_all_by_label(more).next().is_some(), "More Rules… stays English");
}
}
+5
View File
@@ -420,6 +420,11 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
gridcraft_engine::Mode::Point => "Point",
};
text(ui, egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim));
// F8 / Shift+F8 selection mode.
if let Some(label) = app.grid.selection_mode.status_text() {
ui.add_space(12.0);
text(ui, egui::RichText::new(app.ui.language.tr(label)).font(theme::ui_font(12.5)).color(t.text_dim));
}
crate::macro_ui::status(app, ui);
if let Some(d) = app.session.active() {
if d.wb.vba_project.is_some() {
+332
View File
@@ -0,0 +1,332 @@
//! New Formatting Rule: the 2-/3-colour scale branch and in-place editing.
use egui::vec2;
use egui_kittest::kittest::Queryable;
use gridcraft_engine::Session;
use gridcraft_engine::model::{CfRule, CfValueKind, Color};
use gridcraft_ui_egui::SheetApp;
use gridcraft_ui_egui::i18n::Language;
use serde_json::json;
fn harness() -> egui_kittest::Harness<'static, SheetApp> {
let mut session = Session::new();
session.new_workbook();
session.run("range.setValues", json!({"range": "A1:A3", "values": [[1], [2], [3]]})).unwrap();
session.run("selection.set", json!({"range": "A1:A3"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
h.run_steps(6);
h
}
fn stops(h: &egui_kittest::Harness<'static, SheetApp>) -> Vec<(CfValueKind, Color)> {
let doc = h.state().session.active().unwrap();
let rule = &doc.wb.active().unwrap().cond_formats[0].rule;
match rule {
CfRule::ColorScale { stops } => stops.clone(),
_ => Vec::new(),
}
}
#[test]
fn creates_a_three_colour_scale_with_per_stop_thresholds() {
let mut h = harness();
h.state_mut().run("home.conditionalFormat", json!({})).unwrap();
h.run_steps(6);
assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("newFormattingRule"));
h.state_mut().dialog.as_mut().unwrap().values.insert(
"stops".into(),
json!([
{"type": "min", "color": "#112233"},
{"type": "percentile", "value": 90, "color": "#445566"},
{"type": "max", "color": "#778899"},
]),
);
h.run_steps(2);
// The rule covers the sheet and range the dialog opened on, not the one shown at OK.
h.state_mut().run("home.insertSheet", json!({"name": "Two"})).unwrap();
h.state_mut().run("selection.set", json!({"range": "B1:B2"})).unwrap();
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
let two = h.state_mut().run("home.manageRules", json!({"sheet": "Two"})).unwrap();
assert_eq!(two["rules"].as_array().map(Vec::len), Some(0), "the rule does not land on the sheet shown at OK");
let list = h.state_mut().run("home.manageRules", json!({"sheet": "Sheet1"})).unwrap();
assert_eq!(list["rules"][0]["ranges"], json!(["A1:A3"]));
h.state_mut().run("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
assert_eq!(
stops(&h),
vec![
(CfValueKind::Min, Color::Rgb(0x112233)),
(CfValueKind::Percentile(90.0), Color::Rgb(0x445566)),
(CfValueKind::Max, Color::Rgb(0x778899)),
]
);
}
#[test]
fn edits_an_existing_scale_in_place() {
let mut h = harness();
h.state_mut()
.run(
"home.conditionalFormat",
json!({"rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "percentile", "value": 50, "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
h.run_steps(6);
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
h.state_mut().dialog.as_mut().unwrap().values.insert(
"stops".into(),
json!([
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
{"type": "max", "color": "#DEFDEF"},
]),
);
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
assert_eq!(stops(&h), vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
}
#[test]
fn new_rule_still_creates_a_formula_rule() {
let mut h = harness();
h.state_mut().open_dialog("newFormattingRule", json!({}));
h.run_steps(6);
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("allCells"));
h.get_by_label("Use a formula to determine which cells to format").click();
h.run_steps(4);
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("formula"));
h.state_mut().dialog.as_mut().unwrap().values.insert("formula".into(), json!("=A1>2"));
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
let rule = &h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule;
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2");
}
#[test]
fn the_editor_widgets_drive_the_scale() {
let mut h = harness();
h.state_mut().open_dialog("newFormattingRule", json!({}));
h.run_steps(6);
// Format Style: 3 -> 2 -> 3 through the combo itself.
h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("format style").click();
h.run_steps(2);
h.get_by_label("2-Color Scale").click();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().len(), 2);
h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("format style").click();
h.run_steps(2);
h.get_by_label("3-Color Scale").click();
h.run_steps(2);
// Midpoint: Percentile -> Number, then type a new threshold.
h.get_all_by_role(egui::accesskit::Role::ComboBox).nth(2).expect("midpoint type").click();
h.run_steps(2);
h.get_by_label("Number").click();
h.run_steps(2);
h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("midpoint threshold").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.key_press(egui::Key::Backspace);
h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("midpoint threshold").type_text("75");
h.key_press(egui::Key::Tab);
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().unwrap().values["stops"][1]["value"], json!(75.0));
h.get_by_label(" OK ").click();
h.run_steps(6);
assert_eq!(
stops(&h),
vec![(CfValueKind::Min, Color::Rgb(0xF8696B)), (CfValueKind::Number(75.0), Color::Rgb(0xFFEB84)), (CfValueKind::Max, Color::Rgb(0x63BE7B)),]
);
}
#[test]
fn switching_three_to_two_to_three_uses_the_default_midpoint() {
let mut h = harness();
h.state_mut()
.run(
"home.conditionalFormat",
json!({"rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "percentile", "value": 50, "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
h.run_steps(6);
// The style combo drives these transitions in `new_formatting_rule`.
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
h.run_steps(2);
let two = h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().clone();
assert_eq!(two.len(), 2);
assert_eq!(two[0]["color"], json!("#112233"), "dropping the midpoint keeps the minimum's colour");
assert_eq!(two[1]["color"], json!("#778899"), "dropping the midpoint keeps the maximum's colour");
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("3color"));
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
assert_eq!(
stops(&h),
vec![
(CfValueKind::Min, Color::Rgb(0x112233)),
(CfValueKind::Percentile(50.0), Color::Rgb(0xFFEB84)),
(CfValueKind::Max, Color::Rgb(0x778899)),
]
);
}
#[test]
fn edit_keeps_an_unchanged_theme_colour() {
let mut h = harness();
h.state_mut()
.run(
"home.conditionalFormat",
json!({"rule": {"type": "colorScale", "stops": [
{"type": "min", "color": {"theme": 4, "tint": 0}},
{"type": "percentile", "value": 50, "color": {"theme": 2, "tint": 0}},
{"type": "max", "color": {"theme": 6, "tint": 0}},
]}}),
)
.unwrap();
let rule = serde_json::to_value(&h.state().session.active().unwrap().wb.active().unwrap().cond_formats[0].rule).unwrap();
h.state_mut().open_dialog("newFormattingRule", json!({"edit": 0, "rule": rule}));
h.run_steps(6);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
assert_eq!(
stops(&h),
vec![(CfValueKind::Min, Color::Theme(4, 0)), (CfValueKind::Percentile(50.0), Color::Theme(2, 0)), (CfValueKind::Max, Color::Theme(6, 0)),]
);
}
#[test]
fn an_empty_formula_keeps_ok_disabled() {
let mut h = harness();
h.state_mut().open_dialog("newFormattingRule", json!({}));
h.run_steps(6);
h.get_by_label("Use a formula to determine which cells to format").click();
h.run_steps(4);
assert_eq!(h.state().dialog.as_ref().unwrap().values["ruleType"], json!("formula"));
// No formula typed: OK (and Enter) must do nothing, or the rule never applies.
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_some(), "the dialog stays open for a formula");
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
}
#[test]
fn an_unparseable_formula_is_refused_with_a_message() {
let mut h = harness();
h.state_mut().open_dialog("newFormattingRule", json!({}));
h.run_steps(6);
h.get_by_label("Use a formula to determine which cells to format").click();
h.run_steps(4);
h.state_mut().dialog.as_mut().unwrap().values.insert("formula".into(), json!("=C1>"));
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_some(), "an invalid formula keeps the dialog open");
let message = h.state().message.as_ref().map(|(_, m)| m.clone()).unwrap_or_default();
assert!(message.contains("invalid") && message.contains("does not parse"), "{message}");
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty(), "no unopenable rule is stored");
}
#[test]
fn switching_a_numeric_stop_to_formula_needs_a_formula() {
let mut h = harness();
h.state_mut().open_dialog("newFormattingRule", json!({}));
h.run_steps(6);
// Switching a Number stop to Formula without touching the field: the editor must store the
// field as a string rather than leave the old number in place, and OK must wait for one.
h.state_mut().dialog.as_mut().unwrap().values.insert(
"stops".into(),
json!([
{"type": "formula", "value": 7, "color": "#112233"},
{"type": "max", "color": "#778899"},
]),
);
h.run_steps(2);
let stops_json = h.state().dialog.as_ref().unwrap().values["stops"].as_array().unwrap().clone();
assert_eq!(stops_json[0]["value"], json!(""), "a numeric value is not a formula");
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_some(), "a formula stop with no formula does not confirm");
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
// A blank formula is refused the same way.
h.state_mut().dialog.as_mut().unwrap().values.insert(
"stops".into(),
json!([
{"type": "formula", "value": " ", "color": "#112233"},
{"type": "max", "color": "#778899"},
]),
);
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_some(), "a blank formula does not confirm");
assert!(h.state().session.active().unwrap().wb.active().unwrap().cond_formats.is_empty());
// A real formula confirms.
h.state_mut().dialog.as_mut().unwrap().values.insert("style".into(), json!("2color"));
h.state_mut().dialog.as_mut().unwrap().values.insert(
"stops".into(),
json!([
{"type": "formula", "value": "$Z$1", "color": "#112233"},
{"type": "max", "color": "#778899"},
]),
);
h.run_steps(2);
h.get_by_label(" OK ").click();
h.run_steps(6);
assert!(h.state().dialog.is_none());
assert_eq!(stops(&h), vec![(CfValueKind::Formula("$Z$1".into()), Color::Rgb(0x112233)), (CfValueKind::Max, Color::Rgb(0x778899))]);
}
#[test]
fn the_rule_list_translates_its_edit_button() {
let mut h = harness();
h.state_mut()
.run(
"home.conditionalFormat",
json!({"rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
h.state_mut().run("app.language.set", json!({"language": Language::Es.code()})).unwrap();
h.state_mut().open_dialog("manageRules", json!({}));
h.run_steps(6);
let edit = Language::Es.tr("Edit");
assert_ne!(edit, "Edit");
assert!(h.query_all_by_label(edit).next().is_some(), "Edit stays English");
}
@@ -0,0 +1,346 @@
use crate::common;
use egui::{Event, Key, Modifiers, PointerButton};
use egui_kittest::kittest::{NodeT, Queryable};
use gridcraft_engine::Session;
use gridcraft_engine::core::CellRef;
use gridcraft_engine::model::{ObjKind, ObjRef};
use gridcraft_ui_egui::grid;
use serde_json::json;
fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) {
for pressed in [true, false] {
h.input_mut().events.push(Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers });
}
h.run_steps(3);
}
fn click_filter(h: &mut common::Harness, cell: &str) {
let app = h.state();
let sh = app.session.active().unwrap().wb.active().unwrap();
let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll);
let at = grid::filter_button_rect(&geo, sh, CellRef::parse(cell).unwrap()).center();
h.input_mut().events.push(Event::PointerMoved(at));
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
h.run_steps(3);
}
#[test]
fn a_header_only_tables_popup_has_no_value_choices() {
let mut session = Session::new();
session.new_workbook();
session.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap();
session.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap();
session.execute("selection.set", json!({"cell": "B3"})).unwrap();
let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows);
click_filter(&mut h, "B3");
assert_eq!(h.state().grid.filter_menu.map(|(col, row, _)| (col, row)), Some((1, 2)));
let sh = h.state().session.active().unwrap().wb.active().unwrap();
assert_eq!(sh.tables[0].range.height(), 1);
assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3");
assert_eq!(h.state().grid.filter_checks, Some(vec![]));
assert!(h.query_by_label("(Blanks)").is_none());
key(&mut h, Key::Escape, Modifiers::NONE);
assert!(h.state().grid.filter_menu.is_none());
}
#[test]
fn switching_filter_columns_discards_old_edits_and_recomputes_eligible_choices() {
let mut session = Session::new();
session.new_workbook();
session
.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]
]}),
)
.unwrap();
session.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
session.execute("selection.set", json!({"cell": "B1"})).unwrap();
let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows);
key(&mut h, Key::ArrowDown, Modifiers::ALT);
h.get_by_label("Other").click();
h.run_steps(2);
assert!(h.state().grid.filter_search.is_empty());
click_filter(&mut h, "A1");
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0));
assert!(h.state().grid.filter_search.is_empty(), "the new column starts without the old search");
assert!(h.query_by_label("East").is_some(), "the new column's choices must remain available");
click_filter(&mut h, "B1");
assert_eq!(h.get_by_label("Other").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "old checkbox edits are discarded");
click_filter(&mut h, "A1");
h.get_by_label("West").click();
h.run_steps(2);
h.get_by_label("Apply").click();
h.run_steps(3);
click_filter(&mut h, "B1");
assert!(h.query_by_label("Alpha").is_some());
assert!(h.query_by_label("Beta").is_some(), "eligible alternatives must remain available");
assert!(h.query_by_label("Other").is_none(), "the other column's new criterion must narrow the reopened list");
}
#[test]
fn switching_filter_columns_keeps_another_windows_pending_choices() {
let mut session = Session::new();
session.new_workbook();
session
.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]
]}),
)
.unwrap();
session.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
session.execute("selection.set", json!({"cell": "B1"})).unwrap();
let image = std::env::var("GRIDCRAFT_FILTER_WINDOW_SNAPSHOT").ok();
let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0));
let builder = if image.is_some() { builder.wgpu() } else { builder };
let mut h = common::harness_with(builder, common::app(session), 4);
let first = h.state().session.active_window().unwrap();
key(&mut h, Key::ArrowDown, Modifiers::ALT);
h.state_mut().run("view.newWindow", json!({})).unwrap();
h.run_steps(3);
let second = h.state().session.active_window().unwrap();
assert_ne!(first, second);
assert_eq!(h.state().session.documents().len(), 1, "two windows on the same workbook");
click_filter(&mut h, "B1");
h.input_mut().events.push(Event::Text("Bet".into()));
h.run_steps(2);
h.get_by_label("Beta").click();
h.run_steps(2);
assert!(h.query_by_label("Alpha").is_none());
assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));
if let Some(path) = &image {
h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap();
}
h.state_mut().enter_window(first);
h.run_steps(2);
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1));
click_filter(&mut h, "A1");
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0));
h.state_mut().enter_window(second);
h.run_steps(3);
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1));
assert!(h.query_by_label("Alpha").is_none(), "switching the other window's column must keep this search");
assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False), "its unsaved checkbox stays unchecked");
if let Some(path) = image {
h.render().unwrap().save(path).unwrap();
}
assert!(h.state().session.active().unwrap().wb.active().unwrap().autofilter.as_ref().unwrap().criteria.is_empty(), "no filter was applied");
}
#[test]
fn a_form_button_window_switch_keeps_the_incoming_filter_edits() {
let mut session = Session::new();
session.new_workbook();
session
.execute("range.setValues", json!({"range": "A1", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]}))
.unwrap();
session.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
let button = session.execute("insert.button", json!({"at": "E12", "text": "Other window"})).unwrap()["control"].as_u64().unwrap() as u32;
let image = std::env::var("GRIDCRAFT_FILTER_BUTTON_WINDOW_SNAPSHOT").ok();
let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0));
let builder = if image.is_some() { builder.wgpu() } else { builder };
let mut h = common::harness_with(builder, common::app(session), 4);
let first = h.state().session.active_window().unwrap();
click_filter(&mut h, "A1");
h.state_mut().run("view.newWindow", json!({})).unwrap();
h.run_steps(3);
let second = h.state().session.active_window().unwrap();
h.state_mut().run("control.assign", json!({"id": button, "command": "view.switchWindows", "params": {"window": second}})).unwrap();
click_filter(&mut h, "B1");
h.input_mut().events.push(Event::Text("Bet".into()));
h.run_steps(2);
h.get_by_label("Beta").click();
h.run_steps(2);
let checks = h.state().grid.filter_checks.clone();
assert_eq!(h.state().grid.filter_search, "Bet");
assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));
if let Some(path) = &image {
h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap();
}
h.state_mut().enter_window(first);
h.run_steps(2);
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0));
let app = h.state();
let sh = app.session.doc().unwrap().wb.active().unwrap();
let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll);
let at = gridcraft_ui_egui::chartview::object_rect(&geo, sh, ObjRef::new(ObjKind::Control, button)).unwrap().center();
for pressed in [true, false] {
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
h.input_mut().events.push(Event::PointerMoved(at));
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
assert_eq!(h.state().session.active_window(), Some(second), "the real button action switches windows during grid interaction");
assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1));
assert_eq!(h.state().grid.filter_search, "Bet", "the outgoing popup must not clear the incoming search");
assert_eq!(h.state().grid.filter_checks, checks, "the incoming window keeps its unsaved checkbox edits");
assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));
if let Some(path) = image {
h.render().unwrap().save(path).unwrap();
}
}
#[test]
fn applying_eligible_choices_preserves_values_and_blanks_hidden_by_another_filter() {
for table in [false, true] {
for click in [false, true] {
for edit in [false, true] {
for (values, blanks, other_hidden, blank_hidden) in
[(vec!["Alpha", "Other"], false, false, true), (vec!["Alpha", "Beta"], false, true, true), (vec!["Alpha"], true, true, false)]
{
let mut session = Session::new();
session.new_workbook();
session
.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["West", null]
]}),
)
.unwrap();
if table {
session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap();
} else {
session.execute("data.filter", json!({"range": "A1:B5"})).unwrap();
}
session.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": blanks})).unwrap();
session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
session.execute("selection.set", json!({"cell": "B1"})).unwrap();
let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows);
key(&mut h, Key::ArrowDown, Modifiers::ALT);
assert!(h.query_by_label("Other").is_none());
assert!(h.query_by_label("(Blanks)").is_none());
if edit {
h.get_by_label("Beta").click();
h.run_steps(2);
}
if click {
h.get_by_label("Apply").click();
h.run_steps(3);
} else {
key(&mut h, Key::Enter, Modifiers::NONE);
}
assert!(h.state().grid.filter_menu.is_none());
h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap();
let sh = h.state().session.active().unwrap().wb.active().unwrap();
let beta_hidden = values.contains(&"Beta") == edit;
assert_eq!(
(1..=4).map(|row| sh.is_row_hidden(row)).collect::<Vec<_>>(),
[false, beta_hidden, other_hidden, blank_hidden],
"table={table}, click={click}, edit={edit}, values={values:?}"
);
}
}
}
}
}
#[test]
fn search_apply_excludes_hidden_nonmatches_and_keeps_hidden_matches() {
for click in [false, true] {
for beta in [false, true] {
let mut session = Session::new();
session.new_workbook();
let mut values = vec![json!(["Company", "Job"]), json!(["East", "Alpha"])];
if beta {
values.push(json!(["East", "Beta"]));
}
values.extend([json!(["West", "Alphonse"]), json!(["West", "Other"]), json!(["West", null])]);
let last = values.len() - 1;
session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
session.execute("data.filter", json!({"range": format!("A1:B{}", last + 1)})).unwrap();
session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
session.execute("selection.set", json!({"cell": "B1"})).unwrap();
let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows);
key(&mut h, Key::ArrowDown, Modifiers::ALT);
assert!(h.query_by_label("Other").is_none());
assert!(h.query_by_label("Alphonse").is_none());
h.input_mut().events.push(Event::Text("Alph".into()));
h.run_steps(2);
assert_eq!(h.state().grid.filter_search, "Alph");
assert!(h.query_by_label("Alpha").is_some());
assert!(h.query_by_label("Beta").is_none());
if click {
h.get_by_label("Apply").click();
h.run_steps(3);
} else {
key(&mut h, Key::Enter, Modifiers::NONE);
}
assert!(h.state().grid.filter_menu.is_none());
h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap();
let sh = h.state().session.active().unwrap().wb.active().unwrap();
assert!(!sh.is_row_hidden(1), "Alpha must remain selected");
assert!(!sh.is_row_hidden((last - 2) as u32), "hidden Alphonse must still match the search");
assert!(sh.is_row_hidden((last - 1) as u32), "hidden Other must be excluded: click={click}, beta={beta}");
assert!(sh.is_row_hidden(last as u32), "hidden blanks do not match the search");
if beta {
assert!(sh.is_row_hidden(2), "eligible Beta does not match the search");
}
}
}
}
#[test]
fn dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() {
for table in [false, true] {
let mut session = Session::new();
session.new_workbook();
session
.execute(
"range.setValues",
json!({"range": "A1", "values": [
["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["East", null]
]}),
)
.unwrap();
if table {
session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap();
}
session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
session.execute("data.filterBy", json!({"column": "B", "values": ["Alpha"]})).unwrap();
session.execute("selection.set", json!({"cell": "B1"})).unwrap();
let screenshot = std::env::var("GRIDCRAFT_CASCADING_SNAPSHOT").ok().filter(|_| !table);
let mut h = if screenshot.is_some() {
common::harness_with(
common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)).wgpu(),
common::app(session),
4,
)
} else {
common::os_harness(session, egui::os::OperatingSystem::Windows)
};
key(&mut h, Key::ArrowDown, Modifiers::ALT);
assert!(h.query_by_label("Alpha").is_some());
assert!(h.query_by_label("Beta").is_some(), "current-column filtering must not remove alternatives");
assert!(h.query_by_label("(Blanks)").is_some());
assert!(h.query_by_label("Other").is_none(), "the other company's job must not be listed");
if let Some(path) = screenshot {
h.render().unwrap().save(path).unwrap();
}
h.get_by_label("Alpha").click();
h.run_steps(2);
h.get_by_label("Beta").click();
h.run_steps(2);
h.get_by_label("Apply").click();
h.run_steps(3);
let hidden = |h: &common::Harness| {
let sh = h.state().session.active().unwrap().wb.active().unwrap();
(1..=4).map(|row| sh.is_row_hidden(row)).collect::<Vec<_>>()
};
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");
}
}
+6 -3
View File
@@ -286,13 +286,16 @@ fn table_filter_autofit_works_through_command_and_header_double_click() {
let cell = gridcraft_engine::core::CellRef::new(0, 0);
let rect = geo.cell_rect(sheet, cell);
let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell);
let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell));
// The heading as the grid draws it: in the table style's font, bold in the header row.
// Measured as AutoFit measured it, with the app's fonts (they differ from machine to
// machine). The app installs them before AutoFit runs; AutoFit without them, on the
// engine's estimate, is `autofit_filter_buttons` in the engine's tests.
let wb = &app.session.active().unwrap().wb;
let table = sheet.table_at(cell).expect("A1 is the table's header");
let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet(), table, cell).font;
assert!(font.bold, "the table style draws its header bold");
let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts");
let measured = measure("Quarterly Revenue", &style.font, true);
let text_width = measured * geo.z;
let text_width = measure("Quarterly Revenue", &font, true) * geo.z;
assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}");
assert_eq!(app.session.active().unwrap().undo.len(), 1);
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
+33
View File
@@ -1663,6 +1663,39 @@ fn general_numbers_fit_by_the_cells_own_font() {
assert_eq!(texts.iter().filter(|t| t.starts_with('#')).count(), 1, "{texts:?}");
}
/// #1077: after Increase Decimal and the other ribbon number formats the column widens enough for
/// the real font, so the number is drawn instead of ####, at the default size and a large bold one.
#[test]
fn ribbon_number_formats_widen_the_column_enough_to_draw_the_number() {
let mut s = blank();
s.execute("range.setValues", json!({"range": "A1", "values": [[1.23456789, 1234567.891, 98765.4321], [0.5, 1, 2]]})).unwrap();
s.execute("home.fontSize", json!({"range": "C1", "size": 20})).unwrap();
s.execute("home.bold", json!({"range": "C1", "on": true})).unwrap();
for _ in 0..4 {
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
}
s.execute("home.comma", json!({"range": "B1"})).unwrap();
s.execute("home.numberFormat", json!({"range": "C1", "format": "Currency"})).unwrap();
s.execute("selection.set", json!({"cell": "E5"})).unwrap();
let want: Vec<String> =
["A1", "B1", "C1"].iter().map(|a| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].as_str().unwrap().trim().to_string()).collect();
assert_eq!(want, ["1.234567890000", "1,234,567.89", "$98,765.43"]);
let h = harness(s);
let texts: Vec<String> = h
.output()
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some(t.galley.job.text.clone()),
_ => None,
})
.collect();
for t in &want {
assert!(texts.iter().any(|x| x.trim() == t), "{t} drawn in full: {texts:?}");
}
assert!(!texts.iter().any(|t| t.starts_with('#')), "no ####: {texts:?}");
}
fn text_shapes(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::epaint::TextShape, egui::Rect)>) {
match shape {
egui::Shape::Text(t) => out.push((t.clone(), clip)),
+208 -2
View File
@@ -1,10 +1,12 @@
//! Excel keyboard shortcuts (crate::keymap) dispatched through real egui key events.
use egui::{Event, Key, Modifiers};
use egui::{Event, Key, Modifiers, PointerButton};
use egui_kittest::kittest::Queryable as _;
use gridcraft_engine::Session;
use gridcraft_engine::core::CellRef;
use gridcraft_engine::model::BorderStyle;
use gridcraft_ui_egui::SheetApp;
use gridcraft_ui_egui::grid::{Geo, SelectionMode};
use gridcraft_ui_egui::keymap::{Shortcut, lookup};
use serde_json::json;
@@ -77,6 +79,210 @@ fn copy_formula_from_above_and_function_keys() {
assert_eq!(h.state().session.active().unwrap().wb.sheets[0].zoom, 110);
}
fn selection_a1(h: &Harness) -> String {
h.state().session.active().unwrap().selection.a1()
}
fn active_a1(h: &Harness) -> String {
h.state().session.active().unwrap().selection.active.a1()
}
fn mode(h: &Harness) -> SelectionMode {
h.state().grid.selection_mode
}
#[test]
fn f8_extend_selection_extends_from_the_anchor_until_turned_off() {
let mut h = harness(book("A1"));
assert!(h.query_by_label("Extend Selection").is_none());
key(&mut h, Key::F8, Modifiers::NONE);
assert_eq!(mode(&h), SelectionMode::Extend);
assert!(h.query_by_label("Extend Selection").is_some(), "the status bar shows the mode");
key(&mut h, Key::ArrowRight, Modifiers::NONE);
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection_a1(&h), "A1:B2");
assert_eq!(active_a1(&h), "A1", "the active cell stays on the anchor");
// Ctrl+arrow extends to the edge of the data, as Ctrl+Shift+arrow does.
key(&mut h, Key::ArrowDown, CTRL);
assert_eq!(selection_a1(&h), "A1:B3");
// F8 again ends the mode: arrows move again.
key(&mut h, Key::F8, Modifiers::NONE);
assert_eq!(mode(&h), SelectionMode::Off);
assert!(h.query_by_label("Extend Selection").is_none());
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B1");
// Esc ends it too, and keeps the extended selection.
key(&mut h, Key::F8, Modifiers::NONE);
key(&mut h, Key::ArrowRight, Modifiers::NONE);
key(&mut h, Key::Escape, Modifiers::NONE);
assert_eq!(mode(&h), SelectionMode::Off);
assert_eq!(selection_a1(&h), "B1:C1");
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B2");
}
#[test]
fn shift_f8_add_to_selection_builds_areas_with_arrow_keys() {
let mut h = harness(book("A1:A2"));
key(&mut h, Key::F8, Modifiers::SHIFT);
assert_eq!(mode(&h), SelectionMode::Add);
assert!(h.query_by_label("Add or Remove Selection").is_some(), "the status bar shows the mode");
assert!(h.query_by_label("Extend Selection").is_none());
// Arrows move the active cell and keep A1:A2; the next arrow moves the new cell again.
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection_a1(&h), "A1:A2,B1");
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection_a1(&h), "A1:A2,C1");
assert_eq!(active_a1(&h), "C1");
// Shift+arrow grows that area from it and keeps it.
key(&mut h, Key::ArrowRight, Modifiers::SHIFT);
assert_eq!(selection_a1(&h), "A1:A2,C1:D1");
assert_eq!(active_a1(&h), "C1");
// The next arrow starts a third area.
key(&mut h, Key::ArrowDown, Modifiers::NONE);
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection_a1(&h), "A1:A2,C1:D1,C3");
// F8 switches to Extend mode, and Shift+F8 twice ends Add mode.
key(&mut h, Key::F8, Modifiers::NONE);
assert_eq!(mode(&h), SelectionMode::Extend);
key(&mut h, Key::F8, Modifiers::SHIFT);
assert_eq!(mode(&h), SelectionMode::Add);
key(&mut h, Key::F8, Modifiers::SHIFT);
assert_eq!(mode(&h), SelectionMode::Off);
assert!(h.query_by_label("Add or Remove Selection").is_none());
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection_a1(&h), "D3", "with the mode off an arrow drops the areas");
}
#[test]
fn editing_a_cell_ends_the_selection_mode() {
let mut h = harness(book("A1"));
key(&mut h, Key::F8, Modifiers::NONE);
key(&mut h, Key::F2, Modifiers::NONE);
assert!(h.state().editor.is_some());
assert_eq!(mode(&h), SelectionMode::Off);
key(&mut h, Key::Escape, Modifiers::NONE);
key(&mut h, Key::F8, Modifiers::SHIFT);
h.input_mut().events.push(Event::Text("7".into()));
h.run_steps(2);
assert!(h.state().editor.is_some(), "typing starts an edit");
assert_eq!(mode(&h), SelectionMode::Off);
}
fn click(h: &mut Harness, a1: &str) {
let at = {
let app = h.state();
let sheet = app.session.active().unwrap().wb.active().unwrap();
Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll).cell_rect(sheet, CellRef::parse(a1).unwrap()).center()
};
h.input_mut().events.push(Event::PointerMoved(at));
h.run_steps(1);
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(1);
}
h.run_steps(1);
}
#[test]
fn clicks_extend_or_add_in_the_selection_modes() {
let mut h = harness(book("B2"));
key(&mut h, Key::F8, Modifiers::NONE);
click(&mut h, "D4");
assert_eq!(selection_a1(&h), "B2:D4", "in Extend mode a click extends from the anchor");
assert_eq!(mode(&h), SelectionMode::Extend, "the mode stays on");
key(&mut h, Key::F8, Modifiers::SHIFT);
click(&mut h, "F6");
assert_eq!(selection_a1(&h), "B2:D4,F6", "in Add mode a click adds an area");
// (Not a double-click: that would edit the cell.)
h.state_mut().grid.last_click = None;
click(&mut h, "F6");
assert_eq!(selection_a1(&h), "B2:D4", "and a click on a selected area removes it");
// An arrow after a click keeps the clicked areas.
click(&mut h, "H8");
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B2:D4,H8,H9");
// Moving back onto the kept H8 and off again keeps it.
key(&mut h, Key::ArrowUp, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B2:D4,H8");
key(&mut h, Key::ArrowDown, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B2:D4,H8,H9");
}
/// A point in the column header band, above `col`'s cells.
fn column_header_point(h: &Harness, col: &str) -> egui::Pos2 {
let app = h.state();
let sheet = app.session.active().unwrap().wb.active().unwrap();
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
let x = geo.cell_rect(sheet, CellRef::parse(&format!("{col}1")).unwrap()).center().x;
egui::pos2(x, geo.head_top() + 4.0)
}
fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) {
h.input_mut().events.push(Event::PointerMoved(from));
h.run_steps(1);
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.input_mut().events.push(Event::PointerMoved(to));
h.run_steps(2);
h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
#[test]
fn add_mode_header_drag_keeps_the_earlier_areas() {
let mut h = harness(book("B2"));
key(&mut h, Key::F8, Modifiers::SHIFT);
click(&mut h, "F6");
assert_eq!(selection_a1(&h), "B2,F6");
h.state_mut().grid.last_click = None;
let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J"));
drag(&mut h, from, to);
assert_eq!(selection_a1(&h), "B2,F6,H:J", "a header drag in Add mode adds its columns and keeps the areas already selected");
}
#[test]
fn add_mode_header_drag_replaces_only_the_provisional_area() {
let mut h = harness(book("B2"));
key(&mut h, Key::F8, Modifiers::SHIFT);
key(&mut h, Key::ArrowRight, Modifiers::NONE);
assert_eq!(selection_a1(&h), "B2,C2");
h.state_mut().grid.last_click = None;
let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J"));
drag(&mut h, from, to);
assert_eq!(selection_a1(&h), "B2,H:J", "the header drag replaces the provisional area while retaining earlier areas");
}
#[test]
fn add_mode_shift_home_and_end_keep_the_earlier_areas() {
let mut home = harness(book("B2"));
key(&mut home, Key::F8, Modifiers::SHIFT);
click(&mut home, "F6");
key(&mut home, Key::Home, Modifiers::SHIFT);
assert_eq!(selection_a1(&home), "B2,A6:F6", "Shift+Home extends the active area and keeps the earlier area");
let mut end = harness(book("B2"));
key(&mut end, Key::F8, Modifiers::SHIFT);
click(&mut end, "F6");
key(&mut end, Key::End, CTRL_SHIFT);
assert_eq!(selection_a1(&end), "B2,C3:F6", "Ctrl+Shift+End extends the active area and keeps the earlier area");
}
#[test]
fn selection_mode_command_sets_and_reports_without_a_dialog() {
let mut h = harness(book("A1"));
assert_eq!(h.state_mut().run("ui.selectionMode", json!({})), Ok(json!({"mode": "off"})));
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "extend"})), Ok(json!({"mode": "extend"})));
h.run_steps(2);
assert!(h.query_by_label("Extend Selection").is_some());
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "add"})), Ok(json!({"mode": "add"})));
assert!(h.state_mut().run("ui.selectionMode", json!({"mode": "sideways"})).is_err());
assert!(h.state_mut().run("ui.selectionMode", json!({"mode": 3})).is_err());
assert_eq!(mode(&h), SelectionMode::Add, "a bad mode changes nothing");
assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "off"})), Ok(json!({"mode": "off"})));
assert!(h.state().dialog.is_none());
}
#[test]
fn windows_and_mac_variants() {
let cmd = CTRL;
@@ -169,7 +375,7 @@ fn alt_down_opens_autofilter_headers_without_changing_the_workbook() {
// Opening focuses the existing search box; typing must not edit the header.
h.input_mut().events.push(Event::Text("1".into()));
h.run_steps(2);
assert_eq!(h.ctx.data(|data| data.get_temp::<String>(egui::Id::unique(("filter_search", column)))).as_deref(), Some("1"));
assert_eq!(h.state().grid.filter_search, "1");
assert!(h.state().editor.is_none());
assert_eq!(h.state().session.active().unwrap().wb, before);
key(&mut h, Key::Escape, Modifiers::NONE);
+1
View File
@@ -13,6 +13,7 @@ mod argument_names;
mod autosave_persist;
mod autosum_edit;
mod borders;
mod cascading_filter_values;
mod cell_editor_caret;
mod cell_pictures;
mod cf_rule_pick;
+2
View File
@@ -15,6 +15,8 @@ fn harness() -> Harness {
s.execute("cell.set", json!({"cell": "A1", "input": "Executive Producer"})).unwrap();
s.execute("home.formatCells", json!({"range": "A1", "style": shrink})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "Control Producer"})).unwrap();
// Column A's width set by hand (to the default), so the numbers formatted below keep it.
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 64})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "123456789012"})).unwrap();
s.execute("home.formatCells", json!({"range": "A4", "style": {"num_fmt": "#,##0", "align": {"shrink": true}}})).unwrap();
s.execute("cell.set", json!({"cell": "A5", "input": "123456789012"})).unwrap();
+19 -3
View File
@@ -7,8 +7,14 @@
//! mapped to XML elements, form controls other than the buttons, scroll bars and spin buttons
//! `controls.rs` models, ActiveX controls, OLE objects, the sheet background and printer settings, with the sheet's `<picture>`, `<oleObjects>` and `<controls>` XML, the `r:id`
//! of `<pageSetup>`, the legacy VML shapes those controls need and the pictures of the headers and
//! footers, `&G`, with their `<legacyDrawingHF>`). The workbook also keeps its
//! `<fileVersion>` and the calcFeatures extension, which Excel needs to trust the saved values.
//! footers, `&G`, with their `<legacyDrawingHF>`). The workbook's Data Model (`xl/model/item.data`)
//! is kept with its data connections. PivotTables whose source is in another workbook, a data
//! connection or the Data Model are kept too: the PivotTable parts with their sheet, the cache
//! definition and records parts (with the cache's link to the other workbook's path) with the
//! workbook and its `<pivotCache>` entry, its `cacheId` unchanged; a cache on a connection only
//! when the connections are kept, and on the Data Model only when the model is kept. The workbook
//! also keeps its `<fileVersion>` and the calcFeatures extension, which Excel needs to trust the
//! saved values.
//!
//! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in
//! kept XML are rewritten to match. Kept content is conservative:
@@ -19,6 +25,7 @@
//! opened, followed or refreshed. A relative path to a linked workbook is rewritten when the
//! workbook is saved into another folder ([`rebase_links`]), so it still names the same file.
//! - Sheet content lives on the sheet: deleting the sheet drops it, Copy Sheet doesn't copy it.
//! A kept pivot cache no kept PivotTable uses any more is dropped with it.
//! Cell references inside kept parts (a control's linked cell, a query table's range, a cell
//! mapped to an XML element) are kept as they were, not adjusted to inserted or deleted rows.
//! - Strict Open XML files are not passed through (their namespaces differ from what we write).
@@ -38,6 +45,7 @@ use quick_xml::{Reader, Writer};
use crate::IoError;
use crate::package::{self, normalize};
use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot, KeptSource};
use crate::read::Ctx;
use crate::write::{NS_REL, Out, Rels, XML_DECL};
use crate::xml::{self, esc_attr};
@@ -50,7 +58,7 @@ pub use read::KeptReader;
pub use rebase::{SheetKept, rebase_links};
#[cfg(test)]
pub(crate) use write::sheet_names_in;
pub use write::{KeptOut, SheetIds, WorkbookKept, workbook_elements, write_package_rels, write_workbook};
pub use write::{KeptOut, SheetIds, WorkbookKept, finish_style_ids, workbook_elements, write_package_rels, write_workbook};
/// Most bytes kept for one workbook.
pub const MAX_KEPT_TOTAL: usize = 256 * 1024 * 1024;
@@ -101,6 +109,13 @@ const SHEET_ELEMENT_KINDS: &[&str] = &["oleObject", "ctrlProp", "control", "imag
const FILE_VERSION_ATTRS: &[&str] = &["appName", "lastEdited", "lowestEdited", "rupBuild", "codeName"];
/// Kept sheet elements, in schema order (all after `<legacyDrawing>`, before `<tableParts>`).
const SHEET_SLOTS: &[&str] = &["legacyDrawingHF", "picture", "oleObjects", "controls"];
/// Rewritten kinds a kept PivotTable (source in another workbook) reaches: the table, from the
/// sheet, and its cache, which the workbook keeps (several tables can share one cache).
const PIVOT_TABLE_GRAPH: &[&str] = &["pivotTable", "pivotCacheDefinition"];
/// Rewritten kinds a kept pivot cache reaches.
const PIVOT_CACHE_GRAPH: &[&str] = &["pivotCacheDefinition", "pivotCacheRecords"];
/// The workbook's Data Model part (Power Pivot), kept byte for byte when its connections are.
const DATA_MODEL_GRAPH: &[&str] = &["powerPivotData"];
/// Relationship kinds GridCraft reads and rewrites, or that depend on content it rewrites:
/// kept content whose graph reaches one of them is dropped.
@@ -166,6 +181,7 @@ const OWN_DIRS: &[&str] = &[
"xl/activex/",
"xl/webextensions/",
"xl/printersettings/",
"xl/model/",
];
fn kind(rel_type: &str) -> &str {
+167 -4
View File
@@ -53,6 +53,9 @@ pub struct KeptReader {
overrides: HashMap<String, String>,
budget: usize,
parts_left: usize,
/// Cache definition parts of the PivotTables kept with their sheets (source in another
/// workbook, a data connection or the Data Model), kept with the workbook.
pivot_caches: Vec<(String, KeptSource)>,
}
impl KeptReader {
@@ -69,6 +72,7 @@ impl KeptReader {
overrides: HashMap::new(),
budget: kept_total(),
parts_left: MAX_KEPT_PARTS,
pivot_caches: vec![],
};
if let Ok(root) = raw_rels(cx, "")
&& root.iter().any(|r| r.rel_type.starts_with("http://purl.oclc.org/"))
@@ -146,7 +150,12 @@ impl KeptReader {
}
queue.push_back((r.target.clone(), depth + 1));
}
parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels });
let (dxfs, num_fmts) = if content_type == CT_PIVOT_TABLE || content_type == CT_PIVOT_CACHE_DEF {
style_refs(cx, &data).ok_or_else(|| format!("{name} is damaged"))?
} else {
(vec![], vec![])
};
parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels, dxfs, num_fmts });
}
self.budget = self.budget.saturating_sub(bytes);
self.parts_left = self.parts_left.saturating_sub(parts.len());
@@ -217,6 +226,20 @@ impl KeptReader {
cx.warn(format!("{} part {} was dropped: {why}", kind(&r.rel_type), r.target));
}
}
// The Data Model: its tables are loaded through the workbook's connections, so it is kept
// only with them.
let connections = p.rels.iter().any(|r| is_kind(r, &["connections"]));
for r in wb_rels.iter().filter(|r| !r.external && is_kind(r, DATA_MODEL_GRAPH)).take(1) {
let kept = if connections {
self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut seen, DATA_MODEL_GRAPH)
} else {
Err("the workbook's data connections were not kept".into())
};
match kept {
Ok(()) => cx.warn("the workbook's Data Model is kept for saving as it is; it can't be viewed, edited or refreshed here"),
Err(why) => cx.warn(format!("the workbook's Data Model was dropped: {why}")),
}
}
// Chart sheets: the sheet entry (name, state, position) plus the chart sheet part and the
// drawing, chart, style and colour parts behind it.
for (worksheets, se) in chart_sheet_entries(wb_xml, &wb_rels, file_to_model) {
@@ -261,6 +284,7 @@ impl KeptReader {
Err(why) => cx.warn(format!("links to external workbooks were dropped: {why}")),
}
}
self.keep_pivot_caches(cx, wb_xml, &wb_rels, &mut p, &mut seen);
// Excel trusts the saved cell values only when both are present; without them it
// recalculates everything on open, and links into closed workbooks come back as errors.
if let Some(v) = wb_xml.child("fileVersion") {
@@ -278,11 +302,77 @@ impl KeptReader {
(!p.is_empty()).then(|| Arc::new(p))
}
/// Sheet-level content of the sheet part `part`. `controls` says which form controls the
/// The caches of the kept PivotTables, each with its `<pivotCache>` entry (original `cacheId`
/// and relationship id).
fn keep_pivot_caches(&mut self, cx: &mut Ctx<'_>, wb_xml: &xml::El, wb_rels: &[PreservedRel], p: &mut Preserved, seen: &mut HashSet<String>) {
let caches = std::mem::take(&mut self.pivot_caches);
// A cache names its connection by id in the kept connections part, and a Data Model cache
// reads the kept model: without them Excel refuses the file or can't refresh it.
let connections = p.rels.iter().any(|r| is_kind(r, &["connections"]));
let model = p.rels.iter().any(|r| is_kind(r, DATA_MODEL_GRAPH));
let (mut no_connections, mut no_model) = (0usize, 0usize);
for (cache, source) in &caches {
match source {
KeptSource::Connection | KeptSource::DataModel if !connections => {
no_connections += 1;
continue;
}
KeptSource::DataModel if !model => {
no_model += 1;
continue;
}
_ => {}
}
let entry = wb_xml.child("pivotCaches").into_iter().flat_map(|c| c.kids("pivotCache")).find_map(|c| {
let id = c.attr_u32("cacheId")?;
let r = wb_rels.iter().find(|r| Some(r.id.as_str()) == c.attr("id") && !r.external && is_kind(r, &["pivotCacheDefinition"]))?;
(normalize(&r.target) == normalize(cache)).then(|| (id, r.clone()))
});
let Some((id, r)) = entry else {
cx.warn(format!(
"the cache {cache} of a PivotTable on {} is not in the workbook's list; the PivotTable was dropped",
source.describe()
));
continue;
};
match self.keep_through(cx, p, std::slice::from_ref(&r), seen, PIVOT_CACHE_GRAPH) {
Ok(()) => p.elements.push(PreservedXml {
slot: "pivotCache".into(),
xml: format!("<pivotCache xmlns:r=\"{NS_REL}\" cacheId=\"{id}\" r:id=\"{}\"/>", esc_attr(&r.id)),
}),
Err(why) => cx.warn(format!("the cache of a PivotTable on {} was dropped with its PivotTables: {why}", source.describe())),
}
}
if no_connections > 0 {
cx.warn(format!(
"{no_connections} PivotTable cache(s) on a data connection or the Data Model were dropped with their PivotTables (kept as plain cells): the workbook's data connections were not kept"
));
}
if no_model > 0 {
cx.warn(format!(
"{no_model} PivotTable cache(s) on the workbook's Data Model were dropped with their PivotTables (kept as plain cells): the Data Model was not kept"
));
}
}
/// Sheet-level content of the sheet part `part`; `pivots` are its PivotTables whose source is
/// in another workbook. `controls` says which form controls the
/// sheet reader modelled (their VML shapes are left out of the kept content) and whether the
/// VML drawing holds others that only it lists.
pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str, controls: &crate::controls::ReadControls) -> Option<Arc<Preserved>> {
pub fn sheet(
&mut self,
cx: &mut Ctx<'_>,
part: &str,
name: &str,
pivots: &[ExternalPivot],
controls: &crate::controls::ReadControls,
) -> Option<Arc<Preserved>> {
if !self.on {
if !pivots.is_empty() {
cx.warn(format!(
"sheet \"{name}\": PivotTables on another workbook, a data connection or the Data Model are not kept on save in this file"
));
}
return None;
}
let rels = match raw_rels(cx, part) {
@@ -305,6 +395,22 @@ impl KeptReader {
if rels.iter().any(|r| is_kind(r, SHEET_ELEMENT_KINDS)) || vml_drawings > notes || controls.vml_only_unmodelled {
self.sheet_elements(cx, part, name, &rels, &mut p, &mut seen, controls);
}
for ep in pivots {
let Some(r) = rels.iter().find(|r| r.id == ep.rel_id && !r.external && is_kind(r, &["pivotTable"])) else { continue };
// The cache is kept with the workbook, not followed from here.
let mut scoped = seen.clone();
scoped.insert(normalize(&ep.cache_part));
match self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut scoped, PIVOT_TABLE_GRAPH) {
Ok(()) => {
scoped.remove(&normalize(&ep.cache_part));
seen = scoped;
if !self.pivot_caches.iter().any(|(c, _)| normalize(c) == normalize(&ep.cache_part)) {
self.pivot_caches.push((ep.cache_part.clone(), ep.source));
}
}
Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on {} was dropped: {why}", ep.source.describe())),
}
}
(!p.is_empty()).then(|| Arc::new(p))
}
@@ -427,11 +533,68 @@ impl KeptReader {
let mut q = Preserved::default();
let roots: Vec<PreservedRel> = vrels.iter().filter(|r| !r.external).cloned().collect();
self.keep(cx, &mut q, &roots, seen)?;
let vml = PreservedPart { name: rel.target.clone(), content_type: CT_VML.into(), data: Arc::from(text.into_bytes()), rels: vrels };
let vml = PreservedPart {
name: rel.target.clone(),
content_type: CT_VML.into(),
data: Arc::from(text.into_bytes()),
rels: vrels,
..Default::default()
};
Ok((vml, q.parts))
}
}
/// Attribute values of `local` (any prefix) in an XML part, in document order. `None` when the
/// XML is damaged.
fn attr_values(data: &[u8], local: &[&[u8]], mut f: impl FnMut(&[u8], &str)) -> Option<()> {
let text = xml::to_utf8(data);
let mut reader = Reader::from_reader(text.as_ref());
let mut buf = vec![];
loop {
match reader.read_event_into(&mut buf).ok()? {
Event::Eof => return Some(()),
Event::Start(e) | Event::Empty(e) => {
for a in e.attributes().with_checks(false) {
let a = a.ok()?;
let k = a.key.local_name();
if let Some(name) = local.iter().find(|n| **n == k.as_ref())
&& let Ok(v) = std::str::from_utf8(&a.value)
{
f(name, v);
}
}
}
_ => {}
}
buf.clear();
}
}
/// The differential formats (`dxfId`) and custom number formats (`numFmtId`) of the source
/// styles part a kept PivotTable or pivot cache refers to. `None` when its XML is damaged.
type StyleRefs = (Vec<(u32, gridcraft_model::Style)>, Vec<(u32, String)>);
fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option<StyleRefs> {
let mut dxfs: Vec<(u32, gridcraft_model::Style)> = vec![];
let mut fmts: Vec<(u32, String)> = vec![];
// Membership sets: a crafted part can name many distinct ids, so scanning the vectors would be quadratic.
let (mut seen_dxfs, mut seen_fmts) = (HashSet::new(), HashSet::new());
attr_values(data, &[b"dxfId", b"numFmtId"], |name, v| {
let Ok(id) = v.trim().parse::<u32>() else { return };
if name == b"dxfId" {
if let Some(s) = cx.dxfs.get(id as usize)
&& seen_dxfs.insert(id)
{
dxfs.push((id, s.clone()));
}
} else if let Some(code) = cx.num_fmts.get(&id)
&& seen_fmts.insert(id)
{
fmts.push((id, code.clone()));
}
})?;
Some((dxfs, fmts))
}
/// What a sheet part holds for pass-through.
struct SheetScan {
/// (slot, XML with the namespace declarations it needs).
+27 -2
View File
@@ -13,8 +13,33 @@ impl<'a> SheetKept<'a> {
/// Writes the sheet's kept parts and adds their relationships to the sheet's.
pub fn write(sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> SheetKept<'a> {
let Some(p) = sheet.preserved.as_deref() else { return SheetKept { p: None, names: NameMap::new(), ids: HashMap::new() } };
let names = write_parts(out, &p.parts);
let ids = attach(rels, &p.rels, &names);
// A kept PivotTable whose cache wasn't kept with the workbook is left out.
let (wb_names, cache_ids) = (&out.kept.wb_names, &out.kept.cache_ids);
let orphan: HashSet<String> = p
.parts
.iter()
.filter(|q| {
let direct = q.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]));
// A table with no relationship to its cache names it by `cacheId` instead.
let by_id = || {
q.content_type == CT_PIVOT_TABLE
&& crate::xml::parse(&q.data).ok().and_then(|x| x.attr_u32("cacheId")).is_some_and(|id| !cache_ids.contains(&id))
};
let direct_is_orphan = direct.into_iter().any(|r| !wb_names.contains_key(&normalize(&r.target)));
direct_is_orphan || by_id()
})
.map(|q| normalize(&q.name))
.collect();
let (parts, sheet_rels): (Cow<'_, [PreservedPart]>, Cow<'_, [PreservedRel]>) = if orphan.is_empty() {
(Cow::Borrowed(&p.parts), Cow::Borrowed(&p.rels))
} else {
(
p.parts.iter().filter(|q| !orphan.contains(&normalize(&q.name))).cloned().collect(),
p.rels.iter().filter(|r| r.external || !orphan.contains(&normalize(&r.target))).cloned().collect(),
)
};
let names = write_parts(out, &parts);
let ids = attach(rels, &sheet_rels, &names);
SheetKept { p: Some(p), names, ids }
}
+148 -4
View File
@@ -12,6 +12,13 @@ pub struct KeptOut {
vml_blocks: u32,
/// Package-root relationships (type, target, external), added when `_rels/.rels` is written.
root: Vec<(String, String, bool)>,
/// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a
/// kept PivotTable).
pub(super) wb_names: NameMap,
/// The `cacheId`s of the workbook's kept pivot caches: a kept PivotTable that names its cache
/// only by id is written only when its cache is among them.
pub(super) cache_ids: HashSet<u32>,
patches: StylePatches,
}
impl KeptOut {
@@ -60,6 +67,79 @@ impl KeptOut {
}
}
/// Rewrites the values of `dxfId` and `numFmtId` attributes through the maps (ids not in a map
/// are kept). `None` when the XML is damaged.
fn map_style_ids(data: &[u8], dxfs: &HashMap<u32, u32>, fmts: &HashMap<u32, u32>) -> Option<Vec<u8>> {
let text = xml::to_utf8(data);
let mut reader = Reader::from_reader(text.as_ref());
let mut writer = Writer::new(Vec::with_capacity(data.len()));
let mut buf = vec![];
let map = |e: &BytesStart<'_>| -> Option<BytesStart<'static>> {
let name = String::from_utf8(e.name().as_ref().to_vec()).ok()?;
let mut out = BytesStart::new(name);
for a in e.attributes().with_checks(false) {
let a = a.ok()?;
let k = a.key.local_name();
let table = match k.as_ref() {
b"dxfId" => Some(dxfs),
b"numFmtId" => Some(fmts),
_ => None,
};
let new = table.and_then(|t| std::str::from_utf8(&a.value).ok()?.trim().parse::<u32>().ok().and_then(|id| t.get(&id)));
match new {
Some(n) => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(n.to_string().into_bytes()) }),
None => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(a.value.to_vec()) }),
}
}
Some(out)
};
loop {
match reader.read_event_into(&mut buf).ok()? {
Event::Eof => break,
Event::Start(e) => writer.write_event(Event::Start(map(&e)?)).ok()?,
Event::Empty(e) => writer.write_event(Event::Empty(map(&e)?)).ok()?,
ev => writer.write_event(ev).ok()?,
}
buf.clear();
}
Some(writer.into_inner())
}
/// Kept parts whose style ids are renumbered once the styles part is written.
#[derive(Default)]
pub struct StylePatches {
/// (written part name, source bytes, dxf id map, source number format id → code).
pub(super) list: Vec<StylePatch>,
}
pub(super) type StylePatch = (String, Arc<[u8]>, HashMap<u32, u32>, Vec<(u32, String)>);
impl KeptOut {
/// Number format codes kept parts refer to (to be registered in the styles part).
pub fn num_fmt_codes(&self) -> Vec<String> {
let mut v: Vec<String> = vec![];
for (_, _, _, fmts) in &self.patches.list {
for (_, code) in fmts {
if !v.contains(code) {
v.push(code.clone());
}
}
}
v
}
}
/// Renumbers the `dxfId` and `numFmtId` attributes of kept PivotTables and pivot caches to the
/// written styles part. `fmt_id` maps a number format code to its id there.
pub fn finish_style_ids(out: &mut Out, fmt_id: &dyn Fn(&str) -> Option<u32>) {
for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) {
let fmts: HashMap<u32, u32> = fmts.iter().filter_map(|(old, code)| Some((*old, fmt_id(code)?))).collect();
if let Some(x) = map_style_ids(&data, &dxfs, &fmts) {
out.replace(&name, x);
}
}
}
/// Original part name (normalized) → written part name.
pub(super) type NameMap = HashMap<String, String>;
@@ -90,13 +170,21 @@ pub(super) fn write_parts(out: &mut Out, parts: &[PreservedPart]) -> NameMap {
for p in parts {
names.entry(normalize(&p.name)).or_insert_with(|| out.kept.claim(&p.name));
}
let own: HashSet<String> = names.values().cloned().collect();
for (k, v) in &out.kept.wb_names {
names.entry(k.clone()).or_insert_with(|| v.clone());
}
let mut written = HashSet::new();
for p in parts {
let Some(new) = names.get(&normalize(&p.name)).cloned() else { continue };
if !written.insert(new.clone()) {
if !own.contains(&new) || !written.insert(new.clone()) {
continue;
}
out.part(&new, Some(&p.content_type), p.data.to_vec());
if !p.dxfs.is_empty() || !p.num_fmts.is_empty() {
let dxfs = p.dxfs.iter().map(|(old, s)| (*old, crate::styles::dxf_id(&mut out.dxfs, s))).collect();
out.kept.patches.list.push((new.clone(), p.data.clone(), dxfs, p.num_fmts.clone()));
}
if !p.rels.is_empty() {
out.part(&rels_part_name(&new), None, part_rels_xml(&p.rels, &names).into_bytes());
}
@@ -162,9 +250,25 @@ pub struct WorkbookKept {
/// Workbook XML elements that go right after `<sheets>` (`<externalReferences>`).
pub elements: String,
sheets: Vec<KeptSheet>,
/// Kept pivot caches: (`cacheId`, new relationship id).
pivot_caches: Vec<(u32, String)>,
}
impl WorkbookKept {
/// The `cacheId`s of the kept pivot caches (written PivotTables must not reuse them).
pub fn pivot_cache_ids(&self) -> Vec<u32> {
self.pivot_caches.iter().map(|(id, _)| *id).collect()
}
/// The `<pivotCache>` entries of the kept pivot caches.
pub fn pivot_cache_entries(&self) -> String {
let mut x = String::new();
for (id, rid) in &self.pivot_caches {
let _ = write!(x, "<pivotCache cacheId=\"{id}\" r:id=\"{}\"/>", esc_attr(rid));
}
x
}
/// Where the model's sheet `i` is in the file's sheet list: chart sheets come between worksheets.
pub fn file_index(&self, i: usize) -> usize {
i + self.sheets.iter().filter(|s| s.before <= i).count()
@@ -292,9 +396,37 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb
p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s, &mut refs))
};
let root_of = |s: &PreservedSheet| p.rels.iter().find(|r| r.id == s.rel_id);
let dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect();
// Parts reached only by dropped chart sheets go with them.
let mut gone: HashSet<String> = dropped.iter().filter_map(|s| root_of(s)).flat_map(|r| reachable(p, r)).collect();
// Pivot caches no kept PivotTable of a sheet uses any more (their sheets were deleted).
let sheet_parts = || wb.sheets.iter().filter_map(|s| s.preserved.as_deref()).flat_map(|q| q.parts.iter());
let mut used_caches: HashSet<String> = sheet_parts()
.flat_map(|part| part.rels.iter())
.filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]))
.map(|r| normalize(&r.target))
.collect();
// A PivotTable can name its cache only by the workbook's `cacheId`.
let cache_of_id: HashMap<u32, String> = p
.elements
.iter()
.filter(|e| e.slot == "pivotCache")
.filter_map(|e| {
let x = xml::parse(e.xml.as_bytes()).ok()?;
let rel = p.rels.iter().find(|r| Some(r.id.as_str()) == x.attr("id"))?;
Some((x.attr_u32("cacheId")?, normalize(&rel.target)))
})
.collect();
used_caches.extend(
sheet_parts()
.filter(|part| part.content_type == CT_PIVOT_TABLE)
.filter_map(|part| xml::parse(&part.data).ok()?.attr_u32("cacheId"))
.filter_map(|id| cache_of_id.get(&id).cloned()),
);
let unused_caches: Vec<&PreservedRel> =
p.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !used_caches.contains(&normalize(&r.target))).collect();
let mut dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect();
dropped_ids.extend(unused_caches.iter().map(|r| r.id.as_str()));
// Parts reached only by dropped chart sheets and pivot caches go with them.
let mut gone: HashSet<String> =
dropped.iter().filter_map(|s| root_of(s)).chain(unused_caches.iter().copied()).flat_map(|r| reachable(p, r)).collect();
if !gone.is_empty() {
let others = p.rels.iter().filter(|r| !dropped_ids.contains(r.id.as_str())).flat_map(|r| reachable(p, r));
for n in others {
@@ -310,7 +442,19 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb
out.kept.root.push((r.rel_type.clone(), target, r.external));
}
}
let pivot_caches: Vec<(u32, String)> = p
.elements
.iter()
.filter(|e| e.slot == "pivotCache")
.filter_map(|e| {
let x = xml::parse(e.xml.as_bytes()).ok()?;
Some((x.attr_u32("cacheId")?, ids.get(x.attr("id")?)?.clone()))
})
.collect();
out.kept.wb_names = names;
out.kept.cache_ids = pivot_caches.iter().map(|(id, _)| *id).collect();
WorkbookKept {
pivot_caches,
elements: p.elements.iter().filter(|e| e.slot == "externalReferences").filter_map(|e| remap(&e.xml, &ids)).collect(),
sheets: live
.iter()
+9 -1
View File
@@ -18,6 +18,14 @@
//! Reading: the cache's source and field names plus the table's areas, functions, show-values-as,
//! layout flags, grand totals and style become a model [`PivotTable`]. Anything we don't model
//! (OLAP sources, calculated fields, numeric grouping…) becomes a warning.
//!
//! A PivotTable whose source is a range or name in another workbook (its cache's
//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship), a data connection or
//! the workbook's Data Model (`cacheSource type="external"` with a `connectionId` in
//! `xl/connections.xml`) is not modelled: GridCraft never opens the other workbook, runs the
//! connection or loads the model, so it couldn't refresh it. [`read_pivots`] reports it instead,
//! and `passthrough` keeps its PivotTable, cache and records parts unchanged (with the Data Model
//! for a PivotTable on the model).
use std::collections::HashMap;
use std::fmt::Write as _;
@@ -37,7 +45,7 @@ use crate::xml::{El, esc_attr};
mod read;
mod write;
pub use read::{CachesIn, read_pivots};
pub use read::{CachesIn, ExternalPivot, KeptSource, read_pivots};
pub use write::PivotWriter;
pub const CT_PIVOT_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml";
+101 -12
View File
@@ -32,6 +32,47 @@ impl FieldIn {
struct CacheIn {
source: String,
fields: Vec<FieldIn>,
/// Set when the PivotTables on this cache are kept as they are, not modelled.
kept: Option<KeptSource>,
}
/// Where the data of a PivotTable GridCraft keeps unchanged (doesn't model) comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeptSource {
/// A range or name in another workbook.
OtherWorkbook,
/// A data connection of the workbook (`xl/connections.xml`) other than its Data Model.
Connection,
/// The workbook's Data Model (Power Pivot), through its model connection.
DataModel,
}
impl KeptSource {
pub(crate) fn describe(self) -> &'static str {
match self {
KeptSource::OtherWorkbook => "another workbook",
KeptSource::Connection => "a data connection",
KeptSource::DataModel => "the workbook's Data Model",
}
}
}
/// A PivotTable GridCraft doesn't model (its data is in another workbook, a data connection or
/// the Data Model), kept unchanged for saving.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExternalPivot {
/// The id of the sheet's relationship to the PivotTable part.
pub rel_id: String,
/// The pivot cache definition part it uses.
pub cache_part: String,
pub source: KeptSource,
}
/// The PivotTables of a sheet: those modelled, and those kept as they are.
#[derive(Debug, Default)]
pub struct SheetPivots {
pub tables: Vec<PivotTable>,
pub external: Vec<ExternalPivot>,
}
/// Workbook-level pivot cache lookup, filled from `<pivotCaches>`; caches are parsed once.
@@ -40,6 +81,8 @@ pub struct CachesIn {
by_id: HashMap<u32, String>,
parsed: HashMap<String, Option<CacheIn>>,
next_id: u32,
/// The workbook's data connections (`connectionId` → whether it is the Data Model's).
connections: HashMap<u32, bool>,
}
impl CachesIn {
@@ -54,10 +97,28 @@ impl CachesIn {
}
}
}
CachesIn { by_id, parsed: HashMap::new(), next_id: 1 }
CachesIn { by_id, parsed: HashMap::new(), next_id: 1, connections: HashMap::new() }
}
/// Reads the ids of the workbook's data connections (`xl/connections.xml`), which caches on a
/// connection or the Data Model name by `connectionId`.
pub fn read_connections(&mut self, cx: &mut Ctx<'_>, wb_rels: &[crate::package::Rel]) {
let Some(r) = wb_rels.iter().find(|r| r.kind == "connections" && !r.external) else { return };
let Ok(Some(x)) = cx.optional_xml(&r.target) else { return };
for c in x.kids("connection").take(MAX_CONNECTIONS) {
let Some(id) = c.attr_u32("id") else { continue };
// The model connection: `<x15:connection model="1">` in its extension list (Excel
// also gives it `<dbPr command="Model">`).
let x15_model = c.child("extLst").is_some_and(|l| l.kids("ext").filter_map(|e| e.child("connection")).any(|x| x.flag("model", false)));
let dbpr_model = c.attr("type") == Some("5") && c.child("dbPr").and_then(|d| d.attr("command")) == Some("Model");
self.connections.insert(id, x15_model || dbpr_model);
}
}
}
/// Most data connections read from `xl/connections.xml`.
const MAX_CONNECTIONS: usize = 100_000;
fn item_label_el(e: &El, sys: DateSystem) -> String {
let v = e.attr("v").unwrap_or("");
match e.name.as_str() {
@@ -69,7 +130,7 @@ fn item_label_el(e: &El, sys: DateSystem) -> String {
}
}
fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn> {
fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str, connections: &HashMap<u32, bool>) -> Option<CacheIn> {
// A cache that can't be read loses its PivotTable: say so instead of dropping it silently.
// An oversized cache is refused before it inflates, so warning and opening the rest is safe.
let x = match cx.optional_xml(part) {
@@ -93,17 +154,34 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
}
let src = x.child("cacheSource");
let ty = src.and_then(|s| s.attr("type")).unwrap_or("worksheet");
// A data connection or the Data Model (OLAP): kept as it is when the workbook has that
// connection.
if ty == "external" {
let model = src.and_then(|s| s.attr_u32("connectionId")).and_then(|id| connections.get(&id).copied());
let Some(model) = model else {
cx.warn("a PivotTable's data connection is not in the workbook; kept as plain cells");
return None;
};
let kept = if model { KeptSource::DataModel } else { KeptSource::Connection };
return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(kept) });
}
if ty != "worksheet" {
cx.warn(format!("PivotTables with a {ty} data source are not supported; kept as plain cells"));
cx.warn(format!("PivotTables with a data source of type \"{ty}\" are not supported; kept as plain cells"));
return None;
}
let ws = src.and_then(|s| s.child("worksheetSource"));
// A source in another workbook: `r:id` names the cache's link to that workbook's path.
if let Some(rid) = ws.and_then(|w| w.attr("id")) {
let linked = cx.pkg.rels(part).ok().is_some_and(|rels| rels.iter().any(|r| r.id == rid && r.external && r.kind == "externalLinkPath"));
if !linked {
cx.warn("a PivotTable's source is in another workbook that its cache doesn't name; kept as plain cells");
return None;
}
return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(KeptSource::OtherWorkbook) });
}
let source = match ws {
Some(w) if w.attr("name").is_some_and(|n| !n.trim().is_empty()) => w.attr("name").unwrap_or("").trim().to_string(),
Some(w) => {
if w.attr("id").is_some() {
cx.warn("a PivotTable's source is in another workbook; its source reference may not resolve");
}
let r = w.attr("ref").map(|r| r.replace('$', "")).and_then(|r| RangeRef::parse(&r));
let Some(r) = r else {
cx.warn("a PivotTable's source reference is missing or invalid; kept as plain cells");
@@ -151,13 +229,15 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
cx.warn("a PivotTable's cache has no fields; kept as plain cells");
return None;
}
Some(CacheIn { source, fields })
Some(CacheIn { source, fields, kept: None })
}
/// Reads the PivotTables related to a worksheet part.
pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result<Vec<PivotTable>, IoError> {
/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook,
/// a data connection or the Data Model are listed in [`SheetPivots::external`] (with a warning),
/// not modelled.
pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result<SheetPivots, IoError> {
let rels = cx.pkg.rels(sheet_part)?;
let mut out = Vec::new();
let mut out = SheetPivots::default();
for rel in rels.iter().filter(|r| r.kind == "pivotTable" && !r.external) {
let Some(x) = cx.optional_xml(&rel.target)? else { continue };
if x.name != "pivotTableDefinition" {
@@ -178,15 +258,24 @@ pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sh
let cache = match caches.parsed.get(&cache_part) {
Some(c) => c.clone(),
None => {
let c = read_cache(cx, &cache_part, sheet_name);
let c = read_cache(cx, &cache_part, sheet_name, &caches.connections);
caches.parsed.insert(cache_part.clone(), c.clone());
c
}
};
let Some(cache) = cache else { continue };
if let Some(source) = cache.kept {
let name = x.attr("name").unwrap_or("");
let from = source.describe();
cx.warn(format!(
"PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from {from}: it is kept for saving as it is, but can't be edited or refreshed here"
));
out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part, source });
continue;
}
if let Some(pt) = read_table(cx, &x, &cache, caches.next_id) {
caches.next_id = caches.next_id.saturating_add(1);
out.push(pt);
out.tables.push(pt);
}
}
Ok(out)
+25 -3
View File
@@ -104,6 +104,11 @@ pub struct PivotWriter {
caches: Vec<(u32, String)>,
pending: Vec<Pending>,
tables: u32,
/// Cache ids taken by kept pivot caches (PivotTables on another workbook).
reserved: Vec<u32>,
/// `<pivotCache>` entries of the kept caches.
kept_entries: String,
next_id: u32,
}
struct Pending {
@@ -115,6 +120,21 @@ struct Pending {
}
impl PivotWriter {
/// A writer whose caches don't reuse the kept caches' ids; `kept_entries` (their
/// `<pivotCache>` elements) are listed with the written ones.
pub fn new(reserved: Vec<u32>, kept_entries: String) -> PivotWriter {
PivotWriter { reserved, kept_entries, ..PivotWriter::default() }
}
fn next_cache_id(&mut self) -> u32 {
loop {
self.next_id = self.next_id.saturating_add(1);
if !self.reserved.contains(&self.next_id) || self.next_id == u32::MAX {
return self.next_id;
}
}
}
/// Writes the caches of a sheet's PivotTables and adds the sheet's relationships to its
/// PivotTable parts. Pivots whose source can't be resolved are not written.
pub fn add_sheet(&mut self, wb: &Workbook, si: usize, out: &mut Out, rels: &mut Rels) {
@@ -122,6 +142,7 @@ impl PivotWriter {
for (idx, pt) in sheet.pivots.iter().enumerate() {
let Some(cache) = build_cache(wb, pt, si) else { continue };
let n = self.caches.len() as u32 + 1;
let cache_id = self.next_cache_id();
let cache_part = format!("xl/pivotCache/pivotCacheDefinition{n}.xml");
let rec_rid = if let Some((count, xml)) = &cache.records {
let mut r = Rels::default();
@@ -138,24 +159,25 @@ impl PivotWriter {
let refresh_on_load = !pt.values.iter().any(|v| v.func == PivotFunc::DistinctCount);
let xml = cache_xml(&cache, rec_rid.as_deref(), wb.date_system, refresh_on_load);
out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), xml.into_bytes());
self.caches.push((n, format!("pivotCache/pivotCacheDefinition{n}.xml")));
self.caches.push((cache_id, format!("pivotCache/pivotCacheDefinition{n}.xml")));
self.tables += 1;
let t = self.tables;
rels.add("pivotTable", &format!("../pivotTables/pivotTable{t}.xml"));
let mut tr = Rels::default();
tr.add("pivotCacheDefinition", &format!("../pivotCache/pivotCacheDefinition{n}.xml"));
out.part(&format!("xl/pivotTables/_rels/pivotTable{t}.xml.rels"), None, tr.xml().into_bytes());
self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id: n, cache });
self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id, cache });
}
}
/// Adds the workbook relationships to the caches; returns the `<pivotCaches>` element (empty
/// when there are none).
pub fn workbook_xml(&self, wb_rels: &mut Rels) -> String {
if self.caches.is_empty() {
if self.caches.is_empty() && self.kept_entries.is_empty() {
return String::new();
}
let mut s = String::from("<pivotCaches>");
s.push_str(&self.kept_entries);
for (id, target) in &self.caches {
let rid = wb_rels.add("pivotCacheDefinition", target);
let _ = write!(s, "<pivotCache cacheId=\"{id}\" r:id=\"{rid}\"/>");
+7 -2
View File
@@ -381,6 +381,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
// Legacy formula cells per model sheet, rewritten once names and tables are known.
let mut legacy_formulas: Vec<(usize, Vec<gridcraft_core::CellRef>)> = vec![];
let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels);
pivot_caches.read_connections(&mut cx, &wb_rels);
let sheet_els: Vec<&El> = wb_xml.child("sheets").map(|s| s.kids("sheet").collect()).unwrap_or_default();
if sheet_els.len() > MAX_SHEETS {
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_SHEETS} sheets")));
@@ -420,13 +421,17 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
(Sheet::new(name.clone()), Default::default())
}
};
let mut external_pivots = vec![];
legacy_formulas.push((wb.sheets.len(), std::mem::take(&mut cx.legacy_formulas)));
match crate::pivot::read_pivots(&mut cx, &mut pivot_caches, &rel.target, &name) {
Ok(p) => sheet.pivots = p,
Ok(p) => {
sheet.pivots = p.tables;
external_pivots = p.external;
}
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
Err(e) => cx.warn(format!("PivotTables on sheet \"{name}\" could not be read: {e}")),
}
sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &read_controls);
sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &external_pivots, &read_controls);
sheet.preserved = crate::extlist::keep_sheet(&mut cx, &name, sheet.preserved.take(), kept.keeps());
sheet.file_id = se.attr_u32("sheetId").unwrap_or(0);
sheet.visibility = match se.attr("state") {
+6
View File
@@ -426,6 +426,7 @@ struct RawCol {
max: u32,
width: Option<f64>,
custom_width: bool,
best_fit: bool,
hidden: bool,
outline_level: u8,
collapsed: bool,
@@ -441,6 +442,9 @@ fn apply_col_entry(cx: &Ctx<'_>, c: RawCol, remaining: &mut u64, sheet: &mut She
let mut info = LineInfo::default();
if let Some(w) = c.width {
let px = col_width_to_px(w);
// Excel writes customWidth for every width it stores, and bestFit as well for one that
// AutoFit or a number format sized: only customWidth without bestFit was set by hand.
info.custom = c.custom_width && !c.best_fit;
if c.custom_width || px != sheet.default_col_width {
info.size = Some(px);
}
@@ -474,6 +478,7 @@ fn apply_craft_cols(cx: &Ctx<'_>, cols: &[craft_xlsx::Column], sheet: &mut Sheet
max: c.last + 1,
width: c.width,
custom_width: c.custom_width,
best_fit: c.best_fit,
hidden: c.hidden,
outline_level: c.outline_level,
collapsed: c.collapsed,
@@ -497,6 +502,7 @@ fn apply_xml_cols(cx: &Ctx<'_>, sp: &CraftSheetPart, sheet: &mut Sheet) -> Resul
max: c.attr_u32("max").unwrap_or(0),
width: c.attr_f64("width"),
custom_width: c.flag("customWidth", false),
best_fit: c.flag("bestFit", false),
hidden: c.flag("hidden", false),
outline_level: c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8,
collapsed: c.flag("collapsed", false),
+3 -1
View File
@@ -242,8 +242,10 @@ fn build_craft_cols(sheet: &Sheet, sid: &dyn Fn(gridcraft_model::StyleId) -> u32
first: a,
last: b,
width: Some(px_to_col_width(w)),
// As Excel writes them: a width that AutoFit or a number format sized is bestFit too, so
// it keeps widening when the file is opened again; one set by hand is customWidth only.
custom_width: i.size.is_some(),
best_fit: false,
best_fit: i.size.is_some() && !i.custom,
hidden: i.hidden,
outline_level: i.outline.min(7),
collapsed: i.collapsed,
+20 -20
View File
@@ -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<u32> {
let norm = |s: &str| s.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "");
let normalized = norm(name);
let alias = match normalized.as_str() {
"b4jis" => "b4",
"b5jis" => "b5",
"b6jis" => "b6",
"postcard" => "japanesepostcard",
"doublepostcard" => "japanesedoublepostcard",
"chou#3" => "japaneseenvelope#3",
"chou#4" => "japaneseenvelope#4",
"kaku#2" => "japaneseenvelopekaku#2",
"kaku#3" => "japaneseenvelopekaku#3",
other => other,
};
PAPERS.iter().find(|(_, n)| norm(n) == alias).map(|(i, _)| *i)
let name = gridcraft_model::paper::canonical(name)?;
PAPERS.iter().find(|(_, n)| *n == name).map(|(i, _)| *i)
}
/// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with
@@ -336,6 +322,20 @@ pub const EMU_PER_PX: f64 = 9525.0;
mod tests {
use super::*;
/// Every paper in the shared table saves with an XLSX id, so it reopens as itself. ECMA-376
/// has no upright ISO B6 id (35 is the B6 envelope stated wide), so `B6 (ISO)` alone has none.
#[test]
fn every_shared_paper_has_an_xlsx_id() {
for (name, _, _) in gridcraft_model::paper::PAPERS {
let id = paper_id(name);
if name == "B6 (ISO)" {
assert_eq!(id, None);
} else {
assert_eq!(id.and_then(paper_name), Some(name), "{name}");
}
}
}
#[test]
fn widths() {
assert_eq!(col_width_to_px(9.140625), 64.0);
+23
View File
@@ -181,7 +181,9 @@ fn assert_sheet_settings(s: &gridcraft_model::Sheet) {
assert!(s.cols.get(&2).unwrap().hidden);
assert_eq!(s.cols.get(&2).unwrap().size, Some(145.0));
assert_eq!(s.cols.get(&2).unwrap().outline, 1);
assert!(s.cols.get(&2).unwrap().custom, "customWidth: a width set by hand");
assert_ne!(s.cols.get(&3).unwrap().style, None);
assert!(!s.cols.get(&3).unwrap().custom, "no customWidth: not set by hand");
assert_eq!(s.rows.get(&0).unwrap().size, Some(40.0));
let r2 = s.rows.get(&1).unwrap();
assert!(r2.hidden);
@@ -294,6 +296,27 @@ fn dxf_border_is_written_before_protection() {
assert!(b.is_some() && p.is_some() && b < p, "{dx}");
}
/// Which stored widths were set by hand, as Excel 16.0 treats them when a number format makes a
/// number wider (#1077): only customWidth without bestFit keeps its width; the others widen.
#[test]
fn column_widths_set_by_hand() {
let body = r#"<cols><col min="1" max="1" width="15"/><col min="2" max="2" width="15" customWidth="1"/>
<col min="3" max="3" width="15" bestFit="1"/><col min="4" max="4" width="15" bestFit="1" customWidth="1"/>
<col min="5" max="5" width="9.140625" customWidth="1"/></cols><sheetData/>"#;
let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap();
let s = wb.sheet(0).unwrap();
let custom: Vec<bool> = (0..5).map(|c| s.cols.get(&c).is_some_and(|i| i.custom)).collect();
assert_eq!(custom, [false, true, false, false, true]);
assert_eq!(s.col_width(4), s.default_col_width, "E: the default width, but set by hand");
// Written back the way Excel writes them.
let bytes = crate::write_xlsx(&wb).unwrap();
let mut pkg = crate::package::Package::open(&bytes).unwrap();
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
let flags: Vec<(bool, bool)> =
sheet.child("cols").unwrap().kids("col").map(|c| (c.flag("customWidth", false), c.flag("bestFit", false))).collect();
assert_eq!(flags, [(true, true), (true, false), (true, true), (true, false)], "C and D are one run");
}
#[test]
fn strict_namespace_and_shared_strings() {
let ct = super::CT;
+543
View File
@@ -584,6 +584,7 @@ fn rebased(target: &str, from: &str, to: &str) -> String {
content_type: String::new(),
data: Arc::from(&b""[..]),
rels: vec![link("externalLinkPath"), link("hyperlink")],
..Default::default()
};
let mut wb = gridcraft_model::Workbook::new();
wb.preserved = Some(Arc::new(gridcraft_model::Preserved { parts: vec![part], ..Default::default() }));
@@ -971,6 +972,548 @@ fn notes_take_shape_blocks_the_header_pictures_dont_use() {
assert!(notes_ids.iter().all(|b| notes_map.contains(b)), "note ids outside their drawing's blocks");
}
// ---------------------------------------------------------------- PivotTables on another workbook
const EXT_CACHE_RANGE: &str = r#"<worksheetSource ref="A1:B2" sheet="Src" r:id="rId2"/>"#;
const EXT_CACHE_NAME: &str = r#"<worksheetSource name="SrcData" r:id="rId2"/>"#;
const EXT_LINK_TARGET: &str = "file:///C:/data/source.xlsx";
const EXT_RECORDS: &str = r#"<?xml version="1.0"?><pivotCacheRecords xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="1"><r><x v="0"/><n v="5"/></r></pivotCacheRecords>"#;
/// Source styles: custom number format 170 and two differential formats (the second blue).
const EXT_STYLES: &str = r#"<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="170" formatCode="0.0%"/></numFmts><fonts count="1"><font/></fonts><fills count="1"><fill/></fills><borders count="1"><border/></borders><cellXfs count="1"><xf/></cellXfs><dxfs count="2"><dxf><font><b/></font></dxf><dxf><font><color rgb="FF0000FF"/></font></dxf></dxfs></styleSheet>"#;
fn ext_cache(source: &str) -> String {
format!(
r#"<?xml version="1.0"?><pivotCacheDefinition xmlns="{NS_MAIN}" xmlns:r="{NS_R}" r:id="rId1" recordCount="1"><cacheSource type="worksheet">{source}</cacheSource><cacheFields count="2"><cacheField name="K" numFmtId="0"><sharedItems count="1"><s v="x"/></sharedItems></cacheField><cacheField name="V" numFmtId="0"><sharedItems containsNumber="1"/></cacheField></cacheFields></pivotCacheDefinition>"#
)
}
fn ext_table(name: &str, cache_id: u32) -> String {
format!(
r#"<?xml version="1.0"?><pivotTableDefinition xmlns="{NS_MAIN}" name="{name}" cacheId="{cache_id}" dataCaption="Values"><location ref="A3:B5" firstHeaderRow="1" firstDataRow="1" firstDataCol="1"/><pivotFields count="2"><pivotField axis="axisRow" showAll="0"><items count="2"><item x="0"/><item t="default"/></items></pivotField><pivotField dataField="1" showAll="0"/></pivotFields><rowFields count="1"><field x="0"/></rowFields><dataFields count="1"><dataField name="Sum of V" fld="1" baseField="0" baseItem="0" numFmtId="170"/></dataFields><formats count="1"><format dxfId="1"><pivotArea grandRow="1" outline="0" fieldPosition="0"/></format></formats></pivotTableDefinition>"#
)
}
/// Sheets "Report" and "More", each with a PivotTable on cache 1, whose source (a range, or a
/// name with `by_name`) is in another workbook; with `shared` both use one cache, otherwise only
/// "Report" has a PivotTable. `link_kind` is the type of the cache's relationship to the source.
fn ext_pivot_package(by_name: bool, shared: bool, link_kind: &str) -> Vec<u8> {
let workbook = format!(
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="Report" sheetId="1" r:id="rId1"/><sheet name="More" sheetId="2" r:id="rId2"/></sheets><pivotCaches><pivotCache cacheId="1" r:id="rId3"/></pivotCaches></workbook>"#
);
let ct = |part: &str, ty: &str| format!(r#"<Override PartName="/{part}" ContentType="{CT_PREFIX}.spreadsheetml.{ty}+xml"/>"#);
let content_types = format!(
r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>{}{}{}{}{}{}{}{}</Types>"#,
ct("xl/workbook.xml", "sheet.main"),
ct("xl/worksheets/sheet1.xml", "worksheet"),
ct("xl/worksheets/sheet2.xml", "worksheet"),
ct("xl/styles.xml", "styles"),
ct("xl/pivotTables/pivotTable1.xml", "pivotTable"),
ct("xl/pivotTables/pivotTable2.xml", "pivotTable"),
ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"),
ct("xl/pivotCache/pivotCacheRecords1.xml", "pivotCacheRecords"),
);
let sheet = |v: &str| {
format!(
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}"><sheetData><row r="4"><c r="A4" t="inlineStr"><is><t>x</t></is></c><c r="B4"><v>{v}</v></c></row></sheetData></worksheet>"#
)
};
let (s1, s2) = (sheet("5"), sheet("6"));
let cache = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE });
let (t1, t2) = (ext_table("Ext1", 1), ext_table("Ext2", 1));
let link = if link_kind.starts_with("http") { link_kind.to_string() } else { format!("{NS_R}/{link_kind}") };
let cache_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords1.xml"), ("rId2", &link, EXT_LINK_TARGET)]);
let table_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]);
let wb_rels = rels(&[
("rId1", "worksheet", "worksheets/sheet1.xml"),
("rId2", "worksheet", "worksheets/sheet2.xml"),
("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"),
("rId4", "styles", "styles.xml"),
]);
let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]);
let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]);
let mut parts: Vec<(&str, &[u8])> = vec![
("[Content_Types].xml", content_types.as_bytes()),
("_rels/.rels", super::ROOT_RELS.as_bytes()),
("xl/workbook.xml", workbook.as_bytes()),
("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()),
("xl/styles.xml", EXT_STYLES.as_bytes()),
("xl/worksheets/sheet1.xml", s1.as_bytes()),
("xl/worksheets/sheet2.xml", s2.as_bytes()),
("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()),
("xl/pivotTables/pivotTable1.xml", t1.as_bytes()),
("xl/pivotTables/_rels/pivotTable1.xml.rels", table_rels.as_bytes()),
("xl/pivotCache/pivotCacheDefinition1.xml", cache.as_bytes()),
("xl/pivotCache/_rels/pivotCacheDefinition1.xml.rels", cache_rels.as_bytes()),
("xl/pivotCache/pivotCacheRecords1.xml", EXT_RECORDS.as_bytes()),
];
if shared {
parts.push(("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes()));
parts.push(("xl/pivotTables/pivotTable2.xml", t2.as_bytes()));
parts.push(("xl/pivotTables/_rels/pivotTable2.xml.rels", table_rels.as_bytes()));
}
make_zip(&parts)
}
/// The written PivotTable parts of a sheet, through its relationships.
fn written_pivot_tables(u: &Unpacked, sheet: &str) -> Vec<String> {
u.rels(&sheet_part(u, sheet)).into_iter().filter(|r| r.1.ends_with("/pivotTable")).map(|r| r.2).collect()
}
/// `<pivotCache>` entries of a written workbook: (cacheId, cache part).
fn written_pivot_caches(u: &Unpacked) -> Vec<(String, String)> {
let wb = xml::parse(u.parts.get("xl/workbook.xml").unwrap()).unwrap();
wb.child("pivotCaches")
.map(|c| {
c.kids("pivotCache").map(|e| (e.attr("cacheId").unwrap().to_string(), u.target("xl/workbook.xml", e.attr("id").unwrap()).1)).collect()
})
.unwrap_or_default()
}
/// The font colour of `<dxf>` number `dxf` and the code of number format `fmt` in written styles.
fn written_style(u: &Unpacked, dxf: &str, fmt: &str) -> (String, String) {
let st = xml::parse(u.parts.get("xl/styles.xml").unwrap()).unwrap();
let d = st.child("dxfs").unwrap().kids("dxf").nth(dxf.parse().unwrap()).unwrap();
let color = d.child("font").and_then(|f| f.child("color")).and_then(|c| c.attr("rgb")).unwrap_or("").to_string();
let code = st.child("numFmts").unwrap().kids("numFmt").find(|n| n.attr("numFmtId") == Some(fmt)).unwrap().attr("formatCode").unwrap().to_string();
(color, code)
}
#[test]
fn pivot_tables_on_another_workbook_survive_a_save() {
for by_name in [false, true] {
let src = ext_pivot_package(by_name, false, "externalLinkPath");
let (wb, rep) = read_xlsx(&src).unwrap();
// Not modelled (GridCraft can't refresh it), but said so.
assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()));
assert!(rep.warnings.iter().any(|w| w.contains("Ext1") && w.contains("another workbook")), "{:?}", rep.warnings);
assert!(!rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings);
let cache_src = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE });
// Twice: what the first save kept is read back and kept again.
let first = write_xlsx(&wb).unwrap();
let (again, _) = read_xlsx(&first).unwrap();
for saved in [first, write_xlsx(&again).unwrap()] {
let u = Unpacked::new(&saved);
u.assert_valid();
let caches = written_pivot_caches(&u);
assert_eq!(caches.len(), 1, "{caches:?}");
let (id, cache_part) = &caches[0];
assert_eq!(id, "1", "the kept table refers to its cache by this id");
assert_eq!(u.text(cache_part), cache_src);
let cache_rels = u.rels(cache_part);
let records = cache_rels.iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap();
assert_eq!(u.text(&records.2), EXT_RECORDS);
assert!(
cache_rels.iter().any(|r| r.0 == "rId2" && r.1.ends_with("/externalLinkPath") && r.2 == EXT_LINK_TARGET && r.3),
"{cache_rels:?}"
);
let tables = written_pivot_tables(&u, "Report");
assert_eq!(tables.len(), 1);
assert!(written_pivot_tables(&u, "More").is_empty());
let t = u.text(&tables[0]);
assert_eq!(u.rels(&tables[0]).iter().find(|r| r.1.ends_with("/pivotCacheDefinition")).unwrap().2, *cache_part);
// Style ids follow the rewritten styles part.
let (color, code) = written_style(&u, &attr_of(&t, "format", "dxfId"), &attr_of(&t, "dataField", "numFmtId"));
assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{t}");
assert!(t.contains(r#"name="Ext1" cacheId="1""#), "{t}");
// The report cells are plain cells and stay.
assert!(u.text(&sheet_part(&u, "Report")).contains("<v>5</v>"));
}
}
}
#[test]
fn pivot_tables_sharing_a_cache_on_another_workbook_keep_one_cache() {
let (wb, _) = read_xlsx(&ext_pivot_package(false, true, "externalLinkPath")).unwrap();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
let caches = written_pivot_caches(&u);
assert_eq!(caches.len(), 1, "{caches:?}");
assert_eq!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).len(), 1, "the cache is written once");
for sheet in ["Report", "More"] {
let t = written_pivot_tables(&u, sheet);
assert_eq!(t.len(), 1, "{sheet}");
assert_eq!(u.rels(&t[0])[0].2, caches[0].1, "{sheet}");
}
// Deleting one sheet keeps the cache for the other; when no kept table is left, it goes.
let mut one = wb.clone();
one.sheets.remove(1);
let u = Unpacked::new(&write_xlsx(&one).unwrap());
u.assert_valid();
assert_eq!(written_pivot_caches(&u).len(), 1);
let mut none = wb.clone();
none.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None);
let u = Unpacked::new(&write_xlsx(&none).unwrap());
u.assert_valid();
assert!(written_pivot_caches(&u).is_empty());
assert!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).is_empty() && u.find(EXT_RECORDS.as_bytes()).is_empty());
assert!(!u.text("xl/workbook.xml").contains("pivotCaches"));
}
#[test]
fn written_pivot_caches_do_not_reuse_kept_cache_ids() {
use gridcraft_core::{CellRef, Value};
use gridcraft_model::{Cell, PivotField, PivotTable, PivotValue};
let (mut wb, _) = read_xlsx(&ext_pivot_package(false, false, "externalLinkPath")).unwrap();
// A PivotTable GridCraft models, on a list on "More".
{
let more = wb.sheet_mut(1).unwrap();
for (a, v) in [("D1", Value::text("K")), ("E1", Value::text("V")), ("D2", Value::text("a")), ("E2", Value::number(2.0))] {
more.cells.set(CellRef::parse(a).unwrap(), Cell::value(v));
}
more.pivots.push(PivotTable {
name: "Ours".into(),
source: "More!$D$1:$E$2".into(),
anchor: CellRef::parse("H3").unwrap(),
rows: vec![PivotField { source_col: "K".into(), ..Default::default() }],
values: vec![PivotValue { source_col: "V".into(), name: "Sum of V".into(), ..Default::default() }],
..Default::default()
});
}
let saved = write_xlsx(&wb).unwrap();
let u = Unpacked::new(&saved);
u.assert_valid();
let caches = written_pivot_caches(&u);
assert_eq!(caches.len(), 2, "{caches:?}");
assert_ne!(caches[0].0, caches[1].0, "{caches:?}");
let ours = written_pivot_tables(&u, "More");
assert_eq!(ours.len(), 1);
let id = attr_of(&u.text(&ours[0]), "pivotTableDefinition", "cacheId");
assert_ne!(id, "1");
assert!(caches.iter().any(|(i, part)| *i == id && *part == u.rels(&ours[0])[0].2), "{caches:?}");
let (back, _) = read_xlsx(&saved).unwrap();
assert_eq!(back.sheet(1).unwrap().pivots.len(), 1);
assert_eq!(written_pivot_tables(&Unpacked::new(&write_xlsx(&back).unwrap()), "Report").len(), 1);
}
#[test]
fn a_pivot_cache_naming_no_linked_workbook_is_not_kept() {
// The source `r:id` resolves to something other than a link to a workbook's path.
for kind in ["hyperlink", "http://example.com/unknown"] {
let (wb, rep) = read_xlsx(&ext_pivot_package(false, false, kind)).unwrap();
assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()));
assert!(rep.warnings.iter().any(|w| w.contains("another workbook") && w.contains("plain cells")), "{:?}", rep.warnings);
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(written_pivot_caches(&u).is_empty() && written_pivot_tables(&u, "Report").is_empty());
}
}
#[test]
fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() {
// The workbook doesn't list the cache: the table can't be written back without it.
let src = ext_pivot_package(false, false, "externalLinkPath");
let mut parts = Unpacked::new(&src).parts;
let wbx = String::from_utf8(parts.remove("xl/workbook.xml").unwrap()).unwrap().replace(r#"<pivotCache cacheId="1" r:id="rId3"/>"#, "");
parts.insert("xl/workbook.xml".into(), wbx.into_bytes());
let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect();
let (wb, rep) = read_xlsx(&make_zip(&list)).unwrap();
assert!(rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings);
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(written_pivot_tables(&u, "Report").is_empty());
assert!(written_pivot_caches(&u).is_empty());
}
#[test]
fn a_kept_pivot_table_with_an_unlisted_cache_id_is_dropped_even_with_a_cache_relationship() {
let src = ext_pivot_package(false, false, "externalLinkPath");
let mut parts = Unpacked::new(&src).parts;
let table = String::from_utf8(parts.remove("xl/pivotTables/pivotTable1.xml").unwrap()).unwrap().replace(r#"cacheId="1""#, r#"cacheId="99""#);
parts.insert("xl/pivotTables/pivotTable1.xml".into(), table.into_bytes());
let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect();
let (wb, _) = read_xlsx(&make_zip(&list)).unwrap();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(written_pivot_tables(&u, "Report").is_empty());
}
// ---------------------------------------------------------------- PivotTables on a data connection or the Data Model
/// Bytes standing in for the Data Model (Excel's `xl/model/item.data`).
const MODEL_DATA: &[u8] = b"\x00\x01model bytes, not really a model\xFE\xFF";
/// A larger stand-in, for running out of room to keep it.
static BIG_MODEL: [u8; 64 * 1024] = [7; 64 * 1024];
const CT_MODEL: &str = "application/vnd.openxmlformats-officedocument.model+data";
/// The model connection (id 1, as Excel writes it), a plain OLE DB connection (id 2) and a
/// worksheet connection loading a range into the model (id 3).
const MODEL_CONNECTIONS: &str = r#"<?xml version="1.0"?><connections xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><connection id="1" keepAlive="1" name="ThisWorkbookDataModel" description="Data Model" type="5" refreshedVersion="8" minRefreshableVersion="5"><dbPr connection="Data Model Connection" command="Model" commandType="1"/><olapPr sendLocale="1" rowDrillCount="1000"/><extLst><ext uri="{DE250136-89BD-433C-8126-D09CA5730AF9}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:connection id="" model="1"/></ext></extLst></connection><connection id="2" name="Source" type="5" refreshedVersion="8"><dbPr connection="Provider=Example;Data Source=source.xlsx" command="Data$" commandType="3"/></connection><connection id="3" name="WorksheetConnection_T" type="102" refreshedVersion="8" minRefreshableVersion="5"><extLst><ext uri="{DE250136-89BD-433C-8126-D09CA5730AF9}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:connection id="T"><x15:rangePr sourceName="_xlcn.WorksheetConnection_T"/></x15:connection></ext></extLst></connection></connections>"#;
const CONN_RECORDS: &str = r#"<?xml version="1.0"?><pivotCacheRecords xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="1"><r><x v="0"/><n v="6"/></r></pivotCacheRecords>"#;
/// An OLAP cache on the Data Model (no records: `saveData="0"`), on connection `id`.
fn model_cache(id: u32) -> String {
format!(
r#"<?xml version="1.0"?><pivotCacheDefinition xmlns="{NS_MAIN}" xmlns:r="{NS_R}" saveData="0" createdVersion="6" refreshedVersion="8" minRefreshableVersion="3" recordCount="0"><cacheSource type="external" connectionId="{id}"/><cacheFields count="2"><cacheField name="[T].[K].[K]" caption="K" numFmtId="0" level="1"><sharedItems count="1"><s v="x"/></sharedItems></cacheField><cacheField name="[Measures].[Sum of V]" caption="Sum of V" numFmtId="0" hierarchy="1" level="32767"/></cacheFields><cacheHierarchies count="2"><cacheHierarchy uniqueName="[T].[K]" caption="K" attribute="1" defaultMemberUniqueName="[T].[K].[All]" allUniqueName="[T].[K].[All]" dimensionUniqueName="[T]" displayFolder="" count="2" memberValueDatatype="130" unbalanced="0"><fieldsUsage count="2"><fieldUsage x="-1"/><fieldUsage x="0"/></fieldsUsage></cacheHierarchy><cacheHierarchy uniqueName="[Measures].[Sum of V]" caption="Sum of V" measure="1" displayFolder="" measureGroup="T" count="0" oneField="1" hidden="1"><fieldsUsage count="1"><fieldUsage x="1"/></fieldsUsage></cacheHierarchy></cacheHierarchies><kpis count="0"/><dimensions count="2"><dimension measure="1" name="Measures" uniqueName="[Measures]" caption="Measures"/><dimension name="T" uniqueName="[T]" caption="T"/></dimensions><measureGroups count="1"><measureGroup name="T" caption="T"/></measureGroups><maps count="1"><map measureGroup="0" dimension="1"/></maps></pivotCacheDefinition>"#
)
}
/// A relational cache on connection `id`, with records.
fn conn_cache(id: u32) -> String {
format!(
r#"<?xml version="1.0"?><pivotCacheDefinition xmlns="{NS_MAIN}" xmlns:r="{NS_R}" r:id="rId1" refreshedVersion="8" recordCount="1"><cacheSource type="external" connectionId="{id}"/><cacheFields count="2"><cacheField name="K" numFmtId="0"><sharedItems count="1"><s v="x"/></sharedItems></cacheField><cacheField name="V" numFmtId="0"><sharedItems containsNumber="1"/></cacheField></cacheFields></pivotCacheDefinition>"#
)
}
/// What a data-connection test package holds.
#[derive(Clone, Copy)]
struct ConnPkg {
/// The Data Model part and its workbook relationship.
model_part: bool,
/// The larger model stand-in.
big_model: bool,
/// `xl/connections.xml` and its workbook relationship.
connections: bool,
/// The connections part has a relationship to content GridCraft rewrites (so it can't be kept).
connections_blocked: bool,
/// The connection the Data Model cache names.
model_connection: u32,
/// The PivotTables have relationships to their caches (otherwise they name them by `cacheId`).
table_rels: bool,
}
const CONN_PKG: ConnPkg =
ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1, table_rels: true };
/// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the
/// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses.
fn conn_pivot_package(o: ConnPkg) -> Vec<u8> {
let workbook = format!(
r#"<?xml version="1.0"?><workbook xmlns="{NS_MAIN}" xmlns:r="{NS_R}"><sheets><sheet name="Report" sheetId="1" r:id="rId1"/><sheet name="More" sheetId="2" r:id="rId2"/></sheets><definedNames><definedName name="_xlcn.WorksheetConnection_T" hidden="1">More!$D$1:$E$2</definedName></definedNames><pivotCaches><pivotCache cacheId="3" r:id="rId3"/><pivotCache cacheId="4" r:id="rId7"/></pivotCaches></workbook>"#
);
let ct = |part: &str, ty: &str| format!(r#"<Override PartName="/{part}" ContentType="{CT_PREFIX}.spreadsheetml.{ty}+xml"/>"#);
let content_types = format!(
r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="data" ContentType="{CT_MODEL}"/>{}{}{}{}{}{}{}{}{}{}</Types>"#,
ct("xl/workbook.xml", "sheet.main"),
ct("xl/worksheets/sheet1.xml", "worksheet"),
ct("xl/worksheets/sheet2.xml", "worksheet"),
ct("xl/styles.xml", "styles"),
ct("xl/connections.xml", "connections"),
ct("xl/pivotTables/pivotTable1.xml", "pivotTable"),
ct("xl/pivotTables/pivotTable2.xml", "pivotTable"),
ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"),
ct("xl/pivotCache/pivotCacheDefinition2.xml", "pivotCacheDefinition"),
ct("xl/pivotCache/pivotCacheRecords2.xml", "pivotCacheRecords"),
);
let sheet = |v: &str| {
format!(
r#"<?xml version="1.0"?><worksheet xmlns="{NS_MAIN}"><sheetData><row r="4"><c r="A4" t="inlineStr"><is><t>x</t></is></c><c r="B4"><v>{v}</v></c></row></sheetData></worksheet>"#
)
};
let (s1, s2) = (sheet("5"), sheet("6"));
let (c1, c2) = (model_cache(o.model_connection), conn_cache(2));
let (t1, t2) = (ext_table("OnModel", 3), ext_table("OnConnection", 4));
let mut wb_rels = vec![
("rId1", "worksheet", "worksheets/sheet1.xml"),
("rId2", "worksheet", "worksheets/sheet2.xml"),
("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"),
("rId4", "styles", "styles.xml"),
("rId7", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition2.xml"),
];
if o.connections {
wb_rels.push(("rId5", "connections", "connections.xml"));
}
if o.model_part {
wb_rels.push(("rId6", "powerPivotData", "model/item.data"));
}
let wb_rels = rels(&wb_rels);
let t1_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]);
let t2_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition2.xml")]);
let c2_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords2.xml")]);
let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]);
let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]);
let conn_rels = rels(&[("rId1", "worksheet", "worksheets/sheet1.xml")]);
let mut parts: Vec<(&str, &[u8])> = vec![
("[Content_Types].xml", content_types.as_bytes()),
("_rels/.rels", super::ROOT_RELS.as_bytes()),
("xl/workbook.xml", workbook.as_bytes()),
("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()),
("xl/styles.xml", EXT_STYLES.as_bytes()),
("xl/worksheets/sheet1.xml", s1.as_bytes()),
("xl/worksheets/sheet2.xml", s2.as_bytes()),
("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()),
("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes()),
("xl/pivotTables/pivotTable1.xml", t1.as_bytes()),
("xl/pivotTables/_rels/pivotTable1.xml.rels", t1_rels.as_bytes()),
("xl/pivotTables/pivotTable2.xml", t2.as_bytes()),
("xl/pivotTables/_rels/pivotTable2.xml.rels", t2_rels.as_bytes()),
("xl/pivotCache/pivotCacheDefinition1.xml", c1.as_bytes()),
("xl/pivotCache/pivotCacheDefinition2.xml", c2.as_bytes()),
("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()),
("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()),
];
if !o.table_rels {
parts.retain(|(name, _)| !name.starts_with("xl/pivotTables/_rels/"));
}
if o.connections {
parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes()));
}
if o.connections_blocked {
parts.push(("xl/_rels/connections.xml.rels", conn_rels.as_bytes()));
}
if o.model_part {
parts.push(("xl/model/item.data", if o.big_model { &BIG_MODEL[..] } else { MODEL_DATA }));
}
make_zip(&parts)
}
/// The content type a written package gives a part.
fn content_type_of(u: &Unpacked, part: &str) -> String {
let types = xml::parse(u.parts.get("[Content_Types].xml").unwrap()).unwrap();
if let Some(o) = types.kids("Override").find(|o| normalize(o.attr("PartName").unwrap()) == normalize(part)) {
return o.attr("ContentType").unwrap().to_string();
}
let ext = part.rsplit('.').next().unwrap().to_ascii_lowercase();
types.kids("Default").find(|d| d.attr("Extension").unwrap().eq_ignore_ascii_case(&ext)).unwrap().attr("ContentType").unwrap().to_string()
}
/// Bytes kept by a read workbook.
fn kept_bytes(wb: &gridcraft_model::Workbook) -> usize {
wb.preserved.as_ref().map_or(0, |p| p.byte_len()) + wb.sheets.iter().filter_map(|s| s.preserved.as_ref()).map(|p| p.byte_len()).sum::<usize>()
}
#[test]
fn pivot_tables_on_the_data_model_and_a_connection_survive_a_save() {
let (wb, rep) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap();
assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()), "not modelled: GridCraft can't refresh them");
assert!(rep.warnings.iter().any(|w| w.contains("OnModel") && w.contains("Data Model")), "{:?}", rep.warnings);
assert!(rep.warnings.iter().any(|w| w.contains("OnConnection") && w.contains("a data connection")), "{:?}", rep.warnings);
assert!(rep.warnings.iter().any(|w| w.contains("Data Model is kept")), "{:?}", rep.warnings);
assert!(!rep.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep.warnings);
// Twice: what the first save kept is read back and kept again.
let first = write_xlsx(&wb).unwrap();
let (again, rep2) = read_xlsx(&first).unwrap();
assert!(!rep2.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep2.warnings);
for saved in [first, write_xlsx(&again).unwrap()] {
let u = Unpacked::new(&saved);
u.assert_valid();
// The Data Model: same bytes, name and content type, related from the workbook.
assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA));
assert_eq!(content_type_of(&u, "xl/model/item.data"), CT_MODEL);
let wb_rels = u.rels("xl/workbook.xml");
assert!(wb_rels.iter().any(|r| r.1.ends_with("/powerPivotData") && r.2 == "xl/model/item.data"), "{wb_rels:?}");
// The connections the caches name by id, and the hidden name a worksheet connection uses.
let conn = wb_rels.iter().find(|r| r.1.ends_with("/connections")).unwrap();
assert_eq!(u.text(&conn.2), MODEL_CONNECTIONS);
assert!(u.text("xl/workbook.xml").contains("_xlcn.WorksheetConnection_T"));
let caches = written_pivot_caches(&u);
assert_eq!(caches.len(), 2, "{caches:?}");
let cache = |id: &str| caches.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{caches:?}")).1.clone();
assert_eq!(u.text(&cache("3")), model_cache(1));
assert!(u.rels(&cache("3")).is_empty());
assert_eq!(u.text(&cache("4")), conn_cache(2));
let records = u.rels(&cache("4")).into_iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap();
assert_eq!(u.text(&records.2), CONN_RECORDS);
for (sheet, name, id) in [("Report", "OnModel", "3"), ("More", "OnConnection", "4")] {
let t = written_pivot_tables(&u, sheet);
assert_eq!(t.len(), 1, "{sheet}");
assert_eq!(u.rels(&t[0])[0].2, cache(id), "{sheet}");
let x = u.text(&t[0]);
assert!(x.contains(&format!(r#"name="{name}" cacheId="{id}""#)), "{x}");
let (color, code) = written_style(&u, &attr_of(&x, "format", "dxfId"), &attr_of(&x, "dataField", "numFmtId"));
assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{x}");
}
}
}
#[test]
fn the_data_model_is_kept_without_pivot_tables() {
let (mut wb, _) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap();
wb.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None);
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA));
// No kept table uses the caches any more: they go.
assert!(written_pivot_caches(&u).is_empty());
assert!(u.find(model_cache(1).as_bytes()).is_empty() && u.find(CONN_RECORDS.as_bytes()).is_empty());
}
#[test]
fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() {
// No model part, or no room left to keep it: the PivotTable on the model couldn't be
// refreshed and is dropped (its cells stay); the one on a plain connection is kept.
for too_large in [false, true] {
let pkg = ConnPkg { model_part: too_large, big_model: too_large, ..CONN_PKG };
let src = conn_pivot_package(pkg);
let (wb, rep) = if too_large {
// Room for everything but the model: the caches are kept after it.
let all = kept_bytes(&read_xlsx(&src).unwrap().0);
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(all - BIG_MODEL.len()));
let read = read_xlsx(&src);
crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(crate::passthrough::MAX_KEPT_TOTAL));
let r = read.unwrap();
assert!(r.1.warnings.iter().any(|w| w.contains("Data Model was dropped") && w.contains("too large")), "{:?}", r.1.warnings);
r
} else {
read_xlsx(&src).unwrap()
};
let w = &rep.warnings;
assert!(
w.iter().any(|w| w.contains("1 PivotTable cache(s) on the workbook's Data Model were dropped") && w.contains("plain cells")),
"{w:?}"
);
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(!u.parts.contains_key("xl/model/item.data"));
assert!(written_pivot_tables(&u, "Report").is_empty());
assert!(u.find(model_cache(1).as_bytes()).is_empty());
assert!(u.text(&sheet_part(&u, "Report")).contains("<v>5</v>"), "the report cells stay");
let caches = written_pivot_caches(&u);
assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["4"], "{caches:?}");
assert_eq!(written_pivot_tables(&u, "More").len(), 1);
}
}
#[test]
fn pivot_tables_naming_their_cache_by_id_go_with_a_dropped_cache() {
// No connections part: both caches are dropped, and the tables that name them only by
// `cacheId` must not stay behind with an id the workbook no longer lists.
let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, table_rels: false, ..CONN_PKG })).unwrap();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
for sheet in ["Report", "More"] {
assert!(written_pivot_tables(&u, sheet).is_empty(), "{sheet}");
}
assert!(written_pivot_caches(&u).is_empty());
}
#[test]
fn pivot_tables_naming_their_cache_by_id_keep_it() {
let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { table_rels: false, ..CONN_PKG })).unwrap();
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
for sheet in ["Report", "More"] {
assert_eq!(written_pivot_tables(&u, sheet).len(), 1, "{sheet}");
}
let caches = written_pivot_caches(&u);
assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["3", "4"], "{caches:?}");
}
#[test]
fn connection_pivot_tables_need_their_connections() {
// No connections part: the caches name connections that aren't there.
let (none, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, ..CONN_PKG })).unwrap();
assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings);
// A cache naming a connection id the part doesn't have; the other cache is unaffected.
let (missing, rep) = read_xlsx(&conn_pivot_package(ConnPkg { model_connection: 9, ..CONN_PKG })).unwrap();
assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings);
// A connections part that can't be kept: the model and every connection cache go with it.
let (blocked, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections_blocked: true, ..CONN_PKG })).unwrap();
assert!(rep.warnings.iter().any(|w| w.contains("Data Model was dropped")), "{:?}", rep.warnings);
assert!(rep.warnings.iter().any(|w| w.contains("2 PivotTable cache(s)") && w.contains("connections were not kept")), "{:?}", rep.warnings);
for (wb, all_gone) in [(none, true), (blocked, true), (missing, false)] {
let u = Unpacked::new(&write_xlsx(&wb).unwrap());
u.assert_valid();
assert!(written_pivot_tables(&u, "Report").is_empty());
assert!(u.text(&sheet_part(&u, "Report")).contains("<v>5</v>"));
if all_gone {
assert!(written_pivot_tables(&u, "More").is_empty());
assert!(written_pivot_caches(&u).is_empty());
assert!(!u.parts.contains_key("xl/model/item.data"));
} else {
assert_eq!(written_pivot_tables(&u, "More").len(), 1);
}
}
}
#[test]
fn modelled_form_controls_join_kept_ones_in_one_controls_element() {
use gridcraft_model::{Anchor, ControlKind, FormControl};
+21 -1
View File
@@ -112,7 +112,8 @@ fn sample() -> Workbook {
s.spill.insert(at("H3"), Value::Number(3.0));
s.cols.insert(0, LineInfo { size: Some(100.0), ..Default::default() });
s.cols.insert(1, LineInfo { size: Some(100.0), ..Default::default() });
// Column B was sized by hand (customWidth), A widened by itself; both come back as they were.
s.cols.insert(1, LineInfo { size: Some(100.0), custom: true, ..Default::default() });
s.cols.insert(3, LineInfo { hidden: true, outline: 1, ..Default::default() });
s.cols.insert(5, LineInfo { style: Some(money), ..Default::default() });
s.rows.insert(0, LineInfo { size: Some(30.0), ..Default::default() });
@@ -1921,6 +1922,25 @@ fn japanese_paper_sizes_round_trip() {
assert_eq!(back.sheet(0).unwrap().print.paper, "B5");
}
/// The paper names every spelling folds onto keep their file id: `11x17` is Tabloid (3), and
/// ISO B5 is id 34 (ECMA-376's 176×250 mm "B5 envelope"), read back as `B5 (ISO)`. An empty
/// paper (none stated) writes no `paperSize`, so the reader's own paper applies.
#[test]
fn paper_names_keep_their_xlsx_id_and_an_unstated_paper_writes_none() {
for (paper, id, back_as) in [("11x17", 3, "Tabloid"), ("US Legal", 5, "Legal"), ("B5 (ISO)", 34, "B5 (ISO)"), ("Envelope B5", 34, "B5 (ISO)")] {
let mut wb = Workbook::new();
wb.sheet_mut(0).unwrap().print.paper = paper.into();
let bytes = write_xlsx(&wb).unwrap();
assert!(sheet1_xml(&bytes).0.contains(&format!("paperSize=\"{id}\"")), "{paper}");
let (back, _) = read_xlsx(&bytes).unwrap();
assert_eq!(back.sheet(0).unwrap().print.paper, back_as);
}
let mut wb = Workbook::new();
wb.sheet_mut(0).unwrap().print.paper = String::new();
let (xml, _) = sheet1_xml(&write_xlsx(&wb).unwrap());
assert!(!xml.contains("paperSize"), "{xml}");
}
/// A table's dropdown filter lives in `sheet.autofilter` (the engine's only live filter state),
/// not in `Table::filter`. Writing used to suppress the sheet `<autoFilter>` because a table
/// intersects it and write the table part from `Table::filter`, which was empty: the criteria
+13
View File
@@ -794,6 +794,19 @@ fn xls_window2_right_to_left_sheet_opens_right_to_left() {
assert_eq!(view(&one_sheet_with(&window2(0x0001 | 0x0002 | 0x0010))), (false, true, false, true, true));
}
/// COLINFO's fUserSet marks a width set by hand, which a wider number format leaves alone (#1077).
/// craft-xls does not report fBestFit, so fUserSet with fBestFit also reads as set by hand.
#[test]
fn xls_column_widths_set_by_hand() {
let colinfo = |col: u16, flags: u16| rec(0x007D, &u16s(&[col, col, 20 * 256, 0, flags, 0]));
let file = one_sheet_with(&cat(&[&colinfo(0, 0x0002), &colinfo(1, 0), &colinfo(2, 0x0006)]));
let (wb, _) = read_xls(&file).unwrap();
let sh = &wb.sheets[0];
let custom: Vec<bool> = (0..3).map(|c| sh.cols.get(&c).is_some_and(|i| i.custom)).collect();
assert_eq!(custom, [true, false, true]);
assert!((0..3).all(|c| sh.col_width(c) > sh.default_col_width), "all three keep their stored width");
}
#[test]
fn xls_short_window2_is_ignored() {
for payload in [&[][..], &[0x40][..], &[0x40, 0][..], &[0x40, 0, 0, 0, 0, 0, 0, 0, 0][..]] {
+106 -69
View File
@@ -174,6 +174,12 @@ impl Out {
self.media.insert(key, file.clone());
file
}
/// Replaces the bytes of a part already added.
pub fn replace(&mut self, name: &str, data: Vec<u8>) {
if let Some(p) = self.parts.iter_mut().find(|(n, _)| n == name) {
p.1 = data;
}
}
pub fn default_type(&mut self, ext: &str, ct: &str) {
self.defaults.entry(ext.to_string()).or_insert_with(|| ct.to_string());
}
@@ -261,14 +267,18 @@ fn workbook_view_attrs(wb: &Workbook) -> String {
/// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its
/// PivotTable in Excel only when its link starts with the workbook in brackets.
pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>, functions: FunctionInfo) -> Result<Vec<u8>, IoError> {
fn validate_xlsx_workbook(wb: &Workbook) -> Result<(), IoError> {
if wb.sheets.is_empty() {
return Err(IoError::Format("a workbook needs at least one sheet".into()));
}
if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) {
return Err(IoError::Format("a static cell picture cannot also contain a formula".into()));
}
check_sheet_names(wb)?;
check_sheet_names(wb)
}
pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>, functions: FunctionInfo) -> Result<Vec<u8>, IoError> {
validate_xlsx_workbook(wb)?;
let mut out = Out {
parts: vec![],
overrides: vec![],
@@ -310,77 +320,23 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
};
let mut wb_rels = Rels::default();
let (sheets_xml, kept, pivots) = write_sheets(wb, &mut out, active, &mut wb_rels);
let (sheets_xml, kept, mut pivots) = write_sheets(wb, &mut out, active, &mut wb_rels);
let names = write_defined_names(wb, &kept, &out.chart_names);
let mut w = format!("{XML_DECL}<workbook xmlns=\"{NS_MAIN}\" xmlns:r=\"{NS_REL}\">");
// A workbook read from a file keeps its <fileVersion> as it was: Excel trusts the saved values
// only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it.
let file_version = crate::passthrough::workbook_elements(wb, "fileVersion");
w.push_str(if file_version.is_empty() { "<fileVersion appName=\"gridcraft\"/>" } else { &file_version });
w.push_str("<workbookPr");
match wb.show_objects {
ShowObjects::All => {}
ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""),
ShowObjects::None => w.push_str(" showObjects=\"none\""),
}
if wb.date_system == gridcraft_core::DateSystem::D1904 {
w.push_str(" date1904=\"1\"");
}
if wb.remove_personal_info {
w.push_str(" filterPrivacy=\"1\"");
}
w.push_str("/>");
if wb.protected_structure {
let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default();
let _ = write!(w, "<workbookProtection{pw} lockStructure=\"1\"/>");
}
let _ = write!(w, "<bookViews><workbookView activeTab=\"{}\"", kept.file_index(active));
w.push_str(&workbook_view_attrs(wb));
let _ = write!(w, "/></bookViews><sheets>{sheets_xml}</sheets>");
w.push_str(&kept.elements);
if !names.is_empty() {
let _ = write!(w, "<definedNames>{names}</definedNames>");
}
w.push_str("<calcPr calcId=\"191029\"");
match wb.calc.mode {
CalcMode::Automatic => {}
CalcMode::Manual => w.push_str(" calcMode=\"manual\""),
CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""),
}
// CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept
// while iteration is off, as Options keeps them.
let calc = &wb.calc;
if calc.iterative {
w.push_str(" iterate=\"1\"");
}
if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS {
let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations);
}
if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE {
let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change));
}
if wb.calc.precision_as_displayed {
w.push_str(" fullPrecision=\"0\"");
}
if wb.calc.r1c1 {
w.push_str(" refMode=\"R1C1\"");
}
if out.needs_calc {
w.push_str(" fullCalcOnLoad=\"1\"");
}
w.push_str("/>");
w.push_str(&pivots.workbook_xml(&mut wb_rels));
let exts = crate::passthrough::workbook_elements(wb, "ext");
if !exts.is_empty() {
let _ = write!(w, "<extLst>{exts}</extLst>");
}
w.push_str("</workbook>");
let w = write_workbook_xml(WorkbookHeader { wb, active }, &sheets_xml, &names, &kept, &mut pivots, &mut wb_rels, out.needs_calc);
// Workbook-level parts.
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb), std::mem::take(&mut out.num_fmts));
pivots.finish(wb, &mut out, &|code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied()));
let mut extra_fmts = pivots.number_formats(wb);
for code in out.kept.num_fmt_codes() {
if !extra_fmts.contains(&code) {
extra_fmts.push(code);
}
}
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &extra_fmts, std::mem::take(&mut out.num_fmts));
let fmt_id = |code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied());
pivots.finish(wb, &mut out, &fmt_id);
crate::passthrough::finish_style_ids(&mut out, &fmt_id);
out.part("xl/styles.xml", Some("application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"), styles.into_bytes());
wb_rels.add("styles", "styles.xml");
if !out.python_scripts.is_empty() {
@@ -503,6 +459,87 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
zip.finish()
}
struct WorkbookHeader<'a> {
wb: &'a Workbook,
active: usize,
}
fn write_workbook_xml(
header: WorkbookHeader<'_>,
sheets_xml: &str,
names: &str,
kept: &crate::passthrough::WorkbookKept,
pivots: &mut crate::pivot::PivotWriter,
wb_rels: &mut Rels,
needs_calc: bool,
) -> String {
let WorkbookHeader { wb, active } = header;
let mut w = format!("{XML_DECL}<workbook xmlns=\"{NS_MAIN}\" xmlns:r=\"{NS_REL}\">");
// A workbook read from a file keeps its <fileVersion> as it was: Excel trusts the saved values
// only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it.
let file_version = crate::passthrough::workbook_elements(wb, "fileVersion");
w.push_str(if file_version.is_empty() { "<fileVersion appName=\"gridcraft\"/>" } else { &file_version });
w.push_str("<workbookPr");
match wb.show_objects {
ShowObjects::All => {}
ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""),
ShowObjects::None => w.push_str(" showObjects=\"none\""),
}
if wb.date_system == gridcraft_core::DateSystem::D1904 {
w.push_str(" date1904=\"1\"");
}
if wb.remove_personal_info {
w.push_str(" filterPrivacy=\"1\"");
}
w.push_str("/>");
if wb.protected_structure {
let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default();
let _ = write!(w, "<workbookProtection{pw} lockStructure=\"1\"/>");
}
let _ = write!(w, "<bookViews><workbookView activeTab=\"{}\"", kept.file_index(active));
w.push_str(&workbook_view_attrs(wb));
let _ = write!(w, "/></bookViews><sheets>{sheets_xml}</sheets>");
w.push_str(&kept.elements);
if !names.is_empty() {
let _ = write!(w, "<definedNames>{names}</definedNames>");
}
w.push_str("<calcPr calcId=\"191029\"");
match wb.calc.mode {
CalcMode::Automatic => {}
CalcMode::Manual => w.push_str(" calcMode=\"manual\""),
CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""),
}
// CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept
// while iteration is off, as Options keeps them.
let calc = &wb.calc;
if calc.iterative {
w.push_str(" iterate=\"1\"");
}
if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS {
let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations);
}
if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE {
let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change));
}
if wb.calc.precision_as_displayed {
w.push_str(" fullPrecision=\"0\"");
}
if wb.calc.r1c1 {
w.push_str(" refMode=\"R1C1\"");
}
if needs_calc {
w.push_str(" fullCalcOnLoad=\"1\"");
}
w.push_str("/>");
w.push_str(&pivots.workbook_xml(wb_rels));
let exts = crate::passthrough::workbook_elements(wb, "ext");
if !exts.is_empty() {
let _ = write!(w, "<extLst>{exts}</extLst>");
}
w.push_str("</workbook>");
w
}
fn write_sheets(
wb: &Workbook,
out: &mut Out,
@@ -511,7 +548,7 @@ fn write_sheets(
) -> (String, crate::passthrough::WorkbookKept, crate::pivot::PivotWriter) {
// Kept content first: the chart sheets among the worksheets need their relationship ids.
let kept = crate::passthrough::write_workbook(wb, wb_rels, out);
let mut pivots = crate::pivot::PivotWriter::default();
let mut pivots = crate::pivot::PivotWriter::new(kept.pivot_cache_ids(), kept.pivot_cache_entries());
let mut sheets_xml = String::new();
let any_visible = wb.sheets.iter().any(|s| s.visibility == Visibility::Visible);
let mut ids = crate::passthrough::SheetIds::new(wb, &kept);
+3 -1
View File
@@ -227,11 +227,13 @@ fn sheet_of(s: &x::Sheet, styles: &[StyleId], unparsed: &mut bool) -> Sheet {
let px = col_width_to_px(f64::from(c.width) / 256.0);
let info = LineInfo {
size: (c.custom_width || px != sheet.default_col_width).then_some(px),
// fUserSet. craft-xls does not expose fBestFit, so a width AutoFit stored with both
// flags also counts as set by hand here (#1077).
custom: c.custom_width,
hidden: c.hidden,
outline: c.outline,
collapsed: c.collapsed,
style: c.format.map(|f| style(Some(f))).filter(|&id| id != StyleId::DEFAULT),
..LineInfo::default()
};
if info != LineInfo::default() {
sheet.cols.insert(u32::from(col), info);
+1 -1
View File
@@ -244,7 +244,7 @@ fn preserve_external_links(
let part_name = format!("xl/externalLinks/externalLink{next_ordinal}.xml");
let (xml, rels) = external_link_part_xml(book);
p.rels.push(PreservedRel { id: rid.clone(), rel_type: format!("{NS_REL}/externalLink"), target: part_name.clone(), external: false });
p.parts.push(PreservedPart { name: part_name, content_type: CT_EXT_LINK.into(), data: xml.into_bytes().into(), rels });
p.parts.push(PreservedPart { name: part_name, content_type: CT_EXT_LINK.into(), data: xml.into_bytes().into(), rels, ..Default::default() });
let _ = write!(refs_xml, "<externalReference r:id=\"{rid}\"/>");
}
if had_unpreserved {
+3 -2
View File
@@ -1,6 +1,6 @@
# Architecture
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365)
How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md).
@@ -17,7 +17,7 @@ including tests, 2026-10-10.
| L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits |
| L1 | `functions` | ~13.4k | The function library: `FnSpec` registry (name, arity, category, scalar args, signature, description) and pure implementations; automatic array lifting |
| L1 | `math` | ~1.1k | Equations: LaTeX laid out by RaTeX (MIT, pinned) into plain glyph, rule and path data, and LaTeX to Office Math; every entry point capped and panic-guarded |
| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings, protection |
| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings (paper names and sizes in `paper`, the one table file formats and print layout read), protection |
| L2 | `calc` | ~2.9k | Evaluator (references, names, tables, LET/LAMBDA, special forms like OFFSET/INDIRECT/SUBTOTAL) and dependency-graph recalculation with dynamic arrays, spills and cycle detection; single-threaded |
| L2 | `xlsx` | ~10.7k | XLSX read/write (transitional and strict read), CSV/TSV, XLSB and ODS data import, PivotTable caches, DrawingML charts and drawings; byte slices only (WASM-safe); lenient reader that reports warnings |
| L2 | `pdf` | ~1k | Small PDF 1.7 writer (14 standard fonts, vectors, images) for print and export |
@@ -272,6 +272,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in
| Date | Change | Summary |
|---|---|---|
| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means no paper is stated (no reader sets it yet); `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size |
| 2026-11-13 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut |
| 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` |
| 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused |
+32
View File
@@ -127,3 +127,35 @@ so there the caps and the fuzzed input space are the protection. `crates/math/te
gate on every test run, so a version bump has to pass it. RaTeX positions glyphs with KaTeX
font metrics; GridCraft never bundles the KaTeX fonts, so glyphs are drawn with system fonts
and a glyph no font has is drawn as a `[?]` box.
## Number formats widen columns that weren't sized by hand (#1077)
Increase/Decrease Decimal, the ribbon's other number formats (the Number Format list, Accounting,
Percent, Comma) and a number format set in Format Cells widen a column so the formatted numbers in
the target fit, instead of showing `####`.
Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts
automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic
workbooks:
- A column at the default width, AutoFitted, or widened this way before widens to the widest number
in the formatted range, also with Wrap Text and a large bold font. It never narrows.
- A width set with Column Width (or by dragging the border) stays, even when it equals the default:
the number shows `####`. AutoFit makes such a column automatic again.
- Hidden columns, text, General numbers (they round to fit instead), merged cells and shrink-to-fit
cells don't widen.
- In XLSX, Excel writes `customWidth="1"` for every width it stores and adds `bestFit="1"` for widths
that AutoFit or a number format set. Only `customWidth` without `bestFit` is read as set by hand: a
width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again.
`LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft
writes and reads the two flags as Excel does. In `.xls`, COLINFO's fUserSet marks a column set by
hand; the shared craft-xls reader does not report fBestFit, so a `.xls` width with both flags also
counts as set by hand.
Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored
width, so those columns open as set by hand and keep their width.
The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which
errs on the wide side; a UI test checks that the real font then draws the number, not `####`.
Excel doesn't widen when a value is entered into a cell that already has the format (observed through
the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell
wasn't observed.
+9 -2
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, `<outline/>`, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (form controls: buttons, scroll bars and spin buttons read and written; web pages open their first table as a sheet; external-source PivotTables and the Data Model are kept on save when their connections are kept; earlier: one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, `<outline/>`, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date orderLine truncated
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**
@@ -80,7 +80,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests |
|---|---|---|---|---|---|
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (the first five dropped URIs are named in an open warning, with a count for the rest), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Kept unchanged on save:** the Data Model when its workbook connections are kept, with the PivotTables on it or on a data connection. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (the first five dropped URIs are named in an open warning, with a count for the rest), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
| `.xlsx` Legacy formula behavior | R/W | yes | yes | Formulas without dynamic-array metadata (`cm`) open with Excel's implicit `@`; implied operators are removed on save without `cm`, while explicit single-value `@` is kept as `_xlfn.SINGLE`; formulas the analyzer cannot finish are saved as read. | `roundtrip.rs`, `fixtures.rs` |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection (a sheet or workbook password set in GridCraft is kept as its salted SHA-512 hash, which XLSX stores, and as the SHA-256 digest OpenDocument stores; a digest alone has no XLSX form, so saving keeps that protection without its password, and without a warning yet: the XLSX save path has no warning channel), Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
@@ -161,9 +161,11 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| Date | Change | Summary |
|---|---|---|
| 2026-11-23 | minor | Clarify that imported XLSX paper id 34 changes printed output from the old Letter fallback to ISO B5 (176×250 mm); add import-to-preview/PDF regression coverage |
| 2026-11-14 | minor | A sheet or workbook protection password set in GridCraft is kept both as Excel's salted SHA-512 hash and as a SHA-256 digest (the form OpenDocument stores); XLSX writes the SHA-512 form, and a digest-only password keeps its protection without the password; one shared base64 implementation. GridCraft JSON (`.json`) workbooks keep such a password in the shape earlier GridCraft versions read (the SHA-512 hash, with the digest in an extra `odf` field they ignore), so they still open there |
| 2026-11-14 | minor | Style model: `Alignment::padding` (left, right, top, bottom, hundredths of a point; none where a file states none) keeps an OpenDocument cell's padding; styles differing only by padding stay apart. XLSX and XLS read none and the XLSX writer leaves it out; GridCraft does not draw it yet |
| 2026-11-14 | minor | XLSX fonts' outlined (hollow) letters, `<outline/>`, are read and written back after `<strike/>` as Excel writes them, in cell fonts and differential formats (a differential format that turns it off, `<outline val="0"/>`, keeps that too); they were dropped before. Two fonts differing only in it are different styles. Set by `home.formatCells {style: {font: {outline: true}}}`; GridCraft does not draw outlined text yet (it shows solid) |
| 2026-11-13 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize`; Page Setup and Size now take Statement, Envelope #10 and Envelope DL (Page Setup refused them before) and print them on their own size |
| 2026-11-13 | minor | PDF of a right-to-left sheet keeps explicit Left and Right alignment on the side the grid shows them |
| 2026-11-12 | minor | `.xls` files open with their data validation (drop-down lists, input messages, error alerts and the rules), read by craft-xls and mapped as the `.xlsx` reader maps the same rules. A rule Excel would refuse, or one past 65,536 in a workbook, is skipped with a warning (#3634, from #3636) |
| 2026-11-12 | minor | .xls import reads the file with craft-xls (storytold/craft-libs), the reader that moved there from this repository; GridCraft keeps the mapping onto its model. The workbook now opens on the sheet it was saved on (WINDOW1 `itabCur`), falling back to the first visible sheet as before (from #3551), and cells saved as RString records (text with formatting runs) are read as text instead of skipped |
@@ -194,6 +196,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
| 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export |
| 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance |
| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) |
| 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI `<img>`) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged |
| 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `<rPh sb="…" eb="…">` with `<phoneticPr>`) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `<phoneticPr>` without runs is kept on its own, and when duplicate `<si>` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |
| 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (`<a:font script="Arab" typeface="…"/>`, also Hebr, Jpan and the rest) are read and written back in file order after `<a:cs>`; they were dropped before. A hostile file is held to 64 entries of 256 characters |
@@ -206,6 +209,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged |
| 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` |
| 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) |
| 2026-11-03 | minor | XLSX Data Model: kept on save when its workbook connections are kept; it is not an editable or refreshable data source in GridCraft |
| 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other |
| 2026-10-16 | trivial | XLSX charts: `[0]!Name` (a workbook-scoped defined name) in series references is read as the name, so the series resolve instead of showing `#NAME?`. Names in chart references are written qualified (`[0]!Name`, or `Sheet!Name` for a sheet-scoped name): Excel draws a chart with a bare name blank (#1686) |
| 2026-10-16 | trivial | XLSX reads and writes the workbook's show-objects setting (`workbookPr showObjects`: all, placeholders, none), which Ctrl+6 switches; a file without it is saved without it |
@@ -217,6 +221,9 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-15 | minor | XLSX: formulas and PivotTable sources quote sheet names like Excel (a leading `.`, R1C1-like and cell-like names), so `'.x'!A1` no longer saves as `.x!A1`, which Excel could not open (#1458) |
| 2026-10-15 | minor | XLSX text preserves CR and CRLF across save/reopen; shared strings use `_x000D_` and other XML text uses `&#13;` (#1488) |
| 2026-10-15 | minor | XLSX save keeps legacy `INDEX`/`MATCH` formulas scalar instead of marking them as dynamic arrays (#1505) |
| 2026-10-15 | minor | XLSX PivotTables on a data connection or the Data Model are kept on save with their caches and connections; unsupported sources fall back to plain cells with a warning |
| 2026-10-15 | minor | XLSX PivotTables whose source is in another workbook are kept on save, with style references adjusted to rewritten styles |
| 2026-10-14 | minor | `.xls` import reads cell formatting from Font, XF, Palette and Style records |
| 2026-10-14 | minor | `.xls` import reads cell formatting from the Font, XF, Palette and Style records: fonts, fills, borders, alignment, protection, the custom palette, the Normal font and user cell styles |
| 2026-10-14 | minor | CSV/text export writes General numbers with the 15 significant digits `&` gives (`0.3`, not `0.30000000000000004`) but never an exponent (integers below 1e16 keep every digit; 1E+15 and up as the shortest round-trip digits; small numbers written out), also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display. The underlying `&` conversion changed too (see [function-parity.md](function-parity.md)) |
| 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped |
+4
View File
@@ -2,6 +2,7 @@
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (§5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365)
Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone
using GridCraft for real work first). This is the work list: pick from the top, check the open
PRs first (50 open on 2026-10-10; several already address entries here), and update the entry
@@ -22,6 +23,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
- **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTable
round-trip noted as "unverified in real Excel" since 10-07; #64 (dynamic-array flag) shows the
class of bug.
- **Check:** `packaging/windows/excel-open-check/check.ps1` saves workbooks with `gridcraft-cli` and opens each result in real Excel through COM with `CorruptLoad` = normal load, so a repair is a failure. The 0.12.1 run (18 public synthetic fixtures + 7 feature scenarios: charts, pivots with pivot chart and slicer, CF, validation, tables and names, shapes and pictures, sheets and protection) gave 24 of 25 saved files opening cleanly; the 25th (`gc_legacy_to_array`) is not a repair but Excel taking over 200 s on legacy formulas saved as whole-column array formulas (#410, open PRs #417, #1367, #1660). Still open: a run over a large real-world corpus.
- **Impact:** the main format; a repair prompt or silent loss destroys trust.
- **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md)
@@ -203,6 +205,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 2026-11-01 | minor | §4: chart data tables implemented for column, bar, line, area and compatible combo charts, with legend keys and border settings, live source values, XLSX round-trip and print/PDF; other chart gaps remain. |
| 2026-10-31 | minor | §13: Solver Options (Max Evaluations, Integer Optimality and the Evolutionary options), saved with the model |
| 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog |
| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly |
| 2026-10-26 | minor | §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry. Other script and UI gaps remain. |
| 2026-10-26 | minor | Arabic shared bidi display/editing and persisted cell reading direction; other script and PDF work remain separate |
| 2026-10-26 | minor | §5: Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work |
@@ -211,6 +214,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
| 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) |
| 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step |
| 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite |
| 2026-10-17 | minor | Conditional formatting: the 2-/3-colour scale branch of the New Formatting Rule dialog edits per-stop type/value/colour and updates rules in place (part of #1165) |
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
| 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) |
| 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension |
+2 -1
View File
@@ -295,7 +295,8 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
the fill handle explains how to fill versus select cells.
- Formatting: fonts, fills, all border styles, alignment (wrap, indent, rotation, merge), number
formats, 47 cell styles, 60 table styles, conditional formatting (cell rules, text, dates,
duplicates, top/bottom, averages, data bars, colour scales, icon sets, formulas), automatic
duplicates, top/bottom, averages, data bars, colour scales with per-stop type/value/colour
editors, icon sets, formulas), automatic
row heights, autofit, hide/unhide, freeze panes.
Border presets include visual diagrams; Format Cells previews draft borders before applying.
- Data: sort (multi-level, by colour, custom lists), AutoFilter (values, custom, top 10,
+41 -4
View File
@@ -1,6 +1,6 @@
# UI parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
@@ -65,6 +65,7 @@ this logic, with one undo step.
| AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) |
| Searchable data validation dropdown (typing filters the in-cell list) | done (10-21): entries with a word starting with the typed text, ignoring case and the accents of Latin letters (é, ç, ß, ł, ș, ǎ, Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), in list order; Up/Down highlight, Enter/Tab/Ctrl+Enter/click commit the highlighted entry as the list spells it (other commits, such as clicking another cell, keep the typed text), Escape hides the list then cancels; `data.validationList {cell, search?}` gives agents the same search. The search reads at most 200,000 cells of the list's source and keeps at most 10,000 matches; past either, `truncated` is set and the popup says more entries aren't shown (validation itself still checks the whole list). Fuzzy matching isn't offered (Excel doesn't either); behaviour follows the documented Excel 365 feature, not yet measured against the app |
| Header resize and double-click AutoFit | done (#42, #88 for header dividers) |
| AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Without a search, Apply preserves selected and excluded values and blanks absent from the narrowed list. With a search, Apply excludes nonmatches throughout the column, including values hidden by another filter. Clear Filter clears the whole column. Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. |
| Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). |
| Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog |
| Reorder selected whole columns by dragging their headers | done (10-11) |
@@ -79,6 +80,30 @@ this logic, with one undo step.
| Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar in the tab bar (60/40 split, drag, track click pages) 10-13 (#176, #840); dragging the handle at the scrollbar's left edge gives the tabs more or less of the bar; each workbook keeps its share while it is open (not saved in the file) |
| Text overflow into empty neighbours, wrap, rotation, shrink to fit | done |
## AutoFilter population and pending integrations
[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel)
describes additive column filters and restricting other dropdowns to the filtered range. The
current column is excluded from enumeration so its unchecked alternatives remain available.
The existing one-million-data-row enumeration limit and value sorting remain unchanged.
Imported end rows stop at the last worksheet row in choices, statistics and visibility scans.
Checkbox state uses the row matcher for the active criterion, including raw and formatted
Values matches, custom comparisons, numeric thresholds and colors. A duplicate choice is
checked when any eligible row matches, including when those rows have different colors.
Hidden choices retain that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive
lookup sets once per query rather than scanning every selected value for each row.
This changes the population behind the pending row-count work (#1737, and its stacked Only
button #1741): a future count beside a choice should count eligible rows satisfying the other
columns, including rows rejected by the current column. It must not count the whole original
range or just currently visible rows. Search narrows the displayed choices, not that population;
Apply with a search excludes nonmatching values even when another filter hides them.
These PRs are not incorporated here. Date grouping (#1509) should group this same eligible
population. Table filter activation / roundtrip ownership changes remain in #2506. Enumeration
reads the active sheet AutoFilter without changing criteria, row visibility or the XLSX
representation. A separate table dropdown outside that AutoFilter's columns remains empty;
it does not receive choices from its own eligible-row population.
## Keyboard
| Area | Excel | GridCraft |
@@ -92,7 +117,7 @@ this logic, with one undo step.
| Shortcuts bound to commands | 200+ documented shortcuts per platform | audited below (#110): shortcuts whose feature exists are bound, with the exceptions listed; the rest wait for their features |
| Ctrl+arrow, Ctrl+Shift+arrow, Ctrl+Home/End, Ctrl+Shift+Home/End, Page Up/Down, Alt+Page | yes | done |
| Ctrl+1, Ctrl+; and Ctrl+Shift+; , Ctrl+D/R, Ctrl+E, Ctrl+T/L, Ctrl+K, Ctrl+Shift+L, Ctrl+Shift+~!@#$%^&_ | yes | done |
| F2, F3, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F4 Repeat missing |
| F2, F3, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F8 / Shift+F8 extend and add modes with their status bar text; F11 chart sheet, F4 Repeat missing |
| Mac-specific (Cmd variants, Control variants, Fn keys) | yes | done where a feature exists (`keymap.rs` picks the Mac variant) |
| Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded |
| Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) |
@@ -147,8 +172,9 @@ A character egui has no key for (`č`, `ö`, `<`) falls back to the key's positi
| Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** |
| Ctrl+Alt+Shift+P | Cmd+Option+Shift+P | Python mode on or off | **added** |
| F3 | not checked | Paste Name dialog, only when the workbook has names: OK puts the name at the caret of the formula being edited (or starts `=Name`), Paste List writes each name and what it refers to from the active cell (`formulas.pasteName`) | **added** |
| F1, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) |
| F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) |
| F8, Shift+F8 | same | Extend Selection (arrows, Page keys, Ctrl+arrows, Home and clicks extend from the anchor) and Add or Remove Selection (arrows move the active cell and keep the areas, Shift+arrows grow a new area, a click adds or removes an area); the status bar names the mode; the key again, Esc or editing a cell ends it (`ui.selectionMode`) | **added** |
| F1, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Repeat, pane cycling, chart sheet | missing (no such feature yet) |
| F1, F3, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Paste Name, Repeat, pane cycling, chart sheet | missing (no such feature yet) |
| Ctrl+Q | Control+Q (Cmd+Q stays Quit) | Quick Analysis | **added** (#791) |
| Ctrl+A after a function name, Ctrl+Alt+P | same | Function Arguments, tooltips | missing |
| Ctrl+Shift+A after a function name | Control+Shift+A | argument names: `=SUMIF(` becomes `=SUMIF(range,criteria,sum_range)`, the `(` added when missing; one Undo takes them back | **added** |
@@ -276,10 +302,13 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-11-14 | minor | The searched validation list measures its rows at their real height, like the dropdown arrow's list: it shows eight rows instead of six, the highlighted row stays in view and the last entries of a long list can be reached. It opens above the cell when it would run past the bottom of the window, measures its width once per search instead of every frame, and its "More entries not shown" note goes through the interface translations. Typing over the open dropdown drops the entries the dropdown had read |
| 2026-11-13 | minor | The full list the dropdown arrow (or Alt+Down) opens reads its source once while it stays open, within the same 200,000-cell budget, and draws only the rows in view, so a list over a huge column no longer rereads and redraws every entry each frame; it says when entries aren't shown, and its rows are measured at their real height so eight show, as intended |
| 2026-11-13 | minor | A searched validation list reads at most 200,000 cells of its source (`LIST_SOURCE_BUDGET`), walking a range source within the used range instead of evaluating it whole, so a list over a huge or whole column can't stall the edit; `data.validationList` reports `truncated` and the popup says when entries aren't shown |
| 2026-11-11 | minor | Carry the imported AutoFilter end-row bound through shared statistics and dropdown choices as well as row visibility; retain duplicate-color and per-window pending-choice fixes (#2641) |
| 2026-11-10 | minor | Keep duplicate choices checked when any eligible row matches a color filter; a form-button window switch preserves the incoming window's pending filter search and checkbox edits (#2641) |
| 2026-11-05 | minor | Reconcile upstream form-control coverage with the CJK baseline and cell-alignment updates |
| 2026-11-04 | minor | Keep centered emoji and symbol fallback placement when a row starts with a fallback or contains only fallbacks; use primary or baseline-aligned glyphs to anchor cell alignment |
| 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines |
| 2026-11-04 | minor | Align wrapped and unwrapped cells with the same vertical margins; regressions compare numbers with mixed CJK/Latin text, including explicit line breaks |
| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) |
| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 |
| 2026-11-03 | minor | Find and Replace: workbook Undo/Redo works with a keyboard-focused button; focused text fields keep text-editing Undo, and a modal message blocks workbook shortcuts. Regression covers Replace All, both Redo shortcuts, actual text undo, and an error message |
| 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default |
@@ -294,12 +323,14 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-11-03 | minor | Draw tab: the stroke drawn under the pointer while dragging a pen is the ink that will be committed, in the pen's colour and thickness (translucent for a highlighter), instead of always blue at 2 pt (#1786) |
| 2026-11-03 | minor | Copy puts a cell that holds a quote on the clipboard as it is (`say "hi"`), quoting only text with a tab or line break, as Excel does; pasting text reads a field as quoted only when its closing quote ends it, so `"hi" there` pastes with its quotes (#2225) |
| 2026-11-03 | minor | Ctrl+. (Control+. on a Mac): Next Corner of Selection, `selection.nextCorner`: the active cell moves clockwise to the next corner of the selected area, which stays selected, and becomes the anchor, as in Excel (#1442) |
| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 |
| 2026-11-02 | minor | Dragging the selection's border onto cells that hold data asks "There's already data here. Do you want to replace it?" (OK replaces, Cancel leaves the sheet and clipboard as they were) through the new `range.move` command (#3136); the row no longer claims Ctrl/Option copy and Shift insert for the border drag, which are not wired yet |
| 2026-11-02 | minor | RefEdit reference boxes in dialogs: pick a range on the grid, collapse the dialog while selecting; Goal Seek, Solver (with the Model Range of Load/Save) and Data Analysis use them; while collapsed the arrow keys move the selection and Shift+arrow extends it, F4 cycles a reference's anchors, a click elsewhere keeps the box picking, a dialog opened over a picking one puts the selection back, OK stays on the sheet its command showed, and scripted cancel and confirm end a pick like the buttons; the dialog's sheet is followed through the recorded undo steps, so a sheet deleted and recreated under its name is not taken for it and an undo of the deletion brings it back; a box the dialog stops showing is no longer picked into; the dialog's sheet is recorded when it opens, not at its first pick |
| 2026-11-02 | minor | Python mode edits a cell's code in the formula bar's code editor (Ctrl+Alt+Shift+P, `=PY` then Tab, editing a Python cell), with the PY badge beside fx; its keys apply in input order, also several in one frame, and Ctrl+Enter commits through `python.set` (empty code clears the cell), keeping the code and showing the command's message when the code is refused |
| 2026-11-02 | minor | Insert › Symbols: Equation split button (access keys N E), a gallery of examples, and an equation editor with quick-insert buttons, the error underlined at its position and a live preview; double-clicking an equation edits it |
| 2026-11-02 | minor | Floating objects: one selection for charts, pictures, shapes and slicers, eight resize handles with matching cursors (right-to-left sheets included), Escape drops the selection |
| 2026-11-02 | minor | Record macOS mixed CJK/Latin rendering validation, the actual fallback fonts and the unverified Calibri 10 case |
| 2026-11-01 | minor | Filter popup checkbox edits, search and button state belong to their document window; switching columns in another window no longer discards an open popup's pending choices (#2641); the separate AutoFilter section documents the empty dropdown outside the active sheet filter columns (#2506) |
| 2026-11-01 | minor | Chart Design › Add Chart Element offers Data Table with/no legend keys and None; Format Chart Area has a Data Table section with visibility, legend keys, horizontal/vertical borders and outline. Both use engine commands. |
| 2026-11-01 | minor | Page Setup has a Page order choice (Down, then over, the default, or Over, then down) with a small picture of the order, also when Print Titles opens it on its Sheet tab; OK sets it with the margins in one undo step. Printing, PDF export, the print preview, Page Break Preview's page numbers and Page Layout view's headers and footers follow the order. The dialog is in German now too |
| 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows |
@@ -309,6 +340,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown |
| 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used |
| 2026-10-31 | minor | CJK fallback text shares the Latin baseline in cells, editors and window titles; fixed row heights and clipping remain workbook-controlled |
| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; documents pending counts, date grouping and table roundtrip integration; retains slicer row filtering when its criterion is outside the sheet filter columns |
| 2026-10-30 | minor | Italic and bold in an installed font that has no face for them (Arial Black has a single face) are imitated on the grid, as Excel does: the text is slanted and drawn a second time a little to the right (about 1/36 of the size, at least one pixel). Observed in Excel's PDF of a cell in Arial Black, bold italic: oblique by 1/3 and outlined 0.23 pt thick at 9 pt. egui's slant is fixed at about 1/4. Print and PDF still use the standard PDF fonts (`fonts.rs` test) |
| 2026-10-30 | minor | Checkbox cells print and export to PDF as boxes, as on screen: unchecked white with a grey outline, checked green with a white tick (#2972). They printed their value as TRUE or FALSE; other values in a checkbox cell still print as text |
| 2026-10-29 | minor | Formula pointing from the keyboard: Ctrl+arrow (⌘arrow) moves the pointed cell to the edge of its data and Ctrl+Shift+arrow (⌘⇧arrow) extends the pointed range there, as the same keys move and extend the selection, so typing `=COUNTIF(`, clicking the top of a column and pressing ⌘⇧↓ points at the whole column of data; the keys used to move or extend by one cell. A range reaching the sheet edge is written as whole columns or rows (`A:B`). The editor reads the modifiers of the arrow's own key event, so a keystroke pressed and released within one frame (a control client's `ui.key`, an automation tool) keeps its Shift and Ctrl |
| 2026-10-29 | minor | Insert Hyperlink opens with an existing link's address, display text and ScreenTip (#2876). An address-only edit preserves the cell's content and formula; Cancel leaves the link unchanged, and Undo restores the edit |
@@ -327,6 +360,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-10-24 | minor | Outline Settings (Data ▸ Outline ▸ Settings, `data.outlineSettings`): clearing Summary rows below detail or Summary columns to right of detail puts the − / + buttons on the line above or left of each group, and Hide Detail, Show Detail and the level buttons mark that line collapsed. Changing a direction moves the marks of collapsed groups. Read and written as `outlinePr summaryBelow` / `summaryRight` |
| 2026-10-23 | minor | F3, Formulas › Use in Formula › Paste Names… and Alt+M, S, P open the Paste Name dialog (F3 only when the workbook has names). It lists the workbook's names and the active sheet's own in alphabetical order, hidden names left out; OK or a double-click puts the selected name at the caret of the formula being edited, in place of selected text, or starts `=Name` in the active cell (`formulas.pasteName` `{name}`), and Paste List writes each name and the text of what it refers to in two columns from the active cell (`{list: true}`). While a dialog is open over the edit, the cell editor takes no keys, and Cancel leaves the selected text selected. The Use in Formula menu lists the same names and inserts at the caret too (`formulas.useInFormula`); it used to list hidden names and other sheets' names, the menu added the name at the end of the text, and the command replaced the text being edited |
| 2026-10-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) |
| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) |
| 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) |
| 2026-10-24 | minor | When the fill starts from a date, the right-drag fill menu and the Auto Fill Options button also offer Fill Days, Fill Weekdays (Saturday and Sunday skipped), Fill Months and Fill Years (`edit.autoFill` with `mode` set to `days`, `weekdays`, `months` or `years`). A lone date steps by one unit; two or more dates step by the difference between the first two in that unit, or one unit when they fall in the same one. Fill Months and Fill Years keep the day of the month, clamped to the month's last day. Every fill by months or years (these two, a drag of dates a month apart, and Series by Month or Year) keeps the time of day of a date with a time, which used to be dropped |
@@ -336,6 +370,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running |
| 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking |
| 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button |
| 2026-10-22 | minor | AutoFit Column Width measures a table's cells in the font the table style draws them in, so a bold header row is fitted bold; it measured the cell's own, plain font and could leave a bold heading too narrow |
| 2026-10-22 | minor | Increase/Decrease Decimal, the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) and Format Cells' number formats widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow |
| 2026-10-21 | minor | Typing into a cell with an in-cell list validation shows the list filtered to entries with a word starting with the typed text (case and Latin accents ignored, Vietnamese included, list order kept, only visible rows drawn); Up/Down move the highlight, Enter/Tab/click commit it with the list's spelling, Escape hides the list before cancelling. Column AutoComplete is off for those cells. New query command `data.validationList` |
| 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel |
| 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen |
@@ -346,6 +382,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
| 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) |
| 2026-10-14 | minor | Punctuation shortcuts follow the character the keyboard layout types, digits keep their position: on a Croatian or German keyboard Ctrl+Shift+, (`;`) inserts the date instead of decreasing the font size, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert, Ctrl+' copies the formula above, and Ctrl+Shift+0 (`=`) unhides columns instead of opening Insert |
| 2026-10-17 | minor | A Ctrl+Alt+letter key that types a character (a user-defined Windows hotkey such as Ctrl+Alt+A for `ä`) types it instead of running the Ctrl+letter shortcut, e.g. Select All (#1530) |
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, reached from New Rule… → Format all cells based on their values and Color Scales › More Rules…; Manage Rules edits a scale in place (part of #1165) |
| 2026-10-16 | minor | Right-drag on the fill handle opens the fill menu on release: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…; Esc cancels the drag or closes the menu without filling |
| 2026-10-16 | minor | With the active cell in a Table whose header row is scrolled out of view, the column headings show the header names and their filter buttons in place of the letters (#1423) |
| 2026-10-16 | minor | Custom Sort dialog: Sort by columns are a dropdown of the header names (Column A, B… without headers), Order follows the data (A to Z or Smallest to Largest), levels can be added, deleted, copied and reordered, the window moves and resizes, the grid selection follows "My list has headers" and is restored on close |
@@ -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.
@@ -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"}
@@ -0,0 +1,125 @@
<#
Excel open check: saves workbooks with GridCraft, opens each result in real Excel (COM) and records per
file whether Excel loads it as it is or has to repair it (docs/file-format-parity.md, "Excel open check").
check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe [-Inputs C:\workbooks] [-Out C:\out] [-Csv result.csv]
[-TimeoutSec 120]
Files saved:
- every .xlsx / .xlsm in -Inputs, opened and saved with `gridcraft-cli run --in --out` (the original
is opened in Excel too, so a file Excel itself dislikes or loads slowly is told apart from a
GridCraft regression);
- every *.jsonl scenario next to this script (one feature each), run on the Sales sample.
Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a
failure instead of a silent fix, with DisplayAlerts off and VBA macros disabled so nothing waits on a prompt.
AutomationSecurity does not cover Excel 4.0 (XLM) macros, which would still prompt, so a workbook that
holds XLM macro sheets is never opened: it is reported as SKIP-XLM and the run does not pass.
Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and
that instance (found by its window's process id) is stopped. Nothing is written next to the inputs; any other
Excel, such as one the person starts meanwhile, is never touched. Exit code 1 when any saved file is not PASS.
#>
param(
[Parameter(Mandatory = $true)][string]$Cli,
[string]$Inputs,
[string]$Out = (Join-Path ([IO.Path]::GetTempPath()) 'gridcraft-excel-open-check'),
[string]$Csv,
[int]$TimeoutSec = 120
)
$ErrorActionPreference = 'Stop'
# Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it.
$probe = {
param($path)
$x = $null
try {
# Compiled before Excel starts, so nothing between the start and the PID line can fail or stall on it.
Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);'
$x = New-Object -ComObject Excel.Application
# Report this instance's process id so the caller can stop exactly it and nothing else.
$xlPid = [uint32]0
[void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid)
"PID`t$xlPid"
$x.Visible = $false
$x.DisplayAlerts = $false
$x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: no VBA macros (XLM is screened by Test-HasXlm)
# Named arguments: PowerShell can't skip the optional ones in between positionally.
$wb = [System.__ComObject].InvokeMember('Open', [Reflection.BindingFlags]::InvokeMethod, $null, $x.Workbooks,
@($path, 0, $true, 0), $null, $null, @('Filename', 'UpdateLinks', 'ReadOnly', 'CorruptLoad'))
$sheets = $wb.Worksheets.Count + $wb.Chartsheets.Count
$wb.Close($false)
"PASS`t$sheets sheets"
} catch {
"FAIL`t" + ($_.Exception.Message -replace '\s+', ' ')
} finally {
# Also covers a failure before the PID line: this process's own instance is quit, no other is touched.
if ($x) { try { $x.Quit() } catch {} }
}
}
# True when the package holds Excel 4.0 macro sheets, which ForceDisable does not stop and Excel would prompt for.
function Test-HasXlm([string]$path) {
Add-Type -AssemblyName System.IO.Compression.FileSystem
# Not a zip at all: nothing to screen, Excel gets to report it.
try { $zip = [IO.Compression.ZipFile]::OpenRead($path) } catch { return $false }
try { return [bool]($zip.Entries | Where-Object { $_.FullName -like 'xl/macrosheets/*' }) } finally { $zip.Dispose() }
}
function Test-InExcel([string]$path) {
if (Test-HasXlm $path) { return [pscustomobject]@{ State = 'SKIP-XLM'; Seconds = 0; Detail = 'Excel 4.0 macro sheets; not opened' } }
$clock = [Diagnostics.Stopwatch]::StartNew()
$job = Start-Job -ScriptBlock $probe -ArgumentList $path
$done = Wait-Job $job -Timeout $TimeoutSec
$lines = @(Receive-Job $job -Keep -ErrorAction SilentlyContinue)
$failed = $job.State -eq 'Failed'
if (-not $done) { Stop-Job $job }
Remove-Job $job -Force
$xlPid = ($lines | Where-Object { $_ -like "PID`t*" } | Select-Object -First 1) -replace '^PID\t', ''
$out = $lines | Where-Object { $_ -notlike "PID`t*" } | Select-Object -Last 1
if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif ($failed -or -not $out) { $out = "CRASH`tno result (Excel died)" }
if ($xlPid) {
# A clean Quit lets Excel exit by itself; give it a moment, then stop only this instance.
Wait-Process -Id ([int]$xlPid) -Timeout 15 -ErrorAction SilentlyContinue
Stop-Process -Id ([int]$xlPid) -Force -ErrorAction SilentlyContinue
}
$state, $detail = $out -split "`t", 2
[pscustomobject]@{ State = $state; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); Detail = $detail }
}
$saved = Join-Path $Out 'saved'
Remove-Item -LiteralPath $saved -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path $saved -Force | Out-Null
# (name, original or $null, saved) per file
$work = @()
if ($Inputs) {
foreach ($f in Get-ChildItem -LiteralPath $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) {
$work += , @($f.Name, $f.FullName, (Join-Path $saved $f.Name), @('run', '--in', $f.FullName, '--quiet'))
}
}
foreach ($s in Get-ChildItem -Path $PSScriptRoot -Filter *.jsonl | Sort-Object Name) {
$work += , @("scenario:$($s.BaseName)", $null, (Join-Path $saved "$($s.BaseName).xlsx"), @('run', '--sample', 'sales', '--script', $s.FullName, '--quiet'))
}
$rows = @()
foreach ($w in $work) {
$name, $orig, $dest, $cliArgs = $w
# The CLI reports on stderr, which Stop would turn into an exception.
Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue
$ErrorActionPreference = 'Continue'
& $Cli @cliArgs --out $dest *> $null
$code = $LASTEXITCODE
$ErrorActionPreference = 'Stop'
$base = if ($orig) { (Test-InExcel $orig) } else { $null }
$r = if ($code -eq 0 -and (Test-Path -LiteralPath $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } }
$rows += [pscustomobject]@{
File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State
Seconds = $r.Seconds; Detail = $r.Detail
}
}
$rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output
if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv }
$bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count
$savedBad = @($rows | Where-Object Saved -ne 'PASS').Count
"{0} of {1} saved files pass" -f ($rows.Count - $savedBad), $rows.Count
if ($bad) { exit 1 }
@@ -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"}}
@@ -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"}
@@ -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}
@@ -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"}
@@ -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"}
@@ -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"}