From 95c0800c2224446e892298c15528af9d9e07e8bc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:40:24 -0500 Subject: [PATCH 01/21] XLSX: password to modify (#921): kept on save, asked for on open or open read-only --- ROADMAP.md | 4 ++- crates/engine/src/cmd/file.rs | 17 +++++++++++-- crates/engine/src/io.rs | 4 +++ crates/engine/src/tests.rs | 40 ++++++++++++++++++++++++++++++ crates/model/src/lib.rs | 4 ++- crates/model/src/workbook.rs | 13 ++++++++++ crates/ui-egui/src/dialogs.rs | 19 +++++++++++++- crates/ui-egui/src/lib.rs | 7 ++++++ crates/xlsx/src/read.rs | 8 ++++++ crates/xlsx/src/tests/roundtrip.rs | 7 ++++++ crates/xlsx/src/write.rs | 17 +++++++++++++ docs/file-format-parity.md | 4 ++- 12 files changed, 138 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index da06359b5..03db59417 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-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 | 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 | | 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) | @@ -226,6 +227,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 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/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b3e7309e2..7f6e9e366 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -8,7 +8,7 @@ use crate::DocState; 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), @@ -57,6 +57,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 @@ -76,7 +89,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())) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index be47e0a67..6453cec7a 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -41,6 +41,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/tests.rs b/crates/engine/src/tests.rs index f4c47bb62..0a5da6bd6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4142,6 +4142,46 @@ 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(); + 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 encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 071de683c..f731422a8 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -25,7 +25,9 @@ pub use style::{ Alignment, BorderLine, BorderStyle, Borders, Color, Fill, Font, HAlign, NumFmt, PatternType, Style, StyleId, StyleTable, Theme, Underline, VAlign, VertAlign, }; -pub use workbook::{CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook}; +pub use workbook::{ + CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook, WriteReservation, +}; /// Font used for new workbooks. Only a name: renderers substitute an available open font /// (e.g. the metric-compatible Carlito) when it isn't installed. diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 3b943d295..e930961b6 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -154,6 +154,9 @@ pub struct Workbook { /// Password of the structure protection (XLSX `workbookProtection`), never the password. #[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. @@ -205,6 +208,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, +} + impl Workbook { /// A new workbook with one sheet, "Sheet1". pub fn new() -> Workbook { @@ -220,6 +232,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/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e83db2fa1..6419db68e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -347,6 +347,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 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", @@ -1504,7 +1520,8 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { } // 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!("")); + 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))); } Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 14c442331..4ba19a8e2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -838,6 +838,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(); @@ -1253,6 +1256,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/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 774567bf8..8900b22fd 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -246,6 +246,14 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { 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) = wb_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")), + }); + } let active_tab = wb_xml.path(&["bookViews", "workbookView"]).and_then(|v| v.attr_u32("activeTab")).unwrap_or(0) as usize; // Sheets. `file_to_model[i]` maps the i-th to a model sheet index. diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438db..462cb8449 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 }; 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(), @@ -495,6 +500,8 @@ fn full_roundtrip() { 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); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index cf208d6cd..1a8373060 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -345,6 +345,23 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // 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 }); + if let Some(r) = &wb.write_reservation { + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); + } w.push_str(" {} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd..bfbc51c9f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -60,6 +60,7 @@ values) is still dropped. | `.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 has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-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 @@ -110,6 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 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) | | 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`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ae50127952243b594ffd54de41ac3b3f4a1bf6ae Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:44:33 -0500 Subject: [PATCH 02/21] XLSX password to modify: fix dialog return type and test's Arc workbook edit --- crates/engine/src/tests.rs | 2 +- crates/ui-egui/src/dialogs.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0a5da6bd6..f160b8a2a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4147,7 +4147,7 @@ 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(); - src.doc_mut().unwrap().wb.write_reservation = Some(gridcraft_model::WriteReservation { + 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() }); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6419db68e..3c57ad7fd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -351,7 +351,7 @@ impl Dialog { if p("modify").as_bool().unwrap_or(false) { values["modifyPassword"] = json!(""); values["readOnly"] = json!(false); - return Dialog::form( + return Some(Dialog::form( "openPassword", "Password", "file.open", @@ -361,7 +361,7 @@ impl Dialog { Check { key: "readOnly", label: "Read Only" }, ], values, - ); + )); } values["password"] = json!(""); Dialog::form( From 38fa0dc050ef1f684fc08292405e34adf43c7681 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:02:07 -0500 Subject: [PATCH 03/21] XLSX password to modify: address review comments - A read-only open refuses Save to the file it came from; Save As to another file still works, so the reservation holds. - Verify SHA-1 password-to-modify hashes, as XLSX fileSharing allows. - An encrypted and reserved workbook asks for the password to modify after its decryption password, keeping the decryption password. --- Cargo.lock | 1 + crates/engine/src/cmd/file.rs | 6 ++++++ crates/engine/src/lib.rs | 4 ++++ crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/model/Cargo.toml | 1 + crates/model/src/password.rs | 16 +++++++++++++++- crates/ui-egui/src/dialogs.rs | 9 +++++++++ docs/file-format-parity.md | 4 ++-- 8 files changed, 63 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7f5203188..ecf7a9ba4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,6 +1627,7 @@ dependencies = [ "gridcraft-formula", "serde", "serde_json", + "sha1", "sha2", "thiserror 2.0.21", ] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7f6e9e366..bd454a9ad 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -98,6 +98,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); } @@ -125,6 +128,9 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; + if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + 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(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a..f6b90d605 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -189,6 +189,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 @@ -283,6 +286,7 @@ impl DocState { sheet_selections: vec![], unlocked_ranges: vec![], content_kind: None, + read_only_source: None, scripts_trusted, trust, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f160b8a2a..fecb11fee 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4182,6 +4182,31 @@ fn a_password_to_modify_asks_for_it_or_a_read_only_open() { 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"); + 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/model/Cargo.toml b/crates/model/Cargo.toml index 761cf0093..02c66415a 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] gridcraft-core = { workspace = true } +sha1 = { workspace = true } sha2 = { workspace = true } gridcraft-formula = { workspace = true } serde = { workspace = true } diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index 59b9aafba..994cf324e 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -49,6 +49,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), @@ -114,6 +115,19 @@ mod tests { assert_eq!(legacy_hash(""), 0xCE4B); } + #[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() { let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef"); @@ -123,7 +137,7 @@ mod tests { let PasswordHash::Iterated { hash, salt, .. } = h else { return }; 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").unwrap()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3c57ad7fd..99a417692 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1518,6 +1518,15 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { d.values.insert("askOverwrite".into(), json!(true)); } + // Encrypted and reserved: the password opened it, so the form turns to the password to + // modify. The decryption password stays in the values for the retry. + Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + 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 }; + } + } // A wrong password: say so, clear the field and stay open for another try. Err(e) if d.name == "openPassword" => { let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bfbc51c9f..667abc55d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -60,7 +60,7 @@ values) is still dropped. | `.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 has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-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` | +| 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 @@ -111,7 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 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) | +| 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-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`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ce64da3286516119304e7f7057567b2adbec1591 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:35:28 -0500 Subject: [PATCH 04/21] XLSX password to modify: compare the reserved file by identity on Save; keep a legacy hash only beside a userName (#2508) --- crates/engine/src/cmd/file.rs | 10 +++++++++- crates/engine/src/tests.rs | 4 ++++ crates/xlsx/src/tests/roundtrip.rs | 12 ++++++++++++ crates/xlsx/src/write.rs | 4 +++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e3c23dd03..4fde819f3 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -120,6 +120,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, @@ -128,7 +136,7 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; - if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + 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 diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 98acfddd0..39928c7f9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4423,6 +4423,10 @@ fn a_read_only_open_never_saves_over_its_reserved_file() { 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(); diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index e90ff1781..35c73d568 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1491,3 +1491,15 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); 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(); + assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + 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))); +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index c3ba698f3..34fb2ed89 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -352,9 +352,11 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); } match &r.password { - Some(gridcraft_model::PasswordHash::Legacy(h)) => { + // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. + Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } + Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From d5b23a5e791479bbc45e37f59f95d57759a92aed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 15:50:34 -0700 Subject: [PATCH 05/21] Charts: 100% Stacked Line, with or without markers, draws values as shares of each category's total Insert > Line or Area and the All Charts list offer 100% Stacked Line and 100% Stacked Line with Markers, and insert.chart and chart.set take them as type line with subtype stacked100 or stacked100Markers. Each series' line is drawn at the running sum of its share of the category's total and the shares before it, so when no value is negative, the last series reaches the top in every category with a nonzero total. When every series on the value axis is 100% stacked and no value is negative, the axis runs from 0% to 100%. The with-markers kind draws a marker at each point. An XLSX line chart with percentStacked grouping now opens as 100% stacked, with markers unless every series has the marker symbol none or the group turns markers off, and is saved back as percentStacked. It used to open as a stacked line and was saved as stacked. A 100% stacked line series in a combo chart is still saved as a standard line. --- ROADMAP.md | 1 + crates/chart/src/render.rs | 20 ++++--- crates/chart/src/tests.rs | 60 ++++++++++++++++++- crates/engine/src/cmd/insert.rs | 4 +- .../engine/tests/it/chart_line_stacked100.rs | 38 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/mcp/src/tools.rs | 2 +- crates/model/src/features.rs | 2 + crates/ui-egui/src/dialogs.rs | 4 +- crates/ui-egui/src/i18n/el.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 2 + crates/ui-egui/src/i18n/ro.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/ribbon.rs | 2 + crates/ui-egui/tests/it/interaction.rs | 41 +++++++++++++ crates/xlsx/src/chart.rs | 33 ++++++---- .../src/tests/chart_line_percent_stacked.rs | 57 ++++++++++++++++++ crates/xlsx/src/tests/mod.rs | 1 + crates/xlsx/src/tests/roundtrip.rs | 2 + docs/chart-parity.md | 7 ++- 23 files changed, 264 insertions(+), 25 deletions(-) create mode 100644 crates/engine/tests/it/chart_line_stacked100.rs create mode 100644 crates/xlsx/src/tests/chart_line_percent_stacked.rs diff --git a/ROADMAP.md b/ROADMAP.md index c9e746bc5..779860334 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-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-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 3257082bb..b19098794 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -165,8 +165,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa .clone() .map(|s| { let sw = match plot_kind(chart, s) { - 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, }; @@ -866,6 +868,7 @@ enum Fam { Col100, Line, LineStack, + Line100, Area, AreaStack, Area100, @@ -878,6 +881,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, @@ -887,14 +891,14 @@ 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 { matches!(f, Fam::Col | Fam::ColStack | Fam::Col100) } fn is_line(f: Fam) -> bool { - matches!(f, Fam::Line | Fam::LineStack) + matches!(f, Fam::Line | Fam::LineStack | Fam::Line100) } fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { @@ -907,7 +911,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); - // 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); @@ -938,7 +942,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta 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) { @@ -964,7 +968,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta }), (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); @@ -1150,7 +1154,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta 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 matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); } if labels_on { diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 3f1a068a2..4fa70d4bf 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -5,7 +5,7 @@ use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, Sparkl use crate::*; -const ALL_KINDS: [ChartKind; 26] = [ +const ALL_KINDS: [ChartKind; 28] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, ChartKind::ColumnStacked100, @@ -15,6 +15,8 @@ const ALL_KINDS: [ChartKind; 26] = [ ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, @@ -1137,6 +1139,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/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 9719bf451..4eb4cbe0a 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -65,7 +65,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 ), @@ -578,6 +578,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/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 4c91e58ac..4bb0f7c53 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -3,6 +3,7 @@ mod autofit_filter_buttons; 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 a6879b3ff..36d8e531a 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -260,7 +260,7 @@ pub fn 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/src/features.rs b/crates/model/src/features.rs index 00db5e879..1807570bf 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -406,6 +406,8 @@ pub enum ChartKind { Line, LineMarkers, LineStacked, + LineStacked100, + LineStacked100Markers, Pie, Doughnut, Area, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 46b9b0b2e..a1b3ffbee 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2646,7 +2646,7 @@ fn paste_name(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &m } /// 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"), @@ -2656,6 +2656,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/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index d826b1eb8..993eb296b 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -881,6 +881,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 7f79b4076..c60be7fa1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -765,6 +765,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 ea48f8074..5c3535406 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -777,6 +777,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 1a229f90d..02fb97c0f 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -759,6 +759,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 d72ee2460..a14243e17 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -780,6 +780,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 e71576848..b96899d97 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -765,6 +765,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 8055f77fc..6a504cc30 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -762,6 +762,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/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 0305884ed..6bf1742c6 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1739,6 +1739,8 @@ 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/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index a70efa782..e95602132 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -407,6 +407,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() { @@ -622,6 +645,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 37bcf91b0..a174a9dae 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -29,12 +29,15 @@ fn group_kind(g: &El) -> Option { } } "lineChart" | "line3DChart" => { - if stacked || pct { - ChartKind::LineStacked - } else { - 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")); - if !group_markers || (all_none && g.kids("ser").next().is_some()) { ChartKind::Line } else { ChartKind::LineMarkers } + 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")); + let markers = group_markers && !(all_none && g.kids("ser").next().is_some()); + match (stacked, pct, markers) { + (true, _, _) => ChartKind::LineStacked, + (_, true, true) => ChartKind::LineStacked100Markers, + (_, true, false) => ChartKind::LineStacked100, + (_, _, true) => ChartKind::LineMarkers, + (_, _, false) => ChartKind::Line, } } "pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie, @@ -284,6 +287,7 @@ pub fn read_chart(root: &El) -> Option { enum G { Bar { bar: bool, grouping: &'static str }, Line { stacked: bool, markers: bool }, + Line100 { markers: bool }, Pie, Doughnut, Area { grouping: &'static str }, @@ -303,6 +307,8 @@ fn group_for(k: ChartKind) -> G { 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::LineStacked100 => G::Line100 { markers: false }, + ChartKind::LineStacked100Markers => G::Line100 { markers: true }, ChartKind::Pie => G::Pie, ChartKind::Doughnut => G::Doughnut, ChartKind::Area => G::Area { grouping: "standard" }, @@ -533,7 +539,7 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String } } let color = s.color.as_ref().and_then(|c: &Color| srgb(c, &wb.theme)); - let line_like = matches!(g, G::Line { .. } | G::Radar | G::Scatter { lines: true }); + let line_like = matches!(g, G::Line { .. } | G::Line100 { .. } | G::Radar | G::Scatter { lines: true }); match (&color, line_like) { (Some(c), true) => { let _ = write!(x, "{c}"); @@ -552,7 +558,9 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String } match g { G::Bar { .. } => x.push_str(""), - G::Line { markers: false, .. } | G::Scatter { lines: true } | G::Stock => x.push_str(""), + G::Line { markers: false, .. } | G::Line100 { markers: false } | G::Scatter { lines: true } | G::Stock => { + x.push_str("") + } G::Bubble => x.push_str(""), _ => {} } @@ -581,7 +589,7 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String x.push_str(&cat_data(c, &s.values, wb, si)); } x.push_str(&num_data("val", Some(&s.values), wb, si)); - if matches!(g, G::Line { .. }) { + if matches!(g, G::Line { .. } | G::Line100 { .. }) { let _ = write!(x, "", s.smooth as u8); } } @@ -670,6 +678,9 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb "{sers}{dl}{ax}", if stacked { "stacked" } else { "standard" } ), + G::Line100 { .. } => { + format!("{sers}{dl}{ax}") + } G::Pie => format!("{sers}{dl}"), G::Doughnut => { format!("{sers}{dl}") @@ -766,7 +777,9 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if ch.kind == ChartKind::Combo { // Series without a kind of their own: the first is a column, the others lines (as drawn). let kind = |i: usize, x: &Series| x.kind.filter(|k| *k != ChartKind::Combo).or((i > 0).then_some(ChartKind::Line)); - let is_line = |k: Option| matches!(k.map(group_for), Some(G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })); + let is_line = |k: Option| { + matches!(k.map(group_for), Some(G::Line { .. } | G::Line100 { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })) + }; let bars: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && !is_line(kind(*i, x))).copied().collect(); let lines: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && is_line(kind(*i, x))).copied().collect(); let sec: Vec<(usize, &Series)> = all.iter().filter(|(_, x)| x.secondary).copied().collect(); 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..87c16a4ac --- /dev/null +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -0,0 +1,57 @@ +//! 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_is_saved_as_a_line() { + 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!(kinds.get(1).is_some_and(|k| !matches!(k, Some(ChartKind::ColumnClustered))), "the line series stays out of the column group: {saved}"); +} diff --git a/crates/xlsx/src/tests/mod.rs b/crates/xlsx/src/tests/mod.rs index a7f6f1eb7..8e0b32ba8 100644 --- a/crates/xlsx/src/tests/mod.rs +++ b/crates/xlsx/src/tests/mod.rs @@ -5,6 +5,7 @@ mod cellmetadata; mod chart_book_names; mod chart_bool_default; mod chart_combo_kinds; +mod chart_line_percent_stacked; mod chart_ref_offsets; mod csv_tests; mod encrypted_tests; diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 14fc784f9..61d7cf8a8 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -425,6 +425,8 @@ fn sample() -> Workbook { ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, diff --git a/docs/chart-parity.md b/docs/chart-parity.md index f18283f45..1921350d8 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,6 +1,6 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-24 · **Change:** minor (100% stacked area charts) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-25 · **Change:** minor (100% stacked line charts) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). @@ -15,7 +15,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 | | 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 | @@ -31,7 +31,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Waterfall, Funnel | 2 | 2 of 2 | | | Filled map | 1 | 0 | needs geographic boundary data (licensing decision) | | Combo | custom combinations, secondary axis | yes (line on secondary axis) | | -| **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | +| **Total** | ~60 subtypes | **28 (~47%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | ## Chart elements and formatting @@ -90,6 +90,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | Date | Change | Summary | |---|---|---| +| 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-16 | trivial | Series that refer to defined names (`[0]!Name`, `Sheet!Name`) resolve instead of showing `#NAME?`, and are saved qualified, as Excel needs (#1686) | From 1e3fc9ee37f42f3f11f30a721b4be7f2a20dadf5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:52:05 -0500 Subject: [PATCH 06/21] XLSX: keep a legacy modify password on save when the workbook has no user name --- crates/xlsx/src/tests/roundtrip.rs | 4 +++- crates/xlsx/src/write.rs | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 35c73d568..0f8929711 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1498,7 +1498,9 @@ fn legacy_reservation_password_is_written_with_a_user_name() { 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(); - assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + 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))); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 761c731ce..814e6dd5e 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -348,15 +348,17 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) if r.read_only_recommended { w.push_str(" readOnlyRecommended=\"1\""); } - if !r.user_name.is_empty() { - let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); + // 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 { - // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. - Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { + Some(gridcraft_model::PasswordHash::Legacy(h)) => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } - Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From b4b89a4e3624c404b46fa251ebcb27ba93c6707a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 04:03:37 -0700 Subject: [PATCH 07/21] Charts: Format Chart Area's Chart Type offers 100% Stacked Line with Markers The pane's Chart Type section listed 100% Stacked Line but not its marker variant, so a chart of that type showed no current type there and could not be changed to it from the pane. --- crates/ui-egui/src/panes.rs | 1 + crates/ui-egui/tests/it/format_chart_type.rs | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 54fa9ac02..a21c69243 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -193,6 +193,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { ("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/tests/it/format_chart_type.rs b/crates/ui-egui/tests/it/format_chart_type.rs index ae19e1091..b9ef69da4 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); +} From 8e81dade3359433ad10d168afc37c0aab5ac5c5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:04:36 -0700 Subject: [PATCH 08/21] XLSX: combo charts keep 100% stacked line series and their order when saved A combo chart's 100% stacked line series were saved in the plain line group and reopened as ordinary lines. They now share one percentStacked group, each with its own markers, and reopening a combo chart puts its series back in their c:order order. --- crates/xlsx/src/chart.rs | 34 ++++++++++++++++--- .../src/tests/chart_line_percent_stacked.rs | 29 ++++++++++++++-- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index a174a9dae..dccbb60f5 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -228,19 +228,28 @@ pub fn read_chart(root: &El) -> Option { let (first, first_kind) = *groups.first()?; let first_axes = axis_ids(first); let mut series = vec![]; + let mut orders = vec![]; for (gi, (g, k)) in groups.iter().enumerate() { for s in g.kids("ser") { let mut ser = read_series(s); if groups.len() > 1 { // Every series of a combo chart keeps its own group's kind, the first group's included. - ser.kind = Some(*k); + let no_marker = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker { ChartKind::LineStacked100 } else { *k }); } if gi > 0 { ser.secondary = axis_ids(g) != first_axes; } + orders.push(s.child_val("order").and_then(|v| v.trim().parse::().ok())); series.push(ser); } } + // A combo chart lists its series group by group; `c:order` gives the order they are drawn in. + if groups.len() > 1 && orders.iter().all(Option::is_some) { + let mut keyed: Vec<(Option, Series)> = orders.into_iter().zip(series).collect(); + keyed.sort_by_key(|(o, _)| *o); + series = keyed.into_iter().map(|(_, s)| s).collect(); + } let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal")); let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val)); @@ -663,7 +672,17 @@ fn dlbls(show: bool) -> String { } fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { - let sers: String = series.iter().map(|(i, s)| series_xml(s, *i, g, wb, si)).collect(); + let sers: String = series + .iter() + .map(|(i, s)| { + // In a combo chart's 100% stacked line group, each series writes its own markers. + let sg = match (g, s.kind.map(group_for)) { + (G::Line100 { .. }, Some(own @ G::Line100 { .. })) if ch.kind == ChartKind::Combo => own, + _ => g, + }; + series_xml(s, *i, sg, wb, si) + }) + .collect(); let dl = dlbls(ch.data_labels); let ax = format!("", axes.0, axes.1); match g { @@ -787,8 +806,15 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); } - if !lines.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &lines, ch, (1, 2), wb, si)); + // 100% stacked line series share one percentStacked group, each with its own markers. + let pct = |i: usize, x: &Series| matches!(kind(i, x).map(group_for), Some(G::Line100 { .. })); + let plain: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); + let stacked: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + if !plain.is_empty() { + s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &plain, ch, (1, 2), wb, si)); + } + if !stacked.is_empty() { + s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 87c16a4ac..5ecba4049 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -35,7 +35,7 @@ fn standard_and_stacked_lines_keep_their_kinds() { } #[test] -fn a_hundred_percent_stacked_line_series_in_a_combo_chart_is_saved_as_a_line() { +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!( @@ -53,5 +53,30 @@ fn a_hundred_percent_stacked_line_series_in_a_combo_chart_is_saved_as_a_line() { 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!(kinds.get(1).is_some_and(|k| !matches!(k, Some(ChartKind::ColumnClustered))), "the line series stays out of the column group: {saved}"); + assert_eq!(kinds, [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)], "{saved}"); +} + +#[test] +fn combo_line_series_keep_their_kinds_order_and_shared_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::Line), 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}"); } From 4550a1eba7df4381b59612e5c18984e291a7ff33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:10:02 -0700 Subject: [PATCH 09/21] XLSX: 100% stacked lines on a combo chart's secondary axis keep their kind when saved --- crates/xlsx/src/chart.rs | 19 ++++++++++++------ .../src/tests/chart_line_percent_stacked.rs | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index dccbb60f5..17c945eac 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -817,12 +817,19 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { - let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { - Some(b @ G::Bar { .. }) => b, - _ => G::Line { stacked: false, markers: false }, - }; - s.push_str(&group_xml(g, &sec, ch, (3, 4), wb, si)); - secondary = Some(g); + if let Some(b @ G::Bar { .. }) = sec.first().and_then(|(_, x)| x.kind).map(group_for) { + s.push_str(&group_xml(b, &sec, ch, (3, 4), wb, si)); + secondary = Some(b); + } else { + let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); + let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + for (g, members) in [(G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] { + if !members.is_empty() { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); + } + } + } } } else { primary_g = match group_for(ch.kind) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 5ecba4049..b5c58faa5 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -80,3 +80,23 @@ fn combo_line_series_keep_their_kinds_order_and_shared_percent_stack_when_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}"); +} From a6f9b80e43a7e9a5e60627a9ab784586a9e4349e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:39:04 -0700 Subject: [PATCH 10/21] Charts: move the marker check out of cartesian to keep it under the complexity limit --- crates/chart/src/render/cartesian.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 99199deed..fbb46e199 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -53,6 +53,11 @@ fn is_line(f: Fam) -> bool { 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) +} + fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { // Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); @@ -321,7 +326,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 matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) && cw >= 3.0 { + if has_markers(k) && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); } if labels_on { From 3adf6625787ec49257de67b30795761e417f589e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:49:07 -0700 Subject: [PATCH 11/21] XLSX: combo charts keep secondary columns, lines and 100% stacked lines in separate groups when saved --- crates/xlsx/src/chart.rs | 26 +++++++++------- .../src/tests/chart_line_percent_stacked.rs | 30 +++++++++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 17c945eac..2e611dcf5 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -817,17 +817,21 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { - if let Some(b @ G::Bar { .. }) = sec.first().and_then(|(_, x)| x.kind).map(group_for) { - s.push_str(&group_xml(b, &sec, ch, (3, 4), wb, si)); - secondary = Some(b); - } else { - let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); - let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - for (g, members) in [(G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] { - if !members.is_empty() { - s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); - secondary.get_or_insert(g); - } + // Secondary bars, lines and 100% stacked lines each get their own group. + let bar_of = |x: &Series| match x.kind.map(group_for) { + Some(b @ G::Bar { .. }) => Some(b), + _ => None, + }; + let sec_bars: Vec<(usize, &Series)> = sec.iter().filter(|(_, x)| bar_of(x).is_some()).copied().collect(); + let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| bar_of(x).is_none() && !pct(*i, x)).copied().collect(); + let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + let bar_g = sec_bars.first().and_then(|(_, x)| bar_of(x)).unwrap_or(G::Bar { bar: false, grouping: "clustered" }); + for (g, members) in + [(bar_g, sec_bars), (G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] + { + if !members.is_empty() { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); } } } diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index b5c58faa5..8156dfb9d 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -100,3 +100,33 @@ fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_save 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}"); } + +#[test] +fn secondary_columns_lines_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::Line), 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}"); +} From 9680794bc4eb91228f87734bdb73f00ae1d45979 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 08:00:31 -0700 Subject: [PATCH 12/21] XLSX: combo charts keep each area, marked line and column grouping in its own group when saved Lines and secondary series are written as one chart group per kind, so areas, lines with markers and columns with different groupings open again as the same kinds instead of plain lines or the first column's grouping. --- crates/xlsx/src/chart.rs | 51 +++++++++---------- .../src/tests/chart_line_percent_stacked.rs | 35 +++++++++++++ 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 2e611dcf5..bc82effe8 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -767,6 +767,25 @@ fn strip_book(link: &str) -> &str { link.strip_prefix('[').and_then(|r| r.split_once(']')).map_or(link, |(_, rest)| rest) } +/// Splits a combo chart's series into one group per kind, in the order each kind first appears. +/// Columns, bars, lines and areas keep their own grouping and markers; 100% stacked lines share one group +/// whose series write their own markers; other kinds are written as plain lines. +fn combo_groups<'a>(series: &[(usize, &'a Series)], kind: impl Fn(usize, &Series) -> Option) -> Vec<(G, Vec<(usize, &'a Series)>)> { + let mut groups: Vec<(G, Vec<(usize, &'a Series)>)> = vec![]; + for &(i, x) in series { + let g = match kind(i, x).filter(|k| *k != ChartKind::Combo).map(group_for) { + Some(g @ (G::Bar { .. } | G::Line { .. } | G::Area { .. })) => g, + Some(G::Line100 { .. }) => G::Line100 { markers: true }, + _ => G::Line { stacked: false, markers: false }, + }; + match groups.iter_mut().find(|(k, _)| *k == g) { + Some((_, members)) => members.push((i, x)), + None => groups.push((g, vec![(i, x)])), + } + } + groups +} + /// Chart part XML for a model chart on sheet `si`. pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> String { let mut s = String::from( @@ -806,34 +825,12 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); } - // 100% stacked line series share one percentStacked group, each with its own markers. - let pct = |i: usize, x: &Series| matches!(kind(i, x).map(group_for), Some(G::Line100 { .. })); - let plain: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); - let stacked: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - if !plain.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &plain, ch, (1, 2), wb, si)); + for (g, members) in combo_groups(&lines, |i, x| kind(i, x)) { + s.push_str(&group_xml(g, &members, ch, (1, 2), wb, si)); } - if !stacked.is_empty() { - s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); - } - if !sec.is_empty() { - // Secondary bars, lines and 100% stacked lines each get their own group. - let bar_of = |x: &Series| match x.kind.map(group_for) { - Some(b @ G::Bar { .. }) => Some(b), - _ => None, - }; - let sec_bars: Vec<(usize, &Series)> = sec.iter().filter(|(_, x)| bar_of(x).is_some()).copied().collect(); - let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| bar_of(x).is_none() && !pct(*i, x)).copied().collect(); - let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - let bar_g = sec_bars.first().and_then(|(_, x)| bar_of(x)).unwrap_or(G::Bar { bar: false, grouping: "clustered" }); - for (g, members) in - [(bar_g, sec_bars), (G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] - { - if !members.is_empty() { - s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); - secondary.get_or_insert(g); - } - } + for (g, members) in combo_groups(&sec, |_, x| x.kind) { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); } } else { primary_g = match group_for(ch.kind) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 8156dfb9d..20bdac29e 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -130,3 +130,38 @@ fn secondary_columns_lines_and_hundred_percent_stacked_lines_keep_their_kinds_wh 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 combo_areas_marked_lines_and_mixed_column_groupings_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, ""), + ser(4, ""), + ser(5, ""), + ser(6, NO_MARKER) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let got: Vec<(Option, bool)> = ch.series.iter().map(|s| (s.kind, s.secondary)).collect(); + assert_eq!(got[1], (Some(ChartKind::AreaStacked), false)); + assert_eq!(got[3], (Some(ChartKind::ColumnStacked), true)); + assert_eq!(got[4], (Some(ChartKind::ColumnClustered), true)); + assert_eq!(got[5], (Some(ChartKind::AreaStacked100), true)); + assert_eq!(got[6], (Some(ChartKind::Line), true)); + 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::>(), got, "{saved}"); +} From 04f8797ee46597200b9cc0c23da2e9d3d9eb8550 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 08:04:56 -0700 Subject: [PATCH 13/21] XLSX: a 100% stacked line group with mixed markers opens with each series' own markers A single percentStacked line group whose series differ in markers opens as a combo chart, so saving it keeps the marked and unmarked series as they were. --- crates/xlsx/src/chart.rs | 13 +++++++----- .../src/tests/chart_line_percent_stacked.rs | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index bc82effe8..3b3409506 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -227,15 +227,18 @@ pub fn read_chart(root: &El) -> Option { let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect(); let (first, first_kind) = *groups.first()?; let first_axes = axis_ids(first); + let no_marker = |s: &El| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + // A 100% stacked line group whose series differ in markers opens as a combo chart, so each series keeps its own. + let mixed = first_kind == ChartKind::LineStacked100Markers && first.kids("ser").any(no_marker) && !first.kids("ser").all(no_marker); + let combo = groups.len() > 1 || mixed; let mut series = vec![]; let mut orders = vec![]; for (gi, (g, k)) in groups.iter().enumerate() { for s in g.kids("ser") { let mut ser = read_series(s); - if groups.len() > 1 { + if combo { // Every series of a combo chart keeps its own group's kind, the first group's included. - let no_marker = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); - ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker { ChartKind::LineStacked100 } else { *k }); + ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker(s) { ChartKind::LineStacked100 } else { *k }); } if gi > 0 { ser.secondary = axis_ids(g) != first_axes; @@ -245,12 +248,12 @@ pub fn read_chart(root: &El) -> Option { } } // A combo chart lists its series group by group; `c:order` gives the order they are drawn in. - if groups.len() > 1 && orders.iter().all(Option::is_some) { + if combo && orders.iter().all(Option::is_some) { let mut keyed: Vec<(Option, Series)> = orders.into_iter().zip(series).collect(); keyed.sort_by_key(|(o, _)| *o); series = keyed.into_iter().map(|(_, s)| s).collect(); } - let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; + let kind = if combo { ChartKind::Combo } else { first_kind }; let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal")); let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val)); let val_axes: Vec<&El> = plot.kids("valAx").collect(); diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 20bdac29e..e9dcaed9d 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -131,6 +131,26 @@ fn secondary_columns_lines_and_hundred_percent_stacked_lines_keep_their_kinds_wh 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) + ); + let want = [Some(ChartKind::LineStacked100Markers), 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"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); +} + #[test] fn combo_areas_marked_lines_and_mixed_column_groupings_keep_their_kinds_when_saved() { let ser = |i: usize, marker: &str| { From 2c976a6e6baa3560375cc672c3af9e77413c5954 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:51:09 -0500 Subject: [PATCH 14/21] Import engine error in file commands --- crates/engine/src/cmd/file.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d11be6027..54ad9e4f2 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -3,7 +3,7 @@ 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![ From 15eef6b4343a5ed9656686e7d0ccdaeb9ea4a278 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:59:52 -0500 Subject: [PATCH 15/21] Extract XLSX write validation helper --- crates/xlsx/src/write.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 8e025c8a8..0c9236063 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -204,6 +204,16 @@ 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 check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { + if wb.sheets.is_empty() { + return Err(IoError::Format("a workbook needs at least one sheet".into())); + } + if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { + return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); + } + check_sheet_names(wb) +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -211,13 +221,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { /// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its /// PivotTable in Excel only when its link starts with the workbook in brackets. pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { - if wb.sheets.is_empty() { - return Err(IoError::Format("a workbook needs at least one sheet".into())); - } - if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { - return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); - } - check_sheet_names(wb)?; + check_write_xlsx(wb)?; let mut out = Out { parts: vec![], overrides: vec![], From cd6fe4f8bd81595f34a0cc4436c0291fd0a62ba7 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:05:24 -0500 Subject: [PATCH 16/21] Extract file sharing XML writer --- crates/xlsx/src/write.rs | 45 +++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 0c9236063..ac08434c9 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -214,6 +214,29 @@ fn check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { check_sheet_names(wb) } +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) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -263,27 +286,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // 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 }); - if let Some(r) = &wb.write_reservation { - w.push_str(" { - let _ = write!(w, " reservationPassword=\"{h:04X}\""); - } - Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), - None => {} - } - w.push_str("/>"); - } + append_file_sharing(&mut w, wb); w.push_str(" {} From 5f1e609a698451deb386613a92c7c7db398f318e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 21:20:58 -0800 Subject: [PATCH 17/21] Charts: 100% stacked line kinds keep data tables --- crates/model/src/features.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 6eb0a1cbb..1763f3275 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -597,6 +597,8 @@ impl Chart { | ChartKind::Line | ChartKind::LineMarkers | ChartKind::LineStacked + | ChartKind::LineStacked100 + | ChartKind::LineStacked100Markers | ChartKind::Area | ChartKind::AreaStacked | ChartKind::AreaStacked100 From 9c5b6b2dbeb35634bee3038039af62c9fb8d33f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 14:25:28 -0800 Subject: [PATCH 18/21] Charts: data table keys for 100% stacked line charts use line swatches --- crates/chart/src/render/table.rs | 4 ++-- crates/chart/src/tests/data_table.rs | 29 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index f0839dcfe..478f0ffd7 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 plot_kind(chart, series) { - 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/data_table.rs b/crates/chart/src/tests/data_table.rs index 13e2baf6c..6ea403556 100644 --- a/crates/chart/src/tests/data_table.rs +++ b/crates/chart/src/tests/data_table.rs @@ -119,3 +119,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"); + } +} From 2be4be9dd2b5b35fc627c9ada4d594b78f4ce56e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:04:18 -0600 Subject: [PATCH 19/21] Reduce dialog display complexity --- crates/ui-egui/src/dialogs/show.rs | 42 ++++++++++++++++-------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index e0a24a548..9b02051c4 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -121,6 +121,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 }; @@ -431,26 +452,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)); - } - // Encrypted and reserved: the password opened it, so the form turns to the password to - // modify. The decryption password stays in the values for the retry. - Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { - 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 }; - } - } - // A wrong password: say so, clear the field and stay open for another try. - Err(e) if d.name == "openPassword" => { - 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))); - } - 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; From 5d578bef00919d072c9620edd24c366d0b310708 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:05:11 -0600 Subject: [PATCH 20/21] Record model SHA-1 dependency in lockfile --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index dfdde30e7..1c69b16c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2150,6 +2150,7 @@ dependencies = [ "gridcraft-math", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", ] From 2f4b7025300ed8c50765c8aa04f359802edfb75b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:23:48 -0800 Subject: [PATCH 21/21] Charts: stacked and 100% stacked line groups on one axis open as a combo chart The chart reader reports both groupings as stacked lines, so a chart holding both read every series as a 100% stacked line. Each series now takes its own group's kind, and the chart opens as a combo chart when those kinds differ. --- crates/xlsx/src/chart.rs | 44 ++++++++++--------- .../src/tests/chart_line_percent_stacked.rs | 19 ++++++++ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 1fdf8f7e4..6bce0c3a0 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -225,11 +225,24 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { let multi_axis = ser_els.iter().any(|(_, _, sec)| *sec); let base_kind = map_chart_type(dc.kind, &groups); let no_marker = |s: &El| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); - // A 100% stacked line chart whose series differ in markers opens as a combo chart, so each series keeps its own. - let mixed = base_kind == ChartKind::LineStacked100Markers - && ser_els.iter().any(|(s, _, _)| no_marker(s)) - && !ser_els.iter().all(|(s, _, _)| no_marker(s)); - let is_combo = dc.kind == ChartType::Combo || multi_axis || mixed; + // Series `i` takes its own plot group's kind; a 100% stacked line series without markers in a group with them keeps its own. + let own_kind = |i: usize, k: ChartType| { + let (sel, scope): (Option<&El>, &[&El]) = match ser_els.get(i) { + Some((el, g, _)) => (Some(*el), std::slice::from_ref(g)), + None => (None, &groups), + }; + match map_chart_type(k, scope) { + ChartKind::LineStacked100Markers if sel.is_some_and(no_marker) => ChartKind::LineStacked100, + own => own, + } + }; + // A 100% stacked line chart whose series differ in markers, or that also holds a plain stacked line group, opens as a + // combo chart, so each series keeps its own kind. + let own_kinds: Vec = dc.series.iter().enumerate().map(|(i, s)| own_kind(i, s.kind.unwrap_or(dc.kind))).collect(); + let split = dc.kind != ChartType::Combo + && own_kinds.iter().any(|k| matches!(k, ChartKind::LineStacked100 | ChartKind::LineStacked100Markers)) + && own_kinds.windows(2).any(|w| w[0] != w[1]); + let is_combo = dc.kind == ChartType::Combo || multi_axis || split; let kind = if is_combo { ChartKind::Combo } else { base_kind }; let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true)); let mut keyed: Vec<(Option, Series)> = dc @@ -237,18 +250,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .into_iter() .enumerate() .map(|(i, s)| { - let (sel, group, fallback_sec) = match ser_els.get(i).copied() { - Some((el, g, sec)) => (Some(el), Some(g), sec), - None => (None, None, false), - }; - // A series takes its own plot group's kind; a 100% stacked line series without markers in a group with them keeps its own. - let scope: &[&El] = match &group { - Some(g) => std::slice::from_ref(g), - None => &groups, - }; - let own_kind = |k: ChartType| match map_chart_type(k, scope) { - ChartKind::LineStacked100Markers if sel.is_some_and(no_marker) => ChartKind::LineStacked100, - own => own, + let (sel, fallback_sec) = match ser_els.get(i).copied() { + Some((el, _, sec)) => (Some(el), sec), + None => (None, false), }; let color = s .fill @@ -288,9 +292,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { color, secondary: is_combo && (s.secondary_axis || fallback_sec), kind: if dc.kind == ChartType::Combo { - s.kind.map(own_kind) - } else if multi_axis || mixed { - Some(own_kind(s.kind.unwrap_or(dc.kind))) + s.kind.map(|k| own_kind(i, k)) + } else if multi_axis || split { + own_kinds.get(i).copied() } else { None }, diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index e9dcaed9d..384d3a373 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -151,6 +151,25 @@ fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_mar assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); } +#[test] +fn stacked_and_hundred_percent_stacked_line_groups_on_one_axis_keep_their_kinds() { + let ser = |i: usize| { + format!("{NO_MARKER}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let want = [Some(ChartKind::LineStacked), Some(ChartKind::LineStacked100)]; + 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::>(), want); +} + #[test] fn combo_areas_marked_lines_and_mixed_column_groupings_keep_their_kinds_when_saved() { let ser = |i: usize, marker: &str| {