Merge branch 'main' into PR #2371

# Conflicts:
#	ROADMAP.md
This commit is contained in:
FredApps
2026-11-26 20:34:10 +01:00
46 changed files with 756 additions and 74 deletions
Generated
+1
View File
@@ -2987,6 +2987,7 @@ dependencies = [
"gridcraft-math",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
]
+2
View File
@@ -67,6 +67,8 @@ regex = { version = "1", default-features = false, features = ["std", "unicode",
quick-xml = "0.41"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
sha2 = { version = "0.11", default-features = false }
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
sha1 = { version = "0.11", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
+4 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
@@ -154,6 +154,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked |
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
@@ -169,6 +170,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
@@ -317,6 +319,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
| 2026-10-24 | minor | Progress log: password to modify (#921) |
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
+13 -6
View File
@@ -16,6 +16,7 @@ enum Fam {
Col100,
Line,
LineStack,
Line100,
Area,
AreaStack,
Area100,
@@ -31,6 +32,7 @@ fn family(k: ChartKind) -> Fam {
ColumnStacked100 | BarStacked100 => Fam::Col100,
Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line,
LineStacked => Fam::LineStack,
LineStacked100 | LineStacked100Markers => Fam::Line100,
Area => Fam::Area,
AreaStacked => Fam::AreaStack,
AreaStacked100 => Fam::Area100,
@@ -40,7 +42,7 @@ fn family(k: ChartKind) -> Fam {
/// Families stacked to 100%: each category's values are shares of its total.
fn is_100(f: Fam) -> bool {
matches!(f, Fam::Col100 | Fam::Area100)
matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100)
}
fn is_col(f: Fam) -> bool {
@@ -48,7 +50,12 @@ fn is_col(f: Fam) -> bool {
}
fn is_line(f: Fam) -> bool {
matches!(f, Fam::Line | Fam::LineStack)
matches!(f, Fam::Line | Fam::LineStack | Fam::Line100)
}
/// Line kinds that draw a marker at each point.
fn has_markers(k: ChartKind) -> bool {
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
@@ -156,7 +163,7 @@ impl BarSink {
}
fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec<Vec<Option<(f64, f64)>>> {
// Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart).
// Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart).
let mut totals: Vec<((bool, Fam), Vec<f64>)> = Vec::new();
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
@@ -187,7 +194,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
let a = sec.get(i).copied().unwrap_or(false);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100);
let key = (a, fam);
let si = if stacked {
match stacks.iter().position(|(k, _, _)| *k == key) {
@@ -216,7 +223,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
}),
(Some((_, pos, _)), _) => {
let v = v.unwrap_or(0.0);
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
let v = if is_100(fam) { share(key, j, v) } else { v };
pos.get_mut(j).map(|acc| {
let base = *acc;
*acc = clean(*acc + v);
@@ -424,7 +431,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if k == ChartKind::LineMarkers && cw >= 3.0 {
if has_markers(k) && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
}
if labels_on {
+4 -2
View File
@@ -57,8 +57,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
.clone()
.map(|s| {
let sw = match s.kind {
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
Swatch::Line
}
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
_ => Swatch::Box,
};
+2 -2
View File
@@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay
let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 };
if settings.show_keys {
let swatch = match series.kind {
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line,
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
_ => Swatch::Box,
};
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
+59 -1
View File
@@ -8,7 +8,7 @@ use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 26] = [
const ALL_KINDS: [ChartKind; 28] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -18,6 +18,8 @@ const ALL_KINDS: [ChartKind; 26] = [
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -1491,6 +1493,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() {
assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2)));
}
#[test]
fn hundred_percent_stacked_lines_end_each_category_at_its_total() {
let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]);
for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] {
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(),
series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)],
};
let mut c = chart(kind);
c.data_labels = false;
let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
let t = texts(&p);
assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}");
assert!(!t.contains(&"40"), "{kind:?}: {t:?}");
// The value axis labels sit on their gridlines.
let label_y = |s: &str| {
p.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == s => Some(*y),
_ => None,
})
.unwrap_or(f32::NAN)
};
let (y0, y100) = (label_y("0%"), label_y("100%"));
assert!(y0 > y100, "{kind:?}: {y0} {y100}");
let frac = |y: f32| (y0 - y) / (y0 - y100);
let line = |color: Rgba| {
p.iter()
.find_map(|p| match p {
// The series line is 2.25 wide; its legend swatch is 2.0.
Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => {
Some(pts.iter().map(|q| frac(q[1])).collect::<Vec<f32>>())
}
_ => None,
})
.unwrap_or_default()
};
let (north, south) = (line(north_color), line(south_color));
assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}");
// A category whose total is zero stays on the baseline.
for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() {
assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]);
}
// Point markers have a white outline; the legend's marker swatches have none.
let circles = |outlined: bool| {
p.iter()
.filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined))
.count()
};
let with_markers = kind == ChartKind::LineStacked100Markers;
assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}");
}
}
#[test]
fn two_level_categories_resolve_and_draw() {
let years = ["2023", "", "", "2024", "", ""];
+29
View File
@@ -148,3 +148,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() {
assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h);
}
}
#[test]
fn table_keys_for_100_percent_stacked_lines_use_line_swatches() {
for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] {
let mut c = chart(kind);
c.title = Some(String::new());
c.legend = LegendPos::None;
c.data_labels = false;
c.data_table = Some(ChartDataTable::default());
let color = [1, 2, 3, 255];
let d = ChartData {
categories: ["Jan", "Feb"].map(String::from).to_vec(),
series: vec![series("Rate", &[1.0, 3.0], color, kind)],
..Default::default()
};
let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure);
let header_y = p
.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == "Jan" => Some(*y),
_ => None,
})
.unwrap();
let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count();
assert_eq!(key_circles, usize::from(marker), "{kind:?}");
let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y));
assert!(!key_box, "{kind:?} key is a line swatch");
}
}
+30 -3
View File
@@ -3,12 +3,12 @@
use serde_json::{Value as Json, json};
use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param};
use crate::DocState;
use crate::{DocState, EngineError};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
@@ -59,6 +59,19 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
};
let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted;
let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?;
// A password to modify: the right one or a read-only open, or the workbook doesn't open.
let mut read_only = false;
if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) {
read_only = bool_param(p, "readOnly").unwrap_or(false);
match str_param(p, "modifyPassword") {
_ if read_only => {}
None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))),
Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => {
return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into()));
}
Some(_) => {}
}
}
wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir);
// What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but
// never a folder, so it reports `[name]Sheet` with none; an import reports the file it came
@@ -78,7 +91,7 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
// An import has no save target: ordinary Save must ask for a new destination. Neither does a
// workbook decrypted with its password, so Save never replaces the encrypted original with
// an unprotected copy.
let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string);
let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).map(str::to_string);
// Replace an untouched blank Book1 like Excel does.
if s.documents().len() == 1
&& s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty()))
@@ -87,6 +100,9 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
}
// Someone else may have made the file: its active content asks before it runs.
let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile);
if read_only {
doc.read_only_source = str_param(p, "path").map(str::to_string);
}
if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx {
doc.content_kind = Some(crate::io::FileKind::Xlsx);
}
@@ -106,6 +122,14 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
)
}
/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink).
fn same_file(a: &str, b: &str) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(x), Ok(y)) => x == y,
_ => a == b,
}
}
fn save(s: &mut Session, p: &Json) -> Result<Json> {
let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) {
Some(p) => p,
@@ -114,6 +138,9 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
return ok();
}
};
if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) {
return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file."));
}
// A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the
// document keeps its file and its unsaved changes.
if std::path::Path::new(&path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Chart",
["Insert", "Charts"],
None,
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers, title?, at?: \"H2\", width?, height?}",
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
+2
View File
@@ -46,6 +46,8 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
("bar", _) => ChartKind::BarClustered,
("line", "markers") => ChartKind::LineMarkers,
("line", "stacked") => ChartKind::LineStacked,
("line", "stacked100") => ChartKind::LineStacked100,
("line", "stacked100Markers") => ChartKind::LineStacked100Markers,
("line", _) => ChartKind::Line,
("pie", _) => ChartKind::Pie,
("doughnut", _) => ChartKind::Doughnut,
+4
View File
@@ -53,6 +53,10 @@ impl FileKind {
/// The error for an encrypted workbook opened without a password contains this. The interface
/// asks for the password when it sees it; programmatic callers pass `password` instead.
pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it.";
/// The error for a workbook with a password to modify, opened with neither that password
/// (`modifyPassword`) nor `readOnly`, contains this. The interface asks for the password or a
/// read-only open when it sees it.
pub const MODIFY_PASSWORD_REQUIRED: &str = "is reserved by its author. Enter the password to modify it, or open it read-only.";
/// The error for a wrong password contains this.
pub const WRONG_PASSWORD: &str = "The password is incorrect.";
/// The first open warning of a workbook decrypted with its password.
+4
View File
@@ -206,6 +206,9 @@ pub struct DocState {
/// The format `path`'s content was recognised as when its extension doesn't name one (an
/// XLSX called `budget.dat`): Save writes it back in that format.
pub content_kind: Option<io::FileKind>,
/// The file a read-only open came from (`readOnly` on a workbook with a password to modify).
/// Save never writes over it, so the reservation holds; Save As to another file still works.
pub read_only_source: Option<String>,
/// Whether the scripts stored in this workbook may run (`automate.runScript`). A workbook
/// that arrives already carrying scripts (opened from a file) starts untrusted until the
/// user trusts it in this session (`automate.trustScripts`); one with no scripts starts
@@ -364,6 +367,7 @@ impl DocState {
sheet_selections: vec![],
unlocked_ranges: vec![],
content_kind: None,
read_only_source: None,
scripts_trusted,
trust,
touched: None,
+69
View File
@@ -5589,6 +5589,75 @@ fn encrypted_book(password: &str) -> Vec<u8> {
gridcraft_xlsx::testing::encrypt_workbook(&xlsx, password)
}
#[test]
fn a_password_to_modify_asks_for_it_or_a_read_only_open() {
const PW: &str = "synthetic-modify-pw";
let mut src = s();
src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap();
std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation {
password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")),
..Default::default()
});
let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap();
let b64 = crate::io::base64_encode(&bytes);
let open = |s: &mut Session, extra: serde_json::Value| {
let mut p = json!({"name": "Reserved.xlsx", "base64": b64});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
s.execute("file.open", p)
};
let mut s = Session::new();
let err = open(&mut s, json!({})).unwrap_err().to_string();
assert!(err.contains(crate::io::MODIFY_PASSWORD_REQUIRED), "{err}");
assert!(s.take_ui_requests().is_empty(), "programmatic calls never open dialogs");
for wrong in ["not-it", ""] {
let err = open(&mut s, json!({"modifyPassword": wrong})).unwrap_err().to_string();
assert!(err.contains(crate::io::WRONG_PASSWORD), "{err}");
}
assert!(s.documents().is_empty());
// Read-only: opens, keeps the reservation, but has no file to save over.
open(&mut s, json!({"readOnly": true})).unwrap();
assert_eq!(v(&s, "A1"), Value::Number(42.0));
assert!(s.doc().unwrap().wb.write_reservation.is_some());
// The password: opens, and the reservation survives a save.
let mut s = Session::new();
open(&mut s, json!({"modifyPassword": PW})).unwrap();
assert_eq!(v(&s, "A1"), Value::Number(42.0));
let saved = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
let (back, _) = crate::io::open_bytes("book.xlsx", &saved).unwrap();
assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true)));
}
#[test]
fn a_read_only_open_never_saves_over_its_reserved_file() {
const PW: &str = "synthetic-modify-pw";
let dir = std::env::temp_dir().join(format!("gridcraft-read-only-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("reserved.xlsx").to_string_lossy().into_owned();
let copy = dir.join("copy.xlsx").to_string_lossy().into_owned();
let mut src = s();
std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation {
password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")),
..Default::default()
});
let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap();
std::fs::write(&path, &bytes).unwrap();
let mut s = Session::new();
s.execute("file.open", json!({"path": path, "readOnly": true})).unwrap();
let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string();
assert!(err.contains("read-only"), "{err}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched");
let dotted = dir.join(".").join("reserved.xlsx").to_string_lossy().into_owned();
let err = s.execute("file.save", json!({"path": dotted})).unwrap_err().to_string();
assert!(err.contains("read-only"), "the same file under another spelling: {err}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched");
s.execute("file.saveAs", json!({"path": copy})).unwrap();
assert!(std::fs::metadata(&copy).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn encrypted_workbooks_open_with_their_password() {
const PW: &str = "synthetic-pw-5521";
@@ -0,0 +1,38 @@
//! The 100% stacked line charts: `insert.chart` and `chart.set` take type `line` with subtype
//! `stacked100` or `stacked100Markers`.
use gridcraft_engine::Session;
use gridcraft_model::ChartKind;
use serde_json::json;
fn session() -> Session {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", "10", "30"], ["Q2", "30", "10"]]})).unwrap();
s
}
fn kinds(s: &Session) -> Vec<ChartKind> {
s.doc().unwrap().wb.sheet(0).unwrap().charts.iter().map(|c| c.kind).collect()
}
#[test]
fn insert_chart_makes_hundred_percent_stacked_lines() {
let mut s = session();
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100"})).unwrap();
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100Markers"})).unwrap();
assert_eq!(kinds(&s), [ChartKind::LineStacked100, ChartKind::LineStacked100Markers]);
}
#[test]
fn chart_set_changes_a_chart_to_a_hundred_percent_stacked_line_and_back() {
let mut s = session();
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked"})).unwrap();
assert_eq!(kinds(&s), [ChartKind::LineStacked]);
s.execute("chart.set", json!({"type": "line", "subtype": "stacked100Markers"})).unwrap();
assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]);
s.execute("chart.set", json!({"type": "line", "subtype": "stacked100"})).unwrap();
assert_eq!(kinds(&s), [ChartKind::LineStacked100]);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]);
}
+1
View File
@@ -4,6 +4,7 @@ mod autofit_filter_buttons;
mod cascading_filter_values;
mod cf_formula_validate;
mod chart_area_stacked100;
mod chart_line_stacked100;
mod chart_workbook_names;
mod command_sequence_fuzz;
mod cross_sheet_cut;
+1 -1
View File
@@ -288,7 +288,7 @@ fn base_tool_definitions() -> Vec<Value> {
json!({
"range": string("Source data range including headers, e.g. \"A1:C6\""),
"type": enumeration("Chart type", CHART_TYPES),
"subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers"]),
"subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers", "stacked100Markers"]),
"title": string("Chart title"),
"at": string("Top-left anchor cell (default: right of the data)"),
}),
+1
View File
@@ -15,6 +15,7 @@ test-support = []
[dependencies]
gridcraft-core = { workspace = true }
sha1 = { workspace = true }
sha2 = { workspace = true }
gridcraft-formula = { workspace = true }
gridcraft-math = { workspace = true }
+46 -8
View File
@@ -501,6 +501,8 @@ pub enum ChartKind {
Line,
LineMarkers,
LineStacked,
LineStacked100,
LineStacked100Markers,
Pie,
Doughnut,
Area,
@@ -683,10 +685,17 @@ pub struct Chart {
}
/// Whether a series of kind `b` can be drawn in a chart of kind `a` without making it a combo:
/// the same kind, or a line with or without markers, or a scatter with or without lines.
/// the same kind, or a line or 100% stacked line with or without markers, or a scatter with or
/// without lines.
pub fn same_family(a: ChartKind, b: ChartKind) -> bool {
use ChartKind::*;
a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines))
a == b
|| matches!(
(a, b),
(Line | LineMarkers, Line | LineMarkers)
| (LineStacked100 | LineStacked100Markers, LineStacked100 | LineStacked100Markers)
| (Scatter | ScatterLines, Scatter | ScatterLines)
)
}
/// The kind a combo chart's series `i` with its own kind `own` is drawn as.
@@ -730,20 +739,34 @@ fn grouped(k: ChartKind) -> Option<Grouped> {
use ChartKind::*;
match k {
ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column),
Line | LineMarkers | LineStacked => Some(Grouped::Line),
Line | LineMarkers | LineStacked | LineStacked100 | LineStacked100Markers => Some(Grouped::Line),
Area | AreaStacked | AreaStacked100 => Some(Grouped::Area),
_ => None,
}
}
/// Kind `k` drawn in the grouping of `first`, the first series of its type on its axes: columns
/// and areas take its kind; a line is stacked when it is, and unstacked (keeping its own
/// markers) when it isn't.
/// and areas take its kind; a line is stacked when it is, stacked to 100% (keeping its own
/// markers) when it is, and unstacked (keeping its own markers) when it isn't.
fn regroup(k: ChartKind, first: ChartKind) -> ChartKind {
use ChartKind::*;
let marked = matches!(k, LineMarkers | LineStacked100Markers);
match (grouped(k), first) {
(Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked,
(Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line,
(Some(Grouped::Line), _) => k,
(Some(Grouped::Line), LineStacked) => LineStacked,
(Some(Grouped::Line), LineStacked100 | LineStacked100Markers) => {
if marked {
LineStacked100Markers
} else {
LineStacked100
}
}
(Some(Grouped::Line), _) => {
if marked {
LineMarkers
} else {
Line
}
}
_ => first,
}
}
@@ -845,6 +868,8 @@ impl Chart {
| ChartKind::Line
| ChartKind::LineMarkers
| ChartKind::LineStacked
| ChartKind::LineStacked100
| ChartKind::LineStacked100Markers
| ChartKind::Area
| ChartKind::AreaStacked
| ChartKind::AreaStacked100
@@ -1401,6 +1426,10 @@ mod series_kind_tests {
assert_eq!(drawn(&chart(Line, &[None, Some(LineMarkers), Some(Area)])), vec![Line, LineMarkers, Line]);
assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter), Some(Line)])), vec![Scatter, ScatterLines]);
assert_eq!(drawn(&chart(ColumnClustered, &[Some(Line)])), vec![ColumnClustered]);
assert_eq!(
drawn(&chart(LineStacked100Markers, &[Some(LineStacked100), None, Some(LineMarkers)])),
vec![LineStacked100, LineStacked100Markers, LineStacked100Markers]
);
}
#[test]
@@ -1415,6 +1444,15 @@ mod series_kind_tests {
// An unstacked line keeps its own markers; a stacked one after it is unstacked.
let c = chart(Combo, &[Some(Line), Some(LineMarkers), Some(LineStacked)]);
assert_eq!(drawn(&c), vec![Line, LineMarkers, Line]);
// Lines after a 100% stacked one are stacked to 100%, each keeping its own markers; a
// 100% stacked line after a stacked one is stacked, and after an unstacked one unstacked.
let c = chart(Combo, &[Some(LineStacked100), Some(LineMarkers), Some(LineStacked), Some(LineStacked100Markers)]);
assert_eq!(drawn(&c), vec![LineStacked100, LineStacked100Markers, LineStacked100, LineStacked100Markers]);
assert_eq!(c.series_kinds(), drawn(&c));
let c = chart(Combo, &[Some(LineStacked), Some(LineStacked100Markers)]);
assert_eq!(drawn(&c), vec![LineStacked, LineStacked]);
let c = chart(Combo, &[Some(LineMarkers), Some(LineStacked100), Some(LineStacked100Markers)]);
assert_eq!(drawn(&c), vec![LineMarkers, Line, LineMarkers]);
// Each pair of axes has its own first.
let mut c = chart(Combo, &[Some(ColumnClustered), Some(ColumnStacked)]);
c.series[1].secondary = true;
+1 -1
View File
@@ -32,7 +32,7 @@ pub use style::{
};
pub use workbook::{
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
RefHost, ShowObjects, Workbook, WorkbookView,
RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation,
};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
+15 -1
View File
@@ -160,6 +160,7 @@ impl PasswordHash {
return Err("the stored password hash is damaged".into());
};
let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() {
"SHA-1" => iterated::<sha1::Sha1>(password, &salt, *spin_count),
"SHA-512" => iterated::<sha2::Sha512>(password, &salt, *spin_count),
"SHA-384" => iterated::<sha2::Sha384>(password, &salt, *spin_count),
"SHA-256" => iterated::<sha2::Sha256>(password, &salt, *spin_count),
@@ -236,6 +237,19 @@ mod tests {
Ok(())
}
#[test]
fn sha1_iterated_hash_verifies_the_correct_password() {
// Known answer for "s3cret", salt "0123456789abcdef", spin count 10, computed outside this code.
let h = PasswordHash::Iterated {
algorithm: "SHA-1".into(),
hash: "b2+ArdbduWEP3TNb+4NZg6qjkEk=".into(),
salt: crate::b64::encode(b"0123456789abcdef"),
spin_count: 10,
};
assert!(h.verify("s3cret").unwrap());
assert!(!h.verify("s3cret ").unwrap());
}
#[test]
fn iterated_hash_verifies_and_refuses_what_it_cannot_check() -> Result<(), Box<dyn std::error::Error>> {
let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef");
@@ -245,7 +259,7 @@ mod tests {
let PasswordHash::Iterated { hash, salt, .. } = h else { return Err("not an iterated hash".into()) };
let other =
|algorithm: &str, spin_count| PasswordHash::Iterated { algorithm: algorithm.into(), hash: hash.clone(), salt: salt.clone(), spin_count };
assert!(other("SHA-1", 10).verify("s3cret").is_err());
assert!(!other("SHA-1", 10).verify("s3cret").unwrap());
assert!(other("MD5", 10).verify("s3cret").is_err());
assert!(other("SHA-512", MAX_SPIN_COUNT + 1).verify("s3cret").is_err());
assert!(!other("SHA-256", 2).verify("s3cret")?);
+13
View File
@@ -224,6 +224,9 @@ pub struct Workbook {
/// alone has none and is not written there.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub structure_password: Option<crate::PasswordHash>,
/// "Password to modify" (XLSX `fileSharing`): the file opens read-only unless it is given.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub write_reservation: Option<WriteReservation>,
/// Custom fill lists (Options › Custom Lists) beyond the built-in ones.
pub custom_lists: Vec<Vec<String>>,
/// Named cell styles (Cell Styles gallery): name → style.
@@ -294,6 +297,15 @@ impl Default for Workbook {
}
}
/// The write-reservation of a file (XLSX `fileSharing`): who reserved it, whether it asks to open
/// read-only, and the hash of its password to modify, never the password.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WriteReservation {
pub user_name: String,
pub read_only_recommended: bool,
pub password: Option<crate::PasswordHash>,
}
/// The active sheet index of a [`Workbook`].
///
/// Every other part of a workbook value is immutable once shared (the engine keeps versions as
@@ -564,6 +576,7 @@ impl Workbook {
props: DocProps::default(),
protected_structure: false,
structure_password: None,
write_reservation: None,
custom_lists: vec![],
cell_styles: vec![],
phonetics: vec![],
+7
View File
@@ -6,6 +6,9 @@ impl SheetApp {
Ok(r) => self.after_open(Some(path), &r),
// A password-protected workbook: ask for the password; the dialog opens it.
Err(e) if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) => self.open_dialog("openPassword", json!({"path": path})),
Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => {
self.open_dialog("openPassword", json!({"path": path, "modify": true}))
}
Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))),
}
self.after_engine();
@@ -95,6 +98,10 @@ impl SheetApp {
self.backstage = None;
self.open_dialog("openPassword", json!({"name": name, "base64": b64}));
}
Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => {
self.backstage = None;
self.open_dialog("openPassword", json!({"name": name, "base64": b64, "modify": true}));
}
Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))),
}
self.after_engine();
+16
View File
@@ -458,6 +458,22 @@ impl Dialog {
// An empty password from the start, so OK on the untouched field says "incorrect"
// rather than asking for the password again.
let mut values = params.clone();
// A workbook with a password to modify asks for that, or a read-only open.
if p("modify").as_bool().unwrap_or(false) {
values["modifyPassword"] = json!("");
values["readOnly"] = json!(false);
return Some(Dialog::form(
"openPassword",
"Password",
"file.open",
vec![
Note(format!("'{file}' is reserved by its author. Enter the password to modify it, or open it read-only.")),
Password { key: "modifyPassword", label: "Password:" },
Check { key: "readOnly", label: "Read Only" },
],
values,
));
}
values["password"] = json!("");
Dialog::form(
"openPassword",
+3 -1
View File
@@ -2,7 +2,7 @@ use super::show::ok_cancel;
use super::{Color32, Dialog, Icon, Json, Sense, SheetApp, Stroke, StrokeKind, icons, json, vec2};
/// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`.
const ALL_CHARTS: [(&str, &str, &str); 21] = [
const ALL_CHARTS: [(&str, &str, &str); 23] = [
("column", "", "Clustered Column"),
("column", "stacked", "Stacked Column"),
("column", "stacked100", "100% Stacked Column"),
@@ -12,6 +12,8 @@ const ALL_CHARTS: [(&str, &str, &str); 21] = [
("line", "", "Line"),
("line", "markers", "Line with Markers"),
("line", "stacked", "Stacked Line"),
("line", "stacked100", "100% Stacked Line"),
("line", "stacked100Markers", "100% Stacked Line with Markers"),
("pie", "", "Pie"),
("doughnut", "", "Doughnut"),
("area", "", "Area"),
+22 -10
View File
@@ -122,6 +122,27 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
v
}
fn command_error(app: &mut SheetApp, d: &mut Dialog, e: String) {
if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) {
// Data Analysis asks before replacing data in its output range.
d.values.insert("askOverwrite".into(), json!(true));
} else if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) {
// The decryption password opened an encrypted, reserved workbook; ask for the modify password.
let mut params = Json::Object(d.values.clone());
params["modify"] = json!(true);
if let Some(next) = Dialog::open(app, "openPassword", params) {
*d = Dialog { back: d.back.take(), ..next };
}
} else if d.name == "openPassword" {
// A wrong password: say so, clear the field and stay open for another try.
let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" };
d.values.insert(field.into(), json!(""));
app.message = Some((d.title.clone(), crate::clean_error(&e)));
} else {
app.message = Some((d.title.clone(), crate::clean_error(&e)));
}
}
/// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack.
pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
let Some(mut d) = app.dialog.take() else { return };
@@ -444,16 +465,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
app.after_open(path.as_deref(), &r);
}
}
// Data Analysis asks before replacing data in its output range.
Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => {
d.values.insert("askOverwrite".into(), json!(true));
}
// A wrong password: say so, clear the field and stay open for another try.
Err(e) if d.name == "openPassword" => {
d.values.insert("password".into(), json!(""));
app.message = Some((d.title.clone(), crate::clean_error(&e)));
}
Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))),
Err(e) => command_error(app, &mut d, e),
}
} else if confirm {
open = false;
+2
View File
@@ -922,6 +922,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Γραμμή",
"Line with Markers" => "Γραμμή με δείκτες",
"Stacked Line" => "Σωρευμένες γραμμές",
"100% Stacked Line" => "Σωρευμένες γραμμές 100%",
"100% Stacked Line with Markers" => "Σωρευμένες γραμμές 100% με δείκτες",
"Pie" => "Πίτα",
"Doughnut" => "Δακτύλιος",
"Area" => "Περιοχή",
+2
View File
@@ -811,6 +811,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Linee",
"Line with Markers" => "Linee con indicatori",
"Stacked Line" => "Linee in pila",
"100% Stacked Line" => "Linee in pila 100%",
"100% Stacked Line with Markers" => "Linee in pila 100% con indicatori",
"Pie" => "Torta",
"Doughnut" => "Anello",
"Area" => "Area",
+2
View File
@@ -832,6 +832,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Line", "折れ線"),
("Line with Markers", "マーカー付き折れ線"),
("Stacked Line", "積み上げ折れ線"),
("100% Stacked Line", "100% 積み上げ折れ線"),
("100% Stacked Line with Markers", "マーカー付き 100% 積み上げ折れ線"),
("Pie", "円"),
("Doughnut", "ドーナツ"),
("Area", "面"),
+2
View File
@@ -799,6 +799,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Liniowy",
"Line with Markers" => "Liniowy ze znacznikami",
"Stacked Line" => "Liniowy skumulowany",
"100% Stacked Line" => "Liniowy 100% skumulowany",
"100% Stacked Line with Markers" => "Liniowy 100% skumulowany ze znacznikami",
"Pie" => "Kołowy",
"Doughnut" => "Pierścieniowy",
"Area" => "Warstwowy",
+2
View File
@@ -838,6 +838,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Linhas",
"Line with Markers" => "Linhas com Marcadores",
"Stacked Line" => "Linhas Empilhadas",
"100% Stacked Line" => "Linhas 100% Empilhadas",
"100% Stacked Line with Markers" => "Linhas 100% Empilhadas com Marcadores",
"Pie" => "Pizza",
"Doughnut" => "Rosca",
"Area" => "Área",
+2
View File
@@ -805,6 +805,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Linie",
"Line with Markers" => "Linii cu marcaje",
"Stacked Line" => "Linii stivuite",
"100% Stacked Line" => "Linii 100% stivuite",
"100% Stacked Line with Markers" => "Linii 100% stivuite cu marcaje",
"Pie" => "Radială",
"Doughnut" => "Inel",
"Area" => "Arie",
+2
View File
@@ -802,6 +802,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Line" => "Line",
"Line with Markers" => "Line with Markers",
"Stacked Line" => "Stacked Line",
"100% Stacked Line" => "100% Stacked Line",
"100% Stacked Line with Markers" => "100% Stacked Line with Markers",
"Pie" => "Pie",
"Doughnut" => "Doughnut",
"Area" => "Area",
+2
View File
@@ -196,6 +196,8 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
("100% Stacked Bar", "bar", "stacked100"),
("Line", "line", "markers"),
("Stacked Line", "line", "stacked"),
("100% Stacked Line", "line", "stacked100"),
("100% Stacked Line with Markers", "line", "stacked100Markers"),
("Area", "area", ""),
("Stacked Area", "area", "stacked"),
("100% Stacked Area", "area", "stacked100"),
+2
View File
@@ -96,6 +96,8 @@ pub(super) fn insert(app: &mut SheetApp, ui: &mut Ui) {
("Line", "line", ""),
("Line with Markers", "line", "markers"),
("Stacked Line", "line", "stacked"),
("100% Stacked Line", "line", "stacked100"),
("100% Stacked Line with Markers", "line", "stacked100Markers"),
("Area", "area", ""),
("Stacked Area", "area", "stacked"),
("100% Stacked Area", "area", "stacked100"),
@@ -89,3 +89,14 @@ fn chart_type_marks_the_chart_s_current_type() {
}
}
}
#[test]
fn chart_type_offers_and_marks_the_hundred_percent_stacked_line_types() {
let (mut h, id) = open_chart_type("line", "stacked100Markers");
assert!(marked(&h, "100% Stacked Line with Markers"));
assert!(!marked(&h, "100% Stacked Line"));
click(&mut h, "100% Stacked Line");
assert_eq!(kind(&h, id), ChartKind::LineStacked100);
click(&mut h, "100% Stacked Line with Markers");
assert_eq!(kind(&h, id), ChartKind::LineStacked100Markers);
}
+41
View File
@@ -539,6 +539,29 @@ fn insert_column_or_bar_menu_inserts_a_hundred_percent_stacked_bar() {
assert_eq!(kinds, [gridcraft_engine::model::ChartKind::BarStacked100]);
}
#[test]
fn insert_line_or_area_menu_inserts_hundred_percent_stacked_lines() {
// Insert › Line or Area (keytip N, N1) lists both 100% stacked line types.
let mut s = blank();
s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:C3"})).unwrap();
let mut h = harness(s);
for label in ["100% Stacked Line", "100% Stacked Line with Markers"] {
key(&mut h, Key::F10, Modifiers::NONE);
for (k, t) in [(Key::N, "n"), (Key::N, "n"), (Key::Num1, "1")] {
h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.input_mut().events.push(Event::Text(t.into()));
h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
h.run_steps(2);
h.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
h.run_steps(2);
}
let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect();
assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100, gridcraft_engine::model::ChartKind::LineStacked100Markers]);
}
#[test]
/// Every main ribbon tab and dark mode render with accessibility checks.
fn renders_every_ribbon_tab_without_panicking() {
@@ -754,6 +777,24 @@ fn all_charts_inserts_a_hundred_percent_stacked_area() {
assert_eq!(kinds, [gridcraft_engine::model::ChartKind::AreaStacked100]);
}
#[test]
fn all_charts_inserts_a_hundred_percent_stacked_line_with_markers() {
let mut s = blank();
s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:C3"})).unwrap();
let mut h = harness(s);
h.state_mut().open_dialog("recommendedCharts", json!({"tab": "All Charts"}));
h.run_steps(4);
assert!(h.query_by_label("100% Stacked Line").is_some(), "the list has 100% Stacked Line");
h.get_by_label("100% Stacked Line with Markers").click();
h.run_steps(2);
key(&mut h, Key::Enter, Modifiers::NONE);
h.run_steps(2);
assert!(h.state().dialog.is_none());
let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect();
assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100Markers]);
}
#[test]
fn recommended_charts_command_without_a_type_opens_the_dialog() {
// #1399: the ribbon button and the NR keytip ran the command directly and inserted the first
+53 -33
View File
@@ -54,7 +54,16 @@ pub(crate) fn map_dml_color(c: &DmlColor) -> Option<Color> {
}
}
/// Whether a line group draws markers: the group's `c:marker` is on (or missing) and not every
/// series hides its marker.
fn line_group_markers(g: &El) -> bool {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"));
group_markers && !(all_none && g.kids("ser").next().is_some())
}
fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind {
let line_groups = || plot.into_iter().flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart")));
match k {
ChartType::Column => ChartKind::ColumnClustered,
ChartType::StackedColumn => ChartKind::ColumnStacked,
@@ -63,19 +72,22 @@ fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind {
ChartType::StackedBar => ChartKind::BarStacked,
ChartType::PercentBar => ChartKind::BarStacked100,
ChartType::Line => {
let markers = plot
.into_iter()
.flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart")))
.filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked")))
.any(|g| {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"));
group_markers && !(all_none && g.kids("ser").next().is_some())
});
let markers = line_groups().filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked"))).any(line_group_markers);
if markers { ChartKind::LineMarkers } else { ChartKind::Line }
}
ChartType::LineMarkers => ChartKind::LineMarkers,
ChartType::StackedLine => ChartKind::LineStacked,
// `percentStacked` and `stacked` line groups both read as stacked lines; the grouping
// tells them apart.
ChartType::StackedLine => {
let pct: Vec<&El> = line_groups().filter(|g| g.child_val("grouping") == Some("percentStacked")).collect();
if pct.is_empty() {
ChartKind::LineStacked
} else if pct.iter().any(|g| line_group_markers(g)) {
ChartKind::LineStacked100Markers
} else {
ChartKind::LineStacked100
}
}
ChartType::Area => ChartKind::Area,
ChartType::StackedArea => {
let pct = plot
@@ -214,15 +226,17 @@ fn group_kind(g: &El) -> Option<ChartKind> {
}
}
"lineChart" | "line3DChart" => {
if stacked || pct {
if stacked {
ChartKind::LineStacked
} else {
// The group's kind is its first series' (each series may differ; see
// `series_kind_in`).
let (plain, marked) =
if pct { (ChartKind::LineStacked100, ChartKind::LineStacked100Markers) } else { (ChartKind::Line, ChartKind::LineMarkers) };
match g.kids("ser").next() {
Some(first) => series_kind_in(g, ChartKind::LineMarkers, first),
None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => ChartKind::Line,
None => ChartKind::LineMarkers,
Some(first) => series_kind_in(g, marked, first),
None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => plain,
None => marked,
}
}
}
@@ -249,15 +263,20 @@ fn group_kind(g: &El) -> Option<ChartKind> {
})
}
/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line group its own markers
/// (none when it says so), in a scatter group its own lines; otherwise the group's.
/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line or 100% stacked line
/// group its own markers (none when it says so), in a scatter group its own lines; otherwise
/// the group's.
fn series_kind_in(g: &El, k: ChartKind, s: &El) -> ChartKind {
let marked = || {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none");
group_markers && !none
};
match k {
ChartKind::Line | ChartKind::LineMarkers => {
let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true");
let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none");
if group_markers && !none { ChartKind::LineMarkers } else { ChartKind::Line }
}
ChartKind::Line | ChartKind::LineMarkers if marked() => ChartKind::LineMarkers,
ChartKind::Line | ChartKind::LineMarkers => ChartKind::Line,
ChartKind::LineStacked100 | ChartKind::LineStacked100Markers if marked() => ChartKind::LineStacked100Markers,
ChartKind::LineStacked100 | ChartKind::LineStacked100Markers => ChartKind::LineStacked100,
ChartKind::Scatter | ChartKind::ScatterLines if g.child_val("scatterStyle") != Some("marker") => {
if s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()) { ChartKind::Scatter } else { ChartKind::ScatterLines }
}
@@ -468,7 +487,7 @@ pub fn read_chart(root: &El) -> Option<Chart> {
#[derive(Clone, Copy, PartialEq)]
enum G {
Bar { bar: bool, grouping: &'static str },
Line { stacked: bool, markers: bool },
Line { grouping: &'static str, markers: bool },
Pie,
Doughnut,
Area { grouping: &'static str },
@@ -510,7 +529,7 @@ fn fit_axes(g: G, family: Axes) -> G {
let line_like = matches!(g, G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. });
match family {
Axes::None => g,
Axes::Category if line_like => G::Line { stacked: false, markers: false },
Axes::Category if line_like => G::Line { grouping: "standard", markers: false },
Axes::Category => G::Bar { bar: false, grouping: "clustered" },
Axes::Horizontal => G::Bar { bar: true, grouping: "clustered" },
Axes::Values => G::Scatter { lines: true },
@@ -524,9 +543,11 @@ fn group_for(k: ChartKind) -> G {
ChartKind::BarClustered => G::Bar { bar: true, grouping: "clustered" },
ChartKind::BarStacked => G::Bar { bar: true, grouping: "stacked" },
ChartKind::BarStacked100 => G::Bar { bar: true, grouping: "percentStacked" },
ChartKind::Line => G::Line { stacked: false, markers: false },
ChartKind::LineMarkers => G::Line { stacked: false, markers: true },
ChartKind::LineStacked => G::Line { stacked: true, markers: false },
ChartKind::Line => G::Line { grouping: "standard", markers: false },
ChartKind::LineMarkers => G::Line { grouping: "standard", markers: true },
ChartKind::LineStacked => G::Line { grouping: "stacked", markers: false },
ChartKind::LineStacked100 => G::Line { grouping: "percentStacked", markers: false },
ChartKind::LineStacked100Markers => G::Line { grouping: "percentStacked", markers: true },
ChartKind::Pie => G::Pie,
ChartKind::Doughnut => G::Doughnut,
ChartKind::Area => G::Area { grouping: "standard" },
@@ -752,7 +773,7 @@ fn multi_level_cat(f: &str, values: &str, wb: &Workbook, si: usize) -> Option<St
/// or lines within its group.
fn series_xml(s: &Series, idx: usize, g: G, own: ChartKind, wb: &Workbook, si: usize) -> String {
let g = match (g, group_for(own)) {
(G::Line { stacked, .. }, G::Line { markers, .. }) => G::Line { stacked, markers },
(G::Line { grouping, .. }, G::Line { markers, .. }) => G::Line { grouping, markers },
(G::Scatter { .. }, mine @ G::Scatter { .. }) => mine,
_ => g,
};
@@ -902,9 +923,8 @@ fn group_xml(g: G, series: &[(usize, &Series)], kinds: &[ChartKind], ch: &Chart,
)
}
// Each series states its own markers; an empty group's say whether the chart has them.
G::Line { stacked, markers } => format!(
"<c:lineChart><c:grouping val=\"{}\"/><c:varyColors val=\"0\"/>{sers}{dl}<c:marker val=\"{}\"/>{ax}</c:lineChart>",
if stacked { "stacked" } else { "standard" },
G::Line { grouping, markers } => format!(
"<c:lineChart><c:grouping val=\"{grouping}\"/><c:varyColors val=\"0\"/>{sers}{dl}<c:marker val=\"{}\"/>{ax}</c:lineChart>",
u8::from(markers || !series.is_empty())
),
G::Pie => format!("<c:pieChart><c:varyColors val=\"1\"/>{sers}{dl}<c:firstSliceAng val=\"{}\"/></c:pieChart>", ch.first_slice_angle % 360),
@@ -1010,7 +1030,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str
let stock = ch.kind == ChartKind::Stock;
let kinds = ch.series_kinds();
let group_of = |i: usize| match group_for(kinds.get(i).copied().unwrap_or(ChartKind::ColumnClustered)) {
G::Line { stacked, .. } => G::Line { stacked, markers: false },
G::Line { grouping, .. } => G::Line { grouping, markers: false },
G::Scatter { .. } => G::Scatter { lines: true },
g => g,
};
@@ -1037,7 +1057,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str
// A stock group holds 3 or 4 series (high-low-close, open-high-low-close); others are
// lines, which join a line group already there rather than setting its grouping.
let (out, stock_lines): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, m)| *g != G::Stock || (3..=4).contains(&m.len()));
let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { stacked: false, markers: false }, m));
let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { grouping: "standard", markers: false }, m));
// One group per type on a pair of axes (as Excel keeps them; `Chart::series_kind` gives
// the series of one type one grouping). Groups that fit the axes come first, so a group
// moved onto them joins one of its type there rather than setting its grouping.
@@ -1065,7 +1085,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str
// stock group must hold series, so an empty stock chart has a line group).
if primary.is_empty() {
let g = match group_for(ch.kind) {
G::Stock => G::Line { stacked: false, markers: false },
G::Stock => G::Line { grouping: "standard", markers: false },
g => g,
};
primary.push((g, Vec::new()));
+8
View File
@@ -295,6 +295,14 @@ fn read_workbook_properties(cx: &mut Ctx<'_>, wb: &mut Workbook, xml: &El) {
wb.protected_structure = p.flag("lockStructure", false);
wb.structure_password = if wb.protected_structure { crate::sheet_read::read_password(p, "workbook") } else { None };
}
if let Some(f) = xml.child("fileSharing") {
// The iterated hash has bare attribute names; the legacy one is `reservationPassword`.
wb.write_reservation = Some(gridcraft_model::WriteReservation {
user_name: f.attr("userName").unwrap_or("").to_string(),
read_only_recommended: f.flag("readOnlyRecommended", false),
password: crate::sheet_read::read_password(f, "").or_else(|| crate::sheet_read::read_password(f, "reservation")),
});
}
}
/// The single window modelled by GridCraft: prefer the first visible window,
+1
View File
@@ -6,6 +6,7 @@ mod chart_book_names;
mod chart_bool_default;
mod chart_combo_kinds;
mod chart_data_table;
mod chart_line_percent_stacked;
mod chart_ref_offsets;
mod controls_tests;
mod csv_tests;
@@ -338,6 +338,8 @@ fn a_chart_without_series_survives_a_round_trip() {
Line,
LineMarkers,
LineStacked,
LineStacked100,
LineStacked100Markers,
Pie,
Doughnut,
Area,
@@ -0,0 +1,181 @@
//! Line chart groups by `grouping` and markers: `percentStacked` opens as a 100% stacked line.
use gridcraft_model::{ChartKind, Workbook};
use crate::chart::{read_chart, write_chart};
use crate::xml::parse;
/// Reads a line chart whose one group has `grouping` and whose one series holds `marker`.
fn kind(grouping: &str, marker: &str) -> ChartKind {
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea><c:lineChart>\
<c:grouping val=\"{grouping}\"/><c:ser><c:idx val=\"0\"/><c:order val=\"0\"/>{marker}\
<c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser><c:marker val=\"1\"/>\
<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart><c:catAx><c:axId val=\"1\"/></c:catAx><c:valAx><c:axId val=\"2\"/></c:valAx>\
</c:plotArea></c:chart></c:chartSpace>"
);
let root = parse(xml.as_bytes()).unwrap();
read_chart(&root).unwrap().kind
}
const NO_MARKER: &str = "<c:marker><c:symbol val=\"none\"/></c:marker>";
#[test]
fn percent_stacked_lines_open_as_hundred_percent_stacked() {
assert_eq!(kind("percentStacked", NO_MARKER), ChartKind::LineStacked100);
assert_eq!(kind("percentStacked", ""), ChartKind::LineStacked100Markers);
}
#[test]
fn standard_and_stacked_lines_keep_their_kinds() {
assert_eq!(kind("standard", NO_MARKER), ChartKind::Line);
assert_eq!(kind("standard", ""), ChartKind::LineMarkers);
assert_eq!(kind("stacked", NO_MARKER), ChartKind::LineStacked);
assert_eq!(kind("stacked", ""), ChartKind::LineStacked);
}
#[test]
fn a_hundred_percent_stacked_line_series_in_a_combo_chart_keeps_its_kind_when_saved() {
let ser =
|i: usize| format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/><c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>");
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:barChart>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0),
ser(1)
);
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
assert_eq!(ch.kind, ChartKind::Combo);
assert_eq!(ch.series.iter().map(|s| s.kind).collect::<Vec<_>>(), [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)]);
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap();
let kinds: Vec<Option<ChartKind>> = again.series.iter().map(|s| s.kind).collect();
assert_eq!(kinds.first(), Some(&Some(ChartKind::ColumnClustered)), "{saved}");
assert_eq!(kinds, [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)], "{saved}");
}
/// The lines on one pair of axes share the first one's grouping: a standard line after a 100%
/// stacked one is stacked to 100% too, keeping its own markers.
#[test]
fn combo_line_series_keep_their_order_and_share_one_percent_stack_when_saved() {
let ser = |i: usize, marker: &str| {
format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/>{marker}<c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>")
};
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:barChart>\
<c:lineChart><c:grouping val=\"standard\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0, ""),
ser(2, NO_MARKER),
ser(1, ""),
ser(3, NO_MARKER)
);
let want =
[Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers), Some(ChartKind::LineStacked100), Some(ChartKind::LineStacked100)];
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
assert_eq!(ch.series.iter().map(|s| s.kind).collect::<Vec<_>>(), want);
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
assert_eq!(saved.matches("percentStacked").count(), 1, "both 100% stacked series share one stack: {saved}");
let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap();
assert_eq!(again.series.iter().map(|s| s.kind).collect::<Vec<_>>(), want, "{saved}");
}
#[test]
fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_saved() {
let ser =
|i: usize| format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/><c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>");
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:barChart>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}<c:axId val=\"3\"/><c:axId val=\"4\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0),
ser(1)
);
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
assert!(ch.series.get(1).is_some_and(|s| s.secondary && s.kind == Some(ChartKind::LineStacked100Markers)));
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap();
let got: Vec<(Option<ChartKind>, bool)> = again.series.iter().map(|s| (s.kind, s.secondary)).collect();
assert_eq!(got, [(Some(ChartKind::ColumnClustered), false), (Some(ChartKind::LineStacked100Markers), true)], "{saved}");
}
/// On the secondary axes too, a standard line after a 100% stacked one is stacked to 100%.
#[test]
fn secondary_columns_and_hundred_percent_stacked_lines_keep_their_kinds_when_saved() {
let ser = |i: usize, marker: &str| {
format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/>{marker}<c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>")
};
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:barChart>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>{}<c:axId val=\"3\"/><c:axId val=\"4\"/></c:barChart>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}<c:axId val=\"3\"/><c:axId val=\"4\"/></c:lineChart>\
<c:lineChart><c:grouping val=\"standard\"/>{}<c:axId val=\"3\"/><c:axId val=\"4\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0, ""),
ser(1, ""),
ser(2, ""),
ser(3, NO_MARKER)
);
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
let want = [
(Some(ChartKind::ColumnClustered), false),
(Some(ChartKind::ColumnClustered), true),
(Some(ChartKind::LineStacked100Markers), true),
(Some(ChartKind::LineStacked100), true),
];
assert_eq!(ch.series.iter().map(|s| (s.kind, s.secondary)).collect::<Vec<_>>(), want);
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap();
assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::<Vec<_>>(), want, "{saved}");
}
#[test]
fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_markers() {
let ser = |i: usize, marker: &str| {
format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/>{marker}<c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>")
};
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0, ""),
ser(1, NO_MARKER)
);
// A 100% stacked line chart with markers; the second series keeps its own lack of them.
let want = [None, Some(ChartKind::LineStacked100)];
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
assert_eq!(ch.kind, ChartKind::LineStacked100Markers);
assert_eq!(ch.series.iter().map(|s| s.kind).collect::<Vec<_>>(), want);
assert_eq!(ch.series_kinds(), [ChartKind::LineStacked100Markers, ChartKind::LineStacked100]);
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap();
assert_eq!(again.kind, ChartKind::LineStacked100Markers, "{saved}");
assert_eq!(again.series.iter().map(|s| s.kind).collect::<Vec<_>>(), want, "{saved}");
}
/// The lines on one pair of axes share the first one's grouping: a 100% stacked line group after
/// a stacked one is drawn stacked.
#[test]
fn a_hundred_percent_stacked_line_group_after_a_stacked_one_on_the_same_axes_is_stacked() {
let ser = |i: usize| {
format!("<c:ser><c:idx val=\"{i}\"/><c:order val=\"{i}\"/>{NO_MARKER}<c:val><c:numRef><c:f>Data!$A$1:$A$5</c:f></c:numRef></c:val></c:ser>")
};
let xml = format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart><c:plotArea>\
<c:lineChart><c:grouping val=\"stacked\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
<c:lineChart><c:grouping val=\"percentStacked\"/>{}<c:axId val=\"1\"/><c:axId val=\"2\"/></c:lineChart>\
</c:plotArea></c:chart></c:chartSpace>",
ser(0),
ser(1)
);
let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap();
assert_eq!(ch.series_kinds(), [ChartKind::LineStacked, ChartKind::LineStacked]);
let saved = write_chart(&Workbook::default(), 0, &ch, "Book1");
assert!(!saved.contains("percentStacked"), "{saved}");
}
+23
View File
@@ -23,6 +23,11 @@ fn sample() -> Workbook {
wb.calc = CalcSettings { mode: CalcMode::Manual, iterative: true, max_iterations: 42, max_change: 0.5, precision_as_displayed: true, r1c1: true };
wb.protected_structure = true;
wb.structure_password = Some(gridcraft_model::PasswordHash::new_sha512("s3cret", b"0123456789abcdef"));
wb.write_reservation = Some(gridcraft_model::WriteReservation {
user_name: "Ann & <Bob>".into(),
read_only_recommended: true,
password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")),
});
wb.props = DocProps {
title: "T & <x>".into(),
subject: "S".into(),
@@ -447,6 +452,8 @@ fn sample() -> Workbook {
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -530,6 +537,8 @@ fn assert_workbook_metadata_roundtrip(wb: &Workbook, back: &Workbook) {
assert!(back.protected_structure);
assert_eq!(back.structure_password, wb.structure_password);
assert!(back.structure_password.as_ref().unwrap().verify("s3cret").unwrap());
assert_eq!(back.write_reservation, wb.write_reservation);
assert!(back.write_reservation.as_ref().and_then(|r| r.password.as_ref()).unwrap().verify("modify-me").unwrap());
assert_eq!(back.props, wb.props);
assert_eq!(back.theme, wb.theme);
assert_eq!(back.names, wb.names);
@@ -2029,6 +2038,20 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid");
}
#[test]
fn legacy_reservation_password_is_written_with_a_user_name() {
let mut wb = sample();
wb.write_reservation =
Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) });
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
let r = back.write_reservation.expect("the reservation survived");
assert_eq!(r.password, Some(PasswordHash::Legacy(0x83AF)), "a nameless legacy password is kept, under a placeholder name");
assert!(!r.user_name.is_empty());
wb.write_reservation.as_mut().unwrap().user_name = "Ann".into();
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF)));
}
#[test]
fn workbook_view_settings_survive_a_round_trip() {
// #3057: a workbook Excel saved with the sheet tabs and both scroll bars hidden
+24
View File
@@ -239,6 +239,29 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> {
/// Workbook name written in a PivotChart's link when the file name isn't known.
const DEFAULT_BOOK_NAME: &str = "Workbook.xlsx";
fn append_file_sharing(w: &mut String, wb: &Workbook) {
let Some(r) = &wb.write_reservation else { return };
w.push_str("<fileSharing");
if r.read_only_recommended {
w.push_str(" readOnlyRecommended=\"1\"");
}
// Office needs a userName beside a legacy reservationPassword, so a nameless one gets a placeholder
// rather than losing the password.
let legacy = matches!(r.password, Some(gridcraft_model::PasswordHash::Legacy(_)));
let name = if r.user_name.is_empty() && legacy { "GridCraft" } else { r.user_name.as_str() };
if !name.is_empty() {
let _ = write!(w, " userName=\"{}\"", esc_attr(name));
}
match &r.password {
Some(gridcraft_model::PasswordHash::Legacy(h)) => {
let _ = write!(w, " reservationPassword=\"{h:04X}\"");
}
Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")),
None => {}
}
w.push_str("/>");
}
pub fn write_xlsx(wb: &Workbook, kind: XlsxKind, functions: FunctionInfo) -> Result<Vec<u8>, IoError> {
write_xlsx_named_with(wb, kind, None, functions)
}
@@ -479,6 +502,7 @@ fn write_workbook_xml(
// only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it.
let file_version = crate::passthrough::workbook_elements(wb, "fileVersion");
w.push_str(if file_version.is_empty() { "<fileVersion appName=\"gridcraft\"/>" } else { &file_version });
append_file_sharing(&mut w, wb);
w.push_str("<workbookPr");
match wb.show_objects {
ShowObjects::All => {}
+4 -3
View File
@@ -17,7 +17,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) |
| Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 5 of 7 (line, with markers, stacked, 100% stacked, 100% stacked with markers) | no stacked with markers, no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX; 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; 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 |
@@ -32,8 +32,8 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate
| Box & Whisker | 1 | 1 of 1 | |
| Waterfall, Funnel | 2 | 2 of 2 | |
| Filled map | 1 | 0 | needs geographic boundary data (licensing decision) |
| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | |
| **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate |
| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, 100% stacked line with or without markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | |
| **Total** | ~60 subtypes | **28 (~47%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate |
## Chart elements and formatting
@@ -145,6 +145,7 @@ column chart draws and saves its forecast series as columns, not lines.
| 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) |
| 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. |
| 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-25 | minor | 100% Stacked Line and 100% Stacked Line with Markers: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` |
| 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) |
+2
View File
@@ -100,6 +100,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — |
| `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` |
| Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` |
| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open never saves over its file | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-1/256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` |
| `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — |
## Text and data formats
@@ -196,6 +197,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
| 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export |
| 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance |
| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921); a read-only open refuses Save to its own file; SHA-1 modify hashes verify; an encrypted and reserved file asks for the modify password after its decryption password |
| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) |
| 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI `<img>`) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged |
| 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `<rPh sb="…" eb="…">` with `<phoneticPr>`) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `<phoneticPr>` without runs is kept on its own, and when duplicate `<si>` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |