diff --git a/Cargo.lock b/Cargo.lock index a3a797038..88181d25b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2987,6 +2987,7 @@ dependencies = [ "gridcraft-math", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 6a2f96637..39f86f8c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 diff --git a/ROADMAP.md b/ROADMAP.md index 172d0d193..dd7aa49f1 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-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) | diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index fd4c44224..98849447f 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -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>> { - // 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)> = 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> = 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 { diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index d2456ef13..38521ab0e 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -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, }; diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index 9047e0c31..f356108ce 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -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); diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index aa261ab36..7c4169965 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -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::>()) + } + _ => 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", "", ""]; diff --git a/crates/chart/src/tests/data_table.rs b/crates/chart/src/tests/data_table.rs index ddeee07bc..c6f5105b5 100644 --- a/crates/chart/src/tests/data_table.rs +++ b/crates/chart/src/tests/data_table.rs @@ -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"); + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 5479b438e..1887b06a8 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -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 { 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 { }; 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 { // 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 { } // 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 { ) } +/// 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 { 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 { 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")) { diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 7aa1f6927..cb39a2029 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/insert/chart.rs b/crates/engine/src/cmd/insert/chart.rs index 66c99414f..b45e54578 100644 --- a/crates/engine/src/cmd/insert/chart.rs +++ b/crates/engine/src/cmd/insert/chart.rs @@ -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, diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 0f2dd7828..31c183663 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -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. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1238be31d..52a0c6482 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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, + /// 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, /// 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, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e6a3656a0..56e79955d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5589,6 +5589,75 @@ fn encrypted_book(password: &str) -> Vec { 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(©).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/engine/tests/it/chart_line_stacked100.rs b/crates/engine/tests/it/chart_line_stacked100.rs new file mode 100644 index 000000000..68c6357c7 --- /dev/null +++ b/crates/engine/tests/it/chart_line_stacked100.rs @@ -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 { + 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]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3fc84de0f..11df0e9d5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -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; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 87f7fea5d..f61687524 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -288,7 +288,7 @@ fn base_tool_definitions() -> Vec { 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)"), }), diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index d658ae739..b3352fed7 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -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 } diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 3cefcbe24..6de1ac50c 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -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 { 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; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 08adff8fd..14bf4c722 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -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 diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index aa28ad97c..16d5175ff 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -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::(password, &salt, *spin_count), "SHA-512" => iterated::(password, &salt, *spin_count), "SHA-384" => iterated::(password, &salt, *spin_count), "SHA-256" => iterated::(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> { 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")?); diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 7669f0125..2c6689ec5 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -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, + /// "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, /// Custom fill lists (Options › Custom Lists) beyond the built-in ones. pub custom_lists: Vec>, /// 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, +} + /// 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![], diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 0cbde92a8..74de61aad 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -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(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 09554cfac..4621736d9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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", diff --git a/crates/ui-egui/src/dialogs/charts.rs b/crates/ui-egui/src/dialogs/charts.rs index 039b8b0f3..35ce03cf5 100644 --- a/crates/ui-egui/src/dialogs/charts.rs +++ b/crates/ui-egui/src/dialogs/charts.rs @@ -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"), diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index 567289860..64e0096fc 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -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; diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index e26dbe7c3..573b6ba2d 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -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" => "Περιοχή", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5592a5dd0..dbd1a66da 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 04044bbcc..fd809f065 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -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", "面"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 8a4aca379..0f12f8a87 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 4f38afe7d..e8f542634 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 5ab64149c..c427c0b6a 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -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", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 5eab23563..79b9db5db 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -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", diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index d3f35427a..1e9544da5 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -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"), diff --git a/crates/ui-egui/src/ribbon/insert.rs b/crates/ui-egui/src/ribbon/insert.rs index b29257c76..d1f21af77 100644 --- a/crates/ui-egui/src/ribbon/insert.rs +++ b/crates/ui-egui/src/ribbon/insert.rs @@ -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"), diff --git a/crates/ui-egui/tests/it/format_chart_type.rs b/crates/ui-egui/tests/it/format_chart_type.rs index 8fe695b06..a445b6270 100644 --- a/crates/ui-egui/tests/it/format_chart_type.rs +++ b/crates/ui-egui/tests/it/format_chart_type.rs @@ -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); +} diff --git a/crates/ui-egui/tests/it/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index 3bc51f888..20f251f9a 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -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 diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index f8511d623..4408de864 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -54,7 +54,16 @@ pub(crate) fn map_dml_color(c: &DmlColor) -> Option { } } +/// 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 { } } "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 { }) } -/// 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 { #[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 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!( - "{sers}{dl}{ax}", - if stacked { "stacked" } else { "standard" }, + G::Line { grouping, markers } => format!( + "{sers}{dl}{ax}", u8::from(markers || !series.is_empty()) ), G::Pie => format!("{sers}{dl}", 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())); diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 8aa93dce4..901ef885a 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -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, diff --git a/crates/xlsx/src/tests.rs b/crates/xlsx/src/tests.rs index 4caee757e..9749d3f81 100644 --- a/crates/xlsx/src/tests.rs +++ b/crates/xlsx/src/tests.rs @@ -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; diff --git a/crates/xlsx/src/tests/chart_combo_kinds.rs b/crates/xlsx/src/tests/chart_combo_kinds.rs index 04890de53..7b14c3825 100644 --- a/crates/xlsx/src/tests/chart_combo_kinds.rs +++ b/crates/xlsx/src/tests/chart_combo_kinds.rs @@ -338,6 +338,8 @@ fn a_chart_without_series_survives_a_round_trip() { Line, LineMarkers, LineStacked, + LineStacked100, + LineStacked100Markers, Pie, Doughnut, Area, diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs new file mode 100644 index 000000000..2b0f46c9d --- /dev/null +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -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!( + "\ + {marker}\ + Data!$A$1:$A$5\ + \ + " + ); + let root = parse(xml.as_bytes()).unwrap(); + read_chart(&root).unwrap().kind +} + +const NO_MARKER: &str = ""; + +#[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!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + 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::>(), [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> = 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!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}{}\ + ", + 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::>(), 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::>(), want, "{saved}"); +} + +#[test] +fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_saved() { + let ser = + |i: usize| format!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + 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, 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!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}\ + {}\ + ", + 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::>(), 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::>(), want, "{saved}"); +} + +#[test] +fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_markers() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}{}\ + ", + 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::>(), 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::>(), 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!("{NO_MARKER}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + ", + 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}"); +} diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 6ece8aa67..d810f3b64 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -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 & ".into(), + read_only_recommended: true, + password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")), + }); wb.props = DocProps { title: "T & ".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 diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index c785c9517..8845f1b8f 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -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(" { + 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, 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() { "" } else { &file_version }); + append_file_sharing(&mut w, wb); w.push_str(" {} diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 37f482eeb..dc8c468c0 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -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) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5f12dbfb0..1f7757e81 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -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 ``) 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 (ふりがな, `` with ``) 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 `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |