From 5cf0e24f430176fdac37dbd2a284faa7215f1dd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:12:43 +0200 Subject: [PATCH 01/26] Charts: one combo plot-kind rule, no fixed_scale helper, ticks off the step grid (#1146) Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 3 ++- crates/chart/src/axis.rs | 11 ++++------- crates/chart/src/render.rs | 20 +++++++++++--------- crates/chart/src/resolve.rs | 10 ++++++++-- crates/chart/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 19 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07..2e9336683 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** trivial (chart combo plot-kind rule, scale ticks) · **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. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-13 | Charts: one combo plot-kind rule for resolving and drawing; ticks of a scale off the step grid keep their own values (#1146) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | diff --git a/crates/chart/src/axis.rs b/crates/chart/src/axis.rs index 8686bf7d9..46fc43f99 100644 --- a/crates/chart/src/axis.rs +++ b/crates/chart/src/axis.rs @@ -25,9 +25,11 @@ impl Scale { (0..=n) .map(|i| { let v = self.min + i as f64 * self.step; - // Snap away accumulated float error. + // Snap away accumulated float error, but only onto a multiple of the step that is + // really that close: a `min` off the step grid must keep its own ticks. let snapped = (v / self.step).round() * self.step; - if snapped.abs() < self.step * 1e-9 { 0.0 } else { snapped } + let v = if (snapped - v).abs() < self.step * 1e-9 { snapped } else { v }; + if v.abs() < self.step * 1e-9 { 0.0 } else { v } }) .collect() } @@ -107,11 +109,6 @@ pub fn nice_scale(lo: f64, hi: f64, force_zero: bool) -> Scale { Scale { min, max, step } } -/// Exact fixed scale (100% stacked axes). -pub(crate) fn fixed_scale(min: f64, max: f64, step: f64) -> Scale { - Scale { min, max, step } -} - /// A number format prepared once and reused for many labels. pub(crate) struct Fmt { general: bool, diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 037b9099e..82769bcdc 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -5,7 +5,7 @@ use std::f32::consts::{PI, TAU}; use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, Theme, TrendlineKind}; -use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale}; +use crate::axis::{Fmt, Scale, clean, nice_scale}; use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color}; use crate::trend::{auto_name, fit_trendline, moving_average}; use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign}; @@ -120,9 +120,10 @@ pub enum Swatch { Marker, } -/// The kind a series is drawn as (per-series kinds only apply to combo charts). -fn plot_kind(chart: &Chart, s: &SeriesData) -> ChartKind { - if chart.kind == ChartKind::Combo { if s.kind == ChartKind::Combo { ChartKind::Line } else { s.kind } } else { chart.kind } +/// The kind series `i` is drawn as (per-series kinds only apply to combo charts); the same rule +/// as `series_plot_kind`, applied to the already resolved series kind. +fn plot_kind(chart: &Chart, s: &SeriesData, i: usize) -> ChartKind { + crate::resolve::plot_kind(chart.kind, Some(s.kind), i) } /// Colour of point `j` for charts that colour by point (pie, doughnut, treemap, sunburst). @@ -163,8 +164,9 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa let series = data.series.iter().take(MAX_SERIES); let mut out: Vec<(String, Rgba, Swatch)> = series .clone() - .map(|s| { - let sw = match plot_kind(chart, s) { + .enumerate() + .map(|(i, s)| { + let sw = match plot_kind(chart, s, i) { ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, @@ -174,7 +176,7 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa }) .collect(); // Trendlines follow the series, named "Linear (Sales)" unless given a name. - for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) { + for (_, s) in series.enumerate().filter(|(i, s)| supports_trendline(plot_kind(chart, s, *i))) { for t in s.trendlines.iter().take(MAX_TRENDLINES) { out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line)); } @@ -833,7 +835,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta if ncat == 0 { return; } - let kinds: Vec = data.series.iter().map(|s| if horizontal { chart.kind } else { plot_kind(chart, s) }).collect(); + let kinds: Vec = data.series.iter().enumerate().map(|(i, s)| if horizontal { chart.kind } else { plot_kind(chart, s, i) }).collect(); let fams: Vec = kinds.iter().map(|k| family(*k)).collect(); let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); @@ -915,7 +917,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta })); let (lo, hi) = range.unwrap_or((0.0, 0.0)); let (scale, fmt) = if all100 { - (fixed_scale(if lo < -1e-9 { -1.0 } else { 0.0 }, if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, 0.2), Fmt::new("0%")) + (Scale { min: if lo < -1e-9 { -1.0 } else { 0.0 }, max: if hi > 1e-9 || lo >= -1e-9 { 1.0 } else { 0.0 }, step: 0.2 }, Fmt::new("0%")) } else { let code = members.first().and_then(|i| data.series.get(*i)).map(|s| s.number_format.as_str()).unwrap_or("General"); (nice_scale(lo, hi, force_zero), Fmt::new(code)) diff --git a/crates/chart/src/resolve.rs b/crates/chart/src/resolve.rs index c007e3e90..2faeeb356 100644 --- a/crates/chart/src/resolve.rs +++ b/crates/chart/src/resolve.rs @@ -170,7 +170,7 @@ fn series_name(wb: &Workbook, sheet: usize, name: &str) -> String { t.to_string() } -fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { +pub(crate) fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { match (chart_kind, series_kind) { (ChartKind::Combo, Some(k)) if k != ChartKind::Combo => k, (ChartKind::Combo, _) => { @@ -185,9 +185,15 @@ fn effective_kind(chart_kind: ChartKind, series_kind: Option, i: usiz } } +/// The kind series `i` is drawn as: its own kind in a combo chart (first series a column, the +/// rest lines when it has none), else the chart's. The one rule shared by resolving and drawing. +pub(crate) fn plot_kind(chart_kind: ChartKind, series_kind: Option, i: usize) -> ChartKind { + if chart_kind == ChartKind::Combo { effective_kind(chart_kind, series_kind, i) } else { chart_kind } +} + /// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's. pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind { - if chart.kind == ChartKind::Combo { effective_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } else { chart.kind } + plot_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } /// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 01f1aac49..4dcfcde84 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -1057,3 +1057,35 @@ fn area_charts_draw_source_value_labels_only_when_enabled() { assert!(first_label > last_poly, "{kind:?}: label drawn under a later area"); } } + +#[test] +fn drawing_and_resolving_agree_on_the_combo_plot_kind() { + // Resolved series carry `effective_kind`; drawing re-derives the kind from it. Both paths + // must give the same kind for every chart kind, series kind (or none) and series index. + let series_kinds = std::iter::once(None).chain(ALL_KINDS.iter().map(|k| Some(*k))); + for ck in ALL_KINDS { + for sk in series_kinds.clone() { + for i in 0..3 { + let mut c = chart(ck); + c.series = (0..3).map(|j| Series { kind: if j == i { sk } else { None }, ..Default::default() }).collect(); + let from_chart = series_plot_kind(&c, i); + let resolved = crate::resolve::effective_kind(ck, sk, i); + assert_eq!(crate::resolve::plot_kind(ck, Some(resolved), i), from_chart, "{ck:?} {sk:?} {i}"); + if ck != ChartKind::Combo { + assert_eq!(from_chart, ck); + } else { + assert_ne!(from_chart, ChartKind::Combo); + } + } + } + } +} + +#[test] +fn ticks_of_a_scale_off_the_step_grid_start_at_its_min() { + let s = Scale { min: 3.0, max: 7.0, step: 4.0 }; + assert_eq!(s.ticks(), vec![3.0, 7.0]); + // Aligned scales still snap float error away. + let s = Scale { min: 0.0, max: 1.0, step: 0.1 }; + assert!((s.ticks()[3] - 0.3).abs() < 1e-12 && s.ticks()[0] == 0.0); +} From 890870cd57167fda190716689b64897fcb16596e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:11:08 +0100 Subject: [PATCH 02/26] perf: select instead of sort in MEDIAN, PERCENTILE, QUARTILE, LARGE, SMALL Read the needed order statistics with select_nth_unstable_by(total_cmp) instead of a full sort. Results are bit-identical; a test compares them against the previous full-sort code on randomised data. Fixes #2679 Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat.rs | 149 +++++++++++++++++++++++++++++++---- 1 file changed, 132 insertions(+), 17 deletions(-) diff --git a/crates/functions/src/stat.rs b/crates/functions/src/stat.rs index 344ba9ff8..4ef2625cc 100644 --- a/crates/functions/src/stat.rs +++ b/crates/functions/src/stat.rs @@ -51,10 +51,11 @@ fn median(v: Vec) -> R { if v.is_empty() { return Err(CellError::Num); } - let s = sorted(v); - let n = s.len(); - let hi = s.get(n / 2).copied().unwrap_or(0.0); - if n % 2 == 1 { Ok(hi) } else { Ok(s.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) } + let mut v = v; + let n = v.len(); + let (lower, hi, _) = v.select_nth_unstable_by(n / 2, f64::total_cmp); + let hi = *hi; + if n % 2 == 1 { Ok(hi) } else { Ok(lower.iter().copied().max_by(f64::total_cmp).unwrap_or(0.0).midpoint(hi)) } } /// Values occurring at least twice, ordered by first occurrence, with their (equal, maximal) count. @@ -125,29 +126,38 @@ fn kth(v: Vec, k: f64, largest: bool) -> R { if k.is_nan() || k < 1.0 || k > v.len() as f64 { return Err(CellError::Num); } - let s = sorted(v); + let mut v = v; let k = k as usize; - let idx = if largest { s.len() - k } else { k - 1 }; - s.get(idx).copied().ok_or(CellError::Num) + let idx = if largest { v.len() - k } else { k - 1 }; + // Selection instead of a full sort; same total order, so the same bit pattern as `sorted(v)[idx]`. + Ok(*v.select_nth_unstable_by(idx, f64::total_cmp).1) } -fn interp(s: &[f64], pos: f64) -> R { +/// Value at fractional rank `pos` of the sorted data, linearly interpolated, found by selection. +fn interp(mut v: Vec, pos: f64) -> R { let i = pos.floor(); let frac = pos - i; let i = i as usize; - let lo = *s.get(i).ok_or(CellError::Num)?; - match s.get(i + 1) { - Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), - _ => Ok(lo), + if i >= v.len() { + return Err(CellError::Num); } + let (_, lo, upper) = v.select_nth_unstable_by(i, f64::total_cmp); + let lo = *lo; + // The next order statistic is the minimum of the upper partition. + if frac > 0.0 + && let Some(hi) = upper.iter().copied().min_by(f64::total_cmp) + { + return Ok(lo + frac * (hi - lo)); + } + Ok(lo) } fn percentile_inc(v: Vec, k: f64) -> R { if v.is_empty() || !(0.0..=1.0).contains(&k) { return Err(CellError::Num); } - let s = sorted(v); - interp(&s, k * (s.len() - 1) as f64) + let pos = k * (v.len() - 1) as f64; + interp(v, pos) } fn percentile_exc(v: Vec, k: f64) -> R { @@ -159,8 +169,7 @@ fn percentile_exc(v: Vec, k: f64) -> R { if pos < 1.0 || pos > n { return Err(CellError::Num); } - let s = sorted(v); - interp(&s, pos - 1.0) + interp(v, pos - 1.0) } fn quartile_inc(v: Vec, q: f64) -> R { @@ -2274,7 +2283,9 @@ pub(crate) fn specs() -> Vec { #[cfg(test)] mod tests { - use super::{MAX_REGRESSORS, aggregate_values, aggregate_values_k, check_regression_size}; + use super::{ + MAX_REGRESSORS, R, aggregate_values, aggregate_values_k, check_regression_size, kth, median, percentile_exc, percentile_inc, sorted, + }; use crate::util::testutil::*; use gridcraft_core::{CellError, Value}; @@ -2463,6 +2474,110 @@ mod tests { close(ev("RANK.AVG", vec![n(3.5), r2, n(1.0)]), 3.5); } + // Reference implementations: the previous full-sort versions, as the oracle for the selection ones. + fn old_interp(s: &[f64], pos: f64) -> R { + let i = pos.floor(); + let frac = pos - i; + let i = i as usize; + let lo = *s.get(i).ok_or(CellError::Num)?; + match s.get(i + 1) { + Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), + _ => Ok(lo), + } + } + + fn old_median(v: Vec) -> R { + if v.is_empty() { + return Err(CellError::Num); + } + let s = sorted(v); + let n = s.len(); + let hi = s.get(n / 2).copied().unwrap_or(0.0); + if n % 2 == 1 { Ok(hi) } else { Ok(s.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) } + } + + fn old_kth(v: Vec, k: f64, largest: bool) -> R { + let k = k.ceil(); + if k.is_nan() || k < 1.0 || k > v.len() as f64 { + return Err(CellError::Num); + } + let s = sorted(v); + let k = k as usize; + let idx = if largest { s.len() - k } else { k - 1 }; + s.get(idx).copied().ok_or(CellError::Num) + } + + fn old_percentile_inc(v: Vec, k: f64) -> R { + if v.is_empty() || !(0.0..=1.0).contains(&k) { + return Err(CellError::Num); + } + let s = sorted(v); + old_interp(&s, k * (s.len() - 1) as f64) + } + + fn old_percentile_exc(v: Vec, k: f64) -> R { + let n = v.len() as f64; + if v.is_empty() || !(k > 0.0 && k < 1.0) { + return Err(CellError::Num); + } + let pos = k * (n + 1.0); + if pos < 1.0 || pos > n { + return Err(CellError::Num); + } + let s = sorted(v); + old_interp(&s, pos - 1.0) + } + + /// Same Ok bit pattern or same error. + fn same(a: R, b: R) -> bool { + match (a, b) { + (Ok(x), Ok(y)) => x.to_bits() == y.to_bits(), + (Err(x), Err(y)) => x == y, + _ => false, + } + } + + #[test] + fn selection_matches_full_sort_bit_for_bit() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let specials = [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, -f64::NAN, f64::MAX, f64::MIN_POSITIVE, 1.0, -1.0]; + for len in (0..=40).chain([63, 64, 65, 100, 257, 1000, 4096]) { + for round in 0..12 { + let v: Vec = (0..len) + .map(|_| match (round % 4, next() % 8) { + // Few distinct values: many ties. + (0, r) => (r % 3) as f64, + // Specials, including both zeros and NaNs. + (1, r) => specials[(next() as usize + r as usize) % specials.len()], + // Wide random range. + (2, _) => (next() as i64 as f64) / 1e3, + // Integers with some specials mixed in. + (_, 0) => specials[next() as usize % specials.len()], + _ => (next() % 50) as f64, + }) + .collect(); + assert!(same(median(v.clone()), old_median(v.clone())), "median len={len}"); + let ks = [-1.0, 0.0, 0.2, 1.0, 1.5, 2.0, len as f64 / 2.0, len as f64 - 0.5, len as f64, len as f64 + 1.0, f64::NAN]; + for &k in &ks { + for largest in [true, false] { + assert!(same(kth(v.clone(), k, largest), old_kth(v.clone(), k, largest)), "kth len={len} k={k}"); + } + } + let ps = [-0.1, 0.0, 0.01, 0.1, 0.25, 0.3, 0.5, 0.75, 0.9, 0.99, 1.0, 1.1, f64::NAN, (next() % 1001) as f64 / 1000.0]; + for &p in &ps { + assert!(same(percentile_inc(v.clone(), p), old_percentile_inc(v.clone(), p)), "pinc len={len} p={p}"); + assert!(same(percentile_exc(v.clone(), p), old_percentile_exc(v.clone(), p)), "pexc len={len} p={p}"); + } + } + } + } + #[test] fn percentiles() { close(ev("PERCENTILE.INC", vec![c(&[1.0, 3.0, 2.0, 4.0]), n(0.3)]), 1.9); From c567511cf1e5335e4078e5bdd2036e14e72293c6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 22:21:15 +0100 Subject: [PATCH 03/26] calc: rebuild the dependency graph from shared syntax trees Calc::rebuild and Calc::cells_changed called Formula::expr(), which deep-copies each formula's syntax tree only to read its references. Use expr_arc() (already used when formulas are calculated), which hands out the cached Arc without copying. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 17a0e6649..6cd1551fe 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -1010,7 +1010,7 @@ impl Calc { for (si, sheet) in wb.sheets.iter().enumerate() { for (c, cell) in sheet.cells.iter() { if let Some(f) = &cell.formula - && let Some(e) = f.expr() + && let Some(e) = f.expr_arc() { let (areas, dynamic) = precedents(wb, si, &e); self.graph.insert((si, c), Node { areas, dynamic }); @@ -1088,7 +1088,7 @@ impl Calc { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); - match formula.and_then(|f| f.expr()) { + match formula.and_then(|f| f.expr_arc()) { Some(e) => { let (areas, dynamic) = precedents(wb, k.0, &e); self.graph.insert(k, Node { areas, dynamic }); From 4523b817ce53be54a9ce9d5b5b49761c3907a75d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:51:12 +0100 Subject: [PATCH 04/26] Read already-sorted input directly instead of selecting A full sort recognises ascending and descending runs in O(n), which a selection cannot beat, so sorted, reverse-sorted and tie-block input was up to 1.8x slower than before. Check for a monotone run first (one pass that stops at the first out-of-order pair) and index into it. Extend the bit-for-bit oracle test with ascending, descending and nearly ascending data. Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/descriptive.rs | 32 +++++++++++++++++++++++- crates/functions/src/stat/tests.rs | 22 +++++++++++++--- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/crates/functions/src/stat/descriptive.rs b/crates/functions/src/stat/descriptive.rs index 49d30d42c..08938d039 100644 --- a/crates/functions/src/stat/descriptive.rs +++ b/crates/functions/src/stat/descriptive.rs @@ -38,12 +38,31 @@ pub(super) fn sorted(mut v: Vec) -> Vec { v } +/// Sorts `v` if it is already monotone in `total_cmp` order (a descending slice is reversed) and +/// says whether it did. One cheap pass that stops at the first out-of-order pair, so unordered +/// data costs next to nothing. Needed because the std sort recognises ascending and descending +/// runs in O(n), which a selection cannot beat. +fn sorted_if_monotone(v: &mut [f64]) -> bool { + if v.is_sorted_by(|a, b| a.total_cmp(b).is_le()) { + return true; + } + if v.is_sorted_by(|a, b| a.total_cmp(b).is_ge()) { + v.reverse(); + return true; + } + false +} + pub(super) fn median(v: Vec) -> R { if v.is_empty() { return Err(CellError::Num); } let mut v = v; let n = v.len(); + if sorted_if_monotone(&mut v) { + let hi = v.get(n / 2).copied().unwrap_or(0.0); + return if n % 2 == 1 { Ok(hi) } else { Ok(v.get(n / 2 - 1).copied().unwrap_or(0.0).midpoint(hi)) }; + } let (lower, hi, _) = v.select_nth_unstable_by(n / 2, f64::total_cmp); let hi = *hi; if n % 2 == 1 { Ok(hi) } else { Ok(lower.iter().copied().max_by(f64::total_cmp).unwrap_or(0.0).midpoint(hi)) } @@ -120,7 +139,11 @@ pub(super) fn kth(v: Vec, k: f64, largest: bool) -> R { let mut v = v; let k = k as usize; let idx = if largest { v.len() - k } else { k - 1 }; - // Selection instead of a full sort; same total order, so the same bit pattern as `sorted(v)[idx]`. + // Selection instead of a full sort (monotone input is read directly); same total order, so the + // same bit pattern as `sorted(v)[idx]`. + if sorted_if_monotone(&mut v) { + return v.get(idx).copied().ok_or(CellError::Num); + } Ok(*v.select_nth_unstable_by(idx, f64::total_cmp).1) } @@ -132,6 +155,13 @@ fn interp(mut v: Vec, pos: f64) -> R { if i >= v.len() { return Err(CellError::Num); } + if sorted_if_monotone(&mut v) { + let lo = v.get(i).copied().ok_or(CellError::Num)?; + return match v.get(i + 1) { + Some(hi) if frac > 0.0 => Ok(lo + frac * (hi - lo)), + _ => Ok(lo), + }; + } let (_, lo, upper) = v.select_nth_unstable_by(i, f64::total_cmp); let lo = *lo; // The next order statistic is the minimum of the upper partition. diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index 60da9f59e..f11629369 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -263,8 +263,8 @@ fn selection_matches_full_sort_bit_for_bit() { }; let specials = [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, -f64::NAN, f64::MAX, f64::MIN_POSITIVE, 1.0, -1.0]; for len in (0..=40).chain([63, 64, 65, 100, 257, 1000, 4096]) { - for round in 0..12 { - let v: Vec = (0..len) + for round in 0..24 { + let mut v: Vec = (0..len) .map(|_| match (round % 4, next() % 8) { // Few distinct values: many ties. (0, r) => (r % 3) as f64, @@ -277,7 +277,23 @@ fn selection_matches_full_sort_bit_for_bit() { _ => (next() % 50) as f64, }) .collect(); - assert!(same(median(v.clone()), old_median(v.clone())), "median len={len}"); + // Rounds 12..24 repeat the data as already ascending, already descending and nearly + // ascending (ends swapped): the monotone shortcut and its fallback to selection. + match round / 4 { + 3 => v.sort_by(f64::total_cmp), + 4 => { + v.sort_by(f64::total_cmp); + v.reverse(); + } + 5 => { + v.sort_by(f64::total_cmp); + if let Some(last) = v.len().checked_sub(1) { + v.swap(0, last); + } + } + _ => {} + } + assert!(same(median(v.clone()), old_median(v.clone())), "median len={len} round={round}"); let ks = [-1.0, 0.0, 0.2, 1.0, 1.5, 2.0, len as f64 / 2.0, len as f64 - 0.5, len as f64, len as f64 + 1.0, f64::NAN]; for &k in &ks { for largest in [true, false] { From b6bbdcd5cf23626171768d0cf061e4b0319a67c1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:51:45 +0100 Subject: [PATCH 05/26] calc: build precedents from a borrowed syntax tree, no Arc for text-only formulas Formula::with_expr runs a closure on the cached tree, or on a freshly parsed one that is dropped afterwards, so rebuild and cells_changed need neither a tree copy nor an Arc allocation / reference count. Co-Authored-By: Claude Sonnet 5.5 --- crates/calc/src/recalc.rs | 11 +++++------ crates/calc/src/tests.rs | 39 +++++++++++++++++++++++++++++++++++++++ crates/model/src/cell.rs | 10 ++++++++++ 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 34c712ddc..9886ca9bd 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -128,9 +128,8 @@ impl Calc { for (si, sheet) in wb.sheets.iter().enumerate() { for (c, cell) in sheet.cells.iter() { if let Some(f) = &cell.formula - && let Some(e) = f.expr_arc() + && let Some((areas, dynamic)) = f.with_expr(|e| precedents(wb, si, e)) { - let (areas, dynamic) = precedents(wb, si, &e); self.graph.insert((si, c), Node { areas, dynamic }); if cell.value == Value::Error(CellError::Circ) { circ.push((si, c)); @@ -205,10 +204,10 @@ impl Calc { pub fn cells_changed(&mut self, wb: &mut Workbook, changed: &[Key]) { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { - let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); - match formula.and_then(|f| f.expr_arc()) { - Some(e) => { - let (areas, dynamic) = precedents(wb, k.0, &e); + let precedent = + wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.as_ref()).and_then(|f| f.with_expr(|e| precedents(wb, k.0, e))); + match precedent { + Some((areas, dynamic)) => { self.graph.insert(k, Node { areas, dynamic }); } None => { diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e90085..0d4c973d4 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,42 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +/// `rebuild` and `cells_changed` read formulas through `Formula::with_expr`, which borrows the +/// cached tree or parses on the fly. The dependency graph must come out the same for formulas that +/// carry their tree and for formulas that only carry their text (as after loading a file). +#[test] +fn graph_built_from_text_only_formulas_matches_cached() { + fn run(cached: bool) -> Vec { + let mut t = T::new(); + t.set("A1", "2"); + for (at, f) in [("B1", "=A1*10"), ("C1", "=B1+A1"), ("D1", "=SUM(A1:C1)"), ("E1", "=NOPE(")] { + // E1 does not parse, so it has no tree either way and only covers the `None` branch. + let mut formula = Formula::new(f); + if !cached { + formula.expr = None; + } + t.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::formula(formula)); + } + t.calc.rebuild(&t.wb); + t.calc.recalc_all(&mut t.wb); + let mut out: Vec = ["B1", "C1", "D1", "E1"].iter().map(|a| t.get(a)).collect(); + // Editing the input must reach the dependents through the rebuilt graph. + t.set("A1", "5"); + out.extend(["B1", "C1", "D1"].iter().map(|a| t.get(a))); + // A text-only formula that is rewritten through `cells_changed` joins the graph too. + let mut formula = Formula::new("=A1+100"); + if !cached { + formula.expr = None; + } + t.wb.sheet_mut(0).unwrap().cells.set(c("F1"), Cell::formula(formula)); + t.calc.cells_changed(&mut t.wb, &[(0, c("F1"))]); + t.set("A1", "7"); + out.push(t.get("F1")); + out + } + let cached = run(true); + assert_eq!(cached, run(false)); + assert_eq!(cached[4], Value::Number(50.0)); + assert_eq!(cached[7], Value::Number(107.0)); +} diff --git a/crates/model/src/cell.rs b/crates/model/src/cell.rs index d4466365f..7d3a7715e 100644 --- a/crates/model/src/cell.rs +++ b/crates/model/src/cell.rs @@ -46,6 +46,16 @@ impl Formula { pub fn expr_arc(&self) -> Option> { self.expr.clone().or_else(|| gridcraft_formula::parse(&self.text).ok().map(Arc::new)) } + /// Runs `f` on the parsed expression, borrowing the cached tree or, after deserialization, + /// a freshly parsed one that is dropped afterwards. Unlike [`expr`](Self::expr) it never copies + /// the tree, and unlike [`expr_arc`](Self::expr_arc) it needs no reference count or `Arc` + /// allocation. `None` when the text does not parse. + pub fn with_expr(&self, f: impl FnOnce(&Expr) -> R) -> Option { + match &self.expr { + Some(e) => Some(f(e)), + None => gridcraft_formula::parse(&self.text).ok().map(|e| f(&e)), + } + } } /// A static picture stored as cell content, independent of floating drawing anchors. From 8b330ac9e213c05906b4dee0468444e558f6e4a0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 29 Oct 2026 00:52:59 +0100 Subject: [PATCH 06/26] Tighten selection comment and test index arithmetic Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/stat/descriptive.rs | 7 ++++--- crates/functions/src/stat/tests.rs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/functions/src/stat/descriptive.rs b/crates/functions/src/stat/descriptive.rs index 08938d039..3c8f78f69 100644 --- a/crates/functions/src/stat/descriptive.rs +++ b/crates/functions/src/stat/descriptive.rs @@ -39,9 +39,10 @@ pub(super) fn sorted(mut v: Vec) -> Vec { } /// Sorts `v` if it is already monotone in `total_cmp` order (a descending slice is reversed) and -/// says whether it did. One cheap pass that stops at the first out-of-order pair, so unordered -/// data costs next to nothing. Needed because the std sort recognises ascending and descending -/// runs in O(n), which a selection cannot beat. +/// says whether it did. At most two passes, each stopping at the first out-of-order pair, so +/// unordered data costs next to nothing. Needed because the std sort recognises ascending and +/// descending runs in O(n) with a small constant; selection is O(n) too but measured 1.2-1.8x +/// slower on such input. fn sorted_if_monotone(v: &mut [f64]) -> bool { if v.is_sorted_by(|a, b| a.total_cmp(b).is_le()) { return true; diff --git a/crates/functions/src/stat/tests.rs b/crates/functions/src/stat/tests.rs index f11629369..023b36815 100644 --- a/crates/functions/src/stat/tests.rs +++ b/crates/functions/src/stat/tests.rs @@ -269,7 +269,7 @@ fn selection_matches_full_sort_bit_for_bit() { // Few distinct values: many ties. (0, r) => (r % 3) as f64, // Specials, including both zeros and NaNs. - (1, r) => specials[(next() as usize + r as usize) % specials.len()], + (1, r) => specials[(next() as usize).wrapping_add(r as usize) % specials.len()], // Wide random range. (2, _) => (next() as i64 as f64) / 1e3, // Integers with some specials mixed in. From 1ff10df55756d3823bcf91e3d3fc31462b6276b4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 20:56:00 +0100 Subject: [PATCH 07/26] fix(autosum): stop the guessed range at a blank cell (#3291) The single-cell AutoSum guess stepped over one blank cell when a number sat above it, so a second block of numbers below a gap was summed together with the first block. It now stops at the first non-number, as Excel does. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/formulas.rs | 5 +---- crates/engine/src/tests.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index d72f814a1..b38571d64 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -179,10 +179,7 @@ fn guessed_range(sh: &gridcraft_model::sheet::Sheet, at: CellRef) -> Option 0 && (numeric(CellRef::new(at.row - 1, at.col)) || at.col == 0 || !numeric(CellRef::new(at.row, at.col - 1))) { let mut top = at.row - 1; - while top > 0 - && (numeric(CellRef::new(top - 1, at.col)) - || sh.value(CellRef::new(top - 1, at.col)).is_empty() && top > 1 && numeric(CellRef::new(top - 2, at.col))) - { + while top > 0 && numeric(CellRef::new(top - 1, at.col)) { top -= 1; } if numeric(CellRef::new(at.row - 1, at.col)) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fe42b6977..0fccb81e1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2067,6 +2067,19 @@ fn formula_at(s: &Session, a: &str) -> Option { s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).and_then(|c| c.formula.as_ref().map(|f| f.text.clone())) } +#[test] +fn autosum_of_a_single_cell_stops_at_a_blank_cell() { + // #3291: a blank row between two blocks of numbers ended the guess one block too late, so the + // second total summed the first block (and its total) as well. + let mut s = s(); + s.execute("range.setValues", json!({"range": "B4", "values": [[1], [2], [3]]})).unwrap(); + s.execute("cell.set", json!({"cell": "B7", "input": "=SUM(B4:B6)"})).unwrap(); + s.execute("range.setValues", json!({"range": "B9", "values": [[10], [20]]})).unwrap(); + s.execute("selection.set", json!({"cell": "B11"})).unwrap(); + s.execute("formulas.autoSum", json!({})).unwrap(); + assert_eq!(v(&s, "B11"), Value::Number(30.0)); +} + #[test] fn autosum_over_a_row_totals_it_to_the_right() { // As in Excel: a row selected and AutoSum puts one total to its right, not a one-cell total From b3a709f314ef7203959f23a121836868342451aa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 02:12:09 +0100 Subject: [PATCH 08/26] contributors: set names for vangel76 Co-Authored-By: Claude Sonnet 5.5 --- contributors/people.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index 00f6ce76a..1b8bcf996 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -33,7 +33,8 @@ sync_github_name = false [people.vangel76] real_name = "Valentin Klein" -sync_github_name = true +display_name = "vangel76" +sync_github_name = false [people.MacJedi42] sync_github_name = true From ede12f9da631c4cbfe9253ab633be44e5eb356a7 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:33:46 +0100 Subject: [PATCH 09/26] About: credits tables fit without side-scrolling and their columns resize (#3320) * About: credits tables fit without side-scrolling and their columns resize The Contributors table and the Models table were egui Grids inside a two-way scroll area: they opened wider than the dialog, so they scrolled sideways, and Company and Model sat almost touching. Both are now egui_extras tables. Each column opens at the width of its header and widest cell, the spare width goes to the text columns (Name; Company and Model), and every column edge can be dragged. Widening a column grows the table like a spreadsheet, and only then does it scroll sideways; the header stays put while the rows scroll. Counts and dates are right-aligned and every cell is vertically centred. The sorted column stays highlighted and its direction shows on the toolbar's sort-order button, so headers no longer reserve room for an arrow. The opening widths come from fit_widths, a pure function with unit tests that a fitted table fills its room exactly and that only the text columns give way when room is short. The About dialog opens 820 points wide, so every column fits at its natural width. Co-Authored-By: Claude Opus 5.5 * Let every credits column be dragged, and refit changed tables The last column was egui's remainder column, which has no drag handle, so it could only be resized from the edge before it. It is now an ordinary column with its own handle. A table keeps its column widths, so switching to a longer name left the Name column at its old width and clipped the text. The table now goes back to the opening fit whenever that fit changes: a longer widest cell or a resized window. Dragged widths are dropped at that point. fit_widths could overflow the room when one column hit the minimum, because the other columns did not take up its share. Columns now give way in proportion to their width above the minimum. Co-Authored-By: Claude Opus 5.5 * Refit credits tables on what they measure, not the fitted widths Comparing the fitted widths missed the case it was meant for. Name is the only growing column, so a longer name takes its extra width from the spare room and the fit comes out the same: a dragged Name width stayed, clipping the longer name. It could also drop dragged widths by accident. The fit comes from the available width inside the scroll area, which scrolling can nudge, so scrolling a widened table could reset it. The table now compares the natural widths and the clip rect's width, which scrolling does not move. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 55 ++++- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/credits.rs | 375 +++++++++++++++++++++++++---- crates/ui-egui/src/dialogs/show.rs | 2 +- 4 files changed, 369 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20dcf28ab..785493348 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,7 +220,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.59.0", + "windows-sys 0.61.2", "wl-clipboard-rs", "x11rb", ] @@ -1346,6 +1346,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1413,6 +1426,26 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -1478,7 +1511,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2131,6 +2164,7 @@ dependencies = [ "craft-update", "craft-window", "egui", + "egui_extras", "egui_kittest", "epaint_default_fonts", "gridcraft-chart", @@ -3507,7 +3541,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3963,7 +3997,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4348,7 +4382,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4407,7 +4441,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5158,7 +5192,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6151,7 +6185,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6967,11 +7001,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 297f7bab9..fd18f7041 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -18,6 +18,7 @@ gridcraft-chart = { workspace = true } # this feature. The UI draws ✕, ◀, ↘ and 📋 as text; without these faces the strict kittest # harness (and a host with no symbol font) renders them as tofu. egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } +egui_extras = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index 95c39a1a3..0e4eb6295 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -244,12 +244,17 @@ pub fn contributors_ui(ui: &mut egui::Ui) { let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending); ui.label(RichText::new(format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak()); ui.separator(); - egui::ScrollArea::both().auto_shrink([false, false]).max_height(340.0).show(ui, |ui| { - if list.is_empty() { - ui.label("No contributor data was built into this copy."); - } else if v.table { - table(ui, &list, &mut v); - } else { + if list.is_empty() { + ui.label("No contributor data was built into this copy."); + } else if v.table { + // The table scrolls vertically itself, under a fixed header; it only scrolls sideways + // once its columns are dragged wider than the dialog. + ui.allocate_ui(egui::vec2(ui.available_width(), 340.0), |ui| { + ui.set_max_height(340.0); + egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(ui, &list, &mut v)); + }); + } else { + egui::ScrollArea::vertical().auto_shrink([false, false]).max_height(340.0).show(ui, |ui| { ui.horizontal_wrapped(|ui| { for (i, c) in list.iter().enumerate() { if i > 0 { @@ -258,39 +263,153 @@ pub fn contributors_ui(ui: &mut egui::Ui) { ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); } }); - } - }); + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } -fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; - if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { + let spare = room - natural.iter().sum::(); + let weight = grow.iter().sum::(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if *g > 0.0 && spare >= 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + w - (-spare).min(flexible) * slack(*w) / flexible + } else { + *w } - } - ui.end_row(); - for c in list { - ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(k.label().1).strong() +} + +fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0); + + if r.clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); + } + }) + .body(|mut body| { + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login))) + .on_hover_text(c.summary()); + }); + for text in cells { + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -300,21 +419,50 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); - egui::ScrollArea::both().auto_shrink([false, false]).max_height(340.0).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] { - ui.label(RichText::new(h).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } + let h = row_height(ui); + let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + ui.allocate_ui(egui::vec2(ui.available_width(), 340.0), |ui| { + ui.set_max_height(340.0); + egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(title).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); }); } @@ -395,4 +543,131 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec) -> Vec { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec) -> Vec { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index bb1e9f5e7..e4cd5bb24 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -148,7 +148,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { let mut confirm = false; let width = match d.name.as_str() { "formatCells" => 560.0, - "about" => 660.0, + "about" => 820.0, "insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "journal" | "agents" | "equation" => 520.0, "macros" => 480.0, "recommendedCharts" => 600.0, From 1fb191571ba6c487246fa94ee4ce5a37abd22fcc Mon Sep 17 00:00:00 2001 From: Francisco Herrera Date: Wed, 4 Nov 2026 23:13:35 -0500 Subject: [PATCH 10/26] Charts: draw every doughnut series as a ring (#1827) * Charts: draw every doughnut series as a ring (#1827) * Charts: submit doughnut hole size and first slice angle when the drag ends (#1827) --------- Co-authored-by: alosslessdev --- crates/chart/src/render.rs | 9 +- crates/chart/src/render/kinds.rs | 145 +++++++- crates/chart/src/render/legend.rs | 2 + crates/chart/src/tests.rs | 319 +++++++++++++++++- crates/engine/src/cmd/forecast.rs | 2 + crates/engine/src/cmd/insert.rs | 10 +- crates/engine/src/cmd/pivot/charts.rs | 2 + crates/engine/src/tests.rs | 15 + crates/model/src/features.rs | 46 +++ crates/model/src/sheet.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/el.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/nl.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 2 + crates/ui-egui/src/i18n/ro.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/sr.rs | 2 + crates/ui-egui/src/i18n/tr.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/i18n/vi.rs | 2 + crates/ui-egui/src/i18n/zh.rs | 2 + crates/ui-egui/src/panes.rs | 33 ++ crates/xlsx/src/chart.rs | 16 +- crates/xlsx/src/chartex.rs | 2 + crates/xlsx/src/tests/chart_book_names.rs | 4 + crates/xlsx/src/tests/fixtures.rs | 46 +++ .../src/tests/literal_category_roundtrip.rs | 2 + .../tests/multilevel_category_roundtrip.rs | 2 + crates/xlsx/src/tests/roundtrip.rs | 6 + crates/xlsx/src/tests/smooth_roundtrip.rs | 4 + crates/xlsx/src/tests/trendline_roundtrip.rs | 2 + docs/chart-parity.md | 10 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 9 +- 41 files changed, 705 insertions(+), 21 deletions(-) diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 7e50e78f6..2b46c5fbd 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -19,7 +19,7 @@ mod trend; use cartesian::{cartesian, scatter}; use frame::{Bx, axis_titles, chart_title}; -use kinds::{box_whisker, funnel, histogram, pie, radar, stock, treemap, waterfall}; +use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall}; use legend::draw_legend; pub use legend::{Swatch, legend_entries}; pub use trend::supports_trendline; @@ -44,6 +44,11 @@ const MAX_LINE_PTS: usize = 2000; const MAX_MARKERS: usize = 5000; /// Data labels are skipped when a series has more points than this. const MAX_LABELS: usize = 200; +/// Most wedges a doughnut draws for the whole chart. The per-series and per-category limits do not +/// bound their product: 255 series of 20,000 categories would be millions of wedges. Every drawable +/// ring shares this budget, so the innermost ring keeps its largest slices and the outer rings are +/// capped instead of the chart dropping rings wholesale. +pub(crate) const MAX_WEDGES: usize = 2_048; struct Ctx<'a> { out: Vec, @@ -153,7 +158,7 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { use ChartKind::*; match chart.kind { Pie => pie(ctx, chart, data, area, 0.0, false), - Doughnut => pie(ctx, chart, data, area, 0.5, false), + Doughnut => doughnut(ctx, chart, data, area), Sunburst => pie(ctx, chart, data, area, 0.2, true), Treemap => treemap(ctx, chart, data, area), Funnel => funnel(ctx, chart, data, area), diff --git a/crates/chart/src/render/kinds.rs b/crates/chart/src/render/kinds.rs index 10286107b..77a58d0fe 100644 --- a/crates/chart/src/render/kinds.rs +++ b/crates/chart/src/render/kinds.rs @@ -1,8 +1,8 @@ use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range}; use super::legend::{cat_label, point_color}; use super::{ - AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, Prim, QuartileMethod, STOCK, SeriesData, - TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale, + AXIS, Chart, ChartData, Ctx, DOWN, Fmt, GRID, HAlign, LABEL_SIZE, MAX_CATS, MAX_LABELS, MAX_MARKERS, MAX_SERIES, MAX_WEDGES, Prim, + QuartileMethod, Rgba, STOCK, SeriesData, TAU, TEXT, UP, VAlign, WHITE, clean, nice_scale, }; // ---------------------------------------------------------------- histogram @@ -163,6 +163,66 @@ pub(super) fn funnel(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { // ---------------------------------------------------------------- pie, doughnut, sunburst +/// At most `cap` of the largest values, in category order. When a ring has more categories than +/// its share of the wedge budget allows, the big slices survive rather than the first ones. +fn largest_slices(vals: &[f64], cap: usize) -> Vec<(usize, f64)> { + let mut idx: Vec = (0..vals.len()).collect(); + if idx.len() > cap { + // Partition descends by value, so the first `cap` entries are the largest ones. + idx.select_nth_unstable_by(cap - 1, |a, b| vals[*b].total_cmp(&vals[*a])); + idx.truncate(cap); + idx.sort_unstable(); + } + idx.into_iter().map(|j| (j, vals[j])).collect() +} + +/// One ring's geometry and separator stroke: the slices of a ring differ only in angle and colour. +struct Ring { + cx: f32, + cy: f32, + outer: f32, + inner: f32, + stroke: Option<(Rgba, f32)>, +} + +/// A wedge of `ring`, split at 12 o'clock when it crosses the end of the circle. +fn wedge(ctx: &mut Ctx, ring: &Ring, a0: f32, sweep: f32, fill: Rgba) { + let Ring { cx, cy, outer, inner, stroke } = *ring; + if sweep <= 1e-4 { + return; + } + // A slice that starts past 12 o'clock still has to be split against 12 o'clock, not against + // its unwrapped start: otherwise the half after TAU is drawn from 0 over its neighbours. + let a0 = a0.rem_euclid(TAU); + let a1 = a0 + sweep; + if a1 <= TAU { + ctx.out.push(Prim::Wedge { cx, cy, r_outer: outer, r_inner: inner, a0, a1, fill, stroke }); + return; + } + // The halves are filled without a stroke: each would outline its own radial edge at 12 + // o'clock, painting the white separator straight through the slice. + ctx.out.push(Prim::Wedge { cx, cy, r_outer: outer, r_inner: inner, a0, a1: TAU, fill, stroke: None }); + ctx.out.push(Prim::Wedge { cx, cy, r_outer: outer, r_inner: inner, a0: 0.0, a1: a1 - TAU, fill, stroke: None }); + if let Some((color, width)) = stroke { + // One outline for the whole slice: the outer and inner arcs run through 12 o'clock, and + // the two radial edges at the slice's own start and end close the path. + let arc = |r: f32, from: f32, to: f32| -> Vec<[f32; 2]> { + let steps = ((r.abs() * (to - from).abs() / 2.0).ceil() as usize).clamp(4, 512); + let at = |a: f32| [cx + r * a.sin(), cy - r * a.cos()]; + (0..=steps).map(|k| at(from + (to - from) * k as f32 / steps as f32)).collect() + }; + let mut pts = arc(outer, a0, a1); + if inner > 0.0 { + pts.extend(arc(inner, a1, a0)); + } else { + pts.push([cx, cy]); + } + let start = pts[0]; + pts.push(start); + ctx.out.push(Prim::Line { pts, color, width, dash: false }); + } +} + pub(super) fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inner: f32, names: bool) { let Some(s) = data.series.first() else { return }; let vals: Vec = s.values.iter().take(MAX_CATS).map(|v| v.map(f64::abs).unwrap_or(0.0)).collect(); @@ -176,14 +236,15 @@ pub(super) fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inne return; } let ri = r * inner; + let ring = Ring { cx, cy, outer: r, inner: ri, stroke: Some((WHITE, 1.5)) }; let f = Fmt::new(&s.number_format); - let mut a = 0.0f32; + let mut a = (chart.first_slice_angle % 360) as f32 * TAU / 360.0; let mut labels = Vec::new(); for (j, v) in vals.iter().enumerate() { let sweep = (*v / total) as f32 * TAU; if sweep > 1e-4 { let fill = point_color(data, j); - ctx.out.push(Prim::Wedge { cx, cy, r_outer: r, r_inner: ri, a0: a, a1: (a + sweep).min(TAU), fill, stroke: Some((WHITE, 1.5)) }); + wedge(ctx, &ring, a, sweep, fill); if (chart.data_labels || names) && vals.len() <= MAX_LABELS { let t = if names { cat_label(data, j) } else { f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None) }; let mid = a + sweep / 2.0; @@ -201,6 +262,82 @@ pub(super) fn pie(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, inne } } +/// Excel's doughnut: every series is one concentric ring, the first series innermost (measured in +/// Excel: ring outer radii ≈0.83, 0.92 and 1.0 of the plot radius for series 1, 2 and 3). The hole +/// size and first slice angle come from the chart; each ring is scaled to its own total. +pub(super) fn doughnut(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) { + let nser = data.series.len().min(MAX_SERIES); + if nser == 0 { + return; + } + let (cx, cy) = (area.cx(), area.cy()); + let r = area.w.min(area.h) / 2.0 * 0.92; + if r < 2.0 { + return; + } + let hole = f32::from(chart.hole_size.clamp(10, 90)) / 100.0; + let ri = r * hole; + let thick = (r - ri) / nser as f32; + // A ring thinner than a pixel would vanish. Rather than suppressing the whole chart when there + // are more series than the annulus has pixels, keep the outer rings at one pixel each and drop + // the innermost series that no longer fit: Excel's order makes the first series the innermost, + // so the outermost rings are the ones worth keeping. + let band = thick.max(1.0); + let start = (chart.first_slice_angle % 360) as f32 * TAU / 360.0; + // Only rings with a pixel of band are drawn, and the wedge budget is shared across them in + // drawing order: the innermost ring (the first series) gets its slices first, and the outer + // rings are capped instead of the series × category product growing without bound. + let rings: Vec<(&SeriesData, f32, f32)> = data + .series + .iter() + .take(nser) + .enumerate() + .filter_map(|(si, s)| { + let outer = (r - (nser - 1 - si) as f32 * band).min(r); + let inner = (r - (nser - si) as f32 * band).max(ri); + (outer - inner >= 1.0).then_some((s, outer, inner)) + }) + .collect(); + let mut budget = MAX_WEDGES; + let mut labels = Vec::new(); + for (k, (s, outer, inner)) in rings.iter().enumerate() { + // The white separator is 1.5 units wide, wider than a one-pixel band: on a thin ring it + // would paint over the fill of this ring and its neighbour, so such rings keep only fill. + let stroke = if outer - inner > 1.0 { Some((WHITE, 1.5)) } else { None }; + let ring = Ring { cx, cy, outer: *outer, inner: *inner, stroke }; + let vals: Vec = s.values.iter().take(MAX_CATS).map(|v| v.map(f64::abs).unwrap_or(0.0)).collect(); + let cap = (budget / (rings.len() - k)).max(1); + let slices = largest_slices(&vals, cap); + let total: f64 = slices.iter().map(|(_, v)| *v).sum(); + if !(total.is_finite() && total > 0.0) { + continue; + } + let n = slices.len(); + budget = budget.saturating_sub(n); + let f = Fmt::new(&s.number_format); + let mut a = start; + for (j, v) in slices { + let sweep = (v / total) as f32 * TAU; + if sweep > 1e-4 { + let fill = point_color(data, j); + wedge(ctx, &ring, a, sweep, fill); + if chart.data_labels && n <= MAX_LABELS { + let t = f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None); + let mid = a + sweep / 2.0; + let rr = (outer + inner) / 2.0; + if ctx.tw(&t, LABEL_SIZE) <= (sweep * rr).max(outer - inner) && sweep * rr >= LABEL_SIZE { + labels.push((cx + rr * mid.sin(), cy - rr * mid.cos(), t, on(fill))); + } + } + } + a += sweep; + } + } + for (x, y, t, c) in labels { + ctx.text(x, y, &t, LABEL_SIZE, c, (HAlign::Center, VAlign::Middle)); + } +} + // ---------------------------------------------------------------- treemap /// Worst aspect ratio of a row with the given sum, smallest and largest area. diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index 5ddb5a3cd..5b7f5d4d9 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -42,6 +42,8 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa return vec![]; } match chart.kind { + // Pie, doughnut (Excel's default `varyColors=1`, so every ring repeats the category colours + // and the legend names categories rather than series), treemap and sunburst. ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst => { let n = first_len(data).min(MAX_CATS); (0..n).map(|j| (cat_label(data, j), point_color(data, j), Swatch::Box)).collect() diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 6e423802c..11e2756ca 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -48,6 +48,8 @@ fn chart(kind: ChartKind) -> Chart { data_table: None, gridlines: true, style: 0, + hole_size: 75, + first_slice_angle: 0, x_title: Some("Quarter".into()), y_title: Some("Revenue".into()), source: None, @@ -149,6 +151,317 @@ fn every_kind_renders_sanely() { } } +#[test] +fn doughnut_draws_each_series_as_a_ring() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.hole_size = 25; + c.first_slice_angle = 0; + let d = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B", "C"].iter().map(|s| s.to_string()).collect(), + series: vec![ + series("Inner", &[1.0, 2.0, 3.0], [20, 96, 130, 255], ChartKind::Doughnut), + series("Middle", &[3.0, 2.0, 1.0], [221, 132, 82, 255], ChartKind::Doughnut), + series("Outer", &[1.0, 1.0, 1.0], [89, 161, 79, 255], ChartKind::Doughnut), + ], + }; + let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let wedges: Vec<(f32, f32, f32)> = prims + .iter() + .filter_map(|p| match p { + Prim::Wedge { r_outer, r_inner, a0, .. } => Some((*r_outer, *r_inner, *a0)), + _ => None, + }) + .collect(); + assert_eq!(wedges.len(), 9, "three rings of three slices"); + // Excel draws the first series as the innermost ring; the hole is 25% of the radius. + assert!(wedges[0].0 < wedges[3].0 && wedges[3].0 < wedges[6].0, "{wedges:?}"); + assert!(wedges[0].1 > 0.0, "hole: {wedges:?}"); +} + +#[test] +fn doughnut_with_many_series_still_draws_the_outer_rings() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.hole_size = 75; + // The annulus is a few dozen pixels tall and there are far more series than pixels, so every + // ring is thinner than 1 px. The chart used to draw nothing at all. + let many = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + series: (0..255).map(|i| series(&format!("S{i}"), &[1.0, 1.0], [20, 96, 130, 255], ChartKind::Doughnut)).collect(), + }; + let single = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + // Two series, so the title fallback (a lone series names the chart) does not shrink the plot. + series: vec![ + series("Only", &[1.0, 1.0], [20, 96, 130, 255], ChartKind::Doughnut), + series("Other", &[1.0, 1.0], [221, 132, 82, 255], ChartKind::Doughnut), + ], + }; + let (w, h) = (640.0, 400.0); + let radii = |d: &ChartData| -> Vec { + render(&c, d, w, h, &ApproxMeasure) + .iter() + .filter_map(|p| match p { + Prim::Wedge { r_outer, .. } => Some(*r_outer), + _ => None, + }) + .collect() + }; + let outer = radii(&many); + assert!(!outer.is_empty(), "a sub-pixel ring must not suppress the whole chart"); + let mut distinct = outer.clone(); + distinct.sort_by(f32::total_cmp); + distinct.dedup(); + assert!(distinct.len() > 8, "only {} rings drawn", distinct.len()); + assert!(distinct.len() < 255, "too many rings for the pixels available: {}", distinct.len()); + // The outermost ring still reaches the plot radius the single-ring chart uses. + let r = radii(&single).into_iter().fold(0.0f32, f32::max); + let drawn = distinct.last().copied().unwrap_or(0.0); + assert!((drawn - r).abs() < 0.01, "outermost ring {drawn} of {r}"); +} + +#[test] +fn doughnut_one_pixel_rings_skip_the_separator_stroke() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.hole_size = 75; + // 255 series over a 46-pixel annulus: every drawn ring is one pixel tall, narrower than the + // 1.5-pixel white separator, which would otherwise paint over both neighbouring rings. + let thin = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + series: (0..255).map(|i| series(&format!("S{i}"), &[1.0, 1.0], [20, 96, 130, 255], ChartKind::Doughnut)).collect(), + }; + let strokes: Vec> = render(&c, &thin, 640.0, 400.0, &ApproxMeasure) + .iter() + .filter_map(|p| match p { + Prim::Wedge { stroke, .. } => Some(*stroke), + _ => None, + }) + .collect(); + assert!(!strokes.is_empty(), "the chart must still draw its rings"); + assert!(strokes.iter().all(Option::is_none), "a 1.5px stroke covers a 1px band: {strokes:?}"); + + // A ring with room for the separator keeps it. + let thick = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + series: vec![ + series("Inner", &[1.0, 1.0], [20, 96, 130, 255], ChartKind::Doughnut), + series("Outer", &[1.0, 1.0], [221, 132, 82, 255], ChartKind::Doughnut), + ], + }; + let strokes: Vec> = render(&c, &thick, 640.0, 400.0, &ApproxMeasure) + .iter() + .filter_map(|p| match p { + Prim::Wedge { stroke, .. } => Some(*stroke), + _ => None, + }) + .collect(); + assert!(!strokes.is_empty()); + assert!(strokes.iter().all(Option::is_some), "wide rings keep their separators: {strokes:?}"); +} + +#[test] +fn doughnut_wedge_budget_bounds_many_series_and_categories() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.hole_size = 75; + c.first_slice_angle = 0; + // 20,000 categories across 80 series would be hundreds of thousands of wedges: the per-series + // limit does not bound the product. The first ten categories of every ring are the largest. + let cats = 20_000usize; + let values: Vec = (0..cats).map(|j| if j < 10 { 1000.0 } else { 1.0 }).collect(); + let d = ChartData { + category_levels: vec![], + palette: vec![], + categories: (0..cats).map(|j| format!("C{j}")).collect(), + series: (0..80) + .map(|i| SeriesData { name: format!("S{i}"), values: values.iter().map(|v| Some(*v)).collect(), ..SeriesData::default() }) + .collect(), + }; + let wedges: Vec<(f32, f32)> = render(&c, &d, 640.0, 400.0, &ApproxMeasure) + .iter() + .filter_map(|p| match p { + Prim::Wedge { r_outer, a0, a1, .. } => Some((*r_outer, *a1 - *a0)), + _ => None, + }) + .collect(); + assert!(!wedges.is_empty(), "the innermost ring must still be drawn"); + let mut radii: Vec = wedges.iter().map(|(r, _)| *r).collect(); + radii.sort_by(f32::total_cmp); + radii.dedup(); + assert!(radii.len() > 1, "every drawable ring is capped, not dropped"); + // A slice crossing 12 o'clock is split into two primitives, so each ring may add one. + let budget = crate::render::MAX_WEDGES + radii.len(); + assert!(wedges.len() <= budget, "{} wedges for {} rings", wedges.len(), radii.len()); + + // The first (innermost) ring keeps its largest slices and still fills the circle. + let inner: Vec = wedges.iter().filter(|(r, _)| *r == radii[0]).map(|(_, a)| *a).collect(); + assert!(inner.len() < cats, "the ring was not capped: {}", inner.len()); + assert_eq!(inner.iter().filter(|a| **a > 0.1).count(), 10, "largest slices went missing"); + let cover: f32 = inner.iter().sum(); + assert!((cover - std::f32::consts::TAU).abs() < 0.01, "first ring covers {cover}"); +} + +#[test] +fn doughnut_first_slice_angle_rotates_the_start() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.legend = LegendPos::None; + c.first_slice_angle = 90; + let d = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + series: vec![series("Only", &[1.0, 1.0], [20, 96, 130, 255], ChartKind::Doughnut)], + }; + let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let first = prims.iter().find_map(|p| match p { + Prim::Wedge { a0, .. } => Some(*a0), + _ => None, + }); + assert!(first.is_some_and(|a| (a - std::f32::consts::FRAC_PI_2).abs() < 0.01), "{first:?}"); +} + +/// Every slice must occupy exactly its angular share, even when the first slice angle pushes the +/// start past 12 o'clock (the split at TAU used to put whole slices over their neighbours). +#[test] +fn rotated_wedges_cover_each_slice_once_without_overlap() { + const TAU: f32 = std::f32::consts::TAU; + for kind in [ChartKind::Doughnut, ChartKind::Pie] { + for angle in [180u16, 270] { + let mut c = chart(kind); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.first_slice_angle = angle; + let d = ChartData { + category_levels: vec![], + palette: vec![[230, 126, 34, 255], [39, 174, 96, 255], [142, 68, 173, 255]], + categories: ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect(), + series: vec![series("Only", &[1.0; 4], [20, 96, 130, 255], kind)], + }; + let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let wedges: Vec<(f32, f32)> = prims + .iter() + .filter_map(|p| match p { + Prim::Wedge { a0, a1, .. } => Some((*a0, *a1)), + _ => None, + }) + .collect(); + assert!(wedges.len() >= 4, "{kind:?} at {angle}: {wedges:?}"); + for (a0, a1) in &wedges { + assert!((0.0..TAU).contains(a0), "{kind:?} at {angle}: start {a0} outside [0, TAU)"); + assert!(*a1 > *a0 && *a1 <= TAU + 1e-4, "{kind:?} at {angle}: bad sweep {a0}..{a1}"); + } + // Sample away from the boundaries: a correct four-slice chart covers every angle once. + let steps = 1440; + for k in 0..steps { + let theta = (k as f32 + 0.5) * TAU / steps as f32; + let cover = wedges.iter().filter(|(a0, a1)| theta >= *a0 && theta < *a1).count(); + assert_eq!(cover, 1, "{kind:?} at {angle}: {theta} covered {cover} times by {wedges:?}"); + } + } + } +} + +/// A slice that crosses 12 o'clock is filled as two halves but outlined once: stroking each half +/// separately ran the white separator along the shared radial edge, straight through the slice. +#[test] +fn slice_crossing_twelve_has_no_internal_seam() { + const TAU: f32 = std::f32::consts::TAU; + let mut c = chart(ChartKind::Pie); + c.title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.first_slice_angle = 90; + let a = [230, 126, 34, 255]; + let b = [39, 174, 96, 255]; + let d = ChartData { + category_levels: vec![], + palette: vec![a, b], + categories: ["A", "B"].iter().map(|s| s.to_string()).collect(), + series: vec![series("Only", &[1.0, 1.0], a, ChartKind::Pie)], + }; + let (w, h) = (400u32, 400u32); + let prims = render(&c, &d, w as f32, h as f32, &ApproxMeasure); + // The second slice starts at 270° and wraps past 0°, so it is drawn as two unstroked halves. + let mut halves = 0; + let mut cx = 0.0; + let mut cy = 0.0; + let mut r = 0.0; + for p in &prims { + if let Prim::Wedge { cx: x, cy: y, r_outer, a0, a1, fill, stroke, .. } = p + && *fill == b + { + assert!(stroke.is_none(), "a split half must not stroke its shared edge: {p:?}"); + assert!(*a0 == 0.0 || *a1 == TAU, "the crossing slice is split at 12 o'clock: {p:?}"); + halves += 1; + (cx, cy, r) = (*x, *y, *r_outer); + } + } + assert_eq!(halves, 2, "one slice crosses 12 o'clock"); + // Exactly one outline covers the whole crossing slice, drawn as line primitives. + assert_eq!(prims.iter().filter(|p| matches!(p, Prim::Line { color, .. } if *color == [255, 255, 255, 255])).count(), 1, "{prims:?}"); + // No white pixel inside the slice along 12 o'clock, where the shared edge used to be stroked. + let img = rasterize(&prims, w, h, [255, 255, 255, 255]); + for t in [0.3f32, 0.5, 0.7] { + assert_eq!(pixel(&img, w, cx as u32, (cy - r * t) as u32), b, "white seam at {t} of the slice"); + } +} + +#[test] +fn doughnut_legend_names_categories_and_matches_every_ring() { + let mut c = chart(ChartKind::Doughnut); + c.title = None; + c.data_labels = false; + c.legend = LegendPos::Right; + c.first_slice_angle = 180; + let d = ChartData { + category_levels: vec![], + palette: vec![[230, 126, 34, 255], [39, 174, 96, 255], [142, 68, 173, 255]], + categories: ["A", "B", "C", "D"].iter().map(|s| s.to_string()).collect(), + series: vec![ + series("Outer", &[1.0; 4], [20, 96, 130, 255], ChartKind::Doughnut), + series("Inner", &[1.0; 4], [221, 132, 82, 255], ChartKind::Doughnut), + ], + }; + let entries = legend_entries(&c, &d); + assert_eq!(entries.iter().map(|(name, _, _)| name.as_str()).collect::>(), ["A", "B", "C", "D"]); + + let start = f32::from(c.first_slice_angle) * std::f32::consts::TAU / 360.0; + let prims = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let mut rings = Vec::new(); + for p in &prims { + let Prim::Wedge { r_outer, a0, a1, fill, .. } = p else { continue }; + rings.push(*r_outer); + let rel = ((a0 + a1) / 2.0 - start).rem_euclid(std::f32::consts::TAU); + let cat = ((rel / (std::f32::consts::TAU / 4.0)) as usize).min(3); + assert_eq!(*fill, entries[cat].1, "ring wedge at {a0}..{a1} does not match legend entry {}", entries[cat].0); + } + rings.sort_by(f32::total_cmp); + rings.dedup(); + assert_eq!(rings.len(), 2, "two series must draw two rings"); +} + #[test] fn legend_counts() { let d = sample(ChartKind::ColumnClustered); @@ -461,7 +774,11 @@ fn pie_starts_at_twelve_clockwise() { assert!(wedges.windows(2).all(|w| w[1].0 >= w[0].1 - 1e-4)); assert!((wedges[5].1 - std::f32::consts::TAU).abs() < 1e-3); assert!(wedges.iter().all(|w| w.2 == 0.0 && w.3.map(|s| s.0) == Some([255; 4]))); - let prims = render(&chart(ChartKind::Doughnut), &d, 400.0, 400.0, &ApproxMeasure); + let mut c = chart(ChartKind::Doughnut); + c.hole_size = 50; + let mut d = sample(ChartKind::Doughnut); + d.series.truncate(1); + let prims = render(&c, &d, 400.0, 400.0, &ApproxMeasure); let ok = prims.iter().any(|p| matches!(p, Prim::Wedge { r_outer, r_inner, .. } if (r_inner / r_outer - 0.5).abs() < 1e-3)); assert!(ok); } diff --git a/crates/engine/src/cmd/forecast.rs b/crates/engine/src/cmd/forecast.rs index 3c62e469f..d0941a9ca 100644 --- a/crates/engine/src/cmd/forecast.rs +++ b/crates/engine/src/cmd/forecast.rs @@ -427,6 +427,8 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result { data_table: None, gridlines: true, style: 1, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 68fb46505..d832ecddf 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Chart Properties", ["Chart Design"], None, - "{chart?: id, type?, subtype?, title?, legend?: none|bottom|top|left|right, dataLabels?, gridlines?, dataTable?: bool, dataTableKeys?: bool, dataTableHorizontalBorder?: bool, dataTableVerticalBorder?: bool, dataTableOutline?: bool (data tables: column/bar/line/area and compatible combo charts), quartiles?: exclusive|inclusive, style?, xTitle?, yTitle?, at?, width?, height?, dx?, dy?}", + "{chart?: id, type?, subtype?, title?, legend?: none|bottom|top|left|right, dataLabels?, gridlines?, dataTable?: bool, dataTableKeys?: bool, dataTableHorizontalBorder?: bool, dataTableVerticalBorder?: bool, dataTableOutline?: bool (data tables: column/bar/line/area and compatible combo charts), quartiles?: exclusive|inclusive, style?, holeSize?, firstSliceAngle?, xTitle?, yTitle?, at?, width?, height?, dx?, dy?}", has_doc, chart_set ), @@ -850,6 +850,8 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> { data_table: None, gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel), style: 1, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: (areas.len() == 1).then(|| format!("{}!{}", gridcraft_formula::quote_sheet(&sh.name), bounds.a1())), @@ -926,6 +928,12 @@ fn chart_set(s: &mut Session, p: &Json) -> Result { if let Some(v) = u32_param(p, "style") { c.style = v.clamp(1, 16); } + if let Some(v) = u32_param(p, "holeSize") { + c.hole_size = v.clamp(10, 90) as u8; + } + if let Some(v) = u32_param(p, "firstSliceAngle") { + c.first_slice_angle = (v % 360) as u16; + } if let Some(t) = p.get("xTitle") { c.x_title = t.as_str().map(str::to_string); } diff --git a/crates/engine/src/cmd/pivot/charts.rs b/crates/engine/src/cmd/pivot/charts.rs index d7a3b73b1..5551c4d56 100644 --- a/crates/engine/src/cmd/pivot/charts.rs +++ b/crates/engine/src/cmd/pivot/charts.rs @@ -67,6 +67,8 @@ pub(super) fn insert_pivot_chart(s: &mut Session, p: &Json) -> Result { data_labels: false, data_table: None, gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel), + hole_size: 75, + first_slice_angle: 0, style: 1, x_title: None, y_title: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 90f6691bd..ab443bbe6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3237,6 +3237,21 @@ fn every_chart_kind_survives_xlsx() { } } +#[test] +fn chart_set_doughnut_hole_and_angle() { + let mut s = s(); + chart_data(&mut s); + s.execute("insert.chart", json!({"type": "doughnut", "range": "A1:B7"})).unwrap(); + s.execute("chart.set", json!({"holeSize": 5, "firstSliceAngle": 400})).unwrap(); + s.execute("chart.set", json!({"holeSize": 200})).unwrap(); + let c = s.doc().unwrap().wb.active().unwrap().charts[0].clone(); + assert_eq!((c.hole_size, c.first_slice_angle), (90, 40)); + s.execute("chart.set", json!({"holeSize": 25, "firstSliceAngle": 180})).unwrap(); + reopen(&mut s); + let c = &s.doc().unwrap().wb.active().unwrap().charts[0]; + assert_eq!((c.kind, c.hole_size, c.first_slice_angle), (gridcraft_model::ChartKind::Doughnut, 25, 180)); +} + #[test] fn scatter_of_two_columns_is_one_series_with_the_first_as_x() { let mut s = s(); diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index a36fcef1e..06e68839f 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -540,6 +540,12 @@ impl Trendline { } } +/// Charts saved before `hole_size` existed were drawn with a 50% hole. New charts and charts read +/// from XLSX set 75 explicitly (Excel's default), so only a missing JSON field keeps the old look. +fn default_hole_size() -> u8 { + 50 +} + /// A chart's data table (`c:dTable`), independent of the chart legend. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] @@ -569,6 +575,13 @@ pub struct Chart { pub data_table: Option, pub gridlines: bool, pub style: u32, + /// Doughnut hole size as a percentage of the plot radius (Excel's 10–90 range). New charts and + /// XLSX imports use Excel's 75; a document saved before this field existed reads as 50. + #[serde(default = "default_hole_size")] + pub hole_size: u8, + /// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359). + #[serde(default)] + pub first_slice_angle: u16, pub x_title: Option, pub y_title: Option, /// Source range when created from a selection (for Switch Row/Column). @@ -1088,6 +1101,39 @@ mod trendline_forecast_tests { } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chart_without_hole_size_keeps_the_legacy_hole() { + let chart = Chart { + id: 1, + kind: ChartKind::Doughnut, + anchor: Anchor::default(), + title: None, + series: vec![], + legend: LegendPos::Right, + data_labels: false, + data_table: None, + gridlines: false, + style: 1, + hole_size: 75, + first_slice_angle: 0, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + }; + let mut json = serde_json::to_value(&chart).expect("serialize chart"); + json.as_object_mut().expect("chart object").remove("hole_size"); + let legacy: Chart = serde_json::from_value(json).expect("deserialize legacy chart"); + assert_eq!(legacy.hole_size, 50, "documents saved before hole_size existed keep the old 50% hole"); + assert_eq!(chart.hole_size, 75, "new charts keep Excel's 75% default"); + } +} + #[cfg(test)] mod equation_cache_tests { use super::{EquationCache, source_key}; diff --git a/crates/model/src/sheet.rs b/crates/model/src/sheet.rs index 961c0d583..67ca1f13e 100644 --- a/crates/model/src/sheet.rs +++ b/crates/model/src/sheet.rs @@ -831,6 +831,8 @@ mod tests { data_table: None, gridlines: false, style: 0, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b0c648946..58d308413 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -390,6 +390,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: dole", "Legend: Top" => "Legenda: nahoře", "Legend: Right" => "Legenda: vpravo", + "First slice angle" => "Úhel prvního výseku", + "Doughnut hole size" => "Velikost otvoru prstence", "Gridlines: None" => "Mřížka: žádná", "Gridlines: Show" => "Mřížka: zobrazit", "Chart\nTitle" => "Název\ngrafu", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 9bc5cb6ff..2e6ba713f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -407,6 +407,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legende: Unten", "Legend: Top" => "Legende: Oben", "Legend: Right" => "Legende: Rechts", + "First slice angle" => "Winkel des ersten Segments", + "Doughnut hole size" => "Größe des Ringlochs", "Gridlines: None" => "Gitternetzlinien: Keine", "Gridlines: Show" => "Gitternetzlinien: Anzeigen", "Chart\nTitle" => "Diagramm-\ntitel", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index d21c631a0..218fa5a6f 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -353,6 +353,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Υπόμνημα: κάτω", "Legend: Top" => "Υπόμνημα: επάνω", "Legend: Right" => "Υπόμνημα: δεξιά", + "First slice angle" => "Γωνία πρώτης φέτας", + "Doughnut hole size" => "Μέγεθος οπής ντόνατ", "Gridlines: None" => "Γραμμές πλέγματος: καμία", "Gridlines: Show" => "Γραμμές πλέγματος: εμφάνιση", "Chart\nTitle" => "Τίτλος\nγραφήματος", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 98b2410dd..b6adcf774 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -394,6 +394,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Leyenda: abajo", "Legend: Top" => "Leyenda: arriba", "Legend: Right" => "Leyenda: derecha", + "First slice angle" => "Ángulo del primer sector", + "Doughnut hole size" => "Tamaño del orificio del anillo", "Gridlines: None" => "Líneas de cuadrícula: ninguna", "Gridlines: Show" => "Líneas de cuadrícula: mostrar", "Chart\nTitle" => "Título\ndel gráfico", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 1a9aa3bbe..e11ef4599 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Légende : Bas", "Legend: Top" => "Légende : Haut", "Legend: Right" => "Légende : Droite", + "First slice angle" => "Angle du premier secteur", + "Doughnut hole size" => "Taille du trou de l'anneau", "Gridlines: None" => "Quadrillage : Aucun", "Gridlines: Show" => "Quadrillage : Afficher", "Chart\nTitle" => "Titre du\ngraphique", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 2a79d4c7d..9a371e673 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -257,6 +257,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: in basso", "Legend: Top" => "Legenda: in alto", "Legend: Right" => "Legenda: a destra", + "First slice angle" => "Angolo della prima fetta", + "Doughnut hole size" => "Dimensione del foro della ciambella", "Gridlines: None" => "Griglia: nessuna", "Gridlines: Show" => "Griglia: mostra", "Chart\nTitle" => "Titolo\ndel grafico", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 443c2be41..47fd0e9f3 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -266,6 +266,8 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Legend: Bottom", "凡例: 下"), ("Legend: Top", "凡例: 上"), ("Legend: Right", "凡例: 右"), + ("First slice angle", "最初の扇形の角度"), + ("Doughnut hole size", "ドーナツの穴のサイズ"), ("Gridlines: None", "目盛線: なし"), ("Gridlines: Show", "目盛線: 表示"), ("Chart\nTitle", "グラフ タイトル"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index c0052af9a..906dea54f 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -258,6 +258,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "범례: 아래쪽", "Legend: Top" => "범례: 위쪽", "Legend: Right" => "범례: 오른쪽", + "First slice angle" => "첫째 조각의 각도", + "Doughnut hole size" => "도넛 구멍 크기", "Gridlines: None" => "눈금선: 없음", "Gridlines: Show" => "눈금선: 표시", "Chart\nTitle" => "차트\n제목", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index abb1d08b4..b1d415211 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -264,6 +264,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: onder", "Legend: Top" => "Legenda: boven", "Legend: Right" => "Legenda: rechts", + "First slice angle" => "Hoek eerste punt", + "Doughnut hole size" => "Grootte van het donutgat", "Gridlines: None" => "Rasterlijnen: geen", "Gridlines: Show" => "Rasterlijnen: weergeven", "Chart\nTitle" => "Grafiek-\ntitel", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index a2894dcd2..ad9c254c1 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -251,6 +251,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: u dołu", "Legend: Top" => "Legenda: u góry", "Legend: Right" => "Legenda: z prawej", + "First slice angle" => "Kąt pierwszego wycinka", + "Doughnut hole size" => "Rozmiar otworu pączka", "Gridlines: None" => "Linie siatki: brak", "Gridlines: Show" => "Linie siatki: pokaż", "Chart\nTitle" => "Tytuł\nwykresu", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 470909afe..f78ef4cf5 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -258,6 +258,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: Abaixo", "Legend: Top" => "Legenda: Acima", "Legend: Right" => "Legenda: À Direita", + "First slice angle" => "Ângulo da primeira fatia", + "Doughnut hole size" => "Tamanho do orifício da rosca", "Gridlines: None" => "Linhas de Grade: Nenhuma", "Gridlines: Show" => "Linhas de Grade: Exibir", "Chart\nTitle" => "Título\ndo Gráfico", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 6b0c4f737..738fc554f 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -258,6 +258,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legendă: jos", "Legend: Top" => "Legendă: sus", "Legend: Right" => "Legendă: dreapta", + "First slice angle" => "Unghiul primei felii", + "Doughnut hole size" => "Dimensiunea găurii gogoașei", "Gridlines: None" => "Linii de grilă: niciuna", "Gridlines: Show" => "Linii de grilă: afișare", "Chart\nTitle" => "Titlu\ndiagramă", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 2a37c8939..60141a853 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -260,6 +260,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Легенда: снизу", "Legend: Top" => "Легенда: сверху", "Legend: Right" => "Легенда: справа", + "First slice angle" => "Угол первого сектора", + "Doughnut hole size" => "Размер отверстия кольцевой диаграммы", "Gridlines: None" => "Линии сетки: нет", "Gridlines: Show" => "Линии сетки: показать", "Chart\nTitle" => "Название\nдиаграммы", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 39555f6df..d02c66bb8 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -263,6 +263,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Legenda: Dole", "Legend: Top" => "Legenda: Gore", "Legend: Right" => "Legenda: Desno", + "First slice angle" => "Ugao prve kriške", + "Doughnut hole size" => "Veličina rupe prstena", "Gridlines: None" => "Linije mreže: Ništa", "Gridlines: Show" => "Linije mreže: Prikaži", "Chart\nTitle" => "Naslov\ngrafikona", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index d268c2e96..a58505848 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -367,6 +367,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Gösterge: Alt", "Legend: Top" => "Gösterge: Üst", "Legend: Right" => "Gösterge: Sağ", + "First slice angle" => "İlk dilim açısı", + "Doughnut hole size" => "Donut deliği boyutu", "Gridlines: None" => "Kılavuz Çizgileri: Yok", "Gridlines: Show" => "Kılavuz Çizgileri: Göster", "Chart\nTitle" => "Grafik\nBaşlığı", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 82c2e9e5d..96070eaaf 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -253,6 +253,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Легенда: знизу", "Legend: Top" => "Легенда: згори", "Legend: Right" => "Легенда: праворуч", + "First slice angle" => "Кут першого сегмента", + "Doughnut hole size" => "Розмір отвору пончика", "Gridlines: None" => "Лінії сітки: немає", "Gridlines: Show" => "Лінії сітки: показати", "Chart\nTitle" => "Назва\nдіаграми", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 754d4c33a..7a188a08e 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -265,6 +265,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "Chú giải: Dưới", "Legend: Top" => "Chú giải: Trên", "Legend: Right" => "Chú giải: Phải", + "First slice angle" => "Góc lát đầu tiên", + "Doughnut hole size" => "Kích thước lỗ bánh donut", "Gridlines: None" => "Đường lưới: Không", "Gridlines: Show" => "Đường lưới: Hiện", "Chart\nTitle" => "Tiêu đề\nbiểu đồ", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 7707a0cc0..601e0a1bb 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -258,6 +258,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Legend: Bottom" => "图例:底部", "Legend: Top" => "图例:顶部", "Legend: Right" => "图例:右侧", + "First slice angle" => "第一扇区起始角度", + "Doughnut hole size" => "圆环图内径大小", "Gridlines: None" => "网格线:无", "Gridlines: Show" => "网格线:显示", "Chart\nTitle" => "图表\n标题", diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 9675d2a95..d9207cd07 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -178,6 +178,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { return; }; let theme = app.session.active().map(|d| d.wb.theme.clone()).unwrap_or_default(); + let lang = crate::i18n::current(ui.ctx()); ui.collapsing("Chart Title", |ui| { let field = egui::Id::unique(("gridcraft.chart_title", id)); if let Some(title) = crate::widgets::committed_text(ui, field, chart.title.as_deref().unwrap_or(""), None) { @@ -209,6 +210,20 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { } } }); + if matches!(chart.kind, gridcraft_chart::ChartKind::Pie | gridcraft_chart::ChartKind::Doughnut) { + let draft = egui::Id::unique(("gridcraft.chart_first_slice_draft", id)); + let current = u32::from(chart.first_slice_angle); + if let Some(angle) = chart_slider(ui, draft, current, 0..=359, lang.tr("First slice angle")) { + app.run_or_alert("chart.set", json!({"chart": id, "firstSliceAngle": angle})); + } + } + if chart.kind == gridcraft_chart::ChartKind::Doughnut { + let draft = egui::Id::unique(("gridcraft.chart_hole_size_draft", id)); + let current = u32::from(chart.hole_size); + if let Some(hole) = chart_slider(ui, draft, current, 10..=90, lang.tr("Doughnut hole size")) { + app.run_or_alert("chart.set", json!({"chart": id, "holeSize": hole})); + } + } }); ui.collapsing("Legend", |ui| { ui.horizontal(|ui| { @@ -339,3 +354,21 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { } }); } + +/// A chart slider that keeps the value being dragged in a per-chart draft and submits it once +/// through `chart.set` when the interaction ends, like the Size controls. Escape cancels, and a +/// value the chart already has is not sent again. +fn chart_slider(ui: &mut Ui, draft: egui::Id, value: u32, range: std::ops::RangeInclusive, label: &str) -> Option { + let mut current = ui.data_mut(|d| d.get_temp::(draft)).unwrap_or(value); + let r = ui.add(egui::Slider::new(&mut current, range).text(label)); + if r.drag_stopped() || r.clicked() || r.lost_focus() { + ui.data_mut(|d| d.remove::(draft)); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) || current == value { None } else { Some(current) } + } else if r.dragged() || r.has_focus() { + ui.data_mut(|d| d.insert_temp(draft, current)); + None + } else { + ui.data_mut(|d| d.remove::(draft)); + None + } +} diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index a408da5fa..fea91cec5 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -260,6 +260,10 @@ pub fn read_chart(root: &El) -> Option { _ => LegendPos::Right, }, }; + let doughnut = plot.child("doughnutChart"); + let hole_size = doughnut.and_then(|g| g.child_val("holeSize")).and_then(|v| v.trim().parse::().ok()).unwrap_or(75).clamp(10, 90); + let first_slice_angle = + plot.child("pieChart").or(doughnut).and_then(|g| g.child_val("firstSliceAng")).and_then(|v| v.trim().parse::().ok()).unwrap_or(0) % 360; Some(Chart { id: 0, kind, @@ -276,6 +280,8 @@ pub fn read_chart(root: &El) -> Option { }), gridlines: val_axes.iter().any(|a| a.child("majorGridlines").is_some()), style: root.child_val("style").and_then(|v| v.parse().ok()).unwrap_or(2), + hole_size, + first_slice_angle, x_title: x_ax.and_then(|a| a.child("title")).and_then(rich_title), y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title), source: None, @@ -678,10 +684,12 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb "{sers}{dl}{ax}", if stacked { "stacked" } else { "standard" } ), - G::Pie => format!("{sers}{dl}"), - G::Doughnut => { - format!("{sers}{dl}") - } + G::Pie => format!("{sers}{dl}", ch.first_slice_angle % 360), + G::Doughnut => format!( + "{sers}{dl}", + ch.first_slice_angle % 360, + ch.hole_size.clamp(10, 90) + ), G::Area { grouping } => format!("{sers}{dl}{ax}"), G::Scatter { .. } => format!("{sers}{dl}{ax}"), G::Bubble => { diff --git a/crates/xlsx/src/chartex.rs b/crates/xlsx/src/chartex.rs index ce71d4f32..de54c5942 100644 --- a/crates/xlsx/src/chartex.rs +++ b/crates/xlsx/src/chartex.rs @@ -133,6 +133,8 @@ pub fn read_chartex(root: &El) -> Option { data_table: None, gridlines: plot.kids("axis").any(|a| a.child("majorGridlines").is_some()), style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: axis_title("0"), y_title: axis_title("1"), source: None, diff --git a/crates/xlsx/src/tests/chart_book_names.rs b/crates/xlsx/src/tests/chart_book_names.rs index 10edf45a4..94d148da8 100644 --- a/crates/xlsx/src/tests/chart_book_names.rs +++ b/crates/xlsx/src/tests/chart_book_names.rs @@ -78,6 +78,8 @@ fn chart_names_are_written_qualified() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, @@ -157,6 +159,8 @@ fn chart_names_keep_spaces_around_a_quoted_sheet_name() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 4de0be3c3..dadfc096a 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -551,6 +551,8 @@ fn chartex_parts_as_excel_expects_them() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, @@ -586,6 +588,50 @@ fn chartex_parts_as_excel_expects_them() { assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.values.as_str()), (Some("Data!$B$1"), Some("Data!$A$2:$A$5"), "Data!$B$2:$B$5")); } +#[test] +fn doughnut_writes_every_series_as_a_ring_with_hole_and_angle() { + use gridcraft_model::{Chart, ChartKind, LegendPos, Series}; + let ser = |name: &str, values: &str| Series { + name: Some(name.into()), + categories: Some("Data!$A$2:$A$4".into()), + values: values.into(), + ..Default::default() + }; + let mut wb = gridcraft_model::Workbook::new(); + let mut sheet = gridcraft_model::Sheet::new("Data"); + sheet.charts.push(Chart { + id: 1, + kind: ChartKind::Doughnut, + anchor: Default::default(), + title: None, + series: vec![ser("Outer", "Data!$B$2:$B$4"), ser("Inner", "Data!$C$2:$C$4")], + legend: LegendPos::Right, + data_labels: false, + data_table: None, + gridlines: false, + style: 2, + hole_size: 25, + first_slice_angle: 180, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + }); + wb.sheets = vec![std::sync::Arc::new(sheet)]; + let bytes = crate::write_xlsx(&wb).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap(); + let mut cx = String::new(); + std::io::Read::read_to_string(&mut z.by_name("xl/charts/chart1.xml").unwrap(), &mut cx).unwrap(); + assert!(cx.contains(""), "{cx}"); + assert_eq!(cx.matches("").count(), 2, "one series per ring: {cx}"); + assert!(cx.contains(""), "{cx}"); + assert!(cx.contains(""), "{cx}"); + let (back, _) = crate::read_xlsx(&bytes).unwrap(); + let ch = &back.sheet(0).unwrap().charts[0]; + assert_eq!((ch.kind, ch.series.len(), ch.hole_size, ch.first_slice_angle), (ChartKind::Doughnut, 2, 25, 180)); +} + /// #377: a WordArt-style text box keeps its run size, bold, typeface, text fill and outline, its /// centring (horizontal and vertical) and its "no outline" shape line, through a round trip. #[test] diff --git a/crates/xlsx/src/tests/literal_category_roundtrip.rs b/crates/xlsx/src/tests/literal_category_roundtrip.rs index 3a6f9f712..a514fa6ce 100644 --- a/crates/xlsx/src/tests/literal_category_roundtrip.rs +++ b/crates/xlsx/src/tests/literal_category_roundtrip.rs @@ -44,6 +44,8 @@ fn literal_category_with_separators_survives_save() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/xlsx/src/tests/multilevel_category_roundtrip.rs b/crates/xlsx/src/tests/multilevel_category_roundtrip.rs index 7a375a438..f4c118f2b 100644 --- a/crates/xlsx/src/tests/multilevel_category_roundtrip.rs +++ b/crates/xlsx/src/tests/multilevel_category_roundtrip.rs @@ -44,6 +44,8 @@ fn workbook(categories: &str, values: &str) -> Workbook { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 4eb6c3cfe..e2072fe44 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -414,6 +414,8 @@ fn sample() -> Workbook { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: Some("Region".into()), y_title: Some("Amount".into()), source: None, @@ -453,6 +455,9 @@ fn sample() -> Workbook { }); s.charts.push(combo); s.charts.push(Chart { kind: ChartKind::Waterfall, legend: LegendPos::None, title: None, ..base_chart.clone() }); + let mut doughnut = Chart { kind: ChartKind::Doughnut, hole_size: 25, first_slice_angle: 180, legend: LegendPos::Right, ..base_chart.clone() }; + doughnut.series.push(base_chart.series[0].clone()); + s.charts.push(doughnut); wb.sheets = vec![Arc::new(s)]; let mut s2 = Sheet::new("Hidden"); @@ -594,6 +599,7 @@ fn assert_drawing_and_chart_roundtrip(a: &Sheet, b: &Sheet) { assert_eq!(y.title, x.title); assert_eq!(y.legend, x.legend); assert_eq!(y.data_labels, x.data_labels); + assert_eq!((y.hole_size, y.first_slice_angle), (x.hole_size, x.first_slice_angle)); if !matches!(x.kind, ChartKind::Pie | ChartKind::Doughnut) { assert_eq!(y.gridlines, x.gridlines); assert_eq!((&y.x_title, &y.y_title), (&x.x_title, &x.y_title)); diff --git a/crates/xlsx/src/tests/smooth_roundtrip.rs b/crates/xlsx/src/tests/smooth_roundtrip.rs index 1a418bb51..96c346d31 100644 --- a/crates/xlsx/src/tests/smooth_roundtrip.rs +++ b/crates/xlsx/src/tests/smooth_roundtrip.rs @@ -32,6 +32,8 @@ fn smooth_line_setting_round_trips() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, @@ -51,6 +53,8 @@ fn smooth_line_setting_round_trips() { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/crates/xlsx/src/tests/trendline_roundtrip.rs b/crates/xlsx/src/tests/trendline_roundtrip.rs index 2a1e19d05..f5bf7feae 100644 --- a/crates/xlsx/src/tests/trendline_roundtrip.rs +++ b/crates/xlsx/src/tests/trendline_roundtrip.rs @@ -56,6 +56,8 @@ fn chart(id: u32, kind: ChartKind, trendlines: Vec) -> Chart { data_table: None, gridlines: true, style: 2, + hole_size: 75, + first_slice_angle: 0, x_title: None, y_title: None, source: None, diff --git a/docs/chart-parity.md b/docs/chart-parity.md index be5a7fa52..311bd2635 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,13 +1,15 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-02 · **Change:** minor (charts resize from eight handles; earlier: chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-02 · **Change:** minor (doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crates/chart/src` (layout and rendering), `crates/xlsx/src/chart.rs` (DrawingML chart parts), merged PRs #62, #116, -#158 and #161, and issue #190. +#158 and #161, and issue #190. Behaviour checked against Microsoft's +[Pareto](https://support.microsoft.com/en-us/excel/create-a-pareto-chart) and +[pie/doughnut](https://support.microsoft.com/en-us/excel/add-a-pie-chart) support pages. ## Chart types @@ -16,7 +18,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Column | clustered, stacked, 100% stacked, 3-D clustered/stacked/100%, 3-D column | 3 of 7 | no 3-D | | Bar | clustered, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D | | Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 3 of 7 (line, with markers, stacked) | no 100% stacked; smoothed lines landed (#62) | -| Pie | pie, 3-D pie, pie of pie, bar of pie, doughnut | 2 of 5 (pie, doughnut) | no exploded, pie of pie, bar of pie | +| Pie | pie, 3-D pie, pie of pie, bar of pie, doughnut | 2 of 5 (pie, doughnut) | no exploded, pie of pie, bar of pie; doughnut draws every series as a concentric ring, first series innermost; its legend names categories, matching Excel's default vary-by-category colours | | Area | area, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX | | X Y (scatter) | markers, smooth lines (±markers), straight lines (±markers) | 2 of 5 | no smooth lines | | Bubble | bubble, 3-D bubble | 1 of 2 | | @@ -45,6 +47,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Gridlines | major/minor per axis, formatting | one on/off flag | | Axis options | min/max/units, log scale, reverse order, crossing point, display units, date axis, number format | **missing** (auto only) | | Multi-level category axis (a category range two or more columns wide beside the values: year beside month) | the outer levels grouped under the labels with separators | read (`multiLvlStrRef`), drawn (rows under the labels; columns beside them in bar charts; up to three outer levels), written back with Excel's level caches | +| Doughnut hole size, first slice angle | 10–90% hole (Excel default 75%), 0–359° first slice | Format Chart pane sliders; read from and written to `c:holeSize` / `c:firstSliceAng`; documents saved before the setting existed keep their old 50% hole | | Secondary axis | any series | line series in combo charts | | Trendlines | linear, exponential, logarithmic, polynomial, power, moving average, equation and R² | all six types, several per series, name, forward/backward forecast, set intercept, equation and R² label, line colour/width/dash; read, written and drawn on 2-D column, bar, line, area, scatter and bubble series; `chart.addElement` `trendline` adds/removes them. No Format Trendline pane, label position/number format not kept | | Error bars | fixed, %, standard deviation/error, custom | **missing** | @@ -109,6 +112,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | 2026-10-29 | minor | Selected charts highlight their source cells beneath floating objects, so the blue outline no longer crosses the chart; uncovered source cells remain highlighted (#2861) | | 2026-10-24 | minor | 100% Stacked Area: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` | | 2026-10-18 | trivial | Stale notes: stock/combo, treemap/sunburst, box and waterfall kinds survive XLSX round-trip (PRs #158, #161) | +| 2026-10-18 | minor | Doughnut charts: every series is a ring (first series innermost), hole size and first slice angle modelled, editable and round-tripped; rotated slices split at 12 o'clock without overlap; legend names categories like Excel's default (#1823) | | 2026-10-16 | trivial | Series that refer to defined names (`[0]!Name`, `Sheet!Name`) resolve instead of showing `#NAME?`, and are saved qualified, as Excel needs (#1686) | | 2026-10-16 | minor | Box & whisker quartiles default to exclusive, honor each series on draw and XLSX round-trip; `chart.set {quartiles}` changes the method (#1453) | | 2026-10-13 | minor | Multi-level category axes: read, drawn (outer levels under or beside the labels), written back with level caches | diff --git a/docs/roadmap.md b/docs/roadmap.md index 62e1735f7..458af936a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -28,7 +28,7 @@ workflow, would make GridCraft pre-alpha. | Open a colleague's XLSX, edit, save, hand it back | partial, not blocking | Typical workbooks open and save with cells, styles, CF, validation, tables, names and pivots; unmodelled parts are dropped with a warning (gap #3); Excel-side repair prompts unverified (gap #1); ~100 MB files fail (#175) | 0 for alpha (gaps #1–#3 are beta gates) | | Format and present: number formats, styles, conditional formatting, print or PDF | yes | Full number-format language, 47 cell styles, all CF kinds, Page Break Preview, PDF export and printing. PDF can't carry non-Latin text (gap #5) | 0 | | Analyze: sort, filter, tables, PivotTable | yes | Multi-level sort, AutoFilter, tables with totals, PivotTables with field list, layouts, grouping, refresh and XLSX round-trip. Calculated fields done; slicers missing (gap #8) | 0 | -| Chart the data | partial, not blocking | Column, bar, line, pie, area, scatter, combo, histogram, box, waterfall, funnel, treemap, sunburst and stock charts are created, edited and survive save and reopen; trendlines are drawn; no axis options (gap #4) | 0 for alpha | +| Chart the data | partial, not blocking | Column, bar, line, pie, area, scatter, combo, histogram, box, waterfall, funnel, treemap, sunburst and stock charts are created, edited and survive save and reopen; doughnut charts draw every series as a ring (first series innermost) with editable hole size and first slice angle; trendlines are drawn; no axis options (gap #4) | 0 for alpha | | Import and export CSV | yes | Encoding and delimiter detection on read, CSV/TSV write; exports raw rather than displayed values (gap #19) | 0 | **Passes:** every core workflow works end to end on macOS with save and reopen; the two partial diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c18df8d40..9ac4ea015 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -86,10 +86,8 @@ performance 8, stability 8, localization 4, hardware 2, platforms 2, ecosystem 2 | Cell formatting, styles, conditional formatting | 10 | ~95% | ~80% | 8–14 | Full number-format language, borders, 47 cell styles, 60 table styles, all CF rule kinds including data bars, colour scales and icon sets. Gaps: font weights beyond regular/bold (#168), system fonts list (#4), themes | | Sort, filter, tables, validation, outline | 8 | ~82% | ~70% | 10–16 | Multi-level sort, AutoFilter, Advanced Filter, tables with totals, validation, outline, subtotals, consolidate. Advanced Filter copy-to preserves cells outside its result and rejects worksheet overflow (#1031). Bugs: subtotal header (#131), validation edits (#129), table style panic caught (#130); no slicers on tables | | PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, XLSX round-trip. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, GETPIVOTDATA, data-model pivots. Round-trip never checked in Excel | -| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, trendlines, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Several kinds don't survive XLSX round trip (open PRs #158, #161). [chart-parity.md](chart-parity.md) | +| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. Doughnut charts draw every series as a concentric ring (first series innermost), with editable hole size and first slice angle. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Kinds survive XLSX round trip (#158, #161), except stock charts: only 3–4 series are a stock chart, and any other count is written and reimported as a line chart. [chart-parity.md](chart-parity.md) | | Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, page order, Page Break Preview, headers/footers, PDF export and printing. Paper sizes match Japanese Excel: B4/B5/B6 are the JIS sizes, ISO B4/B5/B6 stay reachable by name, and Japanese Postcard (はがき), Japanese Double Postcard (往復はがき), the chou/kaku envelopes and A6 are available. No true Page Layout view; the PDF writer uses only the 14 standard fonts without embedding (no CJK or other non-Latin text in PDF); web print only exports (#141, #143) | -| Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Kinds survive XLSX round trip (#158, #161). [chart-parity.md](chart-parity.md) | -| Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, page order, Page Break Preview, headers/footers, PDF export and printing. No true Page Layout view; the PDF writer uses only the 14 standard fonts without embedding (no CJK or other non-Latin text in PDF); web print only exports (#141, #143) | | What-if and analysis | 4 | ~50% | ~40% | 22–35 | Goal Seek, Scenario Manager, data tables, Analysis ToolPak (all 19 tools, no charts), Solver (Simplex LP, a local nonlinear method and Evolutionary; Answer, Sensitivity and Limits reports; Load/Save Model, Reset All and Solver Options; no Population report), Forecast Sheet. Missing: Analyze Data | | Get & Transform, external data, data model | 5 | ~15% | ~10% | 60–100 | Import of CSV/TSV, JSON, HTML. No Power Query editor, no From Web, database or folder sources, no connections or refresh, no relationships or data model, no external workbook links (dropped with a warning) | | Insert objects | 3 | ~55% | ~45% | 25–40 | Pictures, 8 shape kinds (Excel has ~170), text boxes, own icon set, ink with Ink to Shape, hyperlinks, checkboxes, form buttons, scroll bars and spin buttons, equations (LaTeX with a live preview, Office Math in xlsx, Symbol font in PDF). Missing: SmartArt, WordArt, signature line, objects, 3-D models, screenshot, pictures in cells (PR #105) | @@ -309,8 +307,9 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land - What-if: Goal Seek, scenarios, data tables. Spelling (system word list) and thesaurus. - Draw: pen, highlighter, eraser, ink strokes and Ink to Shape. Task panes: Comments (threaded replies, resolve), Watch Window, Selection, Format Chart. -- Charts: column, bar, line, area, pie, doughnut, scatter, bubble, radar, histogram, waterfall, - funnel, treemap, sunburst, box & whisker, stock and combo charts; sparklines. +- Charts: column, bar, line, area, pie, doughnut (one concentric ring per series), scatter, + bubble, radar, histogram, waterfall, funnel, treemap, sunburst, box & whisker, stock and combo + charts; sparklines. - UI (egui): Excel-style title bar with Quick Access Toolbar and AutoSave, the full ribbon with galleries (cell styles, table styles, colour palettes, conditional formatting menus), contextual Table/Chart Design tabs, formula bar with Name Box, virtualised grid (smooth From cb059716592935b9b0b9542b7e80d34a4748631e Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Thu, 5 Nov 2026 11:47:39 +0600 Subject: [PATCH 11/26] =?UTF-8?q?i18n:=20German=20context=20menus'=20Inser?= =?UTF-8?q?t=20reads=20"Zellen=20einf=C3=BCgen",=20not=20a=20second=20"Ein?= =?UTF-8?q?f=C3=BCgen"=20(#2874)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit German showed "Einfügen" for Paste and again for Insert in the cell menu ("Einfügen…") and the row and column header menus ("Einfügen"). The cell menu's Insert… now reads "Zellen einfügen…", as Excel's German menu does. The header menus' Insert gets its own key, "Header Menu|Insert", German "Zellen einfügen"; the plain "Insert" stays as the Insert dialog's title and button use it, and every other catalog gets the new key with the text it shows today. A test reads the three menus' items from menus.rs and checks that no two read alike in German. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/grid/menus.rs | 4 +-- crates/ui-egui/src/grid/tests.rs | 46 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 3 ++- crates/ui-egui/src/i18n/el.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/nl.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt.rs | 1 + crates/ui-egui/src/i18n/ro.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sr.rs | 1 + crates/ui-egui/src/i18n/tr.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/i18n/vi.rs | 1 + crates/ui-egui/src/i18n/zh.rs | 1 + 20 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index 575dac504..e9ee1a976 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -496,7 +496,7 @@ pub(super) fn header_menu(app: &mut SheetApp, ui: &mut egui::Ui, was_open: bool) ("Copy", "edit.copy"), ("Paste", "edit.paste"), ("-", ""), - ("Insert", "home.insertRows"), + ("Header Menu|Insert", "home.insertRows"), ("Delete", "home.deleteRows"), ("Clear Contents", "edit.clearContents"), ("-", ""), @@ -513,7 +513,7 @@ pub(super) fn header_menu(app: &mut SheetApp, ui: &mut egui::Ui, was_open: bool) ("Copy", "edit.copy"), ("Paste", "edit.paste"), ("-", ""), - ("Insert", "home.insertColumns"), + ("Header Menu|Insert", "home.insertColumns"), ("Delete", "home.deleteColumns"), ("Clear Contents", "edit.clearContents"), ("-", ""), diff --git a/crates/ui-egui/src/grid/tests.rs b/crates/ui-egui/src/grid/tests.rs index 74abfc861..427c67629 100644 --- a/crates/ui-egui/src/grid/tests.rs +++ b/crates/ui-egui/src/grid/tests.rs @@ -180,6 +180,52 @@ fn filter_menu_uses_the_table_whose_header_was_clicked() { assert_eq!(filter_table_range(&sh, 1, 4), None); } +/// The `("Label", "id")` keys written in `src`, without separators. +fn menu_labels(src: &str) -> Vec<&str> { + src.split("(\"").skip(1).filter_map(|rest| rest.split_once("\", \"").map(|(label, _)| label)).filter(|label| *label != "-").collect() +} + +/// The source of `menus.rs` from `start` to the first `end` after it. +fn menu_source<'a>(src: &'a str, start: &str, end: &str) -> &'a str { + let from = src.find(start).unwrap_or_else(|| panic!("{start:?} not in menus.rs")); + let rest = &src[from..]; + &rest[..rest.find(end).unwrap_or_else(|| panic!("{end:?} not after {start:?}"))] +} + +/// German read "Einfügen" for Paste and "Einfügen…"/"Einfügen" for Insert in the same menu +/// (#2874): no two items of the cell, row header or column header menu may read alike, ignoring +/// case and a trailing ellipsis. The items are read from `menus.rs`, so new ones are checked too. +#[test] +fn german_context_menus_have_no_two_items_alike() { + use crate::i18n::Language; + let src = include_str!("menus.rs"); + let cell = menu_labels(menu_source(src, "fn context_menu(", "let lang =")); + let (rows, columns) = + menu_source(src, "fn header_menu(", "let lang =").split_once("} else {").expect("header menu has a rows and a columns list"); + let insert_copied = menu_labels(menu_source(src, "fn insert_copied_item(", "\n}")); + assert_eq!(insert_copied.len(), 3, "{insert_copied:?}"); + for (menu, keys) in [("cell", cell), ("row header", menu_labels(rows)), ("column header", menu_labels(columns))] { + assert!(keys.contains(&"Paste") && keys.len() > 8, "{menu} menu not read from menus.rs: {keys:?}"); + // A menu holds at most one Insert Copied/Cut Cells entry. + for extra in &insert_copied { + let mut seen: Vec<(String, &str)> = Vec::new(); + for key in keys.iter().chain([extra]) { + let shown = Language::De.tr(key).trim_end_matches('…').trim().to_lowercase(); + if let Some((_, other)) = seen.iter().find(|(text, _)| *text == shown) { + panic!("German {menu} menu shows {key:?} and {other:?} both as {shown:?}"); + } + seen.push((shown, key)); + } + } + } + assert_eq!(Language::De.tr("Insert…"), "Zellen einfügen…"); + assert_eq!(Language::De.tr("Header Menu|Insert"), "Zellen einfügen"); + // Only German changed: the header menu's Insert reads as the plain Insert everywhere else. + for language in Language::ALL.into_iter().filter(|l| *l != Language::De) { + assert_eq!(language.tr("Header Menu|Insert"), language.tr("Insert"), "{}", language.code()); + } +} + #[test] fn cell_text_y_moves_monotonically_in_standard_and_tall_rows() { let rect_std = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 20.0)); diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 58d308413..39e6337dd 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -57,6 +57,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Podokno\nformátu", "Format" => "Formát", "Insert" => "Vložit", + "Header Menu|Insert" => "Vložit", "Insert Cells…" => "Vložit buňky…", "Delete" => "Odstranit", "Delete Cells…" => "Odstranit buňky…", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2e6ba713f..f136e483b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -57,6 +57,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Format-\nbereich", "Format" => "Format", "Insert" => "Einfügen", + "Header Menu|Insert" => "Zellen einfügen", "Insert Cells…" => "Zellen einfügen…", "Delete" => "Löschen", "Select Data…" => "Daten auswählen…", @@ -476,7 +477,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { // grid.rs cell and row/column header context menus. "Cut" => "Ausschneiden", "Copy" => "Kopieren", - "Insert…" => "Einfügen…", + "Insert…" => "Zellen einfügen…", "Delete…" => "Löschen…", "Filter by Selected Cell's Value" => "Nach Wert der gewählten Zelle filtern", "New Comment" => "Neuer Kommentar", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 218fa5a6f..dc57982c7 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -56,6 +56,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Παράθυρο\nμορφοποίησης", "Format" => "Μορφοποίηση", "Insert" => "Εισαγωγή", + "Header Menu|Insert" => "Εισαγωγή", "Insert Cells…" => "Εισαγωγή κελιών…", "Delete" => "Διαγραφή", "Delete Cells…" => "Διαγραφή κελιών…", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b6adcf774..3c15a16b1 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -60,6 +60,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Panel\nde formato", "Format" => "Formato", "Insert" => "Insertar", + "Header Menu|Insert" => "Insertar", "Insert Cells…" => "Insertar celdas…", "Delete" => "Eliminar", "Delete Cells…" => "Eliminar celdas…", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index e11ef4599..3e95d4b72 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -67,6 +67,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Volet\nFormat", "Format" => "Format", "Insert" => "Insertion", + "Header Menu|Insert" => "Insertion", "Insert Cells…" => "Insérer des cellules…", "Delete" => "Supprimer", "Delete Cells…" => "Supprimer des cellules…", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9a371e673..3ad0ff328 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -60,6 +60,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Riquadro\nFormato", "Format" => "Formato", "Insert" => "Inserisci", + "Header Menu|Insert" => "Inserisci", "Insert Cells…" => "Inserisci celle…", "Delete" => "Elimina", "Delete Cells…" => "Elimina celle…", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 47fd0e9f3..19fc85f02 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -64,6 +64,7 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Format\nPane", "書式ウィンドウ"), ("Format", "書式"), ("Insert", "挿入"), + ("Header Menu|Insert", "挿入"), ("Insert Cells…", "セルの挿入…"), ("Delete", "削除"), ("Delete Cells…", "セルの削除…"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 906dea54f..8c28be26e 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -62,6 +62,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "서식\n창", "Format" => "서식", "Insert" => "삽입", + "Header Menu|Insert" => "삽입", "Insert Cells…" => "셀 삽입…", "Delete" => "삭제", "Delete Cells…" => "셀 삭제…", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index b1d415211..b5cddb88d 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -61,6 +61,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Opmaak-\nvenster", "Format" => "Opmaak", "Insert" => "Invoegen", + "Header Menu|Insert" => "Invoegen", "Insert Cells…" => "Cellen invoegen…", "Delete" => "Verwijderen", "Delete Cells…" => "Cellen verwijderen…", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index ad9c254c1..f2bfd72c7 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -56,6 +56,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Okienko\nformatowania", "Format" => "Formatuj", "Insert" => "Wstaw", + "Header Menu|Insert" => "Wstaw", "Insert Cells…" => "Wstaw komórki…", "Delete" => "Usuń", "Delete Cells…" => "Usuń komórki…", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index f78ef4cf5..d525f027e 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -59,6 +59,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Painel de\nFormatação", "Format" => "Formatar", "Insert" => "Inserir", + "Header Menu|Insert" => "Inserir", "Insert Cells…" => "Inserir Células…", "Delete" => "Excluir", "Delete Cells…" => "Excluir Células…", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 738fc554f..66eb854b7 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -63,6 +63,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Panou\nformatare", "Format" => "Format", "Insert" => "Inserare", + "Header Menu|Insert" => "Inserare", "Insert Cells…" => "Inserare celule…", "Delete" => "Ștergere", "Delete Cells…" => "Ștergere celule…", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 60141a853..00a3062bd 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -62,6 +62,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Область\nформатирования", "Format" => "Формат", "Insert" => "Вставить", + "Header Menu|Insert" => "Вставить", "Insert Cells…" => "Вставить ячейки…", "Delete" => "Удалить", "Delete Cells…" => "Удалить ячейки…", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index d02c66bb8..9254dc938 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -63,6 +63,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Okno za\noblikovanje", "Format" => "Oblikovanje", "Insert" => "Umetni", + "Header Menu|Insert" => "Umetni", "Insert Cells…" => "Umetni ćelije…", "Delete" => "Obriši", "Delete Cells…" => "Obriši ćelije…", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index a58505848..c8da06cb1 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -59,6 +59,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Biçim\nBölmesi", "Format" => "Biçim", "Insert" => "Ekle", + "Header Menu|Insert" => "Ekle", "Insert Cells…" => "Hücre Ekle…", "Delete" => "Sil", "Delete Cells…" => "Hücreleri Sil…", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 96070eaaf..35fc9f0f7 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -58,6 +58,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Область\nформатування", "Format" => "Формат", "Insert" => "Вставити", + "Header Menu|Insert" => "Вставити", "Insert Cells…" => "Вставити комірки…", "Delete" => "Видалити", "Delete Cells…" => "Видалити комірки…", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 7a188a08e..8cb5a32ac 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -64,6 +64,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "Ngăn\nđịnh dạng", "Format" => "Định dạng", "Insert" => "Chèn", + "Header Menu|Insert" => "Chèn", "Insert Cells…" => "Chèn ô…", "Delete" => "Xóa", "Delete Cells…" => "Xóa ô…", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 601e0a1bb..e71a0df3f 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -62,6 +62,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format\nPane" => "格式\n窗格", "Format" => "格式", "Insert" => "插入", + "Header Menu|Insert" => "插入", "Insert Cells…" => "插入单元格…", "Delete" => "删除", "Delete Cells…" => "删除单元格…", From d628abb7b019cbb9e2230b93d4f2c8be4774b98f Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:53:11 +1030 Subject: [PATCH 12/26] Web: page host mode, so a page can host GridCraft in its own document (#2592) data-host="page" on the canvas opts a page that loads the module into its own document into the host bridge. The ?host=parent messages travel as non-bubbling CustomEvents on the canvas; Bridge holds a Transport (Parent or Page) and shares the save, dirty and ready logic. Unframed ?host=parent still gets no bridge. Hosting guide documents both modes. --- apps/gridcraft-web/Cargo.toml | 2 +- apps/gridcraft-web/src/host.rs | 184 ++++++++++++++++++++++------- apps/gridcraft-web/src/hostmode.rs | 45 +++++++ apps/gridcraft-web/src/main.rs | 12 +- apps/gridcraft-web/src/web.rs | 15 ++- packaging/web/README.md | 72 +++++++++++ 6 files changed, 279 insertions(+), 51 deletions(-) create mode 100644 apps/gridcraft-web/src/hostmode.rs diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index 41059d379..e384ffe09 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -26,4 +26,4 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] } diff --git a/apps/gridcraft-web/src/host.rs b/apps/gridcraft-web/src/host.rs index 2286023e5..8130d2682 100644 --- a/apps/gridcraft-web/src/host.rs +++ b/apps/gridcraft-web/src/host.rs @@ -1,5 +1,10 @@ -//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed -//! GridCraft in an `